What's the difference between ... and an argument variable?

  1. What do you want to achieve? Keep it simple and clear!

I want to find out the different between

Method 1:

local function new(...)
    local args = table.pack(...)
    print(args[1])
end

new(1,2,3)

and

Method 2:

local function new(args)
    print(args[1])
end

new({1,2,3})
  1. What is the issue? Include screenshots / videos if possible!

I’m not sure which way of writing functions with many arguments is better or if there’s no difference. I find method 2 easier to use, since the table is already set up when the function is called and you don’t have to use table.pack. However, because method 1’s “…” is an intentional feature, does that mean method 2 is worse?

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

I looked on the Developer Hub, but I couldn’t find anything that would help me.

It really depends on your use case when calling the functions. Variadic functions are nice when you don’t know in advance how many arguments are going to be passed. The caller is free to pass as many arguments as they’d like (up to some internal limit). Unfortunately, I can’t really think of a practical example off the top of my head.

I guess one advantage of using local args = table.pack(...) is you’ll know exactly how many arguments are passed which can be read from args.n . But even then, using the second method, you could figure out how many arguments were passed by just looping through all the keys. Although that’s more work.

I’d say neither is inherently worse or better. It just depends on what you’re trying to accomplish.

The print function is a great example

1 Like

Oh duh :man_facepalming: How did I not think of that function :sweat_smile:

Well, you’re essentially doing the same thing, but now you have to remember to put your entire input in a table, every time you call this function.

But using a table can also be preferable: you can name keys for more clarity.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.