In Lua, you can create a table whose keys are themselves tables:
t = {}
t[{1,2}] = 2
I would like to know how to do the analogous thing using the C API. That is, I am writing a C function callable from Lua, which will return a table with table keys. I tried to push a table as a key and then use lua_settable, but it seems to do nothing.
Edit: Relevant code:
lua_createtable(L, 0, n);
for(i = 0; i < n; ++开发者_JAVA百科i){
// push the key table
lua_createtable(L, 2, 0);
for(j = 0; j < 2; ++j){
lua_pushinteger(L, j+1);
lua_pushinteger(L, j);
lua_settable(L, -3);
}
// push the value table
lua_createtable(L, 4, 0);
for(j = 0; j < 4; ++j){
lua_pushinteger(L, j+1);
lua_pushnumber(L, j);
lua_settable(L, -3);
}
lua_settable(L, -3);
}
Edit: I was being dumb; I used lua_objlen(L, -1)
at the end to check on the size of the table, which returns 0 since there are no integer keyed entries. Also, in the Lua code that processed the table, I used ipairs
instead of pairs
. Silly mistake.
Pushing a table as the key and using lua_settable is the right thing to do. Most likely, you just forgot to also push on a value and did effectively t = { {} = nil }, which is of course nothing.
I was checking for the table entries in the wrong way. I have edited the question with the solution.
精彩评论