Zack Lee
Zack Lee

Reputation: 3044

How to properly set Lua local variable in C++

I'm trying to write the following Lua code in C++.

local test = require 'test'
test.num = 5
test.update()

I could successfully call test.update() but I don't know how to properly do test.num = 5 in C++.

My Code :

#include "lua.hpp"

int main()
{
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    luaopen_my(L);
    lua_settop(L, 0);
    luaL_dostring(L, "package.preload['test'] = function ()\n"
                         "local test = {}\n"
                         "test.num = 3\n"
                         "function test.update() print(test.num) end\n"
                         "return test\n"
                     "end\n");
    /* require 'test' */
    lua_getglobal(L, "require");
    lua_pushstring(L, "test");
    if (lua_pcall(L, 1, LUA_MULTRET, 0))
    {
        std::cout << "Error : " << lua_tostring(L, -1) << '\n';
        lua_pop(L, 1);
    }
    /* test.num = 5 */
    lua_pushnumber(L, 5);
    lua_setfield(L, -1, "num"); //crashes here

    /* test.update() */
    lua_getfield(L, -1, "update");
    lua_pushnil(L);
    if (lua_pcall(L, 1, LUA_MULTRET, 0))
    {
        std::cout << "Error : " << lua_tostring(L, -1) << '\n';
        lua_pop(L, 1);
    }
    lua_close(L);
}

Expected Result :

5

However, my code crashes when calling lua_setfield(L, -1, "num");

How should I change my code so it can properly set the value of test.num?

Upvotes: 2

Views: 1013

Answers (1)

ratchet freak
ratchet freak

Reputation: 48186

lua_pushnumber(L, 5);
lua_setfield(L, -1, "num"); //crashes here

The -1 there refers to the number 5 you just pushed and not the table you thought it was refering to.

Instead you can either get a fixed index to the table using lua_absindex or use -2;

int testTable = lua_absindex(-1);
lua_pushnumber(L, 5);
lua_setfield(L, testTable , "num"); //crashes here

Upvotes: 2

Related Questions