In Lua, functions are what are known as “first class citizens.”
What does that mean?
Historically, many of the most popular languages did not support functions could be defined in the scope of statement or loop or another function. There were also limitations to how functions could be referenced and used.
So far we’ve seen and demonstrated this “standard” approach. Functions were defined in the top-most scope of a script and limited their usage to invocation.
But we can do a lot more than just that with first class functions.
Functions can be reassigned, they can be passed around and stored just like any other data, and passed as arguments to other functions. Functions can be returned as a result and even defined inside of other statements.
local currentFunction = nil
local function printSum(num1, num2)
print("Sum:", num1 + num2)
end
local function printProduct(num1, num2)
print("Product:", num1 * num2)
end
currentFunction = printSum
currentFunction(10, 20)
currentFunction = printProduct
currentFunction(10, 20)
--Output: 30
--Output: 200
Here, line 1 declares a variable to act as an alias.
And then on line 11, it is assigned a function and invoked just like any function. Then reassigned to a different function and invoked again under a different function.
Note that in order to reference the function itself, the parenthesis is omitted. Otherwise the function will be invoked instead and the result assigned to that variable.