使用Lua进行Unicode字符的字符串格式化

我正在尝试使用Unicode字符来对齐字符串。

但它不起作用。

空格不正确。:(

Lua版本为5.1。

问题在哪里?

local t =
{
    "字符",
    "루아",           -- 韩语
    "abc감사합니다123", -- 韩语
    "ab23",
    "lua很有趣",
    "ㅇㅅㅇ",
    "美国大将",         --中文
    "qwert-54321",
};

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

结果:----------------------------------------------
                     character
                        루아
          abc감사합니다123
                          ab23
                  lua is funny
                      ㅇㅅㅇ
                   美国大将
                   qwert-54321
点赞
用户1009479
用户1009479

ASCII 字符串都已经正确格式化,而非 ASCII 字符串则没有。

这是因为字符串的长度是按照其字节数进行计数的。例如,在 UTF-8 编码中,

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

因此,在 string.format%s 将这两个字符串视为其宽度为 12 / 6。

2016-08-18 03:52:45
用户1847592
用户1847592

```lua 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", "루아", -- 韩文 "abc감사합니다123", -- 韩文 "ab23", "lua is funny", "ㅇㅅㅇ", "美國大將", -- 中文 "qwert-54321", "∞" };

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

但是还有一个问题:在大多数字体中,韩文和中文符号的宽度比拉丁字母更宽。

2016-08-18 18:54:51