string/table扩展模块新增几个方法用于数据打包/解包

This commit is contained in:
MrZ626
2021-06-06 17:29:57 +08:00
parent f9ed93641c
commit 628365cb49
4 changed files with 89 additions and 30 deletions

View File

@@ -1,3 +1,4 @@
local data=love.data
local STRING={}
local int,format=math.floor,string.format
local find,sub,upper=string.find,string.sub,string.upper
@@ -16,10 +17,10 @@ do--function STRING.shiftChar(c)
end
end
function STRING.trim(str)
if not str:find("%S")then return""end
str=str:sub((str:find("%S"))):reverse()
return str:sub((str:find("%S"))):reverse()
function STRING.trim(s)
if not s:find("%S")then return""end
s=s:sub((s:find("%S"))):reverse()
return s:sub((s:find("%S"))):reverse()
end
function STRING.split(s,sep,regex)
@@ -63,16 +64,16 @@ function STRING.time(s)
end
end
do--function STRING.urlEncode(str)
do--function STRING.urlEncode(s)
local rshift=bit.rshift
local b16={[0]='0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'}
function STRING.urlEncode(str)
function STRING.urlEncode(s)
local out=""
for i=1,#str do
if str:sub(i,i):match("[a-zA-Z0-9]")then
out=out..str:sub(i,i)
for i=1,#s do
if s:sub(i,i):match("[a-zA-Z0-9]")then
out=out..s:sub(i,i)
else
local b=str:byte(i)
local b=s:byte(i)
out=out.."%"..b16[rshift(b,4)]..b16[b%16]
end
end
@@ -80,4 +81,25 @@ do--function STRING.urlEncode(str)
end
end
function STRING.packBin(s)
return data.encode('string','base64',data.compress('string','zlib',s))
end
function STRING.packText(s)
return data.encode('string','base64',data.compress('string','gzip',s))
end
function STRING.unpackBin(str)
local res
res,str=pcall(data.decode,'string','base64',str)
if not res then return end
res,str=pcall(data.decompress,'string','zlib',str)
if res then return str end
end
function STRING.unpackText(str)
local res
res,str=pcall(data.decode,'string','base64',str)
if not res then return end
res,str=pcall(data.decompress,'string','gzip',str)
if res then return str end
end
return STRING