MegaLoler

class.lua

Apr 7th, 2013
135
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. --[[
  2.  
  3. class.lua
  4. Version: 1.0.2
  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. --]]
  50.  
  51. function newClass(parent)
  52.     local class = {} -- Method table
  53.     if Class then -- Class class doesn't inherit from anything
  54.         setmetatable(class, {__index = parent or Class}) -- Inherit from parent, Class by default
  55.     end
  56.     return class
  57. end
  58.  
  59. Class = newClass() -- Create Class class
  60.  
  61. function Class:new(...) -- Class constructor
  62.     local instance = setmetatable({}, {__index = self})
  63.     instance:init(...)
  64.     return instance
  65. end
  66.  
  67. function Class:init() -- Instance constructor
  68. end
  69.  
  70. function Class:getClass()  -- Returns the class of an instance
  71.     if Class == self then return nil end
  72.     return getmetatable(self).__index
  73. end
Advertisement
Add Comment
Please, Sign In to add comment