Skip to content

Commit

Permalink
backport __pairs metamethod to our tweaked version of Lua (#1615)
Browse files Browse the repository at this point in the history
* check for user-defined __pairs in luaB_pairs, defaults to luaB_next

* go back to passing in luaB_next as an upvalue as "light C functions" are not supported

* add explainer documentation comment
  • Loading branch information
ChrisFloofyKitsune authored Sep 8, 2024
1 parent cf724c2 commit 306b6df
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions rts/lib/lua/src/lbaselib.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -235,11 +235,23 @@ static int luaB_next (lua_State *L) {
}


/***
* Meta <code>__pairs</code> backported from Lua 5.2,
* originally <code>lua_pushvalue(L, lua_upvalueindex(1)); </code> was <code>lua_pushcfunction(L, luaB_next);</code>
* <br>
* but that requires "light C function" support,
* which makes lua_pushcfunction not allocate extra memory for the GC to clean up.
*/
static int luaB_pairs (lua_State *L) {
luaL_checktype(L, 1, LUA_TTABLE);
lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
lua_pushvalue(L, 1); /* state, */
lua_pushnil(L); /* and initial value */
luaL_checkany(L, 1);
if (luaL_getmetafield(L, 1, "__pairs") == LUA_TNIL) { /* no metamethod? */
lua_pushvalue(L, lua_upvalueindex(1)); /* return generator, */
lua_pushvalue(L, 1); /* state, */
lua_pushnil(L); /* and initial value */
} else {
lua_pushvalue(L, 1); /* argument 'self' to metamethod */
lua_call(L, 1, 3); /* get 3 values from metamethod */
}
return 3;
}

Expand Down

0 comments on commit 306b6df

Please sign in to comment.