Learn Lua by Examples
Lua 5.4Lua is a powerful, efficient, lightweight, embeddable scripting language. It supports procedural programming, object-oriented programming, functional programming, data-driven programming, and data description.
These examples cover the core concepts of Lua, from its flexible table data structure and metatables to coroutines and modular programming.
Variables
Lua is dynamically typed. This sample demonstrates global and local variable declarations and basic types.
Tables
Tables are the only data structuring mechanism in Lua. This example shows how to use them as arrays, dictionaries, and objects.
Functions
Functions in Lua are first-class values. This sample demonstrates definition, multiple return values, and anonymous functions.
Metatables
Metatables allow you to change the behavior of tables. This example shows how to implement operator overloading and custom indexing.
Loops
Lua provides standard loop structures. This sample demonstrates `while`, `repeat-until`, and numeric/generic `for` loops.
Conditionals
Conditional logic uses `if`, `elseif`, and `else`. This example shows how to control program flow based on boolean checks.
Modules
Modules allow you to organize code into reusable files. This sample shows how to create and require a simple module.
Coroutines
Coroutines enable collaborative multitasking. This example shows how to create, resume, and yield from a coroutine.
File Handling
Lua provides a simple I/O library. This sample demonstrates writing to and reading from files.
Error Handling
Lua uses `pcall` (protected call) to catch errors. This example shows how to raise errors and handle them gracefully.

