Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting with unicode characters using Lua

I trying to align string with unicode characters.
But it doesn't works.
Spaces is not correct. :(
Lua's version is 5.1.
What is the problem?

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
like image 854
ddubie Avatar asked Feb 12 '26 11:02

ddubie


1 Answers

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

But there is another problem: on most fonts korean and chinese symbols are wider than latin letters.

like image 157
Egor Skriptunoff Avatar answered Feb 15 '26 18:02

Egor Skriptunoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!