【问题标题】:How to write a unicode symbol in lua如何在lua中写一个unicode符号
【发布时间】:2015-08-28 19:47:55
【问题描述】:

如何在 lua 中编写 Unicode 符号。例如我必须用 9658 写符号
当我写的时候

string.char( 9658 );

我遇到了一个错误。那怎么可能写出这样的符号呢。

【问题讨论】:

  • 了解您希望生成的字符串采用何种编码会有所帮助。

标签: unicode lua


【解决方案1】:

Lua 不查看字符串内部。所以,你可以写

mychar = "►"

(2015年添加)

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

Unicode 字符的 UTF-8 编码可以插入到带有转义序列 \u{XXX} 的文字字符串中(注意强制括起来的括号),其中 XXX 是代表字符的一个或多个十六进制数字的序列代码点。

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

【讨论】:

  • 请注意,这仅在文件本身是 UTF-8 编码的情况下才有效。当然,除非它是 ASCII 或 UTF-8,否则你不能将 Lua 脚本推送到解释器。
【解决方案2】:

这是一个 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.   

【讨论】:

    【解决方案3】:

    也许这可以帮助你:

        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("Byte values between 0x80 to 0xBF cannot start a multibyte sequence")
      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("Byte values between 0xFE and OxFF cannot start a multibyte sequence")
      end
      for i = 2, n do
        pos = pos + 1; c = charat(pos)
        if c < 128 or c > 191 then
          error("Following bytes must have values between 0x80 and 0xBF")
        end
        v = v * 64 + mod(c, 64)
      end
      return v, pos, n
    end
    

    【讨论】:

    • 我很确定这个功能与他想要的相反。他有一个 Unicode 代码点,他想用 UTF-8 编码。
    • 对面也有很长的路要走! :)
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2013-05-13
      • 2018-05-06
      • 2014-06-14
      • 2011-01-26
      • 2012-09-19
      • 2015-05-08
      • 1970-01-01
      • 2018-07-03
      • 2021-12-14
      相关资源
      最近更新 更多