While true loop impairing script functions

I am making a script to allow players to rent a room, and they will be kicked out after a certain amount of time. Here is my script:

while true do
	for _, plr in ipairs(playerTable) do
		if os.time() - playerTable[plr.Name] > cooldownTable[plr.Name] then
			playerTable[plr.Name] = nil
			cooldownTable[plr.Name] = nil
			print(plr.Name.." ran out of time")
		end
	end
	task.wait(1)
end

local function processReceipt(receiptInfo)
	print("purchase", receiptInfo)
	print("callback fired")	
	local productKey = receiptInfo.PlayerId.."_"..receiptInfo.PurchaseId
	local purchased = false
	local success, result, errorMessage
	print("Variables found")
	
	success, errorMessage = pcall(function()
		purchased = purchaseHistoryStore:GetAsync(productKey)
	end)
	if success and purchased then
		print("Purchase Granted")
		return Enum.ProductPurchaseDecision.PurchaseGranted
	elseif not success then
		error("Data store error:"..errorMessage)
	end
	
	local success, isPurchaseRecorded = pcall(function()
		return purchaseHistoryStore:UpdateAsync(productKey, function(alreadyPurchased)
			if alreadyPurchased then
				print("already purchased")
				return true
			end
			
			local plr = Players:GetPlayerByUserId(receiptInfo.PlayerId)
			if not plr then
				print("player not found")
				return nil
			end
			
			local handler = productFunctions[receiptInfo.ProductId]
			print("product function found")
			
			local success, result = pcall(handler, receiptInfo, plr)
			if not success then
				error("Failed to process a product purchase for ProductId: "..tostring(receiptInfo.ProductId).." Player: "..tostring(plr).." Error: "..tostring(result))
				return nil
			end	
			print("pcall for product function done")
			return true
		end)
	end)
	
	if not success then
		error("Failed to process receipt due to data store error.")
		return Enum.ProductPurchaseDecision.NotProcessedYet
	elseif isPurchaseRecorded == nil then
		print("not processed yet")
		return Enum.ProductPurchaseDecision.NotProcessedYet
	else
		print("purchase granted")
		return Enum.ProductPurchaseDecision.PurchaseGranted
	end
end

MarketplaceService.ProcessReceipt = processReceipt

Without the while true loop, it works perfectly, but with the while true loop, it won’t work at all. How do I fix this? Should I use RunService.Heartbeat instead?

You could use RunService.Heartbeat, but a better option would probably be to make a separate thread via task.spawn/coroutine library to house your loop.

The reason this happens is because the loop is infinite, thus that part of your code will never terminate, meaning nothing past that loop will run.

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.