扩展Lua:检查传递给函数的参数数量

Jep*_*sen 8 c c++ lua arguments argument-passing

我想创建一个新的Lua函数.

我可以使用带参数的函数(我正在关注此链接)以读取函数参数.

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 */
}
Run Code Online (Sandbox Code Playgroud)

我想知道是否有办法知道传递给函数的参数数量,以便在用户不使用两个参数调用函数时打印消息.

我想在用户写入时执行该功能

idiv(3, 4)
Run Code Online (Sandbox Code Playgroud)

并在打印时出错

idiv(2)
idiv(3,4,5)
and so on...
Run Code Online (Sandbox Code Playgroud)

Tim*_*per 14

您可以使用它lua_gettop()来确定传递给C Lua函数的参数数量:

int lua_gettop (lua_State *L);
返回堆栈中顶部元素的索引.因为索引从1开始,所以此结果等于堆栈中元素的数量(因此0表示空堆栈).

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 */
}
Run Code Online (Sandbox Code Playgroud)