lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Eric Raible wrote:
The first return value of pairs(t) is rather a private function that
invokes that same code (luaB_next) that 'next' invokes.  But it does
_not_ return 'next' per se.

So either the documentation should be fixed, or the following patch
could be applied which makes the reference manual true.  This patch
both the advantage and the disadvantage that if the value of 'next'
is changed, then pairs(t) will see that change.

Your patch will break if "next" is not available in the global table or is reassigned to something else for some reason.

The following should work (untested!):
--- lbaselib.c.orig     2006-10-09 12:29:55.000000000 -0700
+++ lbaselib.c  2007-02-07 16:13:09.000000000 -0700
@@ -621,11 +621,13 @@
   luaL_register(L, "_G", base_funcs);
   lua_pushliteral(L, LUA_VERSION);
   lua_setglobal(L, "_VERSION");  /* set global _VERSION */
   /* `ipairs' and `pairs' need auxliliary functions as upvalues */
   auxopen(L, "ipairs", luaB_ipairs, ipairsaux);
-  auxopen(L, "pairs", luaB_pairs, luaB_next);
+  lua_getfield(L, -1, "next");
+  lua_pushcclosure(L, luaB_pairs, 1);
+  lua_setfield(L, -2, "pairs");
   /* `newproxy' needs a weaktable as upvalue */
   lua_createtable(L, 0, 1);  /* new table `w' */
   lua_pushvalue(L, -1);  /* `w' will be its own metatable */
   lua_setmetatable(L, -2);
   lua_pushliteral(L, "kv");

With this change, the pairs upvalue is same function as _G.next instead of a new one which refers to the same C function.

					-Mark