21. Functions — Homework solutions
The .lua solution files are in
exercises/21/homework/solutions/.
Problem 1 — Greet
Problem. A function greet(name) that
prints a greeting, called three times.
How to think about it. One parameter, one
print line; the caller passes a string each call.
Worked solution.
local function greet(name)
print("Hello, " .. name .. "!")
end
greet("Keiko")
greet("Roblox")
greet("World")Common mistakes.
- Forgetting
local. Without it,greetbecomes a global. It works, but the habit is wrong. - Misplacing
end. Eachfunctionneeds a matchingend; indent the body to keep it visible.
Problem 2 — is_even
Problem. Return true or
false from n % 2 == 0. No printing inside the
function.
How to think about it. n % 2 == 0 is
already a boolean. return it directly; let the caller print
it.
Worked solution.
local function is_even(n)
return n % 2 == 0
end
print(is_even(4)) -- true
print(is_even(7)) -- false
print(is_even(0)) -- true
print(is_even(-2)) -- trueThat one line is the whole body: Lua evaluates n % 2,
then ... == 0, and returns the boolean.
Common mistakes.
Writing the function as:
if n % 2 == 0 then return true else return false endFour lines for what the one above does.
n % 2 == 0is already a boolean.
Problem 3 — Clamp
Problem. clamp(x, lo, hi) returns
x bounded by lo and hi.
How to think about it. Two guard checks at the top
handle the out-of-range cases; otherwise return x
unchanged.
Worked solution.
local function clamp(x, lo, hi)
if x < lo then
return lo
end
if x > hi then
return hi
end
return x
end
print(clamp(5, 0, 10)) -- 5
print(clamp(-3, 0, 10)) -- 0
print(clamp(99, 0, 10)) -- 10The two if blocks are independent because each returns:
the first to fire exits the function. Otherwise return x
runs.
Common mistakes.
- Expecting
clamp(99, 0, 10)to be99. Bounded by forces the output inside the range, returning10.
Challenge — Swap
Problem. A function that returns two values swapped, plus a multi-assignment call.
How to think about it. The body is one line:
return b, a. The caller writes
x, y = swap(x, y) to receive both at once.
Worked solution.
local function swap(a, b)
return b, a
end
local x = 1
local y = 2
print("Before: x=" .. x .. " y=" .. y)
x, y = swap(x, y)
print("After: x=" .. x .. " y=" .. y)Output:
Before: x=1 y=2
After: x=2 y=1
Same a, b = b, a trick from chapter 11, wrapped in a
function. It adds no power, but it gives the operation a name
that makes calling code clearer.
Common mistakes.
- Writing
x, y = swap(x, y), 0or some other tail. A multi-return call mid-list is clipped to one value: only the first return reachesx,0goes toy, the second return is lost. To use both, the call must be the last expression in the assignment.
Done?
The next two chapters cover tables, the structure behind everything from lists to Roblox object trees. Then modules for splitting code across files, and the Part 5 mini-project: a text adventure.