Lua Quick Guide
Lua - A Modern Quick Guide
Section titled “Lua - A Modern Quick Guide”Lua - Overview
Section titled “Lua - Overview”Lua is a powerful, efficient, lightweight, and embeddable scripting language. It supports procedural programming, object-oriented programming (prototype-based), functional programming, data-driven programming, and data description. Conceived in 1993 by Roberto Ierusalimschy, Luiz Henrique de Figueiredo, and Waldemar Celes at a Brazilian university, Lua was designed to be easily integrated into applications written in C and other languages.
This integration capability is a cornerstone of Lua’s design. Lua doesn’t aim to replace C but rather to complement it, excelling where C is less suited: offering a higher level of abstraction, dynamic typing, automatic memory management, and robust string and table manipulation. This makes Lua ideal for configuration, scripting, and rapid prototyping.
Key Features
Section titled “Key Features”Lua stands out due to several unique features:
- Lightweight: Lua’s core is very small, making it suitable for resource-constrained devices and fast to load.
- Embeddable: Designed from the ground up to be easily integrated into host applications, with a simple C API.
- Fast: Lua is known for its performance, often benchmarked among the fastest scripting languages, thanks to its efficient bytecode virtual machine.
- Portable: Written in ANSI C, Lua compiles and runs on virtually any platform that has a C compiler.
- Simple: Lua has a relatively small set of concepts and a clean syntax, making it easy to learn.
- Dynamically Typed: Types are checked at runtime, and variables do not have fixed types.
- Automatic Memory Management: Uses garbage collection to manage memory, freeing developers from manual allocation and deallocation.
- Extensible: Lua’s functionality can be extended not only via Lua code but also through C libraries.
Hello World Example
Section titled “Hello World Example”print("Hello World!")How Lua is Implemented
Section titled “How Lua is Implemented”Lua is implemented as a small C library. The Lua distribution includes the Lua interpreter (a small program that allows you to run Lua scripts) and the Lua compiler (which compiles Lua source code into bytecode). Lua code is typically compiled to bytecode before being executed by the Lua virtual machine (VM). This compilation step is fast and often happens transparently at runtime.
The interpreter and VM are highly portable and optimized for speed and small footprint. Lua’s design prioritizes simplicity, efficiency, and portability, making it a popular choice for game development (e.g., Roblox, Defold, LÖVE), embedded systems (e.g., firmware), application scripting (e.g., Neovim, Redis, Wireshark), and web development (e.g., OpenResty).
Learning Lua
Section titled “Learning Lua”When learning Lua, focus on understanding its core concepts: tables, functions as first-class values, coroutines, and metatables. These are the building blocks for its powerful features. Mastering these concepts will make you a more effective programmer, capable of leveraging Lua’s flexibility in various applications.
Practical application and experimentation are key. Utilize online resources, the official Lua documentation (highly recommended), and community forums to deepen your understanding.
Common Uses of Lua
Section titled “Common Uses of Lua”- Game Development: Engines like LÖVE, Defold, Solar2D (formerly Corona SDK), and platforms like Roblox heavily use Lua or its variants (Luau).
- Embedded Systems: Its small footprint makes it ideal for microcontrollers and IoT devices.
- Application Scripting & Extension: Used in Neovim, Redis, Nginx (OpenResty), Wireshark, Adobe Lightroom, and many others.
- Web Development: Primarily with OpenResty, a high-performance web platform based on Nginx and LuaJIT.
- Middleware and Tools: For configuration, automation, and plugin systems.
Lua - Environment Setup
Section titled “Lua - Environment Setup”Try Lua Online Before setting up a local environment, you can easily try Lua online. Many websites offer interactive Lua interpreters where you can execute code snippets directly in your browser. Search for “online Lua interpreter” or try platforms like Replit, the official Lua demo page (lua.org/demo.html), or other coding playgrounds. This is a great way to quickly experiment with the language.
Example to try online:
-- This is a commentlocal message = "Hello from an online Lua interpreter!"print(message)
local a = 10local b = 20print("The sum of " .. a .. " and " .. b .. " is " .. (a + b))Local Environment Setup
Section titled “Local Environment Setup”To develop Lua applications locally, you’ll need:
- A Text Editor or Integrated Development Environment (IDE).
- The Lua Interpreter.
- Optionally, LuaRocks (the Lua package manager).
Text Editor / IDE
Section titled “Text Editor / IDE”You can write Lua code in any plain text editor. However, using an editor or IDE with Lua support (syntax highlighting, code completion, debugging) is highly recommended. Popular choices include:
- Visual Studio Code (VS Code): Excellent Lua support via extensions like
vscode-luaby sumneko orEmmyLua. - Neovim: Highly configurable, with built-in LSP support for Lua.
- Sublime Text: Good Lua packages available.
- ZeroBrane Studio: A lightweight, dedicated Lua IDE with debugging capabilities.
- IntelliJ IDEA (with Lua plugin): A powerful IDE with good Lua support.
Lua source files are typically saved with the .lua extension.
The Lua Interpreter
Section titled “The Lua Interpreter”The Lua interpreter executes Lua scripts. It also provides an interactive mode (REPL - Read-Eval-Print Loop) for experimenting with Lua code line by line. You can also use luac, the Lua compiler, to precompile Lua scripts into bytecode for potentially faster loading or to check for syntax errors, though the interpreter can compile source on the fly.
Installation on Windows
Section titled “Installation on Windows”- Official Binaries: Download precompiled Windows binaries from the official LuaBinaries project (often found via a search for “LuaBinaries” or linked from lua.org). Choose the latest stable version (e.g., Lua 5.4.x). Extract the files and add the directory containing
lua.exeandluac.exeto your system’s PATH. - Scoop: If you use Scoop, install Lua with
scoop install lua. - Chocolatey: If you use Chocolatey, install Lua with
choco install lua. - LuaDist: Provides a more comprehensive distribution with pre-built modules (check its current status and compatibility).
- WSL (Windows Subsystem for Linux): Install Lua within your WSL Linux distribution using its package manager (see Linux instructions).
An older option, LuaForWindows, bundled Lua with SciTE and libraries but may not be up-to-date with the latest Lua versions. Modern setups with VS Code and official binaries/package managers are generally preferred.
Installation on Linux
Section titled “Installation on Linux”Most Linux distributions provide Lua through their package managers. This is the easiest way to install it. Open your terminal and use the appropriate command for your distribution (e.g., Lua 5.4):
# For Debian/Ubuntu based systemssudo apt updatesudo apt install lua5.4
# For Fedorasudo dnf install lua
# For Arch Linuxsudo pacman -S luaTo compile from source (for the latest version or custom builds):
Download the latest tarball from lua.org/ftp/ (e.g., lua-5.4.6.tar.gz).
wget http://www.lua.org/ftp/lua-5.4.6.tar.gztar zxf lua-5.4.6.tar.gzcd lua-5.4.6make linux test # or 'make generic test' or 'make posix test'sudo make installTo run a Lua script (e.g., hello.lua):
-- hello.luaprint("Hello from Lua on Linux!")Then, in the terminal:
lua hello.luaOutput:
Hello from Lua on Linux!Installation on macOS
Section titled “Installation on macOS”The easiest way to install Lua on macOS is using Homebrew:
brew install luaTo compile from source (requires Xcode Command Line Tools):
Download the latest tarball from lua.org/ftp/ (e.g., lua-5.4.6.tar.gz).
curl -R -O http://www.lua.org/ftp/lua-5.4.6.tar.gztar zxf lua-5.4.6.tar.gzcd lua-5.4.6make macosx testsudo make installIf make fails, ensure Xcode Command Line Tools are installed: xcode-select --install.
Running a script is the same as on Linux:
-- hello_mac.luaprint("Hello from Lua on macOS!")lua hello_mac.luaOutput:
Hello from Lua on macOS!LuaRocks: The Lua Package Manager
Section titled “LuaRocks: The Lua Package Manager”LuaRocks is a package manager for Lua modules, similar to npm for Node.js or pip for Python. It allows you to easily install and manage Lua libraries (called “rocks”).
Many systems will install LuaRocks if you install a development package for Lua (e.g. lua5.4-dev on Debian/Ubuntu, which often includes luarocks).
Otherwise, you can install it separately. Visit luarocks.org for installation instructions.
Once installed, you can install a Lua module like:
luarocks install <module_name>
Lua - Basic Syntax
Section titled “Lua - Basic Syntax”Lua’s syntax is simple and relatively small. Let’s dive into the basics.
First Lua Program
Section titled “First Lua Program”Interactive Mode (REPL)
Section titled “Interactive Mode (REPL)”You can start Lua’s interactive mode by simply typing lua in your terminal. This opens a REPL where you can type Lua statements and see immediate results.
$ luaLua 5.4.6 Copyright (C) 1994-2023 Lua.org, PUC-Rio> print("Hello from Lua REPL!")Hello from Lua REPL!> x = 10> y = x * 2> print(y)20> -- To exit, type Ctrl+D (Unix) or Ctrl+Z then Enter (Windows), or os.exit()Script Mode
Section titled “Script Mode”For larger programs, you’ll write your code in a .lua file and execute it with the Lua interpreter.
Create a file named myscript.lua:
-- myscript.lualocal name = "Alex"print("Hello, " .. name .. "!")
for i = 1, 3 do print("Count: " .. i)endRun it from the terminal:
$ lua myscript.luaOutput:
Hello, Alex!Count: 1Count: 2Count: 3Executable Scripts (Unix-like systems)
Section titled “Executable Scripts (Unix-like systems)”On Unix-like systems (Linux, macOS), you can make a Lua script executable by adding a shebang line at the beginning and setting execute permissions.
#!/usr/bin/env lua
-- exec_script.luaprint("This is an executable Lua script.")Make it executable and run it:
$ chmod +x exec_script.lua$ ./exec_script.luaOutput:
This is an executable Lua script.Tokens in Lua
Section titled “Tokens in Lua”A Lua program is composed of tokens. Tokens are the smallest individual units of a program, such as keywords, identifiers, constants (literals), string literals, and symbols (operators, punctuation).
For example, the statement local message = "Hello" .. " World!" consists of the following tokens:
local (keyword)message (identifier)= (operator)"Hello" (string literal).. (operator)" World!" (string literal)Comments
Section titled “Comments”Comments are ignored by the interpreter and are used to add explanatory notes to your code.
-- This is a single-line comment.
--[[ This is a multi-line comment. It can span several lines.--]]
local x = 10 -- This comment is at the end of a line.
-- To temporarily disable a block of code using multi-line comments:--[[ local y = 20 print(y)--]]Identifiers
Section titled “Identifiers”Identifiers are names used to identify variables, functions, or tables. An identifier starts with a letter (A-Z, a-z) or an underscore (_), followed by zero or more letters, underscores, or digits (0-9).
Lua is case-sensitive, so myVar and myvar are different identifiers. Punctuation characters like @, $, and % are not allowed within identifiers (except for underscores).
Examples of valid identifiers:
name userName _temp count1 MAX_VALUE is_validKeywords
Section titled “Keywords”Keywords are reserved words that have special meaning in Lua and cannot be used as identifiers. Here is a list of Lua (5.4) keywords:
and | break | do | else |
|---|---|---|---|
else | elseif | end | false |
for | function | goto (use with caution) | if |
in | local | nil | not |
or | repeat | return | then |
true | until | while |
Whitespace in Lua
Section titled “Whitespace in Lua”Whitespace refers to spaces, tabs, and newline characters. Lua uses whitespace to separate tokens but generally ignores extra whitespace. Blank lines (lines with only whitespace and/or comments) are also ignored.
For example, local age requires at least one whitespace character between local and age. However, in total = items + 10, whitespace around = and + is optional but recommended for readability.
local item_count = 5 -- Extra whitespace is ignoredprint(item_count) -- Output: 5Semicolons (;) are optional statement separators in Lua. They are rarely needed but can be used to separate multiple statements on a single line, though this is often discouraged for readability.
a = 1; b = 2 -- Optional semicolonprint(a, b) -- Multiple statements on one line (generally avoid for clarity)