2

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?

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

1 Comment

That fixed my problem. Thank you so much for your help.

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.