Iterate lua table in c using custom pair function

I would like to use a simple example of an ordered table that I found on the lua-wiki site. Here is the link .

In Lua, iterates with this:

for i,v in t:opairs() do print( i,v ) end 

Instead of iterating in lua, I want to pass t to the C method and iterate over the table there. In the C API, I found only lua_next for the source pairs iterator. How can I repeat this lua code in C?

+6
source share
1 answer

What you can do is write a custom next C function that mimics lua_next but works on this ordered table and does not have an opairs method.

 int luaL_orderednext(luaState *L) { luaL_checkany(L, -1); // previous key luaL_checktype(L, -2, LUA_TTABLE); // self luaL_checktype(L, -3, LUA_TFUNCTION); // iterator lua_pop(L, 1); // pop the key since // opair doesn't use it // iter(self) lua_pushvalue(L, -2); lua_pushvalue(L, -2); lua_call(L, 1, 2); if(lua_isnil(L, -2)) { lua_pop(L, 2); return 0; } return 2; } 

Then you can use it in C, similar to lua_next :

 int orderedtraverse(luaState *L) { lua_settop(L, 1); luaL_checktype(L, 1, LUA_TTABLE); // t:opairs() lua_getfield(L, 1, "opairs"); lua_pushvalue(L, -2); lua_call(L, 1, 2); // iter, self (t), nil for(lua_pushnil(L); luaL_orderednext(L); lua_pop(L, 1)) { printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); } return 0; } 

Notice I have not tested this, but it should work.

+2
source

Source: https://habr.com/ru/post/952181/


All Articles