I'm pretty new to Lua. I've been looking at some sample code for how to call a Lua function from C++, but the sample code uses 5.1, and I'm trying to get this to work with 5.2.
Here is the sample code in question with my comments:
lua_State *luaState = luaL_newstate();
luaopen_io(luaState);
luaL_loadfile(luaState, "myLuaScript.lua");
lua_pcall(luaState, 0, LUA_MULTRET, 0);
//the code below needs to be rewritten i suppose
lua_pushstring(luaState, "myLuaFunction");
//the line of code below does not work in 5.2
lua_gettable(luaState, LUA_GLOBALSINDEX);
lua_pcall(luaState, 0, 0, 0);
I've read in the 5.2 reference manuel (http://www.lua.org/manual/5.2/manual.html#8.3) that one needs to get the global environment from the registry (instead of the lua_gettable statement above) but I can't work out which changes I need to make to get this working. I've tried, for instance:
lua_pushglobaltable(luaState);
lua_pushstring(luaState, "myLuaFunction");
lua_gettable(luaState, -2);
lua_pcall(luaState, 0, 0, 0);
The code below should work in both 5.1 and 5.2.
lua_getglobal(luaState, "myLuaFunction");
lua_pcall(luaState, 0, 0, 0);
But make sure to test the return code of luaL_loadfile
and of lua_pcall
. You'll probably be better off using luaL_dofile
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With