Risclua Examples

lua-users home
wiki

Here, for comparison, is a RiscLua version of Base64 encoding/decoding.

#! lua
local char in string
local concat in table
local pairs = pairs

module "base64" -- exports encode,decode

  local f = \ (self, z) self[1 + #self] = z end
  local stk = \ ( ) => { push = f } end

  local C = { } -- encryption table
  for i = 0, 25 do
   C[i], C[26+i]  = char (65+i), char (97+i)  -- upper/lower case letters
  end
  for i = 52, 61 do C[i] = char (i-4) end -- digits
  C[62], C[63] = '-','_' -- 2 extra  +,/ for standard

  encode = \ (data)
     local bb, x, r = { }, stk ( ), nil
     for s = 0, #data - 1, 3 do
       for b = 1, 3 do bb[b] = (data:sub (s + b)):byte ( ) or 0 end
       r = #data - s
       x:push (C[bb[1] >> 2])
       x:push (C[((bb[1] % 4) << 4) | (bb[2] >> 4)] or "=")
       x:push (r>1 and C[((bb[2] % 16) << 2) | (bb[3] >> 6)] or "=")
       x:push (r>2 and C[bb[3] % 64] or "=")
      end -- for
      => concat (x) end -- function

  local B = { } -- decryption table
  for key, value in pairs (C) do B[value] = key end -- invert C

  decode = \ (data)
     local cc, y, n, j = { }, stk ( ), 256, nil
     for d = 0, #data - 1, 4 do
      for c = 1, 4 do j = d + c; cc[c] = B[data:sub (j,j) or "="] end
      y:push (char (((cc[1] << 2) % n) | (cc[2] >> 4)))
      y:push (cc[3] and char (((cc[2] << 4) % n) | (cc[3] >> 2)) or "")
      y:push (cc[4] and char ((((cc[3] << 6) % n) % 192) | cc[4]) or "")
     end -- for
     => concat (y) end -- function

-- end module

RecentChanges · preferences
edit · history
Last edited March 30, 2014 1:26 pm GMT (diff)