How stop function?

I thought I had succeeded in solving the past question on my own so I deleted it, but as it turns out… it was just my imagination.

The situation is as follows: when a player loses, I need to stop the spavn function immediately. I decided to do this through a kind of toggle self.wave_status. It takes the value true when the player loses, so the function should stop abruptly, but in this situation nothing like that happens and the code execution continues.

function mobSpawn(self, wavePoint)
	if wavePoint > 0 and self.wave_status == false then
		if wavePoint >= 5 then 
			local numMonster = math.random(1, 5)
			wavePoint = wavePoint - numMonster
			monster_spawn = monster_spawn - numMonster
			local monster_name = monster_list[numMonster]
			factory.create(monster[monster_name].factory_url, self.position, nil, {damage = monster[monster_name].damage, speed = monster[monster_name].speed, hp = monster[monster_name].hp, height = monster[monster_name].height, experience = monster[monster_name].experience})
		else
			local numMonster = math.random(1, wavePoint)
			wavePoint = wavePoint - numMonster
			monster_spawn = monster_spawn - numMonster
			local monster_name = monster_list[numMonster]
			factory.create(monster[monster_name].factory_url, self.position, nil, {damage = monster[monster_name].damage, speed = monster[monster_name].speed, hp = monster[monster_name].hp, height = monster[monster_name].height, experience = monster[monster_name].experience})
		end
		timer.delay(math.random(1, 4 + (wave_point * 0.1)), false, function()
			if self.wave_status == false then
				mobSpawn(self, wavePoint)
			end
		end)
		monster_point = monster_point + 1
	end
end

I don’t know if this is what causes the problem, but there’s a typo in on of the calls to math.random. wave_point should be wavePoint unless you have wave_point defined earlier somewhere.

This is my first project and as a result of rewriting the code, many things work quite confusingly)

How do you terminate the function? One solution I may propose is getting the timer handle and saving it in self (self.timer = timer.delay(...) and canceling it with timer.cancel(self.timer). If you put the parameters (self, handle, elapsed_time) inside the callback function of the timer, you could also cancel it from the inside with timer.cancel(handle).

2 Likes