LuLua · Lesson 5 of 8

Strings & the Standard Library

Lua's standard library is deliberately tiny — string, table, math, io, os. Small enough to actually learn completely.

Lua
local s = "Hello, Lua!"

print(s:upper())            -- HELLO, LUA!
print(s:len())              -- 11  (same as #s)
print(s:sub(1, 5))          -- Hello
print(s:rep(2))             -- Hello, Lua!Hello, Lua!
print(s:find("Lua"))        -- 8 10 (start and end position)
print(s:gsub("Lua", "World"))  -- Hello, World!   1

-- string.format — like printf:
print(string.format("%s scored %.1f%%", "Ada", 95.5))

-- Lua patterns (like lite regex): %d digit, %a letter, + repeat
for word in ("one two three"):gmatch("%a+") do
  print(word)
end
Lua
-- math:
math.floor(3.7)     -- 3
math.max(1, 5, 3)   -- 5
math.random(1, 6)   -- die roll

-- os and io:
print(os.time())               -- unix timestamp
print(os.date("%Y-%m-%d"))     -- formatted date

-- Read a file:
local f = io.open("data.txt", "r")
if f then
  local content = f:read("a")   -- whole file
  f:close()
  print(content)
end

-- Write a file:
local out = io.open("log.txt", "w")
out:write("saved!\n")
out:close()
◆ Note
Lua patterns are not full regular expressions — simpler, but cover most needs: %d digits, %a letters, %s whitespace, %w alphanumeric, + one-or-more, * zero-or-more, - lazy repeat.