I am attempting to make ULTRA light multi layer OOP. I wonder if I missed anything in my current, please reply!
the main goal is lower memory usage as much as possible without killing readability, make it close to 0 performance / iteration cost without sacrificing redundancy
What I accounted for:
- Prevented recreating IndexSearch function
- Tables start empty by design, and only cache if modified
- Looks up from the listed recipe order, by Ipairs, (ideally core → unique components)
Cons:
- because there aren’t template data it will pull from, I’d have to use functions like getHealth,
- if modified data is equalivent to starter data, it shouldn’t exist, so need to add cleanup methods without having any constant check costs
local HealthComponent = {
maxHealth = 100,
getHealth = function(self)
return self.health or self.maxHealth
end,
takeDamage = function(self, amount)
self.health = math.max(0, (self:getHealth()) - amount)
end
}
local AttackComponent = {
damage = 10,
attack = function(self, target)
target:takeDamage(self.damage)
end
}
local Recipes = {
Soldier = {HealthComponent, AttackComponent},
Building = {HealthComponent}
}
local function indexFunction(self, key)
local value = rawget(self, key)
if value then return value end
for _, component in ipairs(getmetatable(self)[1]) do
value = rawget(component, key)
if not value then continue end
return value
end
end
for className, recipe in Recipes do
Recipes[className] = {__index = indexFunction,[1]=recipe}
end
local function createObject(recipeName)
return setmetatable({}, Recipes[recipeName])
end
local soldier = createObject("Soldier")
local building = createObject("Building")
print(soldier:getHealth()) -- 100
soldier:takeDamage(30)
print(soldier:getHealth()) -- 70
soldier:attack(building)
print(building:getHealth()) -- 70
print(building) -- {health=90}
print(soldier) -- {health=70}
print(createObject("Building")) -- {}