SHOW:
|
|
- or go back to the newest paste.
| 1 | --[[ | |
| 2 | ||
| 3 | class.lua | |
| 4 | - | Version: 1.0 |
| 4 | + | Version: 1.0.1 |
| 5 | ||
| 6 | Author: MegaLoler | |
| 7 | Email: [email protected] | |
| 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 |
| 54 | + | if Class then |
| 55 | - | parent = class |
| 55 | + | setmetatable(class, {__index = parent or Class}) -- Inherit from parent
|
| 56 | - | elseif not parent then |
| 56 | + | |
| 57 | - | parent = Class |
| 57 | + | |
| 58 | end | |
| 59 | - | class.mt = {__index = class} -- Inherited metatable
|
| 59 | + | |
| 60 | - | setmetatable(class, parent.mt) -- Inherit from parent |
| 60 | + | |
| 61 | ||
| 62 | function Class:new(...) -- Class constructor | |
| 63 | instance = setmetatable({}, {__index = self})
| |
| 64 | instance:init(...) | |
| 65 | instance.instanceOf = self | |
| 66 | return instance | |
| 67 | - | instance = setmetatable({}, self.mt)
|
| 67 | + | |
| 68 | ||
| 69 | function Class:init() -- Instance constructor | |
| 70 | end |