String & UTF-8 Manipulation

PyLua treats strings as immutable byte buffers with an optimized pattern matching engine and dedicated UTF-8 Unicode decoding.

1. String Formatting (`string.format`)

Generates formatted strings using standard C printf format specifiers:

string_formatting.lua
name = "Player1"
score = 4250
ratio = 0.8765

msg = string.format("Name: %-10s | Score: %06d | Win Rate: %.1f%%", name, score, ratio * 100)
print(msg)
-- Output: Name: Player1    | Score: 004250 | Win Rate: 87.7%

2. Pattern Matching Engine

PyLua includes a lightweight, linear-time pattern matching engine that avoids backtracking explosion vulnerabilities:

Class Matches Class Matches
%a Letters (a-z, A-Z) %A Non-letters
%d Digits (0-9) %D Non-digits
%s Whitespace characters %S Non-whitespace
%w Alphanumeric characters %W Non-alphanumeric
%x Hexadecimal digits %p Punctuation characters
pattern_matching.lua
text = "Contact: support@pylua.org, phone: +1-555-0199"

-- Extract email via captures ():
email = string.match(text, "[%w%.%-_]+@[%w%.%-_]+")
print("Found Email: " .. email)  -- support@pylua.org

-- Global substitution with string.gsub:
censored = string.gsub(text, "%d", "*")
print(censored)  -- "+1-***-****"

3. UTF-8 Unicode Library (`utf8`)

Standard string length #s returns the byte length. For accurate human-perceived character counts with emojis and international characters, use the utf8 module:

utf8_demo.lua
import utf8

greeting = "Hello, δΈ–η•Œ! πŸš€"

print(#greeting)          -- Raw byte length: 19 bytes
print(utf8.len(greeting)) -- Unicode character count: 12 codepoints

-- Iterate through UTF-8 codepoints:
for pos, code in utf8.codes(greeting) {
    print(string.format("Byte %02d: Codepoint U+%04X (%s)", pos, code, utf8.char(code)))
}