8

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...
Jepessen
  • 11,744
  • 14
  • 82
  • 149
  • 3
    The usual practice in Lua is not to complain about extra arguments. – lhf Apr 04 '15 at 18:21
  • And what about fewer arguments? – Jepessen Apr 04 '15 at 19:23
  • 1
    Fewer arguments is another story. If sensible defaults can be used, then do that. Otherwise, raise an error. – lhf Apr 04 '15 at 22:55
  • In fact. I need that user specifies the exact number of arguments that I need. I don't want to use default values because the user should be always aware of what he's using. – Jepessen Apr 05 '15 at 06:52

1 Answers1

17

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 */
}