Learn Lua from Scratch

Master the powerful, efficient, and embeddable scripting language used in games like World of Warcraft, Roblox, and more.

-- Simple Lua example
function greet(name)
    return "Hello, " .. name .. "!"
end

-- Table with metatable example
local person = {
    name = "Lua Learner",
    age = 25
}

local mt = {
    __tostring = function(self)
        return self.name .. ", age " .. self.age
    end
}

setmetatable(person, mt)

print(greet(person.name))  -- Hello, Lua Learner!
print(person)             -- Lua Learner, age 25

Why Learn Lua?

Game Development

Lua is widely used in game development (World of Warcraft, Roblox, Garry's Mod) for scripting game logic and modding.

Lightweight & Fast

Lua is designed to be lightweight and efficient, making it perfect for embedded systems and performance-critical applications.

Easy to Embed

Lua's C API makes it simple to integrate with existing applications, which is why it's used in software like Redis, Nginx, and Wireshark.

Getting Started with Lua

Installation

To start coding in Lua, you'll need to install the Lua interpreter:

Windows

# Using Chocolatey (recommended)
choco install lua

# Or download from lua.org

MacOS/Linux

# MacOS using Homebrew
brew install lua

# Linux (Debian/Ubuntu)
sudo apt-get install lua5.3

Verify Installation

lua -v
# Should output something like: Lua 5.4.3

Your First Lua Script

Create a file named hello.lua with the following content:

-- This is a comment in Lua
print("Hello, Lua World!")

-- Variables
local name = "Lua Learner"
local age = 25

print("Name:", name)
print("Age:", age)

Run your script with:

lua hello.lua

Congratulations! You've written and executed your first Lua program.

Lua Tutorials

Beginner

  • Variables & Data Types
  • Control Structures
  • Functions & Scope
  • Basic Tables
  • Standard Libraries
Start Learning

Intermediate

  • Advanced Table Usage
  • Metatables & Metamethods
  • Coroutines
  • Error Handling
  • Modules & Packages
Continue Learning

Advanced

  • Lua C API
  • Embedding Lua
  • Performance Optimization
  • Garbage Collection
  • Creating DSLs
Master Lua

Beginner Lua Tutorials

1. Variables and Data Types

Lua is a dynamically typed language with basic types: nil, boolean, number, string, function, userdata, thread, and table.

-- Variable declaration
local name = "Lua"        -- string
local version = 5.4      -- number
local isAwesome = true   -- boolean
local nothing = nil     -- nil

-- Multiple assignment
local a, b, c = 1, 2, "three"

-- Type checking
print(type(name))      -- "string"
print(type(version))  -- "number"
print(type(nothing))  -- "nil"

Key Points:

  • Always use local to declare variables to avoid global scope
  • Lua automatically converts between numbers and strings in many contexts
  • nil represents the absence of a value

2. Control Structures

Lua provides standard control structures with a simple syntax.

If-Else

local age = 18

if age < 13 then
    print("Child")
elseif age < 18 then
    print("Teenager")
else
    print("Adult")
end

Loops

-- While loop
local i = 1
while i <= 5 do
    print(i)
    i = i + 1
end

-- For loop
for j = 1, 5 do
    print(j)
end

3. Functions

Functions are first-class citizens in Lua and can be assigned to variables, passed as arguments, and returned from other functions.

-- Basic function
function greet(name)
    return "Hello, " .. name
end

print(greet("Lua"))  -- Hello, Lua

-- Function as variable
local add = function(a, b)
    return a + b
end

print(add(2, 3))    -- 5

-- Variable number of arguments
function sum(...)
    local total = 0
    for i, num in ipairs({...}) do
        total = total + num
    end
    return total
end

print(sum(1, 2, 3, 4))  -- 10

Intermediate Lua Tutorials

1. Tables - Lua's Only Data Structure

Tables in Lua are associative arrays that can be used as arrays, dictionaries, objects, and more.

-- Array-like table
local fruits = {"apple", "banana", "cherry"}
print(fruits[1])  -- "apple" (Lua arrays are 1-indexed)

-- Dictionary-like table
local person = {
    name = "Alice",
    age = 30,
    profession = "Developer"
}

print(person.name)  -- "Alice"
print(person["age"]) -- 30

-- Mixed table
local mixed = {
    "first",          -- index 1
    "second",         -- index 2
    name = "Lua",
    version = 5.4
}

-- Iterating through tables
for k, v in pairs(person) do
    print(k, v)
end

2. Metatables and Metamethods

Metatables allow you to define the behavior of tables under specific operations, enabling operator overloading and more.

-- Vector addition example
local Vector = {}
Vector.__index = Vector

function Vector.new(x, y)
    return setmetatable({x = x, y = y}, Vector)
end

-- Define addition for vectors
function Vector.__add(a, b)
    return Vector.new(a.x + b.x, a.y + b.y)
end

-- Define string representation
function Vector.__tostring(v)
    return "Vector(" .. v.x .. ", " .. v.y .. ")"
end

local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
local v3 = v1 + v2

print(v3)  -- Vector(4, 6)

Common Metamethods:

  • __add: + operator
  • __sub: - operator
  • __mul: * operator
  • __div: / operator
  • __tostring: string representation
  • __index: table access
  • __newindex: table assignment
  • __call: makes table callable

3. Coroutines

Coroutines in Lua allow cooperative multitasking, enabling the creation of iterators and non-preemptive threads.

-- Simple coroutine example
local co = coroutine.create(function()
    for i = 1, 3 do
        print("Coroutine", i)
        coroutine.yield()
    end
end)

coroutine.resume(co)  -- Coroutine 1
coroutine.resume(co)  -- Coroutine 2
coroutine.resume(co)  -- Coroutine 3

-- Coroutine-based iterator
function countdown(from)
    return coroutine.wrap(function()
        for i = from, 1, -1 do
            coroutine.yield(i)
        end
    end)
end

for num in countdown(5) do
    print(num)  -- 5, 4, 3, 2, 1
end

Advanced Lua Topics

1. Lua C API

Lua's C API allows you to embed Lua in C/C++ applications and extend Lua with C functions.

Embedding Lua in C

/* simple.c - embedding Lua in C */
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>

int main(void) {
    /* create Lua state */
    lua_State *L = luaL_newstate();
    
    /* load Lua libraries */
    luaL_openlibs(L);
    
    /* run Lua code */
    luaL_dostring(L, "print('Hello from Lua!')");
    
    /* cleanup */
    lua_close(L);
    return 0;
}

Calling C from Lua

// Register a C function to be called from Lua
static int l_add(lua_State *L) {
    int a = lua_tonumber(L, 1);
    int b = lua_tonumber(L, 2);
    lua_pushnumber(L, a + b);
    return 1;  // number of return values
}

int main(void) {
    lua_State *L = luaL_newstate();
    luaL_openlibs(L);
    
    // Register our function
    lua_register(L, "add", l_add);
    
    // Call it from Lua
    luaL_dostring(L, "print(add(2, 3))");  // prints 5
    
    lua_close(L);
    return 0;
}

2. Performance Optimization

Lua is fast, but these techniques can help squeeze out even more performance.

Optimization Tips:

  • Use local variables instead of globals
  • Avoid table creation in tight loops
  • Reuse tables when possible
  • Use the most specific loop possible (for is faster than while)
  • Prefer ipairs for array iteration
  • Cache frequently accessed table fields in locals
-- Before optimization
for i = 1, 1000000 do
    local t = {x = 1, y = 2, z = 3}
    math.sqrt(t.x * t.x + t.y * t.y + t.z * t.z)
end

-- After optimization
local sqrt = math.sqrt  -- Cache function
local t = {x = 1, y = 2, z = 3}  -- Reuse table
local x, y, z = t.x, t.y, t.z  -- Cache fields

for i = 1, 1000000 do
    sqrt(x * x + y * y + z * z)
end

3. Creating Domain-Specific Languages (DSLs)

Lua's flexible syntax makes it ideal for creating embedded DSLs.

-- Example: Creating a simple HTML DSL
function tag(name, attrs, ...)
    local attrStr = ""
    if attrs then
        for k, v in pairs(attrs) do
            attrStr = attrStr .. ' ' .. k .. '="' .. v .. '"'
        end
    end
    
    local content = table.concat({...}, "")
    return "<" .. name .. attrStr .. ">" .. content .. "</" .. name .. ">"
end

function div(attrs, ...) return tag("div", attrs, ...) end
function p(attrs, ...) return tag("p", attrs, ...) end

-- Usage
local html = div({class="container"},
    p({}, "Hello, ", "Lua DSL!"),
    div({id="content"}, "This is a test")
)

print(html)
-- Outputs: <div class="container"><p>Hello, Lua DSL!</p><div id="content">This is a test</div></div>

Lua Examples

1. Fibonacci Sequence

-- Memoized Fibonacci function
local fib_cache = {[0] = 0, [1] = 1}

function fib(n)
    if not fib_cache[n] then
        fib_cache[n] = fib(n-1) + fib(n-2)
    end
    return fib_cache[n]
end

-- Print first 10 Fibonacci numbers
for i = 0, 10 do
    print("fib("..i..") =", fib(i))
end

2. Object-Oriented Programming

-- Simple OOP implementation
local Animal = {
    sound = "..."
}

function Animal:new(o)
    o = o or {}
    setmetatable(o, self)
    self.__index = self
    return o
end

function Animal:speak()
    print(self.sound)
end

-- Create a Dog class
local Dog = Animal:new({sound = "woof!"})

function Dog:wag()
    print("Tail wagging!")
end

-- Create instances
local spot = Dog:new()
spot:speak()  -- woof!
spot:wag()    -- Tail wagging!

3. Simple HTTP Server

-- Requires LuaSocket library
local socket = require "socket"

local host = "localhost"
local port = 8080

local server = assert(socket.bind(host, port))
print("Server running on http://"..host..":"..port)

while true do
    local client = server:accept()
    client:settimeout(10)
    
    local request = client:receive()
    print("Request: "..request)
    
    local response = {
        "HTTP/1.1 200 OK\r\n",
        "Content-Type: text/html\r\n\r\n",
        "<html><body>",
        "<h1>Hello from Lua Server!</h1>",
        "<p>Request: "..request.."</p>",
        "</body></html>"
    }
    
    client:send(table.concat(response))
    client:close()
end

4. Game Loop Example

-- Simple game loop structure
local Game = {
    running = true,
    entities = {}
}

function Game:addEntity(entity)
    table.insert(self.entities, entity)
end

function Game:update(dt)
    for i, entity in ipairs(self.entities) do
        if entity.update then
            entity:update(dt)
        end
    end
end

function Game:draw()
    for i, entity in ipairs(self.entities) do
        if entity.draw then
            entity:draw()
        end
    end
end

-- Main game loop
local lastTime = socket.gettime()
while Game.running do
    local currentTime = socket.gettime()
    local dt = currentTime - lastTime
    lastTime = currentTime
    
    Game:update(dt)
    Game:draw()
    
    -- Simple delay to simulate frame rate
    socket.sleep(0.016)  -- ~60 FPS
end

Lua Resources

Official Documentation

The official Lua documentation and reference manuals.

Visit Site →

Lua Tutorial

A comprehensive tutorial covering Lua from basics to advanced topics.

Visit Site →

Lua Users Wiki

Community-driven wiki with code samples, libraries, and tips.

Visit Site →

LÖVE Framework

A framework for making 2D games in Lua.

Visit Site →

LuaRocks

Package manager for Lua modules.

Visit Site →

Lua Forum

Official forum for Lua discussions and questions.

Visit Site →

Join the Community

Get Involved

Lua has a vibrant community of developers, from game modders to embedded systems engineers. Join discussions, ask questions, and share your projects.

Discord Server

Join our Discord community for real-time discussions and support.

GitHub

Contribute to open-source Lua projects and libraries.

YouTube

Watch tutorials and live coding sessions.

Newsletter

Subscribe to our newsletter for Lua tips, tutorials, and community news.