typestar

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

  1. local function damage(...) names a function in scope.
  2. bonus = bonus or 0 is the idiomatic default.
  3. Anonymous functions assign to variables and table slots.

Keywords and builtins used here

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.

Type this snippet

Step 1 of 3 in Functions, step 11 of 27 in Language basics.

← Previous Next →

Functions in other languages