typestar

Language basics

27 steps in 9 sets of Lua.

Lua is the embedded language: a complete interpreter in a few hundred kilobytes of ANSI C, designed at PUC-Rio in Brazil to be dropped inside a bigger program and handed the steering wheel. World of Warcraft addons, Roblox games, Neovim configs, Redis scripts, and nginx request handling all speak it. One data structure — the table — plays array, record, module, and class, and metatables turn that single idea into whatever object system the host application needs.

This tour types the whole core: locals and shadowing, string.format and the colon methods, and/or as the value picker, the three loops, tables as arrays and records with pairs and ipairs, functions with multiple returns and varargs and closures, three-line map and filter, metatables from __index inheritance through operator metamethods to colon-method OOP, Lua patterns, pcall error handling, coroutines, custom iterators, the math library, and the module pattern. The Encore is the cross-language script trio in tidy stdlib Lua — gmatch tallies, elseif ladders, and string.rep bars.

Start this tour

Values

  • The script shapeThe smallest Lua: locals, print, and string.format.
  • locallocal scopes a name to its block; bare assignment goes global.
  • StringsConcatenate with .., format with string.format, # measures.

Control flow

  • if and elseifBlocks close with end; and/or double as a value picker.
  • LoopsNumeric for counts; while guards; repeat tests at the end.
  • Types and conversiontype inspects; tostring and tonumber convert explicitly.

Tables

Functions

  • FunctionsValues like any other; or supplies the default arguments.
  • Multiple returnsFunctions return several values; parentheses truncate to one.
  • Varargs... collects arguments and forwards them untouched.

Closures

Metatables

  • __indexMissed lookups go to the fallback: inheritance in one line.
  • Metamethods__add and __tostring teach operators new types.
  • The colonMethod definition and call pass self in one habit.

Patterns & errors

  • PatternsLua's own matching: %d, %a, captures, gmatch, gsub.
  • pcallerror raises; pcall catches into a status and a message.
  • CoroutinesPause at yield, resume where it left off.

The library

  • The math libraryfloor and ceil, // and %, and one number type in two flavors.
  • ModulesA module is a table a file returns; require caches it.

Encore

  • word_freq.luaA word-frequency table from gmatch, a tally table, and one sort.
  • grade_report.luaReport cards from a table roster, an elseif ladder, and format.
  • temp_stats.luaA week of temperatures: index-tracked extremes, a bar chart, swings.

The other Lua tours