Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Problem With A Piece Of Code Executing When Not Supposed To?

Asked by 5 years ago
for _, object in pairs(game.Workspace.Building.Lights:GetChildren()) do
    if game.Lighting.ClockTime == 13 or 13.1 or 13.2 or 13.3 then 
        object.Transparency = 1
    end
end

As you can see that my code is trying to do gather all children of the building lights then tests if it is 13 Clock time in lighting then it turns the lights invisible but it keeps executing the object transparency bypassing the if statement; anyone got a fix?

2 answers

Log in to vote
1
Answered by
xPolarium 1388 Moderation Voter
5 years ago
Edited 5 years ago

The problem is how you set your conditionals in the if-statement. By having numbers like 13.1 alone in a condition is considered as truthy since you don't compare it to anything. The correct use of comparing numbers for that line would be:

if game.Lighting.ClockTime == 13 or game.Lighting.ClockTime == 13.1 or game.Lighting.ClockTime == 13.2 or game.Lighting.ClockTime == 13.3 then

Obviously it looks very messy so you could use the greater/less than operators, > or <. In your case it could look like:

for _, object in pairs(game.Workspace.Building.Lights:GetChildren()) do
    if game.Lighting.ClockTime > 13 and game.Lighting.ClockTime < 13.3 then 
        object.Transparency = 1
    end
end

The above would only run the code inside of the if-statement if the ClockTime was between 13.3 and 13.

Let me know if this had helped you or if I missed anything.

Ad
Log in to vote
0
Answered by 5 years ago
Edited 5 years ago

Truthy values

In Lua, any value that is not false or nil is truthy. So if you use s number as a condition in your if statement it will pass since numbers are truthy

Additionally, you cannot guarantee that the decimals will exactly be 13.2, 13.3, ect.

for _, object in pairs(game.Workspace.Building.Lights:GetChildren()) do
    if game.Lighting.ClockTime >= 13 and game.Lighting.ClockTime <= 14 then 
        object.Transparency = 1
    end
end

So you should use >= and <= when working with decimals.

Answer this question