MattiasBuelens

Common class

Jun 16th, 2012
75
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 0.78 KB | None | 0 0
  1. --[[
  2.  
  3.     Common utilities
  4.     Classes
  5.  
  6. --]]
  7.  
  8. common = common or {}
  9.  
  10. -- Lookup in list of tables
  11. local function search(k, plist)
  12.     for i=1, table.getn(plist) do
  13.         local v = plist[i][k]
  14.         if v ~= nil then return v end
  15.     end
  16. end
  17.  
  18. -- Define class with multiple inheritance
  19. function common.newClass(...)
  20.     local c = {}
  21.     local parents = { ... }
  22.  
  23.     -- Class searches for each method
  24.     -- in the list of its parents
  25.     setmetatable(c, {
  26.         __index = function(t, k)
  27.             return search(k, parents)
  28.         end
  29.     })
  30.  
  31.     -- Prepare 'c' to be the metatable of its instances
  32.     c.__index = c
  33.  
  34.     -- Define constructor for this new class
  35.     function c:new(o)
  36.         o = o or {}
  37.         setmetatable(o, c)
  38.        
  39.         -- Call constructor
  40.         if o.init then o:init() end
  41.  
  42.         return o
  43.     end
  44.  
  45.     -- Return new class
  46.     return c
  47. end
Advertisement
Add Comment
Please, Sign In to add comment