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

How do I make a toggle script?

Asked by
funzrey 58
8 years ago

I've tried this code

paintBtn.Click:connect(function()
    if btnSelected == false then
        print("Plugin is now active")
        plugin:Activate(true) -- Neccessary to listen to mouse input
        gui.BTPaintToolGUI.Visible = true
        btnSelected = true
    end
    if btnSelected == true then
        print("Plugin is now inactive")
        plugin:Activate(false)
        gui.BTPaintToolGUI.Visible = false
        btnSelected = false
    end

end)

but it dosen't show any results, I click the button and nothing happens, it dosen't show, Output gives me this when i click the button Plugin is now active Plugin is now inactive at the same time. the exact same time. please help.

1 answer

Log in to vote
0
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
8 years ago

It's unnecessary to have two ifs. The value is either false or true, so you can just use else to execute the other block. Use else! (Or at least elseif) when it's what you mean!


That actually fixes your bug.

Before the first if, selected could be true or false.

If it's false it becomes true in the first if.

... so when it gets to the second if, it's always going to be true.


You need the two branches to be mutually exclusive -- only one can happen. That's exactly what else is for!


Remark You're repeating yourself an awful lot!

if not btnSelected then
    print("Plugin is now active")
    btnSelected = true
else
    print("Plugin is now inactive")
    btnSelected = false
end
plugin:Active( btnSelected )
gui.BTPaintToolGUI.Visible = btnSelected

Does the same thing.

In fact, you can even cut out the repetition of setting btnSelected:

btnSelected = not btnSelected
if btnSelected then
    print("Plugin is now active")
else
    print("Plugin is now inactive")
end
plugin:Active( btnSelected )
gui.BTPaintToolGUI.Visible = btnSelected
Ad

Answer this question