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

Posted by romkyns on Stack Overflow See other posts from Stack Overflow or by romkyns
Published on 2010-05-02T12:49:36Z Indexed on 2010/05/02 12:57 UTC
Read the original article Hit count: 192

Filed under:
|

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?

© Stack Overflow or respective owner

Related posts about lua

Related posts about varargs