2016-08-18 128 views
2

我试图将字符串与unicode字符对齐。
但它不起作用。
空格不正确。 :(
Lua的版本为5.1。
这是什么问题?
使用Lua使用unicode字符进行字符串格式化

local t = 
{ 
    "character", 
    "루아",   -- korean 
    "abc감사합니다123", -- korean 
    "ab23", 
    "lua is funny", 
    "ㅇㅅㅇ", 
    "美國大將",   --chinese 
    "qwert-54321", 
}; 

for k, v in pairs(t) do 
    print(string.format("%30s", v)); 
end 


result:---------------------------------------------- 
        character 
         루아 
      abc감사합니다123 
          ab23 
        lua is funny 
         ㅇㅅㅇ 
        美國大將 
        qwert-54321 
+0

格式化Unicode字符可能会非常棘手,因为每个字符不仅在编码时需要可变数量的字节,而且在显示时还会使用可变数量的列。对Luarocks进行快速搜索时,[wcwidth](https://luarocks.org/modules/aperezdc/wcwidth)库看起来与您正在尝试执行的操作相关。 – hugomg

回答

2

的ASCII字符串的所有格式正确无误,而对非ASCII字符串不是。

的原因是因为,串的长度进行计数与它们的字节数。例如,对于UTF-8编码,

print(string.len("美國大將")) -- 12 
print(string.len("루아"))  -- 6 

所以%sstring.format对待这两个字符串,如果他们的宽度是12/6

+0

谢谢。了解。 :d – ddubie

0
function utf8format(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(#s:gsub("[\128-\191]", "")-1) 
     end 
    end 
    return (fmt:format((table.unpack or unpack)(args)) 
     :gsub('\1\2*', function() return table.remove(strings, 1) end) 
    ) 
end 

local t = 
{ 
    "character", 
    "루아",   -- korean 
    "abc감사합니다123", -- korean 
    "ab23", 
    "lua is funny", 
    "ㅇㅅㅇ", 
    "美國大將",   --chinese 
    "qwert-54321", 
    "∞" 
}; 

for k, v in pairs(t) do 
    print(utf8format("%30s", v)); 
end 

但是还有一个问题,因为:在大多数字体韩国和中国符号比拉丁字母宽。

相关问题