🎓 A1Learner
🔍
0 of 47 lessons completed

Lua Function Arguments

Function arguments are values passed into a function when it is called. Inside the function, those values arrive in named parameters, in the same order they were passed.

Two arguments land in order

show takes a label and an amount. The call passes both, and they print in the order given.

local function show(label, amount)
  print(label, amount)
end

show("Apples", 12)

A missing argument prints nil

This call passes only the label. The amount parameter gets nothing, so it prints as nil.

local function show(label, amount)
  print(label, amount)
end

show("Apples")

A default value fills the gap

greet replaces a missing name with "friend" before printing. The first call passes a name, and the second call uses the default.

local function greet(name)
  name = name or "friend"
  print("Hello, " .. name)
end

greet("Maya")
greet()

Example

local function tag(item, price, currency)
  currency = currency or "dollars"
  print(item .. ": " .. price .. " " .. currency)
end

tag("Notebook", 5)
tag("Pen", 2, "euros")

Key points

  • Parameters: the names in parentheses in the definition receive the passed values.
  • Order: the first argument fills the first parameter, and the second argument fills the second.
  • Missing: an argument that is not passed leaves its parameter holding nil.
  • Extra: arguments beyond the parameters are ignored.
  • Default: the pattern name = name or "friend" replaces a missing value with a fallback.

In this example, tag builds one price label from its three parameters. The first call leaves currency out, so the default word dollars is used, while the second call passes euros and keeps it.

Note

nil is what makes the default pattern work, because nil counts as false in a condition.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

A function show(a, b) prints a and b on one line with print(a, b). What does show(7) print?