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})
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?
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.