Log In  

Hello Community!

I wonder if any of you can enlighten me as to the under the hood differences of loops that I am encountering.

does anyone know why this works:

function iterate(tbl,fnc)
  for o in all(tbl) do
    if fnc=='u' then
      o:update()
    elseif fnc=='d' then
      o:draw()
    elseif fnc=='h' then
      hit_test(player,o)
    end
  end
end

while this only works for update and draw but not for testing the collision?

function iterate(tbl,fnc)
  for i=1,#tbl do
    local o=tbl[i]
    if fnc=='u' then
      o:update()
    elseif fnc=='d' then
      o:draw()
    elseif fnc=='h' then
      hit_test(player,o)
    end
  end
end

In order for update and draw to work, the program must know that o=tbl[i] is an object with methods. So why does hit_test act like o is nil?

Any insight is greatly appreciated.

P#131939 2023-07-13 22:23 ( Edited 2023-07-13 22:33)

1

all() goes through each of the values in the table that have an integer index. The other loop assumes that the table contains a valid sequence and goes through each element in the sequence. If o is ending up as nil, then that probably means the table's sequence has holes.

P#131951 2023-07-14 02:57

Thanks very much for the explanation. Just so I understand, should I expect both of these examples to behave identically? And the fact that they don't is evidence of a bugged table?

P#131953 2023-07-14 03:59
1

Not quite. According to the manual, all() goes in the order that the elements were added. They should have the same behavior if the table was created all at once or in sequence order. However, if the table created by manually placing each element in the sequence, then they could have a different order. The loop that uses the length operator will always go through the sequence in order.

It may be good to also know why the loop with the length operator could fail. The way the length operator is defined in lua is that it returns an index that isn't nil but is followed by nil. In the case of a table that has multiple such indices, any one of them is allowed to be returned.

P#131960 2023-07-14 10:29

Ahhh. I see. I didn't pick up on that. Thanks again! This is immensely helpful!

P#131970 2023-07-14 16:08

[Please log in to post a comment]