Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Lua, how to pass vararg to another function while also taking a peek at them?

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?

like image 894
Roman Starkov Avatar asked May 02 '10 12:05

Roman Starkov


1 Answers

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
>
like image 182
Doug Currie Avatar answered Oct 05 '22 04:10

Doug Currie