init.lua 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. --[[
  2. Class system
  3. @author : Siapran Candoris
  4. Supports memoized multiple inheritance
  5. ]]--
  6. local ipairs = ipairs
  7. do
  8. local function metatable_search( k, list )
  9. for _,e in ipairs(list) do
  10. local v = e[k]
  11. if v then return v end
  12. end
  13. end
  14. local function metatable_cache( self, k )
  15. local v = metatable_search(k, self.__parents)
  16. self[k] = v
  17. return v
  18. end
  19. -- genealogy is
  20. local function make_genealogy( self, res, has )
  21. res = res or {}
  22. has = has or {}
  23. local parents = self.__parents
  24. if has[self] then
  25. return
  26. end
  27. if parents and #parents > 0 then
  28. for _,parent in ipairs(parents) do
  29. make_genealogy(parent, res, has)
  30. end
  31. end
  32. res[#res + 1] = self
  33. has[self] = true
  34. return res
  35. end
  36. -- make a class with simple or multiple inheritance
  37. -- inheritance is implemented as cached first found
  38. -- do NOT change class methods at runtime, just don't
  39. function make_class( ... )
  40. local res = {}
  41. res.__parents = {...}
  42. res.__genealogy = make_genealogy(res)
  43. res.__instanceof_cache = {}
  44. -- inherited methods are cached to improve runtime performance
  45. -- caching is done per class, not per object
  46. if #res.__parents > 0 then
  47. setmetatable(res, {__index = metatable_cache})
  48. end
  49. res.__index = res
  50. return res
  51. end
  52. end
  53. return make_class