What is this and what is it used for?

-- Hello!, Just a Question,

local function Ex(...) -- what do these three dots do? What are you used for?

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

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

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.

1 Like

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.


function print(args: {any}?): ()
    -- ...

print({1, 2, 3, 4, 5})


function print(...: any): ()
    -- ...

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…


function print(a: any, ...: any): ()
    -- ...

print() -- You'll get a type error for not passing in 'a'.

That’s Good to know, thanks :slight_smile:

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