In Lua, how do I pass vararg to another function and also look at them?

It seems that in Lua, I can either pass vararg to another function, or look at them through arg , but not both. Here is 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 

Note that a only looks at varargs, b only passes them, and 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? Shouldn't I combine these two? Why not?

+4
source share
3 answers

Using arg is deprecated. Try the following:

 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 is 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 > 
+10
source

For the number of arguments you need to choose. To look at them, you can do this:

 local first,second,third = ... 
+3
source

You can use select() to check ... without resorting to the arg table:

 firstarg = select(1, ...) secondarg = select(2, ...) 

etc.

I'm not sure why you have problems combining the two, however, in my experience, mixing them (and different operations with them) was not a problem.

+2
source

Source: https://habr.com/ru/post/1308592/


All Articles