MegaLoler

class.lua

Apr 7th, 2013
147
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.66 KB | None | 0 0
  1. --[[
  2.  
  3. class.lua
  4. Version: 1.0
  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.instanceOf
  48.  
  49. --]]
  50.  
  51. function newClass(parent)
  52.     class = {} -- Method table
  53.     if not Class then
  54.         parent = class
  55.     elseif not parent then
  56.         parent = Class
  57.     end
  58.     class.mt = {__index = class} -- Inherited metatable
  59.     setmetatable(class, parent.mt) -- Inherit from parent
  60.     return class
  61. end
  62.  
  63. Class = newClass() -- Create Class class
  64.  
  65. function Class:new(...) -- Class constructor
  66.     instance = setmetatable({}, self.mt)
  67.     instance:init(...)
  68.     instance.instanceOf = self
  69.     return instance
  70. end
  71.  
  72. function Class:init() -- Instance constructor
  73. end
Advertisement
Add Comment
Please, Sign In to add comment