Last active
December 14, 2019 02:15
-
-
Save CaptainPRICE/64c7e447d1a3af93b260e909d72af98c to your computer and use it in GitHub Desktop.
"\u" string converter. Reference: https://msdn.microsoft.com/en-us/library/aa664669(v=vs.71).aspx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
local s = [[Hello\u003F World\u0021]] | |
------------------------------------------------------------------------------- | |
local string = string | |
local char, format, gmatch, gsub, sub = string.char, string.format, string.gmatch, string.gsub, string.sub | |
local tonumber = tonumber | |
local UESCAPE_PATTERN = "\\u([0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f][0-9A-Fa-f])" | |
-- Converts a fully uescaped string back to normal. | |
function string:from_uescape() | |
local out = "" | |
for i = 1, #self, 6 do | |
out = out .. char(tonumber(sub(self, i + 2, i + 5), 16)) | |
end | |
return out | |
end | |
-- Converts only portions of given uescaped string back to human readable one. Second return value is number/count of replacements made. | |
function string:from_uescape_parts() | |
return gsub(self, UESCAPE_PATTERN, function(uescape) | |
return char(tonumber(uescape, 16)) | |
end) | |
end | |
-- Converts a given string to uescaped one. | |
function string:to_uescape() | |
local out = "" | |
for i = 1, #self do | |
out = out .. format("\\u%.4X", sub(self, i, i):byte()) | |
end | |
return out | |
end | |
-- Returns an array of uescape matches that are converted back to normal in the given string. | |
function string:uescape_matches() | |
local out = {} | |
for uescape in gmatch(self, UESCAPE_PATTERN) do | |
out[#out + 1] = char(tonumber(uescape, 16)) | |
end | |
return out | |
end | |
------------------------------------------------------------------------------- | |
local s_uescaped = s:to_uescape() | |
print("uescaped:", s_uescaped) | |
print("uescaped from_uescape:", s_uescaped:from_uescape()) | |
print("uescaped from_uescape_parts:", s_uescaped:from_uescape_parts()) | |
print("from_uescape_parts:", s:from_uescape_parts()) | |
for _, m in next, s:uescape_matches() do | |
print(m) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment