← Back to Lua Course | Chapter 5: Functions | Lesson 4 of 7

Functions as values

Functions can be stored in variables, passed to other functions and returned from them.

In this page:

  1. Functions as values

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

lua
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
Common Mistakes
  1. Calling the function when you meant to pass it
  2. Forgetting that functions stored in a table need a key to be found
  3. 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

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.