Parameters and Returns

Most useful functions take some values in and give a value back. The values a function takes in are its parameters. You list them inside the parentheses of the definition.

function priceTag(item, price)
    print(item .. ": $" .. price)
end

priceTag("coffee", 3.5)
priceTag("sandwich", 7.25)

Output:

coffee: $3.5
sandwich: $7.25

priceTag has two parameters, item and price. The values you pass in a call are called arguments. In the first call, item is "coffee" and price is 3.5. The same body runs each time, but with different values.

Giving a value back with return

priceTag prints its result. Often you want the function to hand the result back to you instead, so you can store it or use it in more math. That is what return does:

function area(width, height)
    return width * height
end

local a = area(4, 5)
print(a)
print(area(2, 3) + 1)

Output:

20
7

A call like area(4, 5) now has a value, 20, just like 4 * 5 does. return also ends the function right away. Any code after it inside the function does not run.

Missing arguments become nil

Lua does not check that a call passes the right number of arguments. Extra arguments are ignored. A missing argument arrives as nil. Forget one, and the error appears inside the function:

function area(width, height)
    return width * height
end

print(area(4))

Output:

/usr/bin/lua5.4: main.lua:2: attempt to perform arithmetic on a nil value (local 'height')

The error points to line 2, inside area, but the real mistake is the call on line 5. When you see an error about nil inside a function, check the calls first.

The same rule gives you optional parameters. Use or from the logical operators lesson to fill in a default value:

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

greet("Ada")
greet()

Output:

Hello, Ada
Hello, friend

In the exercise, complete a function that returns the area of a rectangle.