使用UTF8字符的Lua string.format

马里奥

如何使用string.format和包含UTF-8字符的字符串获得“正确”格式?

例:

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?

埃格·斯克里普诺夫(Egor Skriptunoff)
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    ###

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章