Practice

Lua exercises

Make a change, predict what it will do, and compare the result.

  1. 1

    Lua Basics

    Store a local value and print it.

    Adapt the lesson example. Change one value or element, predict the result, and explain why it changes.

    Show starting example
    Lua
    local name = "Ada"
    print("Hello, " .. name)
  2. 2

    Lua Functions

    Write a local function that loops over a table and returns a result.

    Predict average({1, 2}) without math.floor on Lua 5.4.

    Reveal answer and reasoning

    It returns 1.5, because 3 / 2 uses floating-point division.

    Show starting example
    Lua
    local function average(values)
      local total = 0
      for _, v in ipairs(values) do
        total = total + v
      end
      return total / #values
    end
    
    print(math.floor(average({82, 91, 76, 95})))
  3. 3

    Lua Loops

    Count with a numeric for and repeat with while.

    What is printed for n if it starts at 6?

    Reveal answer and reasoning

    6 → 4 → 2; at 2 the condition is false, so it prints 2.

    Show starting example
    Lua
    for i = 1, 3 do
      print(i)
    end
    
    local n = 5
    while n > 2 do
      n = n - 2
    end
    print(n)
  4. 4

    Lua Tables

    Use one table type as both an array and a record.

    What does scores[#scores] return after the insert?

    Reveal answer and reasoning

    The last element, 95.

    Show starting example
    Lua
    local scores = {82, 91, 76}
    table.insert(scores, 95)
    print(#scores .. " " .. scores[1])
    local person = {name = "Ada", age = 36}
    person.age = person.age + 1
    print(person.name .. " " .. person.age)