Lua Functions

Learn how to define functions, return values, assign functions to variables, and use common library functions.

Functions group reusable operations. Functions such as print() and io.read() are already part of the standard library.

Defining Functions

function name(arguments)
  statements
end
function sum(x, y)
  return x + y
end

print(sum(10, 20))

Arguments are passed as values. Reassigning a parameter does not reassign the caller’s variable.

Returning Values

Lua functions can return multiple values.

function values()
  return 10, 20
end

hoge, piyo = values()
print(hoge, piyo)

Extra return values are discarded. Missing values are assigned nil. A function without a return statement returns no values.

Functions as Values

Functions can be assigned to variables.

function sum(x, y) return x + y end
function mul(x, y) return x * y end

operation = sum
print(operation(10, 20))
operation = mul
print(operation(10, 20))

Functions can also be defined inside functions and returned as closures.

function createCounter(value)
  return function(amount)
    value = value + amount
    return value
  end
end

counter = createCounter(10)
print(counter(5))

Common Library Functions

assert() raises an error when its first argument is false.

assert(value, "value must be true")

dofile() executes another Lua file.

dofile("call.lua")

type() returns a value’s type. tonumber() converts a value to a number when possible, and tostring() converts a value to a string.

print(type(10))
print(tonumber("25"))
print(tostring(25))