Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a unicode symbol in lua

Tags:

unicode

lua

How can I write a Unicode symbol in lua. For example I have to write symbol with 9658
when I write

string.char( 9658 );

I got an error. So how is it possible to write such a symbol.

like image 660
unresolved_external Avatar asked Nov 02 '11 16:11

unresolved_external


2 Answers

Lua does not look inside strings. So, you can just write

mychar = "►"

(added in 2015)

Lua 5.3 introduced support for UTF-8 escape sequences:

The UTF-8 encoding of a Unicode character can be inserted in a literal string with the escape sequence \u{XXX} (note the mandatory enclosing brackets), where XXX is a sequence of one or more hexadecimal digits representing the character code point.

You can also use utf8.char(9658).

like image 86
lhf Avatar answered Oct 07 '22 03:10

lhf


Here is an encoder for Lua that takes a Unicode code point and produces a UTF-8 string for the corresponding character:

do
  local bytemarkers = { {0x7FF,192}, {0xFFFF,224}, {0x1FFFFF,240} }
  function utf8(decimal)
    if decimal<128 then return string.char(decimal) end
    local charbytes = {}
    for bytes,vals in ipairs(bytemarkers) do
      if decimal<=vals[1] then
        for b=bytes+1,2,-1 do
          local mod = decimal%64
          decimal = (decimal-mod)/64
          charbytes[b] = string.char(128+mod)
        end
        charbytes[1] = string.char(vals[2]+decimal)
        break
      end
    end
    return table.concat(charbytes)
  end
end

c=utf8(0x24)    print(c.." is "..#c.." bytes.") --> $ is 1 bytes.
c=utf8(0xA2)    print(c.." is "..#c.." bytes.") --> ¢ is 2 bytes.
c=utf8(0x20AC)  print(c.." is "..#c.." bytes.") --> € is 3 bytes.  
c=utf8(0x24B62) print(c.." is "..#c.." bytes.") --> 𤭢 is 4 bytes.   
like image 42
Phrogz Avatar answered Oct 07 '22 02:10

Phrogz