Recommand · October 22, 2021 0

C++ Lua embedding, pushing table to a function that on arguments

so i was trying to push a table on a function inside arguments
*lua

function test1(varlist)
print(varlist[1])
print(varlist[2])
print(varlist[3])
end

addHook("string", "string2", test1)

*cpp

static int lua_addHook(lua_State* L) {
    if (lua_isstring(L, 1) && lua_isstring(L, 2) && lua_isfunction(L, 3)) {
        lua_newtable(L);

        lua_newtable(L);
        for (size_t i = 0; i < 3; ++i) {
            lua_pushinteger(L, i + 1);
            lua_pushstring(L, string("string varlist: " + to_string(i)).c_str());
            lua_settable(L, -3);
        }
        if (lua_pcall(L, 1, 0, 0) != 0) {
            printf("error: %s\n", lua_tostring(L, -1));
            lua_pop(L, 1);
        }
    }
    return 1;
}

so it should printing
string varlist: 0
string varlist: 1
string varlist: 2

but i keep getting error "attempt to call a table value"
u know what the problem is?

The stack looks like this at the point of lua_pcall:

table (constructed by the loop above) # STACK TOP and arg1 to function call
table (empty)                         # interpreted as the function to call
function test1
string "string1"
string "string"

Getting rid of one of the lua_newtable calls should fix it.