Log In  
Follow
ghandolhagen

Curiosity abounds.

[ :: Read More :: ]

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)

[ :: Read More :: ]

Working on trying to understand RLE and I found a simple algorithm which I converted to pico-8 lua. When I run it however it seems like the while loop exits and executes the next line of code every iteration even though the conditions are still being met. I'm not sure what is going on, but I am sure that it is my fault. :D

cls()
string='wwwwweehhhhhhhjjiiioop'

function print_rle(str)
    local string=str
    local n=#string
    local j=0

    for i=1,n do
        local char_count=1

        while i<n-1 and sub(string,i,_)==sub(string,i+1,_) do
            char_count+=1
            i+=1
        end
        print(sub(string,i,_)..char_count,8*j,10,7)
        j+=1

    end 
end

print_rle(string)
P#118567 2022-10-05 01:13