I have a Lua function registered which expects a metatable as parameter and I want to modify the contents of the table in C++ runtime:
int operate(lua_State *L)
{
std::vector<int> values{};
if (auto length = get_length_at_index(L, 1))
{
result.reserve(length);
lua_pushnil(L);
while (lua_next(L, 1))
{
result.push_back(lua_tointeger(L, -1));
lua_pop(L, 1);
}
}
for (auto &v : values)
{
v *= 2;
}
return 0;
}
int main()
{
auto L = luaL_newstate();
luaL_dofile(L, "script.lua");
lua_register(L, "operate", operate);
return 0;
}
The code above reads "lua.script"
which looks like this:
values = {1, 2, 3, 4, 5, 6}
operate(values)
for index = 1, #values do
print(values[index])
end
The expected output is the values from 1 to 6 multiplied by 2, but the output is the unmodified values. Is obvious that this happens because I'm copying the metatable into a std::vector
and modify the copy.
Is there a way to operate from C++ runtime over Lua objects in a way that they reflect the changes applied from C++?
PS: I know that I can return the table as the function return value, but I want to know if there's other options.