lua-users home
lua-l archive

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


But it involves table creation anyway. Is there a solution without
table creation?

Well, you can always write a C function.

/* This function should be called this way:
   local value = findany(A, B, C, k) */
int ll_findany(lua_State *L)
{
    lua_settop(L, 4);
    int i;
    for (i = 1; i < 4; i++)
    {
        lua_pushvalue(L, 4); /* Pushes the key */
        lua_gettable(L, i);
        if (lua_isnil(L, -1))
            lua_pop(L);
        else
            return 1;
    }
    /* You could also raise an error here. */
    return 0;
}

You could put the tables as upvalues, too:

int ll_findany2(lua_State *L)
{
    int i;
    for (i = 1; i < 4; i++)
    {
        lua_pushvalue(1);
        lua_gettable(L, lua_upvalueindex(i));
        if (lua_isnil(L, -1))
            lua_pop(L);
        else
            return 1;
    }
    /* Again, you could raise an error here */
    return 0;
}

But this function must be registered this way:

/* Push the tables to the stack */
lua_newtable(L); /* A */
lua_newtable(L); /* B */
lua_newtable(L); /* C */

/* And push the "closured" function :) */
lua_pushcclosure(L, ll_findany2, 3);

Now you can just write:

local result = findany2(k)

(No need to mention that I haven't tested the code, right?)

--rb