It seems that in Lua, I can either pass vararg on to another function, or take a peek at them through arg
, but not both. Here's an example:
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
Observe that a
only looks at the varargs, b
only passes them on, while c
does both. Here are the results:
>> 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]: ?
What am I doing wrong? Am I not supposed to combine the two? Why not?
The use of arg
is deprecated. Try this:
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
Here's what you get:
> 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
>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With