I am trying to learn lua and I seem to be stuck here.
For some reason the following code doesn't actually run the lua file.
int main()
{
lua_State* L = luaL_newstate();
luaL_openlibs(L);
int width = 0;
int height = 0;
if(!luaL_loadfile(L, "./src/luaconf.lua") || !lua_pcall(L, 0, 0, 0))
{
lua_getglobal(L, "width");
lua_getglobal(L, "height");
if(!lua_isnumber(L, -2))
{
luaL_error(L, "width isn't a number");
}
else
{
width = lua_tointeger(L, -2);
}
if(!lua_isnumber(L, -1))
{
luaL_error(L, "height isn't a number");
}
else
{
height = lua_tointeger(L, -1);
}
}
printf("%i x %i", width, height);
return 0;
}
I know that if I change if(!luaL_loadfile(L, "./src/luaconf.lua") || !lua_pcall(L, 0, 0, 0)
to if(luaL_dofile(L, "./src/luaconf.lua"))
it would work but I want to know why the above code doesn't work.
Shouldn't lua_pcall run the lua code? If not why not?
luaconf.lua
width = 500
height = 40
Note that in the code:
if(!luaL_loadfile(L, "./src/luaconf.lua") || !lua_pcall(L, 0, 0, 0))
if luaL_loadfile
succeeds, it returns LUA_OK
which has the value of 0
, so the left operand of ||
evaluates as 1
, according to short circuit, lua_pcall
won't be executed.
So what you want is probably:
if ((luaL_loadfile(L, "./src/luaconf.lua") || lua_pcall(L, 0, 0, 0))
{
//error handle
}
else
{
//normal handle
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.