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

[Solved]How do you prevent an anonymous function from running multiple times?

Asked by 6 years ago
Edited 4 years ago

I have a function that fires whenever a person steps on a telepad; this function displays a talk button to the player. Inside of that function is another one that runs if the player clicks the talk button.

I wanted to spruce it up a little and add some effects, but I got stumbled on the second function firing multiple times. The code "works", but I just can't seem to figure out why the function runs more than once, and in increasing increments. Here is a code snippet and output sample to show what I mean:

...
local StoodOn = false
local ChatGui = game.Players.LocalPlayer.PlayerGui.ChatGui
local Message1 = game.StarterGui.ChatGui.InitialMessage.Value

script.Parent.Touched:Connect(function()
    --Debounce
    if not StoodOn then
        StoodOn = true
        --effects removed to make it more readable. TalkButton is made visible

            ChatGui.TalkFrame.TalkButton.MouseButton1Click:Connect(function()
            --effects removed except the loop, the loop will make it appear as though
            --the NPC is typing. TalkButton is removed from the screen
            for i = 1, #Message1 do
                wait(.01)
                print("   pass   ", i)
                ChatGui.Frame.TextLabel.Text = string.sub(Message1,1,i)
                if i == #Message1 then
                    print(Message1)
                end 
            end
        end)
        wait(1)
        StoodOn = false
    end
    wait(1)
wait(1)
end)

And the output:

https://imgur.com/wOy7Dwl

The code works exactly as I expected it to the first time the TalkButton is clicked, but the function runs more than once if the player clicks it a second time. I've tried a second debounce within the MouseClicked event, but I'm pretty sure it has something to do with it creating multiple anonymous functions.

Any ideas on how to fix this will be greatly appreciated! Thank you.

0
LocalPlayer is nil to the server. You'll have to get the player on your own. You should also be handling click events from GUIs on the client, not the server. User#19524 175 — 6y
0
Thank you, I'll definitely make those adjustments. SteelMettle1 394 — 6y

1 answer

Log in to vote
0
Answered by 6 years ago

[EDIT]: I figured out the answer to this a while ago: The simple solution is avoid using an event function within another event function. The script will run in increasing increments (and will eventually crash the server) unless you create a completely separate function for the second event function (don't embed it within the other function).

I hope this helps other people from tumbling down the same logical error hole I had.

Ad

Answer this question