Advertisement
MegaLoler

class.lua

Apr 7th, 2013
76
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. 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.instanceOf
  49.  
  50. --]]
  51.  
  52. function newClass(parent)
  53.     class = {} -- Method table
  54.     if not Class then
  55.         parent = class
  56.     elseif not parent then
  57.         parent = Class
  58.     end
  59.     class.mt = {__index = class} -- Inherited metatable
  60.     setmetatable(class, parent.mt) -- Inherit from parent
  61.     return class
  62. end
  63.  
  64. Class = newClass() -- Create Class class
  65.  
  66. function Class:new(...) -- Class constructor
  67.     instance = setmetatable({}, self.mt)
  68.     instance:init(...)
  69.     instance.instanceOf = self
  70.     return instance
  71. end
  72.  
  73. function Class:init() -- Instance constructor
  74. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement