lua-users home
lua-l archive

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


I've been having problems with lua_gettable in 4.0b, which sometimes
would fail to produce the value I expected, or even complain that the
key was nil when it wasn't.

According to the documentation, a call to lua_gettable(L, t) expects
to find the table at position t on the stack, and the key on the top of
the stack. If my understanding is correct, it indeed behaves like this if
the table has its own tag method, but in the ordinary case it instead
requires the key to be just above the table on the stack.

You might expect such a difference to make everything go wrong straight
away, but I guess it's very common to have the key on top of the stack
and the table just below it, which works so you don't notice the bug.

Here's a suggested patch to lua4/src/lvm.c, not extensively tested.
Many apologies if I'm barking up the wrong tree, or if this is already
well-known.

Richard/


==== lua4/src/lvm.c ====
@@ -125,7 +125,7 @@
       ((tg = hvalue(t)->htag) == TAG_TABLE ||  /* with default tag? */
         ttype(luaT_getim(L, tg, IM_GETTABLE)) == TAG_NIL)) { /* or no TM? */
     /* do a primitive get */
-    const TObject *h = luaH_get(L, hvalue(t), t+1);
+    const TObject *h = luaH_get(L, hvalue(t), L->top-1);
     /* result is no nil or there is no `index' tag method? */
     if (ttype(h) != TAG_NIL ||
         (ttype(im=luaT_getim(L, tg, IM_INDEX)) == TAG_NIL))