似乎在 Lua 中,我可以将 vararg 传递给另一个函数,或者通过 arg
查看它们,但不能两者兼而有之。这是一个例子:
function a(marker, ...)
print(marker)
print(#arg, arg[1],arg[2])
end
function b(marker, ...)
print(marker)
destination("--2--", ...)
end
function c(marker, ...)
print(marker)
print(#arg, arg[1],arg[2])
destination("--3--", ...)
end
function destination(marker, ...)
print(marker)
print(#arg, arg[1],arg[2])
end
请注意,a
仅查看可变参数,b
仅传递它们,而 c
则两者兼而有之。结果如下:
>> a("--1--", "abc", "def")
--1--
2 abc def
>> b("--1--", "abc", "def")
--1--
--2--
2 abc def
>> c("--1--", "abc", "def")
--1--
test.lua:13: attempt to get length of local 'arg' (a nil value)
stack traceback:
...test.lua:13: in function 'c'
...test.lua:22: in main chunk
[C]: ?
我做错了什么?我不应该把两者结合起来吗?为什么不呢?
最佳答案
不推荐使用arg
。试试这个:
function a(marker, ...)
print(marker)
print(select('#',...), select(1,...), select(2,...))
end
function b(marker, ...)
print(marker)
destination("--2--", ...)
end
function c(marker, ...)
print(marker)
print(select('#',...), select(1,...), select(2,...))
destination("--3--", ...)
end
function destination(marker, ...)
print(marker)
print(select('#',...), select(1,...), select(2,...))
end
这是你得到的:
> a("--1--", "abc", "def")
--1--
2 abc def
> b("--1--", "abc", "def")
--1--
--2--
2 abc def
> c("--1--", "abc", "def")
--1--
2 abc def
--3--
2 abc def
>
关于lua - 在Lua中,如何将可变参数传递给另一个函数,同时查看它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2753479/