Lua Introduction to Lua C API Table manipulation


In order to access or alter an index on a table, you need to somehow place the table into the stack.
Let's assume, for this examples that your table is a global variable named tbl.

Getting the content at a particular index:

int getkey_index(lua_State *L)
  lua_getglobal(L, "tbl");    // this put the table in the stack
  lua_pushstring(L, "index"); // push the key to access
  lua_gettable(L, -2);        // retrieve the corresponding value; eg. tbl["index"]

  return 1;                   // return value to caller

As we have seen, all you have to do is to push the table into the stack, push the index and call lua_gettable. the -2 argument means that the table is the second element from the top of the stack.
lua_gettable triggers metamethods. If you do not want to trigger metamethods, use lua_rawget instead. It uses the same arguments.

Setting the content at a particular index:

int setkey_index(lua_State *L)
  // setup the stack
  lua_getglobal(L, "tbl");
  lua_pushstring(L, "index");
  lua_pushstring(L, "value");
  // finally assign the value to table; eg. tbl.index = "value"
  lua_settable(L, -3);

  return 0;

The same drill as getting the content. You have to push the stack, push the index and then push the value into the stack. after that, you call lua_settable. the -3 argument is the position of the table in the stack. To avoid triggering metamethods, use lua_rawset instead of lua_settable. It uses the same arguments.

Transferring the content from a table to another:

int copy_tableindex(lua_State *L)
    lua_getglobal(L, "tbl1"); // (tbl1)
    lua_getglobal(L, "tbl2");// (tbl1)(tbl2)
    lua_pushstring(L, "index1");// (tbl1)(tbl2)("index1")
    lua_gettable(L, -3);// (tbl1)(tbl2)(tbl1.index1)
    lua_pushstring(L, "index2");// (tbl1)(tbl2)(tbl1.index1)("index2")
    lua_pushvalue(L, -2); // (tbl1)(tbl2)(tbl1.index1)("index2")(tbl1.index1)
    lua_settable(L, -4);// (tbl1)(tbl2)(tbl1.index1)
    lua_pop(L, 1);

    return 0;

Now we are putting together all we learned here. I put the stack content on the comments so you do not get lost.

We put both tables into the stack, push the index of table 1 into the stack, and get the value at tbl1.index1. Note the -3 argument on gettable. I am looking at the first table (third from the top) and not the second. Then we push the index of the second table, copy the tbl1.index1 to the top of the stack and then call lua_settable, on the 4th item from the top.

For housecleaning sake, I have purged the top element, so only the two tables remains at the stack.