Advertisement
Symmetryc

BBit API

Jun 1st, 2013
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. -- B (Bit) API, By Symmetryc
  2. ase = function(n, b)
  3.     if b==2 then
  4.         local t = string.format("%f", n):find("%.") and {string.format("%f", n):match("(%d*)(.%d*)")} or {n, "0"}
  5.         local stack =  {"", ""}    
  6.         while t[1]~=0 do
  7.             local char = t[1]%2
  8.             t[1] = math.floor(t[1]/2)
  9.             stack[1] = char..stack[1]
  10.         end
  11.         for i=1, 15-#stack[1] do
  12.             local char = math.floor(t[2]*2)
  13.             t[2] = (t[2]*2)%1
  14.             stack[2] = stack[2]..char
  15.         end
  16.         return tonumber(stack[1].."."..stack[2])
  17.     elseif b==10 then
  18.         n = string.format("%f", n)
  19.         local stack = 0
  20.         local len = n:find("%.") and #(n:match("(.-)%.")) or #n
  21.         local i = len
  22.         for char in n:gmatch("%d") do i = i-1 stack = stack+char*(2^i) end
  23.         return stack
  24.     end
  25. end
  26. inary = function(n)
  27.     local mt = {
  28.         __newindex = function(self, key, value) error("attempt to index "..self[1]..", a binary value") end;
  29.         __call = function(self, ...) error("attempt to call "..self[1]..", a binary value") end;
  30.         __metatable = "b";
  31.         __tostring = function(self) return string.format("%f", self[1]) end;
  32.         __unm = function(self) return -self[1] end;
  33.     }
  34.     for k, v in pairs({add="+",sub="-",mul="*",div="/",mod="%",pow="^"}) do
  35.         mt["__"..k] = setfenv(loadstring("return function(l,r) return ase(ase(l[1],10)"..v.."ase(r[1],10),2) end"), getfenv())()
  36.     end
  37.     for k, v in pairs({concat="..",eq="==",lt="<",le="<="}) do
  38.         mt["__"..k] = setfenv(loadstring("return function(l,r) return l[1]"..v.."r[1] end"), getfenv())()
  39.     end
  40.     local t = setmetatable({n}, mt)
  41.     local gate = function(n, a, f) local v = n for i=1, #a do v = f(string.format("%f", v+a[i][1])) end return v end
  42.     t:bnot = function() return tonumber(tostring(self):gsub("0", "O"):gsub("1", "0"):gsub("O", "0") end) end
  43.     t:bor = function(...) return gate(self[1], arg, function(n) return n:gsub("2", "1") end) end
  44.     t:band = function(...) return gate(self[1], arg, function(n) return n:gsub("1", "0"):gsub("2", "1") end) end
  45.     t:bxor = function(...) return gate(self[1], arg, function(n) return n:gsub("2", "0") end) end
  46.     t:bshift = function(n) return self[1]*10^n end
  47.     return t
  48. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement