How do I use multiple If's in Lua?

7.5k views Asked by At

I'm trying to make a UFO in my ROBLOX place, and wanted to create a system that would play an audio when the UFO passes overhead. I created a part, inserted an audio into the part, then placed a script in the audio. So it looks like:

Part->Audio->Script

I plan the system to register when a Humanoid is touched, and if the part is going faster than say, 300 Studs per second, I want it to play an audio (preferably the audio would be played only for the person(s) that was touched by the part) so I wrote a script that goes as follows:

while true do
    if script.parent.parent.Velocity.Magnitude>299 then 
        script.Parent:play()
        wait(5)
        script.Parent:stop()
    else
        wait()
    end
    wait()
end

As you can see I'm missing the part about the humanoid being touched, but I'm not sure how to write that. I'm really new to scripting, and I don't know the proper context for these commands. Help would be greatly appreciated.

Thanks!

3

There are 3 answers

1
Will On

You can use Lua's logical operators: 'and', 'or', and 'not' are the most commonly used. In your case, it sounds like you want to do something like:

if (condition1) and (condition2) then
    play_sound()
else
    wait()
end

You can also "nest" if statements:

if condition1 then
    if condition2 then
        do_something()
    end
end
0
John On

In addition to @Will's answer you could also use elseif to check different conditions.

if (conditionA) then
elseif (conditionB) then
end

If conditionA is true, the next statements will not be checked, thus order is important.

while true do
if script.parent.parent.Velocity.Magnitude>299 then 
 if(humanoidIsTouchedd()) then
    script.Parent:play()
    wait(5)
    script.Parent:stop()
 elseif (somethingElseIsTouched())
    doSomethingElse()
 else
    wait()
end
wait()
0
Winper On

I hope you use this:

script.Parent.Parent.Tounched:Connect(function(hit)
    if not hit.Parent:FindFirstChild("Humanoid") script.parent.parent.Velocity.Magnitude < 299 or then return end
end)
script.Parent:play()
    wait(5)
    script.Parent:stop()