【问题标题】:extending Lua: check number of parameters passed to a function扩展 Lua:检查传递给函数的参数数量
【发布时间】:2015-06-09 13:16:57
【问题描述】:

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

我可以使用带参数的函数(我关注this link)来读取函数参数。

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

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

我想在用户写的时候执行函数

idiv(3, 4)

并在发生时打印错误

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

【问题讨论】:

  • Lua 的惯例是不要抱怨多余的参数。
  • 那么更少的参数呢?
  • 更少的争论是另一回事。如果可以使用合理的默认值,那么就这样做。否则,引发错误。
  • 事实上。我需要该用户指定我需要的确切参数数量。我不想使用默认值,因为用户应该始终知道他在使用什么。

标签: c++ c lua arguments argument-passing


【解决方案1】:

您可以使用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 */
}

【讨论】:

  • 谢谢。这正是我所需要的!
猜你喜欢
  • 1970-01-01
  • 2012-04-16
  • 2022-08-18
  • 1970-01-01
  • 1970-01-01
  • 2013-01-08
  • 2020-11-01
  • 2012-01-25
  • 1970-01-01
相关资源
最近更新 更多