So I've got a few of these little helper modules I've written while making my game, I figured I needed a place to post them so others can get some use from it, I'll be selective with what I release as some of them I would like to keep private but everytime I get a spare moment I'll try to write up a blog post with a new module release and how it's used.
So anyone familiar with OOP will hopefully get some use from this module, Lua already has a semi-OOP system with it's 'metatables' and this module just extends those to be used in a class system with inheritance.
-- This is the definition of the system, only a small file but it does a lot.
class.lua
-- Class system written by Averice _shardClass = {} _shardClass.__index = _shardClass; function class(nme) if( _G[nme] ) then print("Class: "..nme.." already exists."); return; end _G[nme] = {} setmetatable(_G[nme], _shardClass) _G[nme].istype = nme; return _G[nme]; end -- Really no reason for the shardClass metatable but it provides nice looking functionality -- class "CAnimatedEntity" : extends "CBaseEntity" <-- is now correct syntax function _shardClass:extends(superclass) if( _G[superclass] ) then self.parent = superclass; self.__index = _G[superclass]; end end function new(class) if( _G[class] ) then local newClass = {} setmetatable(newClass, _G[class]); for k, v in pairs(_G[class]) do newClass[k] = v; -- For some reason metamethods weren't being accessed properly, here's a hacky fix. end if( newClass.Init ) then newClass:Init(); end return newClass; end print("Class: "..class.." does not exist."); end function ctype(class) return class.istype or type(class); end
Alright, if your hoping to use this and know OOP programming the above should be self-explanatory.
Simple put to define a new class you do this.
class "MyClass";
To define a class that inherits from another you do this.
class "MySecondClass" : extends "MyClass";
To create a new instance of a class you do this.
my_class_instance = new "MySecondClass";
If there is an 'Init()' function it will be called automatically when a new instance of the class is created.
Here is an example.
class "ExampleClass"; function ExampleClass:Init() self.Number = 10; end function ExampleClass:SimpleFunction() print(self.Number); end class "NewExampleClass" : extends "ExampleClass"; function NewExampleClass:Init() self.Number = 15; end -- Now we create an instance. MyClass = new "NewExampleClass"; MyClass:SimpleFunction() -- notice this function was inherited from "ExampleClass" not "NewExampleClass" -- will print 15;
- 8
5 Comments
Recommended Comments