Advertisement
Sebi

Computer Craft URL helper lib

Jul 9th, 2012
334
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.46 KB | None | 0 0
  1.  
  2. local strlib = {}
  3. strlib.findpattern = function( haystack, seed, start )
  4.   return string.sub(haystack, string.find(haystack, seed, start))
  5. end
  6.  
  7. strlib.explode = function(haystack, seed)
  8.   if seed == '' then return haystack end
  9.   local pos, arr = 0, {}
  10.   for st, sp in function() return string.find(haystack,seed,pos,true) end do
  11.     arr[#arr+1] = string.sub(haystack,pos,st-1)
  12.     pos = sp+1
  13.   end
  14.   arr[#arr+1] = string.sub(haystack,pos)
  15.   return arr
  16. end
  17.  
  18. local hex = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"}
  19. local hex2dec = {}
  20. for k, v in pairs(hex) do
  21.   hex2dec[v] = k-1
  22. end
  23.  
  24. strlib.urlencode = function(str)
  25.   local out = ""
  26.   local c = 1
  27.   while c <= #str do
  28.     local chr = string.sub(str,c,c)
  29.     local val = string.byte(chr)
  30.     if(val>=48 and val<=57) or
  31.       (val>=65 and val<=90) or
  32.       (val>=97 and val<=122) then
  33.       out = out..chr
  34.     else
  35.       out = out.."%"..hex[1+math.floor(val/16)]
  36.             ..hex[1+(val%16)]
  37.     end
  38.     c = c+1
  39.   end
  40.   return out
  41. end
  42.  
  43. strlib.urldecode = function(str)
  44.   local out = ""
  45.   local c = 0
  46.   while c <= #str do
  47.     local chr = string.sub(str,c,c)
  48.     if chr ~= "%" then
  49.       out = out .. chr
  50.     else
  51.       if #str < c+2 then return out end
  52.       local code1 = string.sub(str,c+1,c+1)
  53.       local code2 = string.sub(str,c+2,c+2)
  54.      
  55.       out = out..string.char(hex2dec[code1]*16+hex2dec[code2])
  56.       c = c+2
  57.     end
  58.     c=c+1
  59.   end
  60.   return out
  61. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement