Lesson 5 of 8
Strings & the Standard Library
Learn the and the rest of Lua's small : table, math, io and os. It is small enough to learn in full.
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-- 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()Finished reading?Mark it done to track your progress.
Tip: use the ← and → keys to move between lessons.