Check Args

lua-users home
wiki

This is a C variadic[1] function designed for somewhat strict typing of arguments to Lua CFunctions. This code is designed for Lua 5.1 and uses the Auxiliary Library.

int luac_checkargs(lua_State *L, int count, ...)
{
  va_list ap;
  int i, t, u;
  va_start(ap, count);
  for (i = 1; i <= count; i++)
  {
    t = va_arg(ap, int);
    if (t<=LUA_TNIL) continue;
    u = lua_type(L, i);
    if (t!=u)
    {
      va_end(ap);
      return luaL_typerror(L, i, lua_typename(L, t));
    }
  }
  va_end(ap);
  if (lua_gettop(L)>count)
    return luaL_argerror (L, count+1, "too many arguments");
  return 0;
}

An example usage of this function would be as such:

static int luac_testcheckargs(lua_State *L)
{
  luac_checkargs(L, 3, LUA_TNUMBER, LUA_TNIL, LUA_TBOOLEAN);
  return 0;
}

It would be useful for overloaded functions to be able to specifically test a single argument against several types. LUA_TNIL and LUA_TNONE are used as an escape, so that this function doesn't check the type of that argument.

comments appreciated.

--WilliamBubel


RecentChanges · preferences
edit · history
Last edited August 31, 2007 12:29 am GMT (diff)