lua-users home
lua-l archive

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


It's nice that the __index event can refer to either a table or a function, but quite often I'd like to search a list of tables with the __index event.  It would be nice if there was a built in function to create a metamethod for the __index event to do this.

To illustrate what I mean:

$ lua.exe
Lua 5.0 (alpha)  Copyright (C) 1994-2002 Tecgraf, PUC-Rio
> t = {
>>   one = 1;
>>   two = 2;
>> }
> s = {
>>   extra = 'stuff'
>> }
> setmetatable( t, { __index = search{ s, getglobals(), print } } )
>
> = t.one
1
> = t.extra
stuff
> = t.error
function: ec1128
> = error
function: ec1128
> = t.fish
table: ecad78   fish
nil
>

Here's my implementation of the 'search' function:

#include "lua.h"

static int searcher (lua_State *L)
{
  int i=1;
  do {
    lua_settop(L, 2);
    lua_rawgeti(L, lua_upvalueindex(1), i++);
    if (lua_isnil(L, -1)) return 0;
    if (lua_isfunction(L, -1)) {
      lua_pushvalue(L, 1);
      lua_pushvalue(L, 2);
      lua_call(L, 2, 1);
    } else {
      if (lua_rawequal(L, 1, -1)) return 0;
      lua_pushvalue(L, 2);
      lua_gettable(L, -2);
    }
  } while (lua_isnil(L, -1));
  return 1;
}

static int search (lua_State *L)
{
  lua_settop(L, 1);
  lua_pushcclosure(L, searcher, 1);
  return 1;
}

int std_libopen (lua_State *L)
{
  lua_register(L,"search",search);
  return 0;
}

- Peter