luafivem

Print one time in while in and out position


this code print me test while I'm in the position, how i can print it one time until im out and in again?

while true do
    Citizen.Wait(1000)
    for k,v in pairs(zone) do
        if GetDistanceBetweenCoords(v.xyz, GetEntityCoords(GetPlayerPed(-1))) < 100 then
                print('test')
                break
        end
    end
end

Solution

  • If I understand correctly, you are asking how to detect when your condition of the player being in range is true, and print test only once while the player remains in range.

    To do this, I would use a boolean called playerInRange that is set to true the first time the distance check passes. Then you can check whether that boolean is true every subsequent time. When the check does not pass (the player is no longer in range), set it back to false.

    To demonstrate what I mean, for convenience of checking the outcome of the loop, I've moved the distance check into its own function.

    function CheckDistanceFromZone(zone, distance)
        for k,v in pairs(zone) do
            if GetDistanceBetweenCoords(v.xyz, GetEntityCoords(GetPlayerPed(-1))) < distance then
                return true
            end
        end
        return false
    end
    
    --
    
    local playerInRange = false
    
    while true do
        Citizen.Wait(1000)
        if CheckDistanceFromZone(zone, 100) then
            if not playerInRange then
                playerInRange = true
                print("test")
            end
        else
            playerInRange = false
        end
    end