Search code examples
c++cluaargumentsargument-passing

extending Lua: check number of parameters passed to a function


I want to create a new Lua function.

I can use function with parameters (I'm following this link) in order to read function parameters.

static int idiv(lua_State *L) {
  int n1 = lua_tointeger(L, 1); /* first argument */
  int n2 = lua_tointeger(L, 2); /* second argument */
  int q = n1 / n2; int r = n1 % n2;
  lua_pushinteger(L, q); /* first return value */
  lua_pushinteger(L, r); /* second return value */
  return 2; /* return two values */
}

I'd like to know if there's a way to know the number of parameters passed to a function, in order to print a message if user does not call function with two parameters.

I want to execute the function when user writes

idiv(3, 4)

and print an error when

idiv(2)
idiv(3,4,5)
and so on...

Solution

  • You can use lua_gettop() for determining the number of arguments passed to a C Lua function:

    int lua_gettop (lua_State *L);
    Returns the index of the top element in the stack. Because indices start at 1, this result is equal to the number of elements in the stack (and so 0 means an empty stack).

    static int idiv(lua_State *L) {
      if (lua_gettop(L) != 2) {
        return luaL_error(L, "expecting exactly 2 arguments");
      }
      int n1 = lua_tointeger(L, 1); /* first argument */
      int n2 = lua_tointeger(L, 2); /* second argument */
      int q = n1 / n2; int r = n1 % n2;
      lua_pushinteger(L, q); /* first return value */
      lua_pushinteger(L, r); /* second return value */
      return 2; /* return two values */
    }