string

Contents

string#

Lua strings are immutable byte sequences. They are not Unicode by default; a string is a string of bytes. string.len and # return the byte count, not the character count. Indexing is 1-based and uses functions, not subscripts.

Length in bytes.

local s = "operator"
print(#s)                       --> 8

Substring; 1-based, inclusive.

print(string.sub(s, 1, 4))      --> oper

Uppercase via the library function.

print(string.upper(s))          --> OPERATOR

Method-call sugar; s:upper() is identical to string.upper(s).

print(s:upper())                --> OPERATOR

Concatenate with ...

local greet = "hello, " .. "world"

Repeat with string.rep.

local r = string.rep("ab", 3)   --> ababab

string.format mirrors C printf.

print(string.format("%s=%d (%.2f%%)", "cpu", 12, 12.345))

string.gmatch walks every match of a Lua pattern (a tiny regex dialect; see I/O).

for word in ("one two three"):gmatch("%a+") do print(word) end

References#

  • Casting for tostring / tonumber round-trips.

  • Operators for .. concatenation.

  • I/O for Lua patterns.