c - 如何在 lua 中创建接受多个参数的 C 函数?

标签 c lua

如何知道从 lua 传递给 C 函数的参数数量?

下面的方法可行吗?

int test(lua_State *l) {
  int result = 0;
  int n=1;
  while(!lua_isnil(l,n)) {
    result = result + lua_tointeger(l, n);
    ++n
  }

  lua_pushnumber(l, result);
  return 1;
}

注意:这本质上是 question deleted 的复活。由它的主人,我认为值得保留。

最佳答案

所有参数都被推送到 lua 堆栈上, 因此,您可以通过找出堆栈的初始大小来获取元素的数量。 执行此操作的调用是 lua_gettop(L)

因此您的代码大致如下所示:

int test(lua_State *l)
{
  int result = 0;
  int nargs = lua_gettop(l);
  for(int i=1; i<=nargs; ++i)
  {
    result += lua_tointeger(l, i);;
  }

  lua_pushnumber(l, result);
  return 1;
}

最初编写的代码的问题是它无法正确处理空参数。例如 test(1,nil,3) 将返回 1,而不是 4。

关于c - 如何在 lua 中创建接受多个参数的 C 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14639194/

相关文章:

c - Gotoxy() 在 C 中而不是 C++ 中 undefined reference conio.h

无法解析符号 '__aeabi_d2iz'

c - 警告 : pointer/integer type mismatch in conditional expression

java - 如何从 Java 调用 Lua 脚本

function - 只需写入函数名称(不带括号)即可调用 Lua 函数

lua - 如何将 'unpack'表转换为函数参数

c - double-stringize 技巧究竟是如何工作的?

c - 当我们无法更改指针的包含时,为什么要使用 const char *prt1

lua - 为什么redis无法在lua脚本中执行非确定性命令

xcode - Xcode7.2.1如何支持lua语法高亮?