7

我有一张这样的桌子

table = {57,55,0,15,-25,139,130,-23,173,148,-24,136,158}

它是由 php 解包函数编码的 utf8 字节数组

unpack('C*',$str);

如何将其转换为我可以在 lua 中读取的 utf-8 字符串?

4

2 回答 2

5

Lua 没有提供将数字形式的 utf-8 字节表转换为 utf-8 字符串文字的直接函数。但是在以下帮助下为此编写一些东西很容易string.char

function utf8_from(t)
  local bytearr = {}
  for _, v in ipairs(t) do
    local utf8byte = v < 0 and (0xff + v + 1) or v
    table.insert(bytearr, string.char(utf8byte))
  end
  return table.concat(bytearr)
end

请注意,lua 的标准函数或提供的字符串工具都不支持 utf-8。如果您尝试print从上述函数返回 utf-8 编码字符串,您只会看到一些时髦的符号。如果您需要更广泛的 utf-8 支持,您需要查看lua wiki中提到的一些库。

于 2013-09-09T08:59:26.450 回答
4

这是一个适用于 RFC 3629 限制的 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

function utf8frompoints(...)
  local chars,arg={},{...}
  for i,n in ipairs(arg) do chars[i]=utf8(arg[i]) end
  return table.concat(chars)
end

print(utf8frompoints(72, 233, 108, 108, 246, 32, 8364, 8212))
--> Héllö €—
于 2014-09-26T05:18:44.930 回答