Help with a "while" loop

Can someone help me figure out how to use a "while" loop on an sprite interaction? I see the example in the docs, but could use a bit more context. Can someone explain why this doesn't work as expected?

on interact do
	
	power = 6
	
	while power>0 do
		
		ask "attack?" then
		  
		  option "yes" then
		    say "you attacked!"
		    power--
		  end
		  
		  option "no" then
		    say "no damage"
		  end
		  
		end
		
	end
	
end

in fact, running that code will crash the Playdate. Can I not have a "while" inside the interact? If not, can someone suggest another way to loop dialog?

While loops can’t go on forever. There’s a 400 iteration limit. Your while loop can only exit if the user says yes, therefore it has a possibility of going on forever and therefore violates the 'rules of Pulp' :smiley:

What you should do instead is put your ask into a custom event. Then call it from the interact event.

on interact do
	
	power = 6
	call "attackEvent"
end

on attackEvent do

	ask "attack?" then
		  
		option "yes" then
			say "you attacked!"
		    	power--
                  if power>0 then
                  		call "attackEvent"
                  end
		end
		  
		option "no" then
			say "no damage"
                  	if power>0 then
                  		call "attackEvent"
                  end
		end

	end
	
end

This is exactly what I needed! Thanks a bunch!

1 Like