Skip to content
Tutorials Center
My learning

Topics

Lesson 30 of 32 ยท Practice and Review

Exercises with Solutions

Fifteen graded Lua exercises on strings, tables, closures and metatables, each with a worked solution and a runnable JavaScript stand-in to check your thinking.

You learn a language by writing it, not by reading it. This lesson gives you fifteen graded exercises that cover the core of Lua: string patterns, tables, closures and metatables. They start gentle and finish with small classes built from metamethods. Each one is short enough to solve in a few minutes, and each has a worked solution.

Lua cannot run on this site, so the solutions are real Lua shown read-only. After each level there is a runnable JavaScript stand-in that follows the same algorithm and prints the answers, so you can compare the results with what you worked out. The best way to use the page: read a problem, write your own Lua in a file on your machine (see your first Lua program for how to run it), and only then open the solution.

Three levels

Strings Exercises 1 to 5 use patterns, gsub and gmatch.
Tables and closures Exercises 6 to 10 build helpers and counters.
Metatables Exercises 11 to 15 build small types.

Each level is a little harder than the one before.

1 / 2

The problems

Level 1: strings

  1. Reverse the words. reverseWords("the quick brown fox") returns "fox brown quick the".
  2. Count vowels. countVowels("Programming in Lua") returns the number of vowels (upper or lower case).
  3. Palindrome. isPalindrome("A man, a plan, a canal: Panama") is true. Ignore case, spaces and punctuation.
  4. Title case. titleCase("hello wORLD of lua") returns "Hello World Of Lua".
  5. Word frequency. For "the cat and the hat and the bat", produce "the=3, and=2, bat=1, cat=1, hat=1": most frequent first, ties in alphabetical order.

Level 2: tables and closures

  1. Unique. unique({3, 1, 3, 2, 1}) returns {3, 1, 2} (first occurrences, original order).
  2. Map, filter, reduce. Write the three helpers, then use them to find the sum of the squares of the even numbers from 1 to 10.
  3. Group by length. groupBy({"a", "bb", "cc", "d", "eee"}, string.len) returns a table whose keys are the lengths and whose values are lists of the words.
  4. Counter factory. makeCounter(start, step) returns two functions: one that returns the next value each time and one that resets the counter.
  5. Memoize. memoize(fn) returns a version of a one-argument function that remembers its results. Show that the original is called only once per distinct argument.

Level 3: metatables

  1. Vector. Make a Vec type so that Vec.new(1, 2) + Vec.new(3, 4) gives a vector printed as (4, 6), and two vectors with the same components are equal with ==.
  2. Default values. withDefault(t, 0) returns t so that reading a missing key gives 0 (without storing it).
  3. Read-only table. readOnly(t) returns a table that can be read but raises an error on any attempt to assign.
  4. Stack. Build a Stack class with push, pop, the length operator # and tostring, printing like [1, 2, 3].
  5. Set. Build a Set type where + is union, * is intersection and tostring prints sorted members like {1, 2, 3}.

Solutions: Level 1

1. Reverse the words. gmatch("%S+") walks the words; inserting each at position 1 builds the list backwards.

LUA
local function reverseWords(s)
  local words = {}
  for word in s:gmatch("%S+") do
    table.insert(words, 1, word)
  end
  return table.concat(words, " ")
end

2. Count vowels. gsub returns the number of replacements as its second result, and we throw the string part away.

LUA
local function countVowels(s)
  local _, count = s:gsub("[aeiouAEIOU]", "")
  return count
end

3. Palindrome. Lower-case, delete every character that is not a letter or digit, and compare with the reversed string. In local clean = s:lower():gsub(...) only the first value is kept, because there is one variable on the left.

LUA
local function isPalindrome(s)
  local clean = s:lower():gsub("[^%a%d]", "")
  return clean == clean:reverse()
end

4. Title case. The pattern (%a)(%w*) captures a first letter and the rest of the word, and gsub calls our function for each match. The extra parentheses drop gsub's second return value.

LUA
local function titleCase(s)
  return (s:gsub("(%a)(%w*)", function(first, rest)
    return first:upper() .. rest:lower()
  end))
end

5. Word frequency. Count in a dictionary, collect the words, sort with a comparator that is a consistent total order, and format. The tie-break on the word keeps the output stable because table.sort is not.

LUA
local function wordFrequency(s)
  local counts = {}
  for word in s:lower():gmatch("%a+") do
    counts[word] = (counts[word] or 0) + 1
  end

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

  local parts = {}
  for _, word in ipairs(words) do
    parts[#parts + 1] = word .. "=" .. counts[word]
  end
  return table.concat(parts, ", ")
end

The stand-in below mirrors these five. JavaScript regular expressions replace Lua patterns (\S+ for %S+, [^a-z\d] for [^%a%d]).

JS Stand-in: Level 1 solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions: Level 2

6. Unique. A set records what we have already seen; the output list keeps first occurrences in order.

LUA
local function unique(list)
  local seen, result = {}, {}
  for _, value in ipairs(list) do
    if not seen[value] then
      seen[value] = true
      result[#result + 1] = value
    end
  end
  return result
end

7. Map, filter, reduce. Functions are values, so all three take a function argument.

LUA
local function map(list, fn)
  local out = {}
  for i, value in ipairs(list) do
    out[i] = fn(value)
  end
  return out
end

local function filter(list, predicate)
  local out = {}
  for _, value in ipairs(list) do
    if predicate(value) then
      out[#out + 1] = value
    end
  end
  return out
end

local function reduce(list, fn, initial)
  local acc = initial
  for _, value in ipairs(list) do
    acc = fn(acc, value)
  end
  return acc
end

local numbers = {}
for i = 1, 10 do numbers[i] = i end

local evens = filter(numbers, function(n) return n % 2 == 0 end)
local squares = map(evens, function(n) return n * n end)
print(reduce(squares, function(a, b) return a + b end, 0))

8. Group by length. The key function is called for every value, and a list is created on first use.

LUA
local function groupBy(list, keyFn)
  local groups = {}
  for _, value in ipairs(list) do
    local key = keyFn(value)
    local bucket = groups[key]
    if not bucket then
      bucket = {}
      groups[key] = bucket
    end
    bucket[#bucket + 1] = value
  end
  return groups
end

9. Counter factory. Both returned functions share the same upvalues, current and the arguments.

LUA
local function makeCounter(start, step)
  start = start or 0
  step = step or 1
  local current = start - step

  local function nextValue()
    current = current + step
    return current
  end

  local function reset()
    current = start - step
  end

  return nextValue, reset
end

10. Memoize. A cache table keyed by the argument. Check with cache[arg] ~= nil rather than truthiness, so a cached result of false still counts as cached.

LUA
local function memoize(fn)
  local cache = {}
  return function(arg)
    local value = cache[arg]
    if value == nil then
      value = fn(arg)
      cache[arg] = value
    end
    return value
  end
end

If fn could legitimately return nil, this version would call it again each time; storing a sentinel would fix that. For a quick tool it is fine.

JS Stand-in: Level 2 solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Solutions: Level 3

11. Vector. A class table is the metatable of its instances. __add builds a new vector, __eq compares components, __tostring formats. Note that __eq is only called when both operands are tables.

LUA
local Vec = {}
Vec.__index = Vec

function Vec.new(x, y)
  return setmetatable({ x = x, y = y }, Vec)
end

Vec.__add = function(a, b)
  return Vec.new(a.x + b.x, a.y + b.y)
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

print(Vec.new(1, 2) + Vec.new(3, 4))            --> (4, 6)
print(Vec.new(1, 2) == Vec.new(1, 2))           --> true

12. Default values. A function __index runs only when the key is missing, and it does not store anything, so the table does not grow when you read.

LUA
local function withDefault(t, default)
  return setmetatable(t, {
    __index = function()
      return default
    end,
  })
end

local scores = withDefault({ ana = 3 }, 0)
print(scores.ana, scores.ben)   --> 3   0

13. Read-only table. Return an empty proxy that forwards reads to the real table through __index and refuses writes in __newindex. Because the proxy stays empty, every assignment reaches __newindex, even for existing keys. The level argument 2 makes the error point at the caller's line.

LUA
local function readOnly(t)
  return setmetatable({}, {
    __index = t,
    __newindex = function(_, key)
      error("attempt to modify read-only field '" .. tostring(key) .. "'", 2)
    end,
    __len = function()
      return #t
    end,
  })
end

local days = readOnly({ "mon", "tue", "wed" })
print(days[2], #days)           --> tue   3
print(pcall(function() days[1] = "sun" end))

The __len line matters: without it #days would be 0, because the proxy table itself is empty. The last line prints false followed by an error message that names the field, which is how pcall reports a failure.

14. Stack. Items live in an array field. __len makes #stack work, and __tostring joins the items.

LUA
local Stack = {}
Stack.__index = Stack

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

function Stack:push(value)
  self.items[#self.items + 1] = value
  return self
end

function Stack:pop()
  return table.remove(self.items)   -- removes and returns the last item
end

Stack.__len = function(self)
  return #self.items
end

Stack.__tostring = function(self)
  local parts = {}
  for i, value in ipairs(self.items) do
    parts[i] = tostring(value)
  end
  return "[" .. table.concat(parts, ", ") .. "]"
end

Returning self from push allows chaining: Stack.new():push(1):push(2):push(3). table.remove(t) with no index removes the last element and returns nil for an empty table, so popping an empty stack is harmless.

15. Set. The members are keys of a table, so membership is a single lookup. __add and __mul build new sets, and __tostring collects and sorts the keys for a stable display.

LUA
local Set = {}
Set.__index = Set

function Set.new(list)
  local set = setmetatable({ members = {} }, Set)
  for _, value in ipairs(list or {}) do
    set.members[value] = true
  end
  return set
end

Set.__add = function(a, b)            -- union
  local result = Set.new()
  for value in pairs(a.members) do result.members[value] = true end
  for value in pairs(b.members) do result.members[value] = true end
  return result
end

Set.__mul = function(a, b)            -- intersection
  local result = Set.new()
  for value in pairs(a.members) do
    if b.members[value] then
      result.members[value] = true
    end
  end
  return result
end

Set.__tostring = function(set)
  local list = {}
  for value in pairs(set.members) do
    list[#list + 1] = value
  end
  table.sort(list)
  for i, value in ipairs(list) do
    list[i] = tostring(value)
  end
  return "{" .. table.concat(list, ", ") .. "}"
end

The final stand-in checks all five. JavaScript cannot overload + or * on objects, so the operators become methods named after the metamethods, and Proxy plays the role of the metatable for the default-value and read-only tables.

JS Stand-in: Level 3 solutions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Going further

  • Rewrite exercises 6 to 8 so they also work on tables with holes by using pairs and decide what order you promise.
  • Add __lt and __le to Vec (compare by length) and sort a list of vectors with table.sort.
  • Combine exercises 9 and 13: a counter whose state table is read-only from outside.
  • Time memoize on a recursive Fibonacci function, as in recursion and tail calls.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In local _, count = s:gsub("[aeiou]", ""), what is count?

    gsub returns two values: the resulting string and the number of substitutions. The underscore variable swallows the string.
  2. 2. Why does readOnly return an empty proxy table rather than modifying the original table's metatable?

    __newindex is called only when assigning to a key that does not exist in the table itself. With an empty proxy, no key exists, so every assignment is intercepted.
  3. 3. What happens with memoize if you test the cache with if cache[arg] then ... and the function returns false?

    Only nil and false are falsy in Lua. Testing truthiness treats a cached false as missing, so compare against nil instead.
  4. 4. Why is a tie-break needed in the comparator of the word frequency exercise?

    Equal counts would be ordered arbitrarily. Sorting by the word as a second key makes the result deterministic and the comparator consistent.
  5. 5. Which metamethod makes #stack return the number of items in a Stack object whose items are in a field?

    The length operator calls __len when the operand is a table with that metamethod. Without it, # would measure the raw table, which has only the items field.

Summary

  • gmatch walks matches, gsub replaces them and also returns a count, and extra parentheses drop that second value.
  • Sets (keys with true values) give fast membership; build lists with t[#t + 1] = value.
  • Closures share upvalues, so two returned functions can work on the same private state.
  • Compare with nil instead of truthiness when false is a legal cached value.
  • A function __index supplies defaults without storing them; an empty proxy with __newindex makes a table read-only.
  • __add, __mul, __eq, __len and __tostring turn tables into small types with natural syntax.

Next: Interview Questions