Skip to content

Advanced usage

Since Lua is a powerful tool as I've explained before, it can be used to achieve very nice stuff. Let's dive into the advanced stuff smoothly and start from syntax.

Variadic arguments

The three dots (...) in the parameter list indicate that the function has a variable number of arguments. When this function is called, all its arguments are collected in a single table, which the function accesses as a hidden parameter named arg. Besides those arguments, the arg table has an extra field, n, with the actual number of arguments collected.

1
2
3
4
5
6
7
8
9
printResult = ""

function print (...)
    for i,v in ipairs(arg) do
        printResult = printResult .. tostring(v) .. "\t"
    end

    printResult = printResult .. "\n"
end

Functions in functions

As it got explained before, a script is basically a function. Knowing that, we can do something like this:

1
2
3
4
5
6
7
8
9
function my_function()
    function other_function(a, b)
        return a + b
    end

    return other_function(5, 10)
end

var = my_function() -- 15

Functions as arguments

Any function can work like a variable. That's commonly used to implement callbacks. Take a look at this example:

1
2
3
4
5
6
7
8
9
function some_stuff(cbk)
    cbk(1337)
end

function my_cbk(num)
    print(tostirng(num))
end

some_stuff(my_cbk) -- will print 1337

Moreover, we don't even have to declare a function:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
function some_stuff(cbk)
    cbk(1488)
end

function my_cbk(num)
    print(tostirng(num))
end

some_stuff(
    function(num)
        print(tostirng(num))
    end
) -- will print 1488

Ternary operator

A ternary operator is used to shorten similar code:

1
2
3
4
5
if x < 0 then
    print('x is negative')
else
    print('x is non-negative')
end

In C languages it usually looks like this:

1
auto sign = (x < 0) ? "x is negative" : "x is non-negative";

In Lua, it looks like this:

1
print('x is ' .. (x < 0 and 'negative' or 'non-negative'))

So, in short, it has this construction:

1
EXPRESSION and TRUE or FALSE