KananGamer

[TFM-LUA] Class

Sep 21st, 2020
1,767
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. local Class = {
  2.     new = function(_constructor)
  3.         local class = {}
  4.  
  5.         class.length = 0
  6.         class.values = {}
  7.         class.__index = class
  8.  
  9.         local constructor = function(class, ...)
  10.             local self = setmetatable({}, class)
  11.  
  12.             class.length = class.length + 1
  13.             table.insert(class.values, self)
  14.            
  15.             function self:destroy()
  16.                 class.length = class.length - 1
  17.                
  18.                 for i, v in next, class.values do
  19.                     if v == self then
  20.                         table.remove(class.values, i)
  21.                         break
  22.                     end
  23.                 end
  24.  
  25.                 setmetatable(self, {})
  26.             end
  27.  
  28.             if _constructor then
  29.                 _constructor(self, ...)
  30.             end
  31.  
  32.             return self
  33.         end
  34.  
  35.         setmetatable(class, {
  36.             __call = function (...)
  37.                 return constructor(...)
  38.             end
  39.         })
  40.  
  41.         return class
  42.     end
  43. }
  44.  
  45. -- Player Class Sample
  46. local Player = Class.new(function(self, name)
  47.     self.name = name
  48.     self.hp = 100
  49. end)
  50.  
  51. function Player:getName() return self.name end
  52. function Player:getHp() return self.hp end
  53. function Player:removeHp(hp) self.hp = self.hp - (hp or 0) end
  54.  
  55. local player = Player("Nettoork#0000")
  56.  
  57. print(Player.length)
  58.  
  59. player:removeHp(1)
  60.  
  61. print(player.name .. " [" .. player.hp .. "]")
  62.  
  63. player:destroy()
  64.  
  65. print(Player.length)
RAW Paste Data