Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How can I call a pcall function when a value is changed?

Alright, so I've got:

local value = script.Parent.Currency

local save, err = pcall(function()
	currencyStore:SetAsync(player, currency)
end)

(The "value" variable is connected to a number value.)

Then I've got:

value.Changed:Connect()

(I want the pcall function to fire when the value is changed.)

My question is, how can I call the pcall function when the value is changed? I don't want to call a normal function as I will be using this to save a value on a datastore and as such, I want the extra "protection" of a pcall.

5 comments

0

what is value

0

well the event runs when it changes so no need for pcall

0

i mean is it a value object or a variable in the script local value = 2 or local value = workspace.Value

0

There, I changed up the questions a little bit so that it gives more information.

0

ty looks like u have answer

1 answer

✓ Accepted answer

Since pcall runs and returns the success of the function, simply connecting to the new pcall won’t work and will deem the returned values useless — as you seem to have figured out already. To counter this, you can use the pcall inside another function, the other function being the one passed to the connection and enclosing the pcall:

value.Changed:Connect(function() -- Enclosing function 
    local saved, err = pcall(function()
        currencyStore:SetAsync(player, currency)
    end)
    if not saved then warn(err) end
end)

7 comments

0

does this not error since player is an object?

0

Wouldn't using a pcall inside a normal function be basically the same as using a normal function? I wanted to use pcall because it is safer when using data stores but uh... First time I'm using pcall.

0

pcall stops the script if it errors. saved is a true or false value determining if it errors while saving.

0

In this script, "player" is a string and I gathered it using a clickdetector. May seem weird to be using a clickdetector to gather the name of the player to save data, but that's because I'm actually using the clickdetector to gather the name of a player to load data too. I'm making a computer.

0

the value.Changed function runs whenever the value changes. keep in mind if this changes often you might run into an issue of datastore saving too quickly

0

I haven’t edited OPs data part since I’m not sure if player is an object, but if it is then yeah it would. This IS simply using pcall in a simple function, it’s definitely safer for saving data.

0

add UserId to this

This discussion is preserved as it was. New answers, comments, and votes are closed.