util.string.codes

Shared

Returns an iterator over each character's byte position and codepoint


Syntax

local iterator = util.string.codes(
    input,
    lax = false
)

This function's iterator returns byte positions not character positions.

Passing those positions into util.string.sub or util.string.byte - which now index by character will give incorrect results except by coincidence on pure-ASCII input.

Parameters

TypeNameDescription
stringinputString to iterate over
boollaxWhen true - skips validation and decodes even malformed sequences

Returns

TypeNameDescription
functioniteratorIterator function for use in a for loop, yielding byte_position, codepoint per character

Examples

Iterate over every character's position and codepoint
for pos, code in util.string.codes("AB€") do
    core.engine.print("info", pos, code)
end

--[[
Output:
1  65
2  66
3  8364
]]
Count the number of characters in a string
local count = 0

for _ in util.string.codes("hello™") do
    count = count + 1
end

core.engine.print("info", count) -- 6
Build a table of codepoints
local codes = {}

for _, code in util.string.codes("Lua") do
    util.table.insert(codes, code)
end

core.engine.print("info", util.table.concat(codes, " ")) -- '76 117 97'

On this page