Lua Functional Object Oriented Programming is a way you can code that allow you to create classes with ease and simplicity.
It is made to be simple to use and to abide to lua philosophy.
How do you create a functional class
First off you need to create a function. It is functional because it require function to create classes. Inside the function you put an table where it will have the classes method and properties. You can optionally add a metamethod table if you want to add metamethod. You need to return the class table.
local function Human(name, age)
local class = {
}
local mt = {
}
return setmetatable(class, mt)
end
Second of all, you need to set the properties of the class like this:
local function Human(name, age)
local class = {
name = name,
age = age,
_friends = {}
}
local mt = {
}
return setmetatable(class, mt)
end
If you want to add method you can simply add a function with the self keyword at the first parameter. It’s going to be allowing you to call the class like this joe:isFriendWith(anna)
.
local function Human(name, age)
local class = {
name = name,
age = age,
_friends = {},
isFriendWith = function (self, otherHuman)
if table.find(self._friends, otherHuman) then
return true
else
return false
end
end,
addFriend = function (self, otherHuman)
self._friends[#self._friends+1] = otherHuman
otherHuman:addFriend(self)
end
}
local mt = {
}
return setnmetatable(class, mt)
end
Functional classes allow you to simply make foreigin properties not allowed like this. It uses the newindex metamethod which is fired when a unknown key is called onto a table.:
local function Human(name, age)
local class = {
name = name,
age = age,
_friends = {},
isFriendWith = function (self, otherHuman)
if table.find(self._friends, otherHuman) then
return true
else
return false
end
end,
addFriend = function (self, otherHuman)
self._friends[#self._friends+1] = otherHuman
otherHuman:addFriend(self)
end
}
local mt = {
__newindex = function (t, k, v)
error("Cannot set " .. k .. " as its not an valid properties onto the table")
end
}
return setmetatable(class, mt)
end
If you want to inherit an class you can simply do like this:
...
local AwesomeHuman(name, age)
local class = Human(name, age)
rawset(class, "talents", {}) -- use raw set because Human class have __newindex metamethod which prevent adding new keys
rawset(class, doAwesomeStuff, function (self, what)
if not table.find(self.talents, what) then
print(self.name, "cannot do", what, "he is not talent in it.")
else
print(self.name, "is doing", what, "with great power")
end
end)
end
In conclusion, functional classes are a easy way you can create classes without too much effort and lines of codes.