5

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);
user2135428
  • 61
  • 1
  • 4
  • See also http://stackoverflow.com/questions/11093189/lua-updating-from-5-1-lua-globalsindex-problems – lhf Mar 05 '13 at 13:08

1 Answers1

3

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_loadfileand of lua_pcall. You'll probably be better off using luaL_dofile.

lhf
  • 70,581
  • 9
  • 108
  • 149