Skip to content

Lua Quick Guide

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.

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.
print("Hello World!")

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).

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.

  • 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.

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 comment
local message = "Hello from an online Lua interpreter!"
print(message)
local a = 10
local b = 20
print("The sum of " .. a .. " and " .. b .. " is " .. (a + b))

To develop Lua applications locally, you’ll need:

  1. A Text Editor or Integrated Development Environment (IDE).
  2. The Lua Interpreter.
  3. Optionally, LuaRocks (the Lua package manager).

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-lua by sumneko or EmmyLua.
  • 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 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.

  1. 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.exe and luac.exe to your system’s PATH.
  2. Scoop: If you use Scoop, install Lua with scoop install lua.
  3. Chocolatey: If you use Chocolatey, install Lua with choco install lua.
  4. LuaDist: Provides a more comprehensive distribution with pre-built modules (check its current status and compatibility).
  5. 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.

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 systems
sudo apt update
sudo apt install lua5.4
# For Fedora
sudo dnf install lua
# For Arch Linux
sudo pacman -S lua

To 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.gz
tar zxf lua-5.4.6.tar.gz
cd lua-5.4.6
make linux test # or 'make generic test' or 'make posix test'
sudo make install

To run a Lua script (e.g., hello.lua):

-- hello.lua
print("Hello from Lua on Linux!")

Then, in the terminal:

lua hello.lua

Output:

Hello from Lua on Linux!

The easiest way to install Lua on macOS is using Homebrew:

brew install lua

To 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.gz
tar zxf lua-5.4.6.tar.gz
cd lua-5.4.6
make macosx test
sudo make install

If make fails, ensure Xcode Command Line Tools are installed: xcode-select --install.

Running a script is the same as on Linux:

-- hello_mac.lua
print("Hello from Lua on macOS!")
lua hello_mac.lua

Output:

Hello from Lua on macOS!

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’s syntax is simple and relatively small. Let’s dive into the basics.

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.

$ lua
Lua 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()

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.lua
local name = "Alex"
print("Hello, " .. name .. "!")
for i = 1, 3 do
print("Count: " .. i)
end

Run it from the terminal:

$ lua myscript.lua

Output:

Hello, Alex!
Count: 1
Count: 2
Count: 3

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.lua
print("This is an executable Lua script.")

Make it executable and run it:

$ chmod +x exec_script.lua
$ ./exec_script.lua

Output:

This is an executable Lua script.

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 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 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_valid

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:

andbreakdoelse
elseelseifendfalse
forfunctiongoto (use with caution)if
inlocalnilnot
orrepeatreturnthen
trueuntilwhile

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 ignored
print(item_count) -- Output: 5

Semicolons (;) 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 semicolon
print(a, b) -- Multiple statements on one line (generally avoid for clarity)