parse table from c to lua

31 views Asked by At

I have the following, although it does not seem any error on me, nor to AI I get the following error:

int main(void) {
int res;
lua_State *L = luaL_newstate();
luaL_openlibs(L);

const char *luaCode = " function select(xx) \
                            if (xx ~= nil and type(xx) == 'table') then \   
                                local y = 0 \
                                for i = 1, #xx do \
                                    y = y + xx[i] \
                                end \
                                return y \
                            end \
                        end ";

res = luaL_loadstring(L, luaCode);
if (res != LUA_OK) {
    printf("Error loading select function: %s\n", lua_tostring(L, -1));
    lua_close(L);
    exit(1);
}

lua_getglobal(L, "select");
if (!lua_isfunction(L, -1)) {
    printf("Error: select is not a function.\n");
    lua_close(L);
    exit(1);
}

lua_newtable(L); // Create a new Lua table

for (int i = 1; i <= 3; ++i) {
    lua_pushinteger(L, i);
    lua_pushinteger(L, i);
    lua_settable(L, -3);
}

res = lua_pcall(L, 1, 1, 0); // Pass the table to the select function
if (res != LUA_OK) {
    printf("Error running code: %s\n", lua_tostring(L, -1));
    lua_close(L);
    exit(1);
}

if (lua_isinteger(L, -1)) printf("%d\n", (int)lua_tointeger(L, -1));
else if (lua_isnumber(L, -1)) printf("%f\n", lua_tonumber(L, -1));

lua_close(L);
exit(0);
}

I get Error running code: bad argument #1 to 'select' (number expected, got table) Should i add anything in lua code to execute? Is it just sthing else i have to do on Stack?

1

There are 1 answers

0
luther On

In the doc for luaL_loadstring, it says:

this function only loads the chunk; it does not run it.

As stated in the comments, you should use luaL_dostring instead.

Note that select is a preexisting function in the standard library, so the error you see is coming from a whole different function.