1

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?

1 Answer 1

2
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.

Sign up to request clarification or add additional context in comments.

2 Comments

oh, i see, thank you. I thought i needed to call lua_pcall so that variable will actually be added.
Nope, you use lua_pcall() to call functions, all other things are just executed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.