COURSE ยท 7 LESSONS ยท 100% FREE
๐ŸŒ™

Lua Programming

Lightweight scripting language. Embedded in games (Roblox, WoW), Nginx, Redis. Fast and embeddable.

0Lessons
0Code Examples
ZeroPrerequisites
0%
You've completed 0 of 7 lessons
J/โ†“ Next
K/โ†‘ Prev
Esc Collapse
/ Search
Foundations
01

Hello World & Setup

print() for output. No semicolons. 1-based indexing. Run: lua file.lua

print("Hello, World!")

-- Variables (global by default)
name = "Mayank"
age = 15
print(name .. " is " .. age)  -- string concat

-- Local variables (preferred)
local x = 42
local pi = 3.14
print(x, pi)

-- Nil is falsy, everything else is truthy
if nil then print("truthy") else print("falsy") end
if 0 then print("truthy") end  -- 0 is truthy!
02

Variables & Types

nil, boolean, number, string, table, function. type() returns the type name.

print(type(nil))        -- nil
print(type(true))       -- boolean
print(type(42))         -- number
print(type(3.14))       -- number
print(type("hello"))    -- string
print(type(print))      -- function
print(type({}))         -- table

-- Strings
local s = 'hello'
local s2 = "world"
local s3 = [[multi
line string]]
print(#s)  -- length: 5
print(string.upper(s))  -- HELLO
print(string.format("%s is %d", name, age))

-- Numbers
print(math.pi)
print(math.floor(3.7))  -- 3
print(math.random(1, 10))  -- random 1-10
03

Control Flow

if/elseif/else/end, while/do/end, for/do/end. No switch. No ternary.

local score = 85
if score >= 90 then
    print('A')
elseif score >= 80 then
    print('B')
else
    print('C')
end

-- For loops
for i = 1, 5 do print(i) end        -- 1 to 5
for i = 5, 1, -1 do print(i) end    -- 5 to 1
for i = 1, 10, 2 do print(i) end    -- odd: 1,3,5,7,9

-- While
local n = 0
while n < 5 do
    print(n)
    n = n + 1
end

-- Repeat-until (runs at least once)
local m = 0
repeat
    print(m)
    m = m + 1
until m >= 5

-- No break in standard Lua 5.1, but available in 5.2+
04

Functions

function/end. Multiple returns. Variadic. Closures. Functions are first-class.

function add(a, b)
    return a + b
end
print(add(3, 4))

-- Multiple returns
function divmod(a, b)
    return math.floor(a/b), a % b
end
local q, r = divmod(10, 3)
print(q, r)  -- 3, 1

-- Variadic
function sum(...)
    local total = 0
    for _, v in ipairs({...}) do total = total + v end
    return total
end
print(sum(1, 2, 3, 4, 5))  -- 15

-- Closures
function counter()
    local n = 0
    return function()
        n = n + 1
        return n
    end
end
local c = counter()
print(c(), c(), c())  -- 1, 2, 3

-- Table of functions
local ops = {
    add = function(a,b) return a+b end,
    mul = function(a,b) return a*b end,
}
print(ops.add(3, 4))
print(ops.mul(3, 4))
Tables & OOP
05

Tables (Arrays & Maps)

Tables are Lua's only data structure. Array-like with ipairs, map-like with pairs.

-- Array (1-based!)
local nums = {10, 20, 30, 40, 50}
print(nums[1])  -- 10 (not 0!)
print(#nums)    -- 5

table.insert(nums, 60)
table.remove(nums, 1)

for i, v in ipairs(nums) do
    print(i, v)
end

-- Map
local person = {name = "Mayank", age = 15}
print(person.name)
print(person["age"])

person.email = "mayank@test.com"

for k, v in pairs(person) do
    print(k, v)
end

-- Nested
local matrix = {
    {1, 2, 3},
    {4, 5, 6},
    {7, 8, 9},
}
print(matrix[2][3])  -- 6
06

Metatables & OOP

Metatables override behavior. __index, __add, __tostring. OOP via metatables.

-- Metatables
local mt = {
    __add = function(a, b) return {x=a.x+b.x, y=a.y+b.y} end,
    __tostring = function(t) return '(' .. t.x .. ',' .. t.y .. ')' end,
}

local p1 = setmetatable({x=1, y=2}, mt)
local p2 = setmetatable({x=3, y=4}, mt)
local p3 = p1 + p2
print(p3)  -- (4,6)

-- OOP
Dog = {}
Dog.__index = Dog

function Dog.new(name, age)
    return setmetatable({name=name, age=age}, Dog)
end

function Dog:bark()
    print(self.name .. ": Woof!")
end

local d = Dog.new("Rex", 5)
d:bark()
07

Modules & Coroutines

require/load modules. coroutine.create/resume/yield for cooperative multitasking.

-- Module (math_extra.lua)
local M = {}
function M.fib(n)
    if n <= 1 then return n end
    return M.fib(n-1) + M.fib(n-2)
end
return M

-- Using module
local math_extra = require('math_extra')
print(math_extra.fib(10))

-- Coroutines
local co = coroutine.create(function()
    for i = 1, 5 do
        coroutine.yield(i)
    end
end)

print(coroutine.resume(co))  -- true, 1
print(coroutine.resume(co))  -- true, 2
print(coroutine.resume(co))  -- true, 3

-- Producer/Consumer
local producer = coroutine.create(function()
    for i = 1, 10 do
        coroutine.yield('item-' .. i)
    end
end)

while coroutine.status(producer) ~= 'dead' do
    local ok, item = coroutine.resume(producer)
    if ok then print('Got: ' .. item) end
end