Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Lua 5.2 function from C++

Tags:

c++

lua

lua-5.2

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);
like image 563
user2135428 Avatar asked Oct 22 '22 15:10

user2135428


1 Answers

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.

like image 173
lhf Avatar answered Nov 12 '22 22:11

lhf