Advertisement
MegaLoler

class.lua

Apr 7th, 2013
87
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. Email: megaloler9000@gmail.com
  8.  
  9. Contains functions for easily defining and instantiating classes in Lua.
  10.  
  11. First make sure you have this in your code:
  12. require("class.lua")
  13.  
  14. Define a new class with the newClass() function:
  15. NewClass = newClass()
  16.  
  17. Instantiate an new instance of the class with the new() method:
  18. newInstance = NewClass:new()
  19.  
  20. Add methods to the class like this:
  21. function NewClass:newMethod()
  22.     print("New method")
  23. end
  24.  
  25. Call methods of an instance of a class like this:
  26. newInstance:newMethod() -- prints "New method"
  27.  
  28. Add a constructor to the class like this:
  29. function NewClass:init()
  30.     print("New instance created")
  31. end
  32.  
  33. newInstance2 = NewClass:new() -- prints "New instance created"
  34.  
  35. Use constructor parameters like this:
  36. function NewClass:init(par)
  37.     print("New instance: " .. par)
  38. end
  39.  
  40. newInstance3 = NewClass:new("hello") -- prints "New instance: hello"
  41.  
  42. Create subclasses like this:
  43. Subclass = newClass(NewClass)
  44.  
  45. subclassInstance = Subclass:new("hi") -- prints "New instance: hi"
  46.  
  47. Get the class of an instance like this:
  48. subclassInstance.getClass()
  49.  
  50. --]]
  51.  
  52. function newClass(parent)
  53.     local class = {} -- Method table
  54.     if Class then -- Class class doesn't inherit from anything
  55.         setmetatable(class, {__index = parent or Class}) -- Inherit from parent, Class by default
  56.     end
  57.     return class
  58. end
  59.  
  60. Class = newClass() -- Create Class class
  61.  
  62. function Class:new(...) -- Class constructor
  63.     local instance = setmetatable({}, {__index = self})
  64.     instance:init(...)
  65.     return instance
  66. end
  67.  
  68. function Class:init() -- Instance constructor
  69. end
  70.  
  71. function Class:getClass()  -- Returns the class of an instance
  72.     if Class == self then return nil end
  73.     return getmetatable(self).__index
  74. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement