11

I have created a Lua table in C, but I'm not sure how to push that table onto the top of a stack so I can pass it to a Lua function.

Does anyone know how to do this?

This is my current code:

lua_createtable(state, libraries.size(), 0);
int table_index = lua_gettop(state);
for (int i = 0; i < libraries.size(); i++)
{
    lua_pushstring(state, libraries[i].c_str());
    lua_rawseti(state, table_index, i + 1);
}

lua_settable(state, -3);

[ Push other things ]
[ Call function ]
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tom Leese
  • 19,309
  • 12
  • 45
  • 70

3 Answers3

11

Here's a quick helper function to push strings to the table

void l_pushtablestring(lua_State* L , char* key , char* value) {
    lua_pushstring(L, key);
    lua_pushstring(L, value);
    lua_settable(L, -3);
} 

Here I use the helper function to create the table and pass it to a function

// create a lua function
luaL_loadstring(L, "function fullName(t) print(t.fname,t.lname) end");
lua_pcall(L, 0, 0, 0);

// push the function to the stack
lua_getglobal(L, "fullName");

// create a table in c (it will be at the top of the stack)
lua_newtable(L);
l_pushtablestring(L, "fname", "john");
l_pushtablestring(L, "lname", "stewart");

// call the function with one argument
lua_pcall(L, 1, 0, 0);
Nick Van Brunt
  • 15,244
  • 11
  • 66
  • 92
  • How would I push two different tables to the same function? – Tom Leese Oct 21 '10 at 14:42
  • The second argument in lua_pcall is the number of arguments being passed to the function so you would push both tables onto the stack and then change the pcall to lua_pcall(L, 2, 0, 0); – Nick Van Brunt Oct 21 '10 at 16:01
2

The table is already in the stack, where lua_newtable left it, isn't it?

lhf
  • 70,581
  • 9
  • 108
  • 149
  • If it is, I must be making the table incorrectly. Could you tell me how I should be creating the table? All it needs to contain is some strings. – Tom Leese Oct 21 '10 at 13:46
  • 1
    See http://www.lua.org/source/5.1/lua.c.html#getargs for instance. Or show us your code. – lhf Oct 21 '10 at 13:49
1

I made a small snippet open source that solves pushing simple Lua dictionary tables from C to Lua.

You can check it out here, should work well.

Goles
  • 11,599
  • 22
  • 79
  • 140