Simple Educative Class Library
Also known as SECL. This is a simple implementation of classes that works, it's not commented, so it's a nice test of your lua skills.
The current version can always be found in the love-misc-libs repository
Contents
Basic version example
require "class" --this assumes you've saved the code above in class.lua
myclass = class:new()
myclass.value = 13
function myclass:setvalue(v)
self.value = v
end
object = myclass:new()
object:setvalue(128)
--myclass.value is still 13 and object.value is now 128
anotherObject = object:new()
--anotherObject.value is 128
Advanced version example
--NOTE: this example only contains features the basic version doesn't, if you want to see those functions see the basic example
--require it here
--create the tables/classes
cl1 = class:new()
cl2 = class:new()
cl3 = {}
--fill the tables/classes
cl1.val1 = 12
cl2.val2 = 24
cl3.val3 = 48
--create the new merged class
merged = cl1:new()
print(merged.val1, merged.val2, merged.val3) --> 12 nil nil
merged:addparent(cl2)
print(merged.val1, merged.val2, merged.val3) --> 12 24 nil
--remember cl3 is a normal table, not a class?
class:convert(cl3) --converts the table in place and returns it, so you can use it in expressions
merged:addparent(cl3) --could also be merged:addparent(class:convert(cl3))
print(merged.val1, merged.val2, merged.val3) --> 12 24 48
--convert is part of any class, the parent of the converted class is the class where convert is called from
--NOTE: addparent supports multiple parents at once, the way that it's done here is to serve as an example
Full version example
--NOTE: This example only contains features the advanced version doesn't have
--require it here
cl1 = class() --new is implied
cl2 = class()
cl1.val1 = 12
cl2.val2 = 24
merged = cl1() + cl2 --yes, we can just add cl2 as if we were doing math
print(merged.val1, merged.val2) --> 12 24
if merged > cl1 then
print("Merged is a derivative of cl1") --which it is, so this is printed
end
if merged > cl2 then
print("Merged is a derivative of cl2") --it's that as well, so print
end
merged2 = cl1() + cl2 --create another derivative with the same parents
merged2.val1 = 36 --we change one value
if merged == merged2 then
print("Merged2 is of the same type as merged") --they are the same type, note this only works when changing, when you add or remove values it is considered as a new class
end
Revised version example
Same as full.
See also
Bartbes, creator and maintainer of SECL.