Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- --[[
- class.lua
- Version: 1.0.2
- Author: MegaLoler
- Email: megaloler9000@gmail.com
- Contains functions for easily defining and instantiating classes in Lua.
- First make sure you have this in your code:
- require("class.lua")
- Define a new class with the newClass() function:
- NewClass = newClass()
- Instantiate an new instance of the class with the new() method:
- newInstance = NewClass:new()
- Add methods to the class like this:
- function NewClass:newMethod()
- print("New method")
- end
- Call methods of an instance of a class like this:
- newInstance:newMethod() -- prints "New method"
- Add a constructor to the class like this:
- function NewClass:init()
- print("New instance created")
- end
- newInstance2 = NewClass:new() -- prints "New instance created"
- Use constructor parameters like this:
- function NewClass:init(par)
- print("New instance: " .. par)
- end
- newInstance3 = NewClass:new("hello") -- prints "New instance: hello"
- Create subclasses like this:
- Subclass = newClass(NewClass)
- subclassInstance = Subclass:new("hi") -- prints "New instance: hi"
- Get the class of an instance like this:
- subclassInstance.getClass()
- --]]
- function newClass(parent)
- local class = {} -- Method table
- if Class then -- Class class doesn't inherit from anything
- setmetatable(class, {__index = parent or Class}) -- Inherit from parent, Class by default
- end
- return class
- end
- Class = newClass() -- Create Class class
- function Class:new(...) -- Class constructor
- local instance = setmetatable({}, {__index = self})
- instance:init(...)
- return instance
- end
- function Class:init() -- Instance constructor
- end
- function Class:getClass() -- Returns the class of an instance
- if Class == self then return nil end
- return getmetatable(self).__index
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement