MegaLoler

Lua Class Class

Apr 8th, 2013
202
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[
  2.  
  3. class.lua
  4. Version: 1.0.3
  5.  
  6. Author: MegaLoler
  7.  
  8. Contains functions for easily defining and instantiating classes in Lua.
  9.  
  10. First make sure you have this in your code:
  11. require("class.lua")
  12.  
  13. Define a new class with the newClass() function:
  14. NewClass = newClass()
  15.  
  16. Instantiate an new instance of the class with the new() method:
  17. newInstance = NewClass:new()
  18.  
  19. Add methods to the class like this:
  20. function NewClass:newMethod()
  21.     print("New method")
  22. end
  23.  
  24. Call methods of an instance of a class like this:
  25. newInstance:newMethod() -- prints "New method"
  26.  
  27. Add a constructor to the class like this:
  28. function NewClass:init()
  29.     print("New instance created")
  30. end
  31.  
  32. newInstance2 = NewClass:new() -- prints "New instance created"
  33.  
  34. Use constructor parameters like this:
  35. function NewClass:init(par)
  36.     print("New instance: " .. par)
  37. end
  38.  
  39. newInstance3 = NewClass:new("hello") -- prints "New instance: hello"
  40.  
  41. Create subclasses like this:
  42. Subclass = newClass(NewClass)
  43.  
  44. subclassInstance = Subclass:new("hi") -- prints "New instance: hi"
  45.  
  46. Get the class of an instance like this:
  47. subclassInstance:getClass()
  48.  
  49. Get the superclass of an instance like this:
  50. subclassInstance:getSuperClass()
  51.  
  52. Call a method of a superclass that has been overridden in its subclass like this:
  53. subclassInstance:getSuperClass():originalMethod()
  54.  
  55. --]]
  56.  
  57. function newClass(parent)
  58.     local class = {} -- Method table
  59.     if Class then -- Class class doesn't inherit from anything
  60.         setmetatable(class, {__index = parent or Class}) -- Inherit from parent, Class by default
  61.     end
  62.     return class
  63. end
  64.  
  65. Class = newClass() -- Create Class class
  66.  
  67. function Class:new(...) -- Class constructor
  68.     local instance = setmetatable({}, {__index = self})
  69.     instance:init(...)
  70.     return instance
  71. end
  72.  
  73. function Class:init() -- Instance constructor
  74. end
  75.  
  76. function Class:getClass()  -- Returns the class of an instance
  77.     if Class == self then return nil end
  78.     return getmetatable(self).__index
  79. end
  80.  
  81. function Class:getSuperClass()  -- Returns the superclass of an instance
  82.     return self:getClass():getClass()
  83. end
Advertisement
Add Comment
Please, Sign In to add comment