class.lua 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. function class(name)
  2. local cls = {}
  3. cls.__classname = name
  4. cls.__tostring = function(c)
  5. return "Class of type "..c.__classname
  6. end
  7. cls.__newindex = function(t,k,v)
  8. retVal = false
  9. if t["__setvar"] ~= nil then
  10. retVal = t["__setvar"](t,k,v)
  11. end
  12. if retVal == false then
  13. rawset(t,k,v)
  14. end
  15. end
  16. cls.__index = function(t,k)
  17. local prototype = rawget(t,"__prototype")
  18. if prototype ~= nil then
  19. ret = rawget(prototype,k)
  20. if ret ~= nil then return ret end
  21. end
  22. if k ~= "__index" and k ~= "__getvar" then
  23. if t["__getvar"] ~= nil then
  24. local ret = t["__getvar"](t,k)
  25. if ret ~= nil then return ret end
  26. end
  27. return rawget(t,k)
  28. end
  29. end
  30. _G[name] = setmetatable(cls, {
  31. __call = function (c, ...)
  32. local instance = setmetatable({}, cls)
  33. instance.__prototype = cls
  34. if cls[name] then
  35. cls[name](instance, ...)
  36. end
  37. return instance
  38. end})
  39. return function(superclass)
  40. if type(superclass) == 'table' then
  41. cls[superclass.__classname] = {}
  42. setmetatable(cls[superclass.__classname], superclass)
  43. for i,v in pairs(superclass) do
  44. if cls[i] == nil then
  45. cls[i] = v
  46. else
  47. cls[superclass.__classname][i] = v
  48. end
  49. end
  50. cls.__baseclass = superclass
  51. end
  52. end
  53. end