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

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

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

2 comments

0

throws an error, attempt to index a number value to be precise

0

Changed is an event not a function. You are probably thinking about a IntValue object.

1 answer

✓ Accepted answer

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!

2 comments

0

n i c e

0

sorry for the late accept lol

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