Thought I would share some code I've been using for my pico-8 game. It's a simple class library that also includes inheritance.
139 Tokens
617 Characters without comments
How to Use:
Create a new instance with function "new".
The first variable is always the table that holds all the variables, 2nd and onwards are used for the function "__init('table','...')"
Example:
player:new({variablea=1,variableb=2},initarg1,initarg2) |
Variables are copied over just fine, however for tables if you don't want each instance to share the exact same table with each other then I would recommend defining them in the function "__init('table','...')".
Example:
--do this function newclass:__init(varc,vard) self.vartable={varc,vard} self.varemptytable={} end --if you don't do that then instance1.varemptytable==instance2.varemptytable |
When creating a class, you can inherit from other classes upon it's creation by simply including classes after the first argument.
Example:
newclass=cwi:new({vara=3,varb=4},classtoinheritfroma,classtoinheritfromb) |
You can also inherit from other classes by running function "inherit('...')".
Classes have an "init" function that is run every time a new instance is created.
Classes that have been inherited from will NOT run their function "init('...')" upon creation of a new instance.
Function "oftype('class')" allows you to check each if one class is of the type of another.
Classes that have been inherited will also return true for function "oftype('class')".
Finally I present the code:
--Classes With Inheritance! cwi={} cwi.__index=cwi function cwi:__init(...) self.__types={} if #{...}>0 then self:inherit(...) end self.__init=function() end --create an empty function so all classes function "__init" doesn't inherit end function cwi:new(r,...) r=r or {} r.__index=r setmetatable(r,self) if r.__init then r:__init(...) end return r end function cwi:inherit(...) local function c(a,b) for k,l in pairs(b) do if not a[k] then a[k]=l end end end for l in all({...}) do c(self,l) --copy variables over to class c(self.__types,l.__types) --copy inheritance types over to class so that it knows it has inherited from more than class l self.__types[l]=true end end function cwi:oftype(s) if self==s or getmetatable(self)==s or self.__types[s] then return true end return false end |
Let me know if this code helped out, if there's anything else I can improve upon it, or whatever else you may feel like saying.
[Please log in to post a comment]