2011-11-02 41 views
6

一個Unicode符號我怎麼能寫在Lua一個Unicode符號。例如,我有寫符號與9658
當我寫如何寫盧阿

string.char(9658); 

我得到了一個錯誤。那麼怎麼寫這樣的符號呢?

+1

這將有助於瞭解什麼編碼要在生成的字符串 – MattJ

回答

12

的Lua不看裏面的字符串。所以,你可以只寫

mychar = "►" 

(2015年加入)

的Lua 5.3 UTF-8轉義序列推出支持:

Unicode字符的UTF-8編碼可插入在文本字符串與轉義序列\∪{XXX}(注意強制封閉括號中),其中XXX是表示字符碼點的一個或多個十六進制數字的序列。

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

+2

請注意,這隻有在文件本身是UTF-8編碼時纔有效。當然,除非是ASCII或UTF-8,否則你不能在解釋器上使用Lua腳本。 –

2

也許這可以幫助你:

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 
+2

我很確定這個功能與他想要的相反。他有一個他想用UTF-8編碼的Unicode代碼點。 –

+0

對面也可以走很長一段路! :) – 2011-12-21 03:13:18

2

要獲得Unicode字符串的內容更廣泛的支持,一種方法是被開發作爲塞勒涅數據庫庫的一部分slnunicode。它將爲您提供一個模塊,支持標準的string庫的大部分功能,但支持Unicode字符和UTF-8編碼。

3

下面是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.