How to make a table interact with the same table?

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
Jomkin
Prole
Posts: 8
Joined: Wed Jul 15, 2020 2:12 am

How to make a table interact with the same table?

Post by Jomkin »

Hello,

I have this table.

Code: Select all

monsters = {}

function newMonster(x,y)

monster = {}
monster.x = x
monster.y = y
monster.style = "green"
monster.removed = false
table.insert(monsters, monster)

end
How can I interact in the update like if I want to the monster.style "green" to follow the monster.style "blue"?

Thank you!
User avatar
pgimeno
Party member
Posts: 3551
Joined: Sun Oct 18, 2015 2:58 pm

Re: How to make a table interact with the same table?

Post by pgimeno »

How does a style follow another style? I don't understand the question.
Jomkin
Prole
Posts: 8
Joined: Wed Jul 15, 2020 2:12 am

Re: How to make a table interact with the same table?

Post by Jomkin »

pgimeno wrote: Thu Jul 16, 2020 6:58 pm How does a style follow another style? I don't understand the question.
When I was talking about following I meaned :

Code: Select all

if monster.x (the blue one) > monster.x (the green one) then
monster.x = monster.x + monster.speed * dt (the green one)
end
User avatar
pgimeno
Party member
Posts: 3551
Joined: Sun Oct 18, 2015 2:58 pm

Re: How to make a table interact with the same table?

Post by pgimeno »

Oh OK, thanks for the clarification. Well, if you're sure that the table will only contain 1 blue monster, you could do this:

Code: Select all

local blue_monster
local monster
-- Loop to find the blue monster
for i = 1, #monsters do
  monster = monsters[i]
  if monster.style == "blue" then
    blue_monster = monster
    break
  end
end
assert(blue_monster, "There's no blue monster in the monsters table")
-- Loop to make all green monsters go right when the blue monster is to their right
for i = 1, #monsters do
  monster = monsters[i]
  if monster.style == "green" then
    if blue_monster.x > monster.x then
      monster.x = monster.x + monster.speed * dt
    end
  end
end
But if there's only one blue monster, then it's better to store it in a variable when you create it, instead of having to loop to look for it.
Jomkin
Prole
Posts: 8
Joined: Wed Jul 15, 2020 2:12 am

Re: How to make a table interact with the same table?

Post by Jomkin »

Thank you very much for your time! It helped me a lot!
Post Reply

Who is online

Users browsing this forum: Ahrefs [Bot], Google [Bot] and 64 guests