Risclua 示例

lua-users home
wiki

这里,为了比较,是一个 RiscLua 版本的 Base64 编码/解码。

#! 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

最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2014 年 3 月 30 日下午 1:26 GMT (差异)