-- Hello!, Just a Question,
local function Ex(...) -- what do these three dots do? What are you used for?
end
It’s for variadic functions (you can search online for this, the Roblox documentation also refers to them as exactly this).
The print
global function is an example of a variadic function, it takes any number of arguments and handles them accordingly.
You can handle and iterate through the values of a variadic parameter using table.pack
.
local args = table.pack(...) -- { [number]: any, n: number }
local function printVariadic(...: any): ()
if ... == nil then print("no args were passed"); return end -- not ... also works.
local args = table.pack(...)
-- This numerical loop serves as an example of using n from table.pack,
-- you'd probably more likely use a generic loop.
for i = 1, args.n do print(args[i]) end
end
printVariadic("Hello,", "World!")
You can also have named arguments at the same time.
local function printNamedAndVariadic(one: string, two: number, ...: any): ()
if ... == nil then print("no variadic args were passed") end
print(one, two)
local args = table.pack(...)
for i = 1, args.n do print(args[i]) end
end
local one, two = "One", 2
printNamedAndVariadic(one, two, "Hello,", "World!")
Both of these examples will loop through ...
and print each argument (excluding named arguments) passed to it—one by one.
Interesting, I usually find scripts that have this, but never use it, is that normal?
You usually only use it if you need it, which is typically when you’re anticipating an unknown number of arguments. Think of it like making the last argument an array table, but it doesn’t need to be passed as a table (without {}
), or even at all.
So…
function print(args: {any}?): ()
-- ...
end
print({1, 2, 3, 4, 5})
Becomes…
function print(...: any): ()
-- ...
end
print(1, 2, 3, 4, 5)
If you do want to enforce the caller passing at least one argument (as far as type-checking goes) you can write it like so…
--!strict
function print(a: any, ...: any): ()
-- ...
end
print() -- You'll get a type error for not passing in 'a'.
That’s Good to know, thanks
This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.