Page 1 of 1

How to make a table interact with the same table?

Posted: Thu Jul 16, 2020 1:36 pm
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!

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

Posted: Thu Jul 16, 2020 6:58 pm
by pgimeno
How does a style follow another style? I don't understand the question.

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

Posted: Thu Jul 16, 2020 7:14 pm
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

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

Posted: Thu Jul 16, 2020 11:44 pm
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.

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

Posted: Thu Jul 16, 2020 11:49 pm
by Jomkin
Thank you very much for your time! It helped me a lot!