Advertisement
theoriginalbit

Data Structure: Stack

Aug 26th, 2013
363
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.04 KB | None | 0 0
  1. local Stack = {
  2.   new = function(...)
  3.     local data = {...}
  4.  
  5.     local obj = setmetatable({}, {
  6.       __newindex = function(self, key, value)
  7.         if type(value) == "function" then
  8.           local func = setmetatable({}, {
  9.             __call = function(_, ...)
  10.               if rawequal(self, ({...})[1]) then
  11.                 return value(...)
  12.               end
  13.               return value(self, ...)
  14.             end;
  15.           })
  16.           rawset(self, key, func)
  17.         else
  18.           rawset(self, key, value)
  19.         end
  20.       end;
  21.     })
  22.  
  23.     function obj.push(self, value)
  24.       data[#data+1] = value
  25.       return self
  26.     end
  27.  
  28.     function obj.pop(self)
  29.       assert(not self.isEmpty(), "stack underflow")
  30.       return table.remove(data)
  31.     end
  32.  
  33.     function obj.size(self)
  34.       return #data
  35.     end
  36.  
  37.     function obj.isEmpty(self)
  38.       return self.size() == 0
  39.     end
  40.  
  41.     function obj.top(self)
  42.       assert(not self.isEmpty(), "stack underflow")
  43.       return data[#data]
  44.     end
  45.  
  46.     return obj
  47.   end
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement