Jump to content




how to get unlimited args in a function


  • You cannot reply to this topic
5 replies to this topic

#1 Exerro

  • Members
  • 801 posts

Posted 26 December 2012 - 02:27 PM

Im trying to make a function where you can input as many args as you want and i think its functionname(...) but im not sure how to access the args after that...can someone help?

#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 26 December 2012 - 02:48 PM

function doFunc(func, ...)
  local args = {...}
  for i = 1, #args do
    func(args[i])
  end
end


#3 ChunLing

  • Members
  • 2,027 posts

Posted 26 December 2012 - 06:12 PM

That is valid, and more consistent with how arguments are passed to the program as a whole, but for a function inside of a program, you can just use the table arg without needing to assign it or anything.
function doFunc(func, ...)
   for i = 1, #arg do
    func(arg[i])
  end
end


#4 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 26 December 2012 - 06:34 PM

You can indeed. That method seems to have too much of a flavor of "magic" to it for my tastes, though. I much prefer "wasting" a line on an explicit definition over using a "magic" variable when taking variadic arguments.

#5 KaoS

    Diabolical Coder

  • Members
  • 1,510 posts
  • LocationThat dark shadow under your bed...

Posted 26 December 2012 - 06:57 PM

View PostLyqyd, on 26 December 2012 - 06:34 PM, said:

You can indeed. That method seems to have too much of a flavor of "magic" to it for my tastes, though. I much prefer "wasting" a line on an explicit definition over using a "magic" variable when taking variadic arguments.

I agree... I prefer to make my code slightly more verbose if it means that it is not subject to the whims of the Lua updaters, you never know if stuff like that will change

#6 ChunLing

  • Members
  • 2,027 posts

Posted 26 December 2012 - 11:43 PM

Meh, don't know why they would change that more than they'd change the meaning of any other token. I do take the point that the arg identifier has a bit of an odd place in Lua. For some reason, it's described as a "hidden parameter". I guess because you write the parameter as ... then access it as arg (or by assigning something else to {...}).





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users