如何在Lua中编写Unicode符号

如何在Lua中编写Unicode符号。例如我必须编写符号9658。

当我写

string.char(9658);

我得到了一个错误。那么如何编写这样的符号呢?

原文链接 https://stackoverflow.com/questions/7983574

点赞
stackoverflow用户1004962
stackoverflow用户1004962
function FromUTF8(pos)
  local mod = math.mod
  local function charat(p)
    local v = editor.CharAt[p]; if v < 0 then v = v + 256 end; return v
  end
  local v, c, n = 0, charat(pos), 1
  if c < 128 then v = c
  elseif c < 192 then
    error("字节值从0x80到0xBF之间不能开始一个多字节序列")
  elseif c < 224 then v = mod(c, 32); n = 2
  elseif c < 240 then v = mod(c, 16); n = 3
  elseif c < 248 then v = mod(c,  8); n = 4
  elseif c < 252 then v = mod(c,  4); n = 5
  elseif c < 254 then v = mod(c,  2); n = 6
  else
    error("字节值从0xFE到0xFF之间不能开始一个多字节序列")
  end
  for i = 2, n do
    pos = pos + 1; c = charat(pos)
    if c < 128 or c > 191 then
      error("以下字节必须有0x80到0xBF之间的值")
    end
    v = v * 64 + mod(c, 64)
  end
  return v, pos, n
end
2011-11-02 16:13:43
stackoverflow用户107090
stackoverflow用户107090

Lua 不会查看字符串内容。所以,你可以直接写

mychar = "â–º"

(2015年添加)

Lua 5.3 引入了对 UTF-8 转义序列的支持:

一个 Unicode 字符的 UTF-8 编码可以通过转义序列 \u{XXX}(注意必须要有括号)插入到字面字符串中,其中 XXX 表示字符代码点的一个或多个十六进制数字的序列。

你也可以使用 utf8.char(9658)

2011-11-02 16:18:37
stackoverflow用户68204
stackoverflow用户68204

为了获得更广泛的支持,Unicode字符串内容的一种方法是 slnunicode,它是 Selene 数据库库的一部分。它将为您提供一个支持大多数标准 string 库功能的模块,但使用 Unicode 字符和 UTF-8 编码。

2011-11-03 05:26:34
stackoverflow用户405017
stackoverflow用户405017

下面是一个 Lua 的编码器,它接受一个 Unicode 码点并产生相应字符的 UTF-8 字符串:

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.
2014-09-27 03:33:49