I know that declare a function, ...
would act as tuple, for example:
01 | local function hey(...) |
02 | local t = { ... } |
03 | local Concat = "" |
04 | for i, v in pairs (t) do |
05 | Concat = Concat..v |
06 | end |
07 |
08 | print (Concat) |
09 | end |
10 |
11 | hey( 1 , 2 , 3 , "hey" ) --output: 123hey |
But the thing I don't know that is we can use ...
as the arguments when call a function too, you can see the example in here(go to line 30-32).
Can someone explain for me, thanks :D
It just means it can hold undetermined amount of parameters
example :
01 | function PrintStuff ( . . . ) -- A function with tuple parameter |
02 | local tupleTable = { . . . } --Putting it in a table variable so we can access it easily |
03 | print (tupleTable [ 1 ] ) -- Print the first parameter |
04 | for _,v in pairs (tupleTable) do |
05 | print (v) -- Print all the object in the table |
06 | end |
07 | end |
08 |
09 | PrintStuff ( "Hello" , 3 , 2 , 'A' ) -- Printing 4 different stuff |
10 | PrintStuff ( "Ok" , "screeeee" ) -- printing 2 stuff |
11 | PrintStuff ( 3.1415926 ) -- printing a single thing |
I know this is already answered, but I'd like to add on to what Azure said.
So in the Java programming language, there's a concept called "overloading", it means that you can have 2 functions with the same name but 2 different sets of arguments:
1 | function a(arg 1 ) |
2 | print (arg 1 ) |
3 | end |
4 |
5 | function b(arg 1 ,arg 2 ) |
6 | return arg 1 +arg 2 |
7 | end |
Unfortunately, this will not work in lua, which is where the ...
argument comes in. You can do the same thing as above, just structured differently:
1 | function a(...) |
2 | local args = { ... } |
3 | if #args = = 1 then |
4 | print (args [ 1 ] ) |
5 | elseif #args = = 2 then |
6 | return args [ 1 ] +args [ 2 ] |
7 | end |
8 | end |
I just checked for the number of arguments in the table because I knew the first function took 1 argument and the second took 2, but you can also check the type and value of the arguments to set them apart allowing you to have more freedom in adding as much functionality as you want to the function a().