Functions in Lua
Values like any other; or supplies the default arguments.
-- Functions are values; local function names them in scope.
local function damage(sides, bonus)
bonus = bonus or 0 -- the default-argument idiom
return sides + bonus
end
print("Dagger hit: " .. damage(4))
print("Blessed dagger: " .. damage(4, 2))
-- Functions assign to variables and table slots alike.
local shout = function(line)
return line:upper() .. "!"
end
print(shout("the floor is trapped"))
How it works
local function damage(...)names a function in scope.bonus = bonus or 0is the idiomatic default.- Anonymous functions assign to variables and table slots.
Keywords and builtins used here
damageendfunctionlocalprintreturnshoutupper
The run, in numbers
- Lines
- 14
- Characters to type
- 403
- Tokens
- 68
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 58 seconds.
Step 1 of 3 in Functions, step 11 of 27 in Language basics.