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
Lua is widely used in game development (World of Warcraft, Roblox, Garry's Mod) for scripting game logic and modding.
Lua is designed to be lightweight and efficient, making it perfect for embedded systems and performance-critical applications.
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.
To start coding in Lua, you'll need to install the Lua interpreter:
# Using Chocolatey (recommended)
choco install lua
# Or download from lua.org
# MacOS using Homebrew
brew install lua
# Linux (Debian/Ubuntu)
sudo apt-get install lua5.3
lua -v
# Should output something like: Lua 5.4.3
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 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"
Lua provides standard control structures with a simple syntax.
local age = 18
if age < 13 then
print("Child")
elseif age < 18 then
print("Teenager")
else
print("Adult")
end
-- 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
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
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
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)
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
Lua's C API allows you to embed Lua in C/C++ applications and extend Lua with C functions.
/* 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;
}
// 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;
}
Lua is fast, but these techniques can help squeeze out even more performance.
-- 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
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>
-- 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
-- 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!
-- 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
-- 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 has a vibrant community of developers, from game modders to embedded systems engineers. Join discussions, ask questions, and share your projects.
Join our Discord community for real-time discussions and support.
Contribute to open-source Lua projects and libraries.
Watch tutorials and live coding sessions.
Subscribe to our newsletter for Lua tips, tutorials, and community news.