2
votes

I would like to read a Lua file in a level editor so I can display its data in visual format for users to edit.

If I have a Lua table like so:

properties = {
  Speed = 10,
  TurnSpeed = 5
}

Speed is obviously the key and 10 the value. I know I can access the value if I know the key like so (provided the table is already on the stack):

lua_pushstring(L, "Speed");
lua_gettable(L, idx); 
int Speed = lua_tointeger(L, -1);
lua_pop(L, 1); 

What I want to do is access the key's name and the corresponding value, in C++. Can this be done? If so how do I go about it?

1

1 Answers

4
votes

This is covered by the lua_next function, which iterates over the elements of a table:

// table is in the stack at index 't'
lua_pushnil(L);  // first key
while (lua_next(L, t) != 0)
{
  // uses 'key' (at index -2) and 'value' (at index -1)
  printf("%s - %s\n", luaL_typename(L, -2), luaL_typename(L, -1));
  // removes 'value'; keeps 'key' for next iteration
  lua_pop(L, 1);
}

lua_next keys off of the, um, key of the table, so you need to keep that on the stack while you're iterating. Each call will jump to the next key/value pair. Once it returns 0, then you're done (and while the key was popped, the next wasn't pushed).

Obviously adding or removing elements to a table you're iterating over can cause issues.