Những gì bạn có thể làm là viết một hàm tùy chỉnh next
C bắt chước lua_next
nhưng hoạt động trên bảng đã đặt hàng đó thay vì có phương thức opairs
.
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;
}
Sau đó bạn có thể sử dụng nó trong C tương tự như 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;
}
Lưu ý, tôi đã không kiểm tra này, nhưng nó cũng làm việc.