示例工程 04-strings
04-strings/03-utf8-vs-bytes/main.lua
-- @runtimes lua54
--- 演示:# 是字节数,utf8.len 才是码点数;非法 UTF-8 返回 nil,pos。
local M = {}
--- @return table { bytes = integer, chars = integer|nil, bad_pos = integer|nil }
function M.run(log)
log = log or print
local text = "中文"
local bytes = #text
local chars = utf8.len(text)
local bad_chars, bad_pos = utf8.len("\xff\xfe")
log(("bytes=%d"):format(bytes))
log(("chars=%d"):format(chars))
log(("bad_is_nil=%s"):format(tostring(bad_chars == nil)))
log(("bad_pos=%s"):format(tostring(bad_pos)))
return { bytes = bytes, chars = chars, bad_pos = bad_pos }
end
if not ... then
M.run()
end
return M