1
votes

Good afternoon, I am working on a LUA/C++ application, from which i need lua to be able to call other lua code recursively, e.g: C++ calls lua function, lua function calls another lua function from another string that is loaded using a registered C function that runs at the start of the first lua function;

here are the steps i am following:

    lua_State* state = luaL_newstate();
    luaL_openlibs(state);
    lua_register(state, "secondLua", secondLua);
    lua_getfield( _luaState, LUA_GLOBALSINDEX, "init" );
    lua_pcall( _luaState, 0, 0, 0 );

    int secondLua(lua_State* state){
    char* myString[128] = "function init2()\n io.write(\"hello\")\n end";
    luaL_loadstring(pLuaState, myString);
    lua_getfield(pLuaState,LUA_GLOBALSINDEX, "init2"); // function init2 declared on myString
    lua_pcall(pLuaState, 0, LUA_MULTRET, 0);
//getting "attempt to call a nil value" here

    return 0;  
    }

Any help is appreciated, and second, i would like to know if there is a way i can name the second function "init" as well as the first one;

PS: I am using C++14 and lua 5.1 on LUAJIT, and i cant use lua's dofile;

1
Unrelated to your actual problem but have you considered using a wrapper library such as sol ? - Borgleader
Why is this tagged [c]? - 3442
@KemyLand Because this is C API for Lua I guess. - Jakuje
@Jakuje: The OP is talking about C++ anyways, not C. - 3442
This compiles? That second call to lua_getfield is missing an argument. - Etan Reisner

1 Answers

2
votes

lua_loadstring() compiles supplied source and puts Lua chunk on stack. It won't execute it though, so init2() still not defined when you expect that.
Replace lua_loadstring() with luaL_dostring() to actually run that chunk and define new lua functions. Or call lua_pcall() right after lua_loadstring(). Actually, luaL_dostring() does exactly that - lua_loadstring() followed by lua_pcall().