Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 32 ยท Projects

Project: A To-Do List Manager

Build a command-driven to-do list in Lua with tables, closures, string patterns and string.format, then run a JavaScript stand-in of the same design in your browser.

A to-do list is a small program with a big lesson inside it: almost every real application is a collection of records plus a few commands that change them. In this project you build that shape in Lua. You will store tasks in a table, hide the data behind a closure so only your own functions can change it, turn text commands such as add Buy milk into actions, and print a tidy report with string.format.

The real Lua program is shown read-only, because this site cannot run Lua. Each step has a JavaScript stand-in that follows the same structure line by line, so you can run it, change it and watch the output. Where JavaScript differs (arrays start at 0, class instead of tables) we point it out. If any of the ingredients feel rusty, review closures, the table library and string patterns.

The plan

We build four pieces, and each one is small enough to test alone.

  1. A store. A function newTodoList() that returns an object with add, complete, remove, render and counts. The tasks live in local variables, so nothing outside can corrupt them.
  2. A formatter. render() turns the tasks into lines like 1 [x] Buy milk.
  3. A command table. A table that maps a word (add, done, rm, list) to a function.
  4. A parser. One pattern that splits a line into the command word and the rest.

Four small pieces

Store Tasks live in locals behind a closure.
Formatter string.format builds each line.
Commands A table maps words to functions.
Parser One pattern splits word and argument.

Parse, look up, call.

1 / 2

Step 1: the store with a closure

In Lua, a function can capture local variables from where it was defined (these are upvalues). A function that creates local variables and returns functions using them gives you private state without any special class syntax.

LUA
local function newTodoList()
  local items = {}
  local nextId = 1
  local list = {}

  local function indexOf(id)
    for i, item in ipairs(items) do
      if item.id == id then
        return i
      end
    end
    return nil
  end

  function list.add(text)
    local item = { id = nextId, text = text, done = false }
    items[#items + 1] = item
    nextId = nextId + 1
    return item.id
  end

  function list.complete(id)
    local i = indexOf(id)
    if not i then
      return false
    end
    items[i].done = true
    return true
  end

  function list.remove(id)
    local i = indexOf(id)
    if not i then
      return false
    end
    table.remove(items, i)
    return true
  end

  return list
end

Notice three things. items and nextId are local, so the only way to reach them is through the functions in list. indexOf is a local helper that is not exported at all. And the ids never get reused: removing task 2 does not make the next task 2, because nextId only goes up. That avoids confusing bugs where an old reference points at a new task.

The first stand-in is the same store in JavaScript. We add counts() and render() here so that you can see the formatted output straight away.

JS Stand-in: the to-do store

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

No output.

The new task got id 4, not 2: ids only move forward. The failed complete(99) returns false instead of crashing, which is the contract the command layer will rely on.

Step 2: rendering with string.format

Add these two functions inside newTodoList, before return list. The %2d pads numbers to width 2, and table.concat joins the lines. Building a list of lines and concatenating once is the idiomatic, fast way to assemble text in Lua.

LUA
  function list.render()
    if #items == 0 then
      return "(nothing to do)"
    end
    local lines = {}
    for _, item in ipairs(items) do
      lines[#lines + 1] = string.format(
        "%2d [%s] %s", item.id, item.done and "x" or " ", item.text)
    end
    return table.concat(lines, "\n")
  end

  function list.counts()
    local done = 0
    for _, item in ipairs(items) do
      if item.done then
        done = done + 1
      end
    end
    return done, #items
  end

item.done and "x" or " " is the classic Lua conditional expression. It is safe here because "x" is never nil or false; see operators and truthiness for the pitfall when the middle value can be falsy. counts returns two values (done and total) rather than a table: callers write local done, total = list.counts().

Step 3: a command table

Lua has no switch, and it does not need one. A table that maps names to functions is clearer and can be extended at run time. Each handler receives the list and the argument text and returns a message to print.

LUA
local function buildCommands()
  local commands = {}

  function commands.add(list, arg)
    if arg == "" then
      return "usage: add <text>"
    end
    local id = list.add(arg)
    return "added #" .. id
  end

  function commands.done(list, arg)
    local id = tonumber(arg)
    if id and list.complete(id) then
      return "completed #" .. id
    end
    return "no task " .. arg
  end

  function commands.rm(list, arg)
    local id = tonumber(arg)
    if id and list.remove(id) then
      return "removed #" .. id
    end
    return "no task " .. arg
  end

  function commands.list(list)
    local done, total = list.counts()
    return list.render() .. string.format("\n(%d of %d done)", done, total)
  end

  return commands
end

tonumber("abc") returns nil, so id and list.complete(id) safely skips the call for a bad argument. Because the handlers share one signature, adding a new command later is one more function in the table.

Step 4: parsing a line

A Lua pattern splits done 3 into done and 3. %S+ means "one or more non-space characters", %s* skips spaces, and (.*) captures everything that remains (possibly nothing).

LUA
local function run(list, commands, line)
  local word, arg = line:match("^(%S+)%s*(.*)$")
  if not word then
    return "empty command"
  end
  local handler = commands[word:lower()]
  if not handler then
    return "unknown command: " .. word
  end
  return handler(list, arg)
end

local todo = newTodoList()
local commands = buildCommands()

for _, line in ipairs({ "add Buy milk", "add Write lesson", "done 1", "list" }) do
  print("> " .. line)
  print(run(todo, commands, line))
end

Run in real Lua 5.4, the loop prints each command, then its result. The structure is the important part: parse, look up, call. The same three steps drive shells, chat bots and game consoles.

Here is the finished program as a JavaScript stand-in. The regular expression /^(\S+)\s*(.*)$/ is the same idea as the Lua pattern (JavaScript uses \S and \s, Lua uses %S and %s), and the handlers live in an object that plays the role of the command table.

JS Stand-in: commands, parser and report

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

No output.

Read the output from the bottom up. LIST worked because we lower-case the command word, dance now is reported rather than crashing, the empty line is caught by the pattern failing to match, and bad ids for done come back as friendly messages.

Ideas to extend it

  • Priorities: add a priority field and sort the output with table.sort(items, function(a, b) ... end); remember that Lua's sort is not stable, so tie-break on id.
  • Saving: write tasks to a file with io.open and read them back with io.lines (see files and I/O).
  • Undo: keep a stack of closures, each one reversing a command, and add an undo command that pops and calls the last one.
  • Real input: replace the fixed list of lines with for line in io.lines() do ... end to read commands from standard input.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why are items and nextId declared with local inside newTodoList?

    Local variables captured by closures are private. Code outside newTodoList has no name that refers to them, so it can only use add, complete, remove and so on.
  2. 2. What does line:match("^(%S+)%s*(.*)$") return for the line "done 3"?

    match returns one value per capture. The first capture is the command word, the second is whatever follows after optional spaces.
  3. 3. Why is a table of handler functions a good replacement for a switch statement in Lua?

    Lua has no switch. Functions are ordinary values, so a table keyed by command name gives you dispatch that is easy to read and extend.
  4. 4. What does tonumber("abc") return in Lua?

    tonumber returns nil when the string is not a valid number, which is why id and list.complete(id) can guard against bad input.

Summary

  • A closure that creates local variables and returns functions is Lua's lightweight way to make an object with private state.
  • Never reuse ids: let a counter only increase.
  • string.format and table.concat assemble report text cleanly.
  • A table of functions replaces switch; look up the command word, then call the handler.
  • One pattern, ^(%S+)%s*(.*)$, splits a command from its argument.
  • Return friendly messages for bad input instead of crashing.

Next: Project: Inventory with Classes