Advertisement
Guest User

Untitled

a guest
Aug 24th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. -- wengwengweng
  2.  
  3. local int = {}
  4.  
  5. local function class(specs)
  6.  
  7. local struct = {}
  8. local types = {}
  9. local fns = {}
  10.  
  11. local super = specs.__super
  12.  
  13. if type(super) == "table" then
  14.  
  15. local super_types = super.__types
  16. local super_fns = super.__fns
  17.  
  18. if type(super_types) == "table" then
  19. for k, v in pairs(super_types) do
  20. types[k] = v
  21. end
  22. end
  23.  
  24. if type(super_fns) == "table" then
  25. for k, v in pairs(super_fns) do
  26. fns[k] = v
  27. end
  28. end
  29.  
  30. end
  31.  
  32. for k, v in pairs(specs) do
  33. if type(v) == "table" then
  34. if v == string then
  35. types[k] = "string"
  36. elseif v == int then
  37. types[k] = "number"
  38. end
  39. elseif type(v) == "function" then
  40. fns[k] = v
  41. else
  42. error("expected type or function")
  43. end
  44. end
  45.  
  46. struct.__types = types
  47. struct.__fns = fns
  48.  
  49. setmetatable(struct, {
  50.  
  51. __call = function()
  52.  
  53. local obj = {}
  54. local proxy = {}
  55.  
  56. for k, v in pairs(fns) do
  57. obj[k] = function()
  58. v(obj)
  59. end
  60. end
  61.  
  62. setmetatable(obj, {
  63.  
  64. __index = function(self, k)
  65. return proxy[k]
  66. end,
  67.  
  68. __newindex = function(self, k, v)
  69.  
  70. local expected_type = types[k]
  71. local actual_type = type(v)
  72.  
  73. if not expected_type then
  74. error("failed to set " .. k)
  75. else
  76. if actual_type ~= expected_type then
  77. error("expected " .. expected_type .. ", found " .. actual_type)
  78. end
  79. end
  80.  
  81. proxy[k] = v
  82.  
  83. end,
  84.  
  85. })
  86.  
  87. return obj
  88.  
  89. end,
  90.  
  91. })
  92.  
  93. return struct
  94.  
  95. end
  96.  
  97. local A = class {
  98. name = string,
  99. age = int,
  100. foo = function(self)
  101. print("from A", self.name, self.age)
  102. end
  103. }
  104.  
  105. local B = class {
  106. __super = A,
  107. foo = function(self)
  108. print("from B", self.name, self.age)
  109. end
  110. }
  111.  
  112. local a = A()
  113.  
  114. a.name = "hanmeimei"
  115. a.age = 17
  116. a:foo()
  117.  
  118. local b = B()
  119.  
  120. b.name = "lilei"
  121. b.age = 18
  122. b:foo()
  123.  
  124. a.name = 20
  125. a.age = "20"
  126. b.foo = "x"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement