Functions as values
Functions can be stored in variables, passed to other functions and returned from them.
In this page:
Functions as values
Functions are first-class values in Lua, which means you can put them in tables, pass them as arguments and create them anonymously. A function that takes another function as an argument is a higher-order function, such as a custom map or filter. Anonymous functions are written function(...) ... end without a name.
Note:
The syntax function f() end is just sugar for f = function() end.
Example: Functions as values
local function map(t, f)
local out = {}
for i, v in ipairs(t) do out[i] = f(v) end
return out
end
local squares = map({1, 2, 3}, function(x) return x * x end)
print(table.concat(squares, ","))
local ops = {
add = function(a, b) return a + b end,
mul = function(a, b) return a * b end,
}
print(ops.add(2, 3), ops.mul(2, 3))
-- Output:
-- 1,4,9
-- 5 6
Login to try C/C++/Java/PHP code in the editor
Common Mistakes
- Calling the function when you meant to pass it
- Forgetting that functions stored in a table need a key to be found
- Expecting anonymous functions to have a name in error messages
Chapter Summary
- Functions are values
- They can be passed and returned
- Anonymous functions have no name
- Higher-order functions take functions
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: