0Pricing
Lua Academy · Lesson

Simple Expression Parser

Build a recursive descent parser for arithmetic expressions in pure Lua.

Goal: Parse Arithmetic Expressions

Build a recursive descent parser in pure Lua that parses and evaluates expressions like 3 + 4 * (2 - 1), respecting operator precedence.

Tokenizer

First, tokenize the input into numbers, operators, and parentheses.

local function tokenize(expr)
  local tokens = {}
  for tok in expr:gmatch("[%d%.]+|[%+%-%*/%(%)%^]|%S") do
    tokens[#tokens+1] = tok
  end
  return tokens
end

All lessons in this course

  1. DSL Design Principles in Lua
  2. Operator Overloading for DSL Fluency
  3. Building a Config DSL
  4. Simple Expression Parser
← Back to Lua Academy