首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用string.format字符的Lua string.format

使用string.format字符的Lua string.format
EN

Stack Overflow用户
提问于 2016-03-10 07:59:07
回答 2查看 4.8K关注 0票数 6

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

示例:

代码语言:javascript
复制
local str = "\xE2\x88\x9E"
print(utf8.len(str), string.len(str))
print(str)
print(string.format("###%-5s###", str))
print(string.format("###%-5s###", 'x'))

输出:

代码语言:javascript
复制
1   3
∞
###∞  ###
###x    ###

看起来string.format使用的是无穷大符号的字节长度,而不是“字符长度”。是否有一个UTF-8 string.format当量?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-10 13:34:12

代码语言:javascript
复制
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    ###
票数 2
EN

Stack Overflow用户

发布于 2016-03-10 11:00:50

Lua添加了版本5.3的UTF-8库,功能很小,满足了最小的需求。它是“新鲜的”,并不是这种语言的焦点。您的问题是如何解释和呈现字符,但是图形不是标准库或Lua的常用用法。

现在,您应该修复输入的模式。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35910704

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档