Utf16 = {} -- 支持这种写法:local str = L"测试的Utf16字符串" function L(utf8String) return Utf16:create(utf8String) end -- 从Utf8字符串构造一个Utf16字符串 function Utf16:create(value) local instance = {} if type(value) == "string" then instance.s = utf8.utf8_to_utf16(value); elseif type(value) == "number" then instance.s = utf8.utf16_char(value); else instance.s = ""; end setmetatable(instance , Utf16); return instance; end -- 返回utf8字符串 function Utf16:str() return utf8.utf16_to_utf8(self.s); end -- 获得长度 function Utf16:__len() return self:len(); end -- 获得长度 function Utf16:len() return string.len(self.s) / 2; end -- 等于符号 function Utf16:__eq(target) return self.s == target.s; end -- 连接字符串 function Utf16:__concat(target) local sourceLength = string.len(self.s); if sourceLength > 0 then self.s = string.sub(self.s , 0 , string.len(self.s)) .. target else self.s = target; end return self; end -- 获取一个子字符串 function Utf16:sub(startIndex , endIndex) if endIndex == -1 or endIndex == nil then endIndex = startIndex; end local str = Utf16:create(); str.s = string.sub(self.s , startIndex * 2 - 1 , endIndex * 2); return str; end -- 通过str[1] = 123的形式赋值 function Utf16:__newindex(index , value) error("不允许对Utf16进行[]=赋值") -- local up = math.floor(value / 256); -- -- local startIndex = index * 2 - 1; -- self.s[startIndex] = value - up * 256; -- self.s[startIndex + 1] = up; end -- 通过str[1]的形式获取第几个字符,返回Utf16字符数值 function Utf16:__index(index) if type(index) == "number" then local startIndex = index * 2 - 1; local ch1 , ch2 = string.byte(self.s , startIndex , startIndex + 1); return ch2 * 256 + ch1; else return Utf16[index] end end