Variadic functions

Learn what variadic arguments and functions are

by EXpodo1234ALT

Author Avatar

Introduction

If you having a understanding of what arguments, parameters and functions

are (in which you should probably know before taking this tutorial), you might not know what variadic arguments are or heard of them, but dont know what they are.

Variadic functions can take in pretty much any amount of arguments unlike

normal arguments which you'd need to define a parameter. There are

in fact multiple built in methods from the library that are variadic functions such as print(), if you

didnt know can print multiple strings without calling it multiple times.

Structure

A variadic function can be defined by 3 dots "..." and can only

be placed as the last parameter or the only parameter in the function.

Usually you should put the arguments it stores inside a table ex

"local table = {...}". Then to access those parameters you could either

iterate through the table or just index a specific element.

local function myHobbies(prefix, ...) -- the last parameter
    local hobbies = {...}

    print(prefix..table.concat(hobbies, ", "))

    --then if you wanted to iterate through it...

    for i,v in pairs(hobbies) do
        print(i,v)
    end

end

myHobbies("my hobbies are: ", "sleeping", "drinking", "doing nothing")

That should print "my hobbies are: sleeping, drinking, doing nothing" and we

didnt even need to create a parameter for each of those hobbies!. Also

if you're wondering what the "table.concat()" method is, I might just

create a simple explantion. table.concat pretty much just concatenates every

element in a table in one string and a separator string can be used

to separate each element one from each other. Now that we have a basic

understanding of what a variadic function is, we might just create an algorithm or system

that kind've replicates how print() would work.

local function printStuff(...)
    local strs = {...}

    print(table.concat(strs, " "))
end

printStuff("aa", "lol") -- "aa lol"

Uses

You might be wondering "what can I use this for?", in which it could be

used for to create an algorithm to challenge yourself, creating your own

custom classes with Object Oriented Programming (OOP). Maybe you could

create a function that takes in numbers and gets the sum out of all of them.

local function getSum(a, b, ...)
        local numbers = {a, b, ...}
        local sum = 0 

        for _,num in pairs(numbers) do
            if type(num) == "number" then -- check if its a number
                sum = sum + num
            end
        end

        return sum -- return the sum
    end
end

print(getSum(10,12,234,12)) -- prints "268"
print(getSum(19,100,nil,3)) -- prints "122"

View in-game to comment, award, and more!