Drill 01: Fundamentals
Types, variables, strings, operators, and control flow. The foundation of Lua.
Run This Drill
bash ~/atelier/_bibliotheca/domus-captures/docs/modules/ROOT/examples/lua-drills/01-fundamentals.sh
Drill Script
#!/bin/bash
# LUA DRILL 01: FUNDAMENTALS
# Paste this entire script into your terminal
# Topics: Types, variables, operators, control flow
echo "=================================================================="
echo " LUA DRILL 01: FUNDAMENTALS "
echo "=================================================================="
echo ""
echo "NOTE: These drills use 'lua' interpreter. For Neovim-specific APIs,"
echo "run :lua commands in Neovim or use nvim --headless -c 'lua ...'"
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.1: BASIC TYPES"
echo "nil, boolean, number, string"
echo "------------------------------------------------------------------"
echo ""
lua << 'LUAEOF'
-- nil (absence of value)
local missing = nil
print("nil value:", missing)
print("type:", type(missing))
-- boolean
local enabled = true
local disabled = false
print("\nboolean:", enabled, disabled)
-- number (integer and float are both "number")
local port = 443
local latency = 45.7
print("\nnumber (int):", port, type(port))
print("number (float):", latency, type(latency))
-- string
local hostname = "ise-01"
local domain = "inside.domusdigitalis.dev"
print("\nstring:", hostname, type(hostname))
print("concatenation:", hostname .. "." .. domain)
print("length:", #hostname)
LUAEOF
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.2: STRING OPERATIONS"
echo "Concatenation, formatting, methods"
echo "------------------------------------------------------------------"
echo ""
lua << 'LUAEOF'
local hostname = "ise-01"
local ip = "10.50.1.20"
local port = 443
-- Concatenation with ..
local url = "https://" .. ip .. ":" .. port
print("URL:", url)
-- String formatting (like printf)
local msg = string.format("Server %s at %s:%d", hostname, ip, port)
print("Formatted:", msg)
-- String methods
print("\nupper:", string.upper(hostname))
print("lower:", string.lower("ISE-01"))
print("length:", string.len(hostname), "or", #hostname)
print("substring:", string.sub(hostname, 1, 3)) -- "ise"
print("find 'ise':", string.find(hostname, "ise")) -- returns start, end
print("replace:", string.gsub(hostname, "-", "_")) -- ise_01
-- Pattern matching (like regex but simpler)
local fqdn = "ise-01.inside.domusdigitalis.dev"
local short = string.match(fqdn, "^([^.]+)") -- capture up to first dot
print("\nshort name:", short)
LUAEOF
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.3: VARIABLES AND SCOPE"
echo "local vs global, multiple assignment"
echo "------------------------------------------------------------------"
echo ""
lua << 'LUAEOF'
-- ALWAYS use local (global by default is a footgun)
local hostname = "ise-01"
local ip, port = "10.50.1.20", 443 -- multiple assignment
print("hostname:", hostname)
print("ip, port:", ip, port)
-- Swapping values
local a, b = 1, 2
a, b = b, a -- swap without temp variable
print("\nswapped:", a, b)
-- nil for extra values
local x, y, z = 10, 20 -- z is nil
print("x, y, z:", x, y, z)
-- Table unpacking
local function get_endpoint()
return "10.50.1.20", 443
end
local host, p = get_endpoint()
print("\nfrom function:", host, p)
LUAEOF
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.4: OPERATORS"
echo "Arithmetic, comparison, logical"
echo "------------------------------------------------------------------"
echo ""
lua << 'LUAEOF'
-- Arithmetic
local a, b = 10, 3
print("add:", a + b)
print("sub:", a - b)
print("mul:", a * b)
print("div:", a / b) -- 3.333...
print("floor div:", a // b) -- 3 (Lua 5.3+)
print("mod:", a % b) -- 1
print("power:", a ^ 2) -- 100
-- Comparison
print("\n== equals:", 10 == 10)
print("~= not equal:", 10 ~= 5) -- NOTE: ~= not !=
print("> greater:", 10 > 5)
print("<= less/eq:", 10 <= 10)
-- Logical
local enabled = true
local active = false
print("\nand:", enabled and active) -- false
print("or:", enabled or active) -- true
print("not:", not enabled) -- false
-- Short-circuit (idiomatic Lua)
local timeout = nil
local default_timeout = timeout or 30 -- use 30 if timeout is nil/false
print("\ndefault:", default_timeout)
-- Ternary-like pattern
local status = enabled and "ON" or "OFF"
print("status:", status)
LUAEOF
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.5: CONTROL FLOW"
echo "if/elseif/else, loops"
echo "------------------------------------------------------------------"
echo ""
lua << 'LUAEOF'
-- if/elseif/else
local status = "active"
if status == "active" then
print("Server is running")
elseif status == "standby" then
print("Server is standby")
else
print("Server status unknown")
end
-- while loop
print("\nwhile loop:")
local i = 1
while i <= 3 do
print(" iteration", i)
i = i + 1
end
-- for loop (numeric)
print("\nfor loop (1 to 5):")
for i = 1, 5 do
print(" i =", i)
end
-- for with step
print("\nfor loop (10 to 1, step -2):")
for i = 10, 1, -2 do
print(" i =", i)
end
-- repeat/until (do-while equivalent)
print("\nrepeat/until:")
local count = 0
repeat
count = count + 1
print(" count =", count)
until count >= 3
LUAEOF
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "DRILL 1.6: FUNCTIONS"
echo "Definition, multiple returns, varargs"
echo "------------------------------------------------------------------"
echo ""
lua << 'LUAEOF'
-- Basic function
local function greet(name)
return "Hello, " .. name .. "!"
end
print(greet("admin"))
-- Multiple return values
local function parse_endpoint(endpoint)
local host, port = string.match(endpoint, "([^:]+):(%d+)")
return host, tonumber(port)
end
local h, p = parse_endpoint("10.50.1.20:443")
print("\nparsed:", h, p)
-- Default arguments pattern
local function connect(host, port, timeout)
timeout = timeout or 30 -- default
return string.format("Connecting to %s:%d (timeout: %ds)", host, port, timeout)
end
print("\n" .. connect("10.50.1.20", 443))
print(connect("10.50.1.20", 443, 60))
-- Varargs
local function log(level, ...)
local args = {...}
print(string.format("[%s]", level), table.unpack(args))
end
log("INFO", "Server", "started", "on port", 8080)
log("ERROR", "Connection", "failed")
LUAEOF
echo ""
# ---------------------------------------------------------------------------
echo "------------------------------------------------------------------"
echo "YOUR TURN - TRY THESE IN nvim :lua"
echo "------------------------------------------------------------------"
echo ""
echo "1. String formatting:"
echo " :lua print(string.format('Port %d', 443))"
echo ""
echo "2. Default value pattern:"
echo " :lua local x = nil; print(x or 'default')"
echo ""
echo "3. Ternary pattern:"
echo " :lua local enabled = true; print(enabled and 'ON' or 'OFF')"
echo ""
echo "------------------------------------------------------------------"
echo "KEY TAKEAWAYS:"
echo "1. ALWAYS use 'local' (global by default)"
echo "2. ~= for not-equal (NOT !=)"
echo "3. .. for string concatenation"
echo "4. 'or' for defaults: x = val or default"
echo "5. a and b or c for ternary (when b is truthy)"
echo "------------------------------------------------------------------"