我不明白为什么会发生这种情况。我正在使用 Moonsharp 在我的应用程序中运行 LUA 脚本,我创建了一个 LUA 函数 IN(v, ...) 并且我想对 ... 参数进行配对。
IN('param1', 'param2', 'param1') -- expected it to return true
function IN(v, ...)
local args = ...
local res = true
for i, v in pairs(args) do
if valueIn == v then
res = true
break
end
end
return res
end
Run Code Online (Sandbox Code Playgroud)
如果它被调用,我会收到以下异常:
“MoonSharp.Interpreter.ScriptRuntimeException” 'next' 的错误参数 #1(需要表,得到字符串)
所以我决定检查我的 ... 变量中是否有一个字符串而不是一个表。
function args(v, ...)
return ...
end
Run Code Online (Sandbox Code Playgroud)
C# 中的返回值是一个包含 'param2' 和 'param1' 的 2 个值的元组,所以它应该与对或 ipairs 一起使用,不是吗?
提前致谢。
在您的示例中使用此定义:
function test(...)
local arg = ...
end
Run Code Online (Sandbox Code Playgroud)
并打电话
test(1,2,3)
Run Code Online (Sandbox Code Playgroud)
会导致
local arg = 1, 2, 3
Run Code Online (Sandbox Code Playgroud)
这当然只分配 1 给 arg。其余省略。
但是当表构造函数...作为输入时,你可以写
local arg = {...}或者然后愉快地迭代你的新表 arg。
...不是 lua 刚刚告诉你的表。因此你不能迭代...
或者本地arg = table.pack(...)也可以工作。
可变参数系统已在 Lua 5.1 中更改,以防您好奇 https://www.lua.org/manual/5.1/manual.html#7.1
vararg 系统从带有带有额外参数的表的伪参数 arg 更改为 vararg 表达式。(参见 luaconf.h 中的编译时选项 LUA_COMPAT_VARARG。)
之前你可以做类似的事情
function test(...)
for k,v in pairs(arg) do
print("I'm a generic for loop yeah!!!")
end
end
Run Code Online (Sandbox Code Playgroud)
所以local arg = {...}没有必要。
| 归档时间: |
|
| 查看次数: |
768 次 |
| 最近记录: |