Selecting multiple functions in one class depending on the modificator/table index
Posted: Wed Dec 11, 2019 7:17 am
Hey people, I've been lurking the forum for some time and I've been playing around in Love2D for a little bit already. I finally decided to create an account since I hit a brick wall and can't find a solution to my problem.
I have a class that spawns enemies and depending of the enemy type they have different behavior. I want to store this behavior in class functions, like enemy:walking(), enemy:attacking() etc. Now the kicker is that I don't want all enemies to run all functions with every update, I also want to be able to dynamically add function to an enemy with player actions. The way I'd like to do it is to store all names of the functions in the table and then depending of the enemy type, select specific functions to run. Right now I have unelegant if, elseif statements that run through all enemy instances
This code works, but with every update I look if I have specific enemy typ, and if I have I run specific functions declared in class. I checked Lua switch - case but I couldn't make any of presented solutions work with self: . If I have 10 enemy instances and I have 10 enemy types I have to do 100 comparisons, and I want to avoid that. Ideally it should look like that in pseudocode
I have a feeling that it will never work that way but I'll take next best option.
I have a class that spawns enemies and depending of the enemy type they have different behavior. I want to store this behavior in class functions, like enemy:walking(), enemy:attacking() etc. Now the kicker is that I don't want all enemies to run all functions with every update, I also want to be able to dynamically add function to an enemy with player actions. The way I'd like to do it is to store all names of the functions in the table and then depending of the enemy type, select specific functions to run. Right now I have unelegant if, elseif statements that run through all enemy instances
Code: Select all
function enemy:update()
if self.typ == 1 then
self:Throwable(self.typ)
self:Bounce()
self:Gravity()
elseif self.typ == 2 then
self:BounceAndRicochet()
self:Gravity()
elseif self.typ == 3 then
self:Chase()
self:Gravity()
elseif self.typ == 4 then
self:NoGravity()
end
end
Code: Select all
functionTable = {
{self:Throwable(self.typ)}, {self:Bounce()},{self:Gravity()},
{self:BounceAndRicochet(),self:Gravity()},
{self:Chase(), self:Gravity()},
{self:NoGravity()}
}
function enemy:update()
for i = 1, #functionTable do
functionTable[self.typ][i]
end
end