A function that computes a result and hands it to you with return — so calls become values.
Functions that only print are fine, but the real power is when a function computes something and hands it back. That hand-back is return.
function double(value)
return value * 2
end
local doubledScore = double(10)
print(doubledScore) --> 20
return sends the result out of the function, and the call site becomes that result. So double(10) becomes 20, and that's what lands in doubledScore.
Read it out loud: "the function takes 10, doubles it, and the place where I called it turns into 20."
function add(a, b)
return a + b
end
print(add(4, 5))
Because a call becomes its result, you can use it anywhere a value fits:
function triple(n)
return n * 3
end
local total = triple(5) + triple(2) --> 15 + 6
print(total) --> 21
The two calls are just numbers by the time + runs. That's the whole trick: return turns function call into value.
local x = double(3) + 1 where double doubles its input. What number does x hold?
The moment a function hits return, it stops — nothing after it on that call runs:
function go()
return "first"
print("never printed")
end
That print is dead code. It's how you build early exits: check a condition, and return early if something's wrong.
function buyIfEnough(coins, price)
if coins < price then
return "not enough"
end
return "bought"
end
A function can also return nothing at all — then its result is nil. That's fine; plenty of functions exist just to do a job.
double(10) by itself does the math and throws it away. Catch it: local x = double(10).print shows you something. return hands a value back to the caller. A function can do one, the other, both, or neither.A player has 30 coins and an item costs 10. Write a function salePrice that returns half the item's price, then print the result of salePrice(10).
Next: making decisions with if.