Warning. This is a question where I’m probably not thinking correctly about the problem and thus far have not found an article or similar question+answer on the web. In fact I know this because this is a fundamental operation.
The problem
I am writing a plugin that takes a table of tables as one of the arguments, processes those sub-tables, and then returns a reference to one of those sub tables. My issue is quite simply, I can’t figure out how to return a reference to a table.
What I know how to do
- Traverse the table of tables and ‘identify’ the sub-table I want to return.
- Create new tables and return those. No good because I need to return a reference to the original (sub-) table.
- Return just about any other kind of data.
Plugin Code Showing Basics of Traversal
Here is an example of a function that iterates over a table of tables (passed as first argument) and returns the id field in the (last) sub-table that has the tag field set to ‘1’.
Yes, this is a totally bogus piece of code, but it shows how I’m traversing the table of tables, and simplifies the ‘sub-table’ selection logic for this example.
I’d rather return a reference to the sub-table, but I’m not sure how.
int getTaggedTableID(lua\_State \*L, int idx ) { lua\_pushnil(L); int curTag = 0; int curID = -1; while (lua\_next(L, idx) != 0) { if (lua\_type(L, VAL) == LUA\_TTABLE) { int top = lua\_gettop(L); lua\_getfield(L, top, "tag"); lua\_getfield(L, top, "id"); int tag = luaL\_checkint(L, -2); int id = luaL\_checkint(L, -1); if(tag == 1) { curID = id; }; lua\_pop(L, 2); //lua\_pop(L, 1); }; lua\_pop(L, 1); } return curID; // Would rather return table reference here } int getTaggedObject(lua\_State \*L) { int curID = -1; curID = getTaggedTableID(L, 1); lua\_pushinteger(L, curID); // Would rather return table reference here return 1; }
Calling this code in lua:
local tbls = { { tag = 0, id = 1 }, { tag = 0, id = 2 }, { tag = 1, id = 3 }, { tag = 0, id = 4 }, { tag = 0, id = 5 }, } local id = objTests.getTaggedObject(tbls) print("getTaggedObject(tbls) returned: ", id )
Prints 3, but I’d rather get a reference to the third table instead.