Stals
Stals

Reputation: 1603

c++ lua error on setting global variable

I have the folowing code:

lua_State *lua;
lua = lua_open();
luaL_openlibs(lua);

std::string code = "print(gvar)\n"
    "function test()\n"
    "print(gvar)\n"
    "end\n";

if(!luaL_loadstring(lua, code.c_str())){
    if (lua_pcall(lua, 0, 0, 0)){
        const char* error = lua_tostring(lua, -1); 
        lua_pop(lua, 1);
    }
}

lua_pushstring(lua, "100");
lua_setglobal(lua, "gvar");
if (lua_pcall(lua, 0, 0, 0)){
    const char* error = lua_tostring(lua, -1); // returns "attempt to call a nil value"
    lua_pop(lua, 1);
}

lua_close(lua);

Calling functions and getting global variables works fine, but when i try to set global variable i get "attempt to call a nil value". And i cant understand why is that?

Upvotes: 1

Views: 3847

Answers (1)

Caladan
Caladan

Reputation: 1491

if(!luaL_loadstring(lua, code.c_str())){
    if (lua_pcall(lua, 0, 0, 0)){
        const char* error = lua_tostring(lua, -1); 
        lua_pop(lua, 1);
    }
}

This code loads string into a anonymous function using luaL_loadstring(), puts it on the stack and then executes the function using lua_pcall(lua, 0, 0, 0).

lua_pushstring(lua, "100");
lua_setglobal(lua, "gvar");
if (lua_pcall(lua, 0, 0, 0)){
    const char* error = lua_tostring(lua, -1); // returns "attempt to call a nil value"
    lua_pop(lua, 1);
}

This piece of code pushes string onto the stack then sets global variable gvar. There should be nothing on the stack after call to lua_setglobal(). The var is already there.

Now after that you try to call a function which is at the top of the stack with lua_pcall, but the stack is empty - that's why you get attempt to call a nil value message.

Upvotes: 2

Related Questions