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

How do you use a :changed() function on an in-script variable?

Asked by
tantec 305 Moderation Voter
5 years ago

So this is what I want to achieve in a sense...

lol = 0 -- my variable
lol.Changed:connect(function()

end) -- might not be this, but something like this where it detects if it changes
0
throws an error, attempt to index a number value to be precise User#19524 175 — 5y
0
Changed is an event not a function. You are probably thinking about a IntValue object. User#5423 17 — 5y

1 answer

Log in to vote
2
Answered by
mattscy 3725 Moderation Voter Community Moderator
5 years ago
Edited 5 years ago

You could achieve this in multiple ways.

The simplest way would be to call a function that is in control of changing the variable. Then, within that function, you could include the code that you want to run when the variable changes.

local lol = 0
local ChangeLol = function(NewVal)
    print("lol has changed")
    lol = NewVal
end

So, whenever you want to change the value of 'lol', you would call the ChangeLol function. For example to add 1 to its current value, you would go:

ChangeLol(lol + 1) --> "lol has changed"

Another way of doing this would be to use metatables. You can detect when a value within a table is changed, and do something when that occurs. For example:

local lol = setmetatable({Value = 0},{
    __newindex = function(self,index,value)
        print("lol has changed")
        rawset(self,index,value)
    end;
})

Then, if you wanted to add 1 to the value of 'lol', you could go:

lol.Value = lol.Value + 1 --> "lol has changed"

which would also print that the value changes. You would then run the desired code inside the __newindex function.

Hope this helps!

0
n i c e User#19524 175 — 5y
0
sorry for the late accept lol tantec 305 — 5y
Ad

Answer this question