lua-users home
lua-l archive

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


Hi,
lua_next() does not handle numerical indices.  Is it supposed to ?  
next(t, [i]) does.  lua_next() stops with the following error:

error: invalid key for 'next'

Here's the C code to show the bug:

#include <stdio.h>
#ifdef  __cplusplus
  extern "C" {
    #include "lua.h"
    #include "lualib.h"
  }
#endif

// A function to be called from Lua
static int LuaCallMe(lua_State* ls)
{
  // expect a table as only argument on the stack.
  lua_pushnil(ls);  /* first key */
  while (lua_next(ls, 1) != 0) {
    /* `key' is at index -2 and `value' at index -1 */
    printf("%s - %s - %s - %s\n", 
            lua_tostring(ls, -2), lua_type(ls, -2), 
            lua_tostring(ls, -1), lua_type(ls, -1));
    lua_pop(ls, 1);  /* removes `value'; keeps `index' for next 
iteration */
  }
  return 0;
}

int main (int argc, char *argv[])
{
  if ((argc < 2) || argv[1][0] == 0) {
    printf("Usage : Test4beta <luafile>\n");
    return 1;
  }

  // Create local state with default 1024 stack positions
  lua_State* ls = lua_open(0);  

  // Open libraries
  lua_baselibopen(ls);
  lua_strlibopen(ls);
  lua_mathlibopen(ls);
  lua_iolibopen(ls);

  // Register the C function LuaCallMe()
  lua_pushcfunction(ls, LuaCallMe);
  lua_setglobal(ls, "LuaCallMe");   // function now registered.

    // now execute the Lua code
  if (lua_dofile(ls, argv[1])) {
    printf("Error executing lua_dofile : %s\n", argv[1]);
    return 1;
  } 
  else {
    return 0;
  }
}


Here's the Lua code:

t1 = {a=1, b=2, c=3, d=4, e=5}
t2 = {'a', 'b', 'c', 'd', 'e', 'f'}

LuaCallMe(t1) -- OK
LuaCallMe(t2) -- Error

Here's the output:
a - string - 1 - number
c - string - 3 - number
b - string - 2 - number
e - string - 5 - number
d - string - 4 - number
1 - number - a - string
error: invalid key for 'next

Other info:
VCPP 6.0 on Win98.
I traced it for a while and coulnd't figure out why the ttype of the 
numerical key had a TAG_STRING (2) instead of TAG_NUMBER (1), since 
the output shows that the offending key is a number.  Hope someone 
can look into this.

Regards,
Philip Yi