Fooksie

fCompress/fRead

Sep 1st, 2013
321
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.25 KB | None | 0 0
  1. --[[
  2.     fCompress/fRead usage
  3.     playerStats={
  4.         wins=123,
  5.         loses=456
  6.         }
  7.  
  8.     --variable names don't take up space in the file!
  9.     playerStatNames={"wins","loses"}
  10.  
  11.     --stats are only 2 bytes each!
  12.     playerStatBytes={2,2}
  13.  
  14.     --fCompress
  15.     local savedata=fCompress({playerStats.wins,playerStats.loses},playerStatBytes)
  16.     #savedata --only 4 bytes!
  17.  
  18.     --fRead
  19.     local statArray=fRead(savedata,playerStatBytes)
  20.     for i,stat in ipairs(playerStatNames) do
  21.         playerStats[stat]=statArray[i]
  22.         end
  23.  
  24.     --Byte size
  25.     --1 bytes max # 256^1-1 = 255
  26.     --2 bytes max # 256^2-1 = 65535
  27.     --3 bytes max # 256^3-1 = 16777215
  28.     --4 bytes max # 256^4-1 = 4294967295
  29. ]]--
  30.  
  31. function fCompress(nArray,nSizeArray)
  32.     local output={}
  33.     for i,bytes in ipairs(nSizeArray) do
  34.         nArray[i]=math.min(nArray[i],256^bytes-1)
  35.         local mod=0
  36.         for ii=0,bytes-1 do
  37.             mod=(nArray[i]-mod)/256^ii%256
  38.             table.insert(output,string.char(mod))
  39.             end
  40.         end
  41.     return table.concat(output)
  42.     end
  43.  
  44. function fRead(fString,nSizeArray)
  45.     local output={}
  46.     local index=1
  47.     for i,bytes in ipairs(nSizeArray) do
  48.         local number=0
  49.         for i=0,bytes-1 do
  50.             number=number+string.byte(string.sub(fString,index+i,index+i))*256^i
  51.             end
  52.         table.insert(output,number)
  53.         index=index+bytes
  54.         end
  55.     return output
  56.     end
Advertisement
Add Comment
Please, Sign In to add comment