如何使用包含UTF-8字符的字符串使用string.format获得“正确”格式?
示例:
local str = "\xE2\x88\x9E"
print(utf8.len(str), string.len(str))
print(str)
print(string.format("###%-5s###", str))
print(string.format("###%-5s###", 'x'))输出:
1 3
∞
###∞ ###
###x ###看起来string.format使用的是无穷大符号的字节长度,而不是“字符长度”。是否有一个UTF-8 string.format当量?
发布于 2016-03-10 13:34:12
function utf8.format(fmt, ...)
local args, strings, pos = {...}, {}, 0
for spec in fmt:gmatch'%%.-([%a%%])' do
pos = pos + 1
local s = args[pos]
if spec == 's' and type(s) == 'string' and s ~= '' then
table.insert(strings, s)
args[pos] = '\1'..('\2'):rep(utf8.len(s)-1)
end
end
return (
fmt:format(table.unpack(args))
:gsub('\1\2*', function() return table.remove(strings, 1) end)
)
end
local str = "\xE2\x88\x9E"
print(string.format("###%-5s###", str)) --> ###∞ ###
print(string.format("###%-5s###", 'x')) --> ###x ###
print(utf8.format ("###%-5s###", str)) --> ###∞ ###
print(utf8.format ("###%-5s###", 'x')) --> ###x ###发布于 2016-03-10 11:00:50
Lua添加了版本5.3的UTF-8库,功能很小,满足了最小的需求。它是“新鲜的”,并不是这种语言的焦点。您的问题是如何解释和呈现字符,但是图形不是标准库或Lua的常用用法。
现在,您应该修复输入的模式。
https://stackoverflow.com/questions/35910704
复制相似问题