TExcelTAD
Home › Lua › Lua Exercises

Lua Exercises

Time to practise. Each exercise has a starter playground that runs as-is and prints a placeholder, so you can see the expected format. Replace the TODO parts, press ▶ Run and compare with the "Expected" output. The solutions are hidden; try for a few minutes before you open one.

# Exercise Topics
1 FizzBuzz numeric for, %, if/elseif
2 Vowel counter strings, gsub, patterns
3 Word frequency dictionaries, gmatch, sorting
4 Reverse the words split, table.concat
5 Statistics in one pass varargs, multiple returns
6 A Stack class metatables, : methods
7 Vector arithmetic metamethods
8 Memoised Fibonacci closures
9 Countdown generator coroutines
10 Safe division error, pcall

1. FizzBuzz

For the numbers 1 to 15, print Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise. Print everything on one line separated by spaces.

Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

lua · try it yourself
local out = {}
for i = 1, 15 do
  -- TODO: choose "Fizz", "Buzz", "FizzBuzz" or the number
  out[#out + 1] = i
end
print(table.concat(out, " "))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
lua · try it yourself
local out = {}
for i = 1, 15 do
  if i % 15 == 0 then
    out[#out + 1] = "FizzBuzz"
  elseif i % 3 == 0 then
    out[#out + 1] = "Fizz"
  elseif i % 5 == 0 then
    out[#out + 1] = "Buzz"
  else
    out[#out + 1] = i
  end
end
print(table.concat(out, " "))
1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

Test % 15 first: otherwise 15 would match % 3 and print only Fizz.

2. Vowel counter

Write countVowels(text) that returns the number of vowels (a e i o u, either case).

Expected: 6 and 5.

lua · try it yourself
local function countVowels(text)
  -- TODO
  return 0
end

print(countVowels("Programming in Lua"))
print(countVowels("AEIOU xyz"))
0
0
Show solution
lua · try it yourself
local function countVowels(text)
  local _, n = text:gsub("[aeiouAEIOU]", "")
  return n
end

print(countVowels("Programming in Lua"))
print(countVowels("AEIOU xyz"))
6
5

gsub returns the number of replacements as its second value, a neat way to count matches.

3. Word frequency

Count how often each word occurs (ignoring case) and print the six most frequent words, sorted by count (highest first) and then alphabetically, one word<TAB>count per line.

Expected:

text
the	3
moon	2
a	1
is	1
lamp	1
over	1
lua · try it yourself
local text = "The moon rises over the sea. The moon is a lamp."
local counts = {}
-- TODO: fill counts with gmatch, then sort and print
print("no words counted yet")
no words counted yet
Show solution
lua · try it yourself
local text = "The moon rises over the sea. The moon is a lamp."
local counts = {}
for word in text:lower():gmatch("%a+") do
  counts[word] = (counts[word] or 0) + 1
end

local words = {}
for w in pairs(counts) do words[#words + 1] = w end
table.sort(words, function(a, b)
  if counts[a] ~= counts[b] then return counts[a] > counts[b] end
  return a < b
end)

for i = 1, 6 do print(words[i], counts[words[i]]) end
the	3
moon	2
a	1
is	1
lamp	1
over	1

text:lower() makes The and the the same word, and the tie-breaker a < b keeps the order stable for words with equal counts.

4. Reverse the words

Write reverseWords(s) that reverses the order of the words in a sentence, keeping single spaces between them.

Expected: Lua love I and three two one.

lua · try it yourself
local function reverseWords(s)
  -- TODO: split into words, reverse, join
  return s
end

print(reverseWords("I love Lua"))
print(reverseWords("  one   two three "))
I love Lua
  one   two three 
Show solution
lua · try it yourself
local function reverseWords(s)
  local words = {}
  for w in s:gmatch("%S+") do
    table.insert(words, 1, w)    -- insert at the front: reversed order
  end
  return table.concat(words, " ")
end

print(reverseWords("I love Lua"))
print(reverseWords("  one   two three "))
Lua love I
three two one

5. Statistics in one pass

Write stats(...) that takes any number of numbers and returns their count, minimum, maximum and average as four values.

Expected: 5 2 9 5.2.

lua · try it yourself
local function stats(...)
  -- TODO
  return 0, 0, 0, 0
end

print(stats(4, 9, 2, 7, 4))
0	0	0	0
Show solution
lua · try it yourself
local function stats(...)
  local n = select("#", ...)
  local lo, hi, sum = math.huge, -math.huge, 0
  for i = 1, n do
    local v = (select(i, ...))
    lo, hi, sum = math.min(lo, v), math.max(hi, v), sum + v
  end
  return n, lo, hi, sum / n
end

print(stats(4, 9, 2, 7, 4))
5	2	9	5.2

6. A Stack class

Complete the Stack class with push, pop (returns nil when empty), peek and isEmpty.

Expected: c b a, then true.

lua · try it yourself
local Stack = {}
Stack.__index = Stack

function Stack.new()
  return setmetatable({ items = {} }, Stack)
end

-- TODO: Stack:push(v), Stack:pop(), Stack:peek(), Stack:isEmpty()

print("Stack has", type(Stack.push))
Stack has	nil
Show solution
lua · try it yourself
local Stack = {}
Stack.__index = Stack

function Stack.new()
  return setmetatable({ items = {} }, Stack)
end
function Stack:push(v) self.items[#self.items + 1] = v end
function Stack:pop() return table.remove(self.items) end
function Stack:peek() return self.items[#self.items] end
function Stack:isEmpty() return #self.items == 0 end

local s = Stack.new()
s:push("a"); s:push("b"); s:push("c")
print(s:pop(), s:pop(), s:peek())
s:pop()
print(s:isEmpty(), s:pop())
c	b	a
true	nil

7. Vector arithmetic

Give Vec metamethods so that a + b, a * 2, a == b and tostring(a) work.

Expected: (4, 6) (2, 4) true false.

lua · try it yourself
local Vec = {}
Vec.__index = Vec
local function vec(x, y) return setmetatable({ x = x, y = y }, Vec) end

-- TODO: Vec.__add, Vec.__mul (vector * number), Vec.__eq, Vec.__tostring

local a, b = vec(1, 2), vec(3, 4)
print(getmetatable(a) == Vec)
true
Show solution
lua · try it yourself
local Vec = {}
Vec.__index = Vec
local function vec(x, y) return setmetatable({ x = x, y = y }, Vec) end

Vec.__add = function(a, b) return vec(a.x + b.x, a.y + b.y) end
Vec.__mul = function(v, k) return vec(v.x * k, v.y * k) end
Vec.__eq = function(a, b) return a.x == b.x and a.y == b.y end
Vec.__tostring = function(v) return "(" .. v.x .. ", " .. v.y .. ")" end

local a, b = vec(1, 2), vec(3, 4)
print(tostring(a + b), tostring(a * 2), a == vec(1, 2), a == b)
(4, 6)	(2, 4)	true	false

8. Memoised Fibonacci

Write memoize(fn) so that the recursive fib below runs quickly. Count how many times the real computation runs for fib(40).

Expected: 102334155 and 41 computations.

lua · try it yourself
local computations = 0
local function memoize(fn)
  -- TODO: return a function that caches fn's results
  return fn
end

local fib
fib = memoize(function(n)
  computations = computations + 1
  if n < 2 then return n end
  return fib(n - 1) + fib(n - 2)
end)

print(fib(10), computations .. " computations")
55	177 computations
Show solution
lua · try it yourself
local computations = 0
local function memoize(fn)
  local cache = {}
  return function(n)
    local v = cache[n]
    if v == nil then
      v = fn(n)
      cache[n] = v
    end
    return v
  end
end

local fib
fib = memoize(function(n)
  computations = computations + 1
  if n < 2 then return n end
  return fib(n - 1) + fib(n - 2)
end)

print(fib(40), computations .. " computations")
102334155	41 computations

fib is declared before it is assigned so that the inner function calls the memoised version.

9. Countdown generator

Write countdown(n) using coroutine.wrap so that for x in countdown(5) yields 5, 4, 3, 2, 1.

Expected: 5 4 3 2 1 liftoff.

lua · try it yourself
local function countdown(n)
  -- TODO: return coroutine.wrap(function() ... end)
  return function() return nil end
end

for x in countdown(5) do io.write(x, " ") end
print("liftoff")
liftoff
Show solution
lua · try it yourself
local function countdown(n)
  return coroutine.wrap(function()
    for i = n, 1, -1 do coroutine.yield(i) end
  end)
end

for x in countdown(5) do io.write(x, " ") end
print("liftoff")
5 4 3 2 1 liftoff

10. Safe division

Write divide(a, b) that raises an error with the message division by zero (no position, use level 0) when b is 0, and a function tryDivide(a, b) that returns the result or the string error: <message>.

Expected: 2.5 and error: division by zero.

lua · try it yourself
local function divide(a, b)
  -- TODO: raise an error when b == 0
  return a / b
end

local function tryDivide(a, b)
  -- TODO: use pcall
  return divide(a, b)
end

print(tryDivide(5, 2))
print(tryDivide(5, 0))
2.5
inf
Show solution
lua · try it yourself
local function divide(a, b)
  if b == 0 then error("division by zero", 0) end
  return a / b
end

local function tryDivide(a, b)
  local ok, result = pcall(divide, a, b)
  if ok then return result end
  return "error: " .. result
end

print(tryDivide(5, 2))
print(tryDivide(5, 0))
2.5
error: division by zero

Without the check, 5 / 0 is not an error in Lua: float division by zero gives inf.

Test yourself

Which expression counts the matches of a pattern p in s?

  1. #s:match(p)
  2. select(2, s:gsub(p, ""))
  3. s:count(p)
  4. string.len(p)

In exercise 8, why is local fib declared on its own line before fib = memoize(...)?

  1. Style only
  2. So the inner function's recursive calls refer to the memoised fib local
  3. To make fib global
  4. Because memoize requires it