【发布时间】:2015-08-28 19:47:55
【问题描述】:
如何在 lua 中编写 Unicode 符号。例如我必须用 9658 写符号
当我写的时候
string.char( 9658 );
我遇到了一个错误。那怎么可能写出这样的符号呢。
【问题讨论】:
-
了解您希望生成的字符串采用何种编码会有所帮助。
如何在 lua 中编写 Unicode 符号。例如我必须用 9658 写符号
当我写的时候
string.char( 9658 );
我遇到了一个错误。那怎么可能写出这样的符号呢。
【问题讨论】:
Lua 不查看字符串内部。所以,你可以写
mychar = "►"
(2015年添加)
Lua 5.3 引入了对 UTF-8 转义序列的支持:
Unicode 字符的 UTF-8 编码可以插入到带有转义序列 \u{XXX} 的文字字符串中(注意强制括起来的括号),其中 XXX 是代表字符的一个或多个十六进制数字的序列代码点。
您也可以使用utf8.char(9658)。
【讨论】:
这是一个 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.
【讨论】:
也许这可以帮助你:
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 字符串内容的更广泛支持,一种方法是 slnunicode,它是作为 Selene 数据库库的一部分开发的。它将为您提供一个模块,该模块支持标准 string 库的大部分功能,但使用 Unicode 字符和 UTF-8 编码。
【讨论】: