Can I replace a table? e.g. I cannot get this working:
lua_createtable(L,0,0);
lua_replace(L,2); // is the 2nd parameter of a function call
You can lua_replace
any lua value at the given index with whatever is at the top. Here's a simple unit test that takes your new empty table and moves it to position 2, replacing whatever happens to be there:
int test_replace(lua_State *L)
{
lua_getglobal(L, "_VERSION");
lua_getglobal(L, "os");
lua_getglobal(L, "os");
printstack(L);
lua_createtable(L, 0, 0);
lua_replace(L, 2);
printstack(L);
return 0;
}
A simple printstack
to show what's on the lua stack:
const char *lprint =
"function lprint(...)"
" local _, arg2 = ..."
" print(...)"
" return ..."
" end";
int printstack(lua_State *L)
{
const int argc = lua_gettop(L);
lua_getglobal(L, "lprint");
lua_insert(L, 1);
lua_call(L, argc, argc);
return argc;
}
Now if you run test_replace
, eg.
luaL_dostring(L, lprint);
lua_pushcfunction(L, test_replace);
lua_call(L, 0, 0);
Possible output:
Lua 5.2 table: 00431A10 table: 00431A10
Lua 5.2 table: 00431DD0 table: 00431A10
If the code snippet in your question isn't working then you're doing something wrong in the surrounding context that you're not showing.
Unless the newly created table is pushed as a return value, it won't be reflected in variables outside of the function because parameters in lua are always passed by value.
The only way to accomplish this is to not create a new table and instead append to the table you started with. You want to keep the pointer to your original table intact.