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
| Type | Name | Description |
|---|---|---|
string | input | String to iterate over |
bool | lax | When true - skips validation and decodes even malformed sequences |
Returns
| Type | Name | Description |
|---|---|---|
function | iterator | Iterator function for use in a for loop, yielding byte_position, codepoint per character |
Examples
for pos, code in util.string.codes("AB€") do
core.engine.print("info", pos, code)
end
--[[
Output:
1 65
2 66
3 8364
]]local count = 0
for _ in util.string.codes("hello™") do
count = count + 1
end
core.engine.print("info", count) -- 6local 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'