Code
lua
local s = "Hello, World!"
-- Basic functions
print(#s) -- 13 (length)
print(string.upper(s)) -- "HELLO, WORLD!"
print(string.lower(s)) -- "hello, world!"
print(string.sub(s, 1, 5)) -- "Hello"
print(string.rep("-", 10)) -- "----------"
-- Find and replace (Lua patterns, NOT regex!)
local date = "2024-06-15"
local y, m, d = date:match("(%d+)-(%d+)-(%d+)")
print(y, m, d) -- 2024 06 15
-- gsub: replace all
local new = ("hello world"):gsub("o", "0") -- "hell0 w0rld"
print(new)
-- Format
print(string.format("Pi: %.2f", 3.14159)) -- "Pi: 3.14"
print(string.format("%5d", 42)) -- " 42"
-- Split (not built-in, implement with gmatch)
local function split(str, sep)
local parts = {}
for part in str:gmatch("([^" .. sep .. "]+)") do
table.insert(parts, part)
end
return parts
end
print(split("a,b,c", ",")) -- {a, b, c}