Question

I am struggling finding and understanding how to pass a table from lua to c++

What I have:

Lua File:

-- lua script for sending table data
io.write("lua table to send")
tableexample = {x = 1, y = 2, z = 100}
return tableexample

c/c++ side

L = lua_open();
luaL_openfile(L, "luafile");
... call the function...
luaLdofile(L, luafile);
int result;
result = lua_pcall(L,0, LUA_MULTRET,0);
if(result){
fprintf(stderr, "failed %s\n", lua_tostring(L,-1));

if(lua_istable(L,-1)){
  lua_gettable(L,-1);
  x = lua_tonumber(L,-2);
  y = lua_tonumber(L,-3);
  z = lua_tonumber(L,-4);
}
else
printf("fail");

the result comes back with a failure "attempt to call a table value"

I've looked at many different tutorials/examples but haven't found a simple tutorial that doesn't have 100 other things going on and am getting myself confused

some references that are similar - but too complex for what I am looking for Iterating through a Lua table from C++?

Was it helpful?

Solution

Your use of lua_gettable is wrong.

Have a look at the Lua manual:

void lua_gettable (lua_State *L, int index);

Pushes onto the stack the value t[k], where t is the value at the given index and k is the value at the top of the stack.

This function pops the key from the stack (putting the resulting value in its place).

In your example, the value at the top of the stack is the table itself, so you are doing the equivalent of a tableexample[tableexample] lookup.

The shortest way to achieve what you want is to use lua_getfield instead, which allows accessing table elements by string keys:

lua_getfield(L, -1, "x");

Alternatively, push a Lua value of type string on the stack first and use lua_gettable for the lookup.

lua_pushliteral(L, "x");
lua_gettable(L, -2);

Don't forget to keep your stack balanced. Every value that you push on the stack needs to be popped properly. The Lua manual specifies how each API call changes the stack by the numbers in the \[ \] brackets on the right side of each function name.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top