I'm using Lua's C API to extend Lua. In my module, I want to populate a table using luaL_ref, and remove fields using luaL_unref. I also want to be able to iterate over this table, hopefully using lua_next.
Iterating over the table is a problem because of luaL_unref. In Lua it is common to "delete" table fields by assigning nil (because uninitialized table fields evaluate to nil). The next function is smart enough to skip over nil. I would have expected luaL_unref to assign nil to unreferenced table fields, but it seems to assign an integer. The value of this integer seems to be undocumented.
Consider the following code:
/* tableDump prints a table: */
/* key: value, key: value, ... */
lua_newtable(L);
lua_pushboolean(L, 0);
int ref1 = luaL_ref(L, -2);
lua_pushinteger(L, 7);
int ref2 = luaL_ref(L, -2);
lua_pushstring(L, "test");
int ref3 = luaL_ref(L, -2);
tableDump(L, -1);
luaL_unref(L, -1, ref1);
tableDump(L, -1);
luaL_unref(L, -1, ref3);
tableDump(L, -1);
luaL_unref(L, -1, ref2);
tableDump(L, -1);
printf("done.\n");
Output:
1: false, 2: 7, 3: `test',
3: `test', 2: 7, 0: 1,
3: 1, 2: 7, 0: 3,
3: 1, 2: 3, 0: 2,
done.
What's going on here? How could I work around this? Is there some trick to iterate over references and ignore the unreferenced? Do I have to stop using luaL_ref and luaL_unref?
Edit
First off, thank you for your responses!
Maybe I've asked the wrong question.
Allow me to be a little more specific. I have a client userdata which needs to manage many subscription userdatas. Subscriptions are created by the client's subscribe method. Subscriptions are removed by the client's unsubscribe method. The subscription userdatas are basically an implementation detail, so they are not exposed in the client API. Instead the client API uses subscription references, hence the use of luaL_ref to populate a subscription table.
ref = client:sub(channel, func)
cleint:unsub(ref)
Here's the catch. I would like the client to automatically unsubscribe all remaining subscriptions on __gc (or else the user will get a segfault). So it seems I need to iterate over the subscriptions. Am I really abusing the API here? Is there a better way to do this?
luaL_refandluaL_unrefis not to "populate a table". It is to create a simple reference system for being able to store values by reference and fetch them again later. You should not be iterating over the table; you should be using the returned reference to access table entries.