You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 line
1.8 KiB

  1. Utf16 = {}
  2. -- 支持这种写法:local str = L"测试的Utf16字符串"
  3. function L(utf8String)
  4. return Utf16:create(utf8String)
  5. end
  6. -- 从Utf8字符串构造一个Utf16字符串
  7. function Utf16:create(value)
  8. local instance = {}
  9. if type(value) == "string" then
  10. instance.s = utf8.utf8_to_utf16(value);
  11. elseif type(value) == "number" then
  12. instance.s = utf8.utf16_char(value);
  13. else
  14. instance.s = "";
  15. end
  16. setmetatable(instance , Utf16);
  17. return instance;
  18. end
  19. -- 返回utf8字符串
  20. function Utf16:str()
  21. return utf8.utf16_to_utf8(self.s);
  22. end
  23. -- 获得长度
  24. function Utf16:__len()
  25. return self:len();
  26. end
  27. -- 获得长度
  28. function Utf16:len()
  29. return string.len(self.s) / 2;
  30. end
  31. -- 等于符号
  32. function Utf16:__eq(target)
  33. return self.s == target.s;
  34. end
  35. -- 连接字符串
  36. function Utf16:__concat(target)
  37. local sourceLength = string.len(self.s);
  38. if sourceLength > 0 then
  39. self.s = string.sub(self.s , 0 , string.len(self.s)) .. target
  40. else
  41. self.s = target;
  42. end
  43. return self;
  44. end
  45. -- 获取一个子字符串
  46. function Utf16:sub(startIndex , endIndex)
  47. if endIndex == -1 or endIndex == nil then
  48. endIndex = startIndex;
  49. end
  50. local str = Utf16:create();
  51. str.s = string.sub(self.s , startIndex * 2 - 1 , endIndex * 2);
  52. return str;
  53. end
  54. -- 通过str[1] = 123的形式赋值
  55. function Utf16:__newindex(index , value)
  56. error("不允许对Utf16进行[]=赋值")
  57. -- local up = math.floor(value / 256);
  58. --
  59. -- local startIndex = index * 2 - 1;
  60. -- self.s[startIndex] = value - up * 256;
  61. -- self.s[startIndex + 1] = up;
  62. end
  63. -- 通过str[1]的形式获取第几个字符,返回Utf16字符数值
  64. function Utf16:__index(index)
  65. if type(index) == "number" then
  66. local startIndex = index * 2 - 1;
  67. local ch1 , ch2 = string.byte(self.s , startIndex , startIndex + 1);
  68. return ch2 * 256 + ch1;
  69. else
  70. return Utf16[index]
  71. end
  72. end