lua-users home
lua-l archive

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


On Sun, Apr 13, 2014 at 1:27 PM, Sean Conner <sean@conman.org> wrote:
>   -spc (From what I see, you remove one line, change three lines, and you
>         have your function)

I believe it would look something like this.  These functions are
based on luaL_testudata() and luaL_checkudata().

testtable() basically returns a boolean, similar to how
luaL_testudata() returns NULL if the check fails.
checktable() errors if the test fails, otherwise it returns the
absindex() ((just because))

I wish they hadn't made typeerror() internal in 5.2 :(  That's the
lua_pushfstring() line in checktable().  I don't like having to
remember the form of type errors.

int testtable(lua_State *L, int tbl, const char *tname)
{
    if (!lua_istable(L, tbl))
        return 0;

    int tmp = 0;

    if (lua_getmetatable(L, tbl))
    {
        luaL_getmetatable(L, tname);

        if (lua_rawequal(L, -1, -2))
            tmp = 1;

        lua_pop(L, 2);
    }

    return tmp;
}

int checktable(lua_State *L, int tbl, const char *tname)
{
    if (testtable(L, tbl, tname))
        return lua_absindex(L, tbl);

    lua_pushfstring(L, "%s expected, got %s", tname, luaL_typename(L, tbl));
}