Lexical Structure & Conventions

An exhaustive guide to PyLua's lexical grammar, character set, tokenization engine, comments, identifiers, reserved words, and how the underlying C99 lexer processes source text.

1. Character Encoding & Source Representation

PyLua source files must be encoded in UTF-8. The lexer operates directly on byte streams while honoring multi-byte UTF-8 sequences in strings and comments. Source files are parsed without requiring a byte order mark (BOM); if a UTF-8 BOM (0xEF 0xBB 0xBF) is present at the beginning of a source script, the lexer automatically skips it transparently.

Unix Shebang Support

If the first line of a PyLua source file begins with #! (such as #!/usr/bin/env pylua), the lexer automatically ignores the entire line, allowing PyLua scripts to be executed directly as executable scripts on Linux and POSIX environments.

2. Identifiers & Naming Rules

Identifiers in PyLua denote variable names, function names, table keys, and labels. An identifier is any sequence of Latin letters (A-Z, a-z), digits (0-9), and underscores (_), provided it does not begin with a digit and is not a reserved keyword.

  • Valid identifiers: player_x, velocity2D, _internalState, Score_100, __init__
  • Invalid identifiers: 2player (starts with digit), player-x (minus operator), if (reserved keyword)
  • Case Sensitivity: PyLua is strictly case-sensitive. Counter, counter, and COUNTER are three distinct identifiers.
Reserved Pattern: Leading Underscore + Uppercase

Identifiers starting with an underscore followed by uppercase letters (e.g., _ENV, _G, _VERSION) are reserved by convention for PyLua internal variables and global metamethod configurations. Avoid creating user variables with this pattern.

3. Reserved Keywords

The following tokens are reserved keywords and cannot be used as variable or function identifiers:

Category Keywords
Control Flow if, then, else, elseif, end, while, do, repeat, until, for, in, break, goto, return
Definitions function, local
Module System import PyLua Extension
Logical Operators and, or, not
Literals nil, true, false

4. Comments

PyLua supports single-line comments and multi-line block comments:

Single-Line Comments

A single-line comment begins with two hyphens (--) and continues until the end of the line:

single_line_comments.lua
-- Calculate acceleration vector
acceleration = force / mass  -- Newton's Second Law

Multi-Line Block Comments

A block comment begins with --[[ and extends across any number of lines until the matching ]] delimiter:

block_comments.lua
--[[
  =======================================================
  PyLua Engine Subsystem Initializer
  Handles hardware display queries and initializes GLFW.
  =======================================================
--]]
import engine
print("Engine booting...")

Block comments can also contain nested brackets with equal signs (e.g. --[=[ ... ]=]) to allow embedding code that contains literal ]] brackets without terminating the comment early.

5. Literals

Numerical Literals

PyLua differentiates between 64-bit signed integers (lua_Integer) and 64-bit IEEE 754 double-precision floats (lua_Number):

  • Decimal Integers: 42, 1000000, -15
  • Hexadecimal Integers: 0x2A, 0xFF00AA, 0xDEADBEEF
  • Decimal Floats: 3.14159, 0.001, .75
  • Scientific Notation: 1e6 (1,000,000.0), 2.5e-3 (0.0025)
  • Hexadecimal Floats: 0x1.fp10 (1984.0)

String Literals

Strings in PyLua can be delimited by single quotes ('...'), double quotes ("..."), or long brackets ([[...]]):

string_literals.lua
s1 = "Hello, PyLua!\n"       -- Supports escape sequences like \n, \t, \x41, \u{1F600}
s2 = 'Single-quoted string'
s3 = [[
  Multi-line raw string.
  Escape characters like \n are not evaluated here.
]]

6. Backend Lexical Architecture (`llex.c`)

In the PyLua compiler backend, lexical scanning is implemented in src/parser/llex.c. The lexer uses a zero-allocation streaming model backed by ZIO (a buffered I/O stream):

Source Code Stream (ZIO buffer)
             │
             ▼
      llex() [llex.c] ──────▶ Dispatches on current character:
             │                   ├── Letter / '_'  ──▶ Reads Identifier / Keyword via TString hash
             │                   ├── Digit / '.'   ──▶ Reads Number (luaO_str2num)
             │                   ├── Quote ' or "  ──▶ Reads Escaped String Literal
             │                   ├── '['           ──▶ Reads Long String or Bracket
             │                   ├── '{' or '}'    ──▶ Emits TK_CBRACE / TK_OBRACE
             │                   ├── '!'           ──▶ Checks next '=' ──▶ TK_NE (!=)
             │                   └── '-'           ──▶ Checks next '-' ──▶ Skips comment
             ▼
     Token Descriptor [Token]
     ├── token: TK_IMPORT / TK_NAME / TK_INT / TK_FLT / etc.
     ├── seminfo: SemInfo union { lua_Number r; lua_Integer i; TString *ts; }
     └── linenumber: int

Every keyword and identifier is automatically interned into the global string table (global_State.strt). This guarantees that subsequent comparisons during parsing are simple \(O(1)\) pointer equality checks rather than \(O(N)\) string comparisons.