There isn't a direct way to watch a variable change.
This is mostly to make Lua understandable -- when you change a variable, only that variable changes.
You can still accomplish this, though. First: there is a reason you cannot do extra work when dealing simply with variable. It makes Lua easier to understand when you play by the normal rules. ROBLOX cheats all over the place with Lua's rules; if you think about it, you can probably come up with lots of different places where it cheats. That doesn't mean you should!
Getters and Setters
An idiomatic solution is getters and setters. Instead of using a variable directly, you use two functions. This lets you react to changes. For instance, we can limit a number to be between 0 and 1:
do
local x = 0
function getX()
return x
end
function setX(newX)
if newX > 1 then
x = 1
elseif newX < 0 then
x = 0
else
x = newX
end
end
end
setX(2)
print(getX())
setX(0.5)
print(getX())
Polling
An often sufficient method is to just repeatedly ask. If, for instance, you just need to show a value on the screen, this is probably enough:
while wait() do
script.Parent.Text = value
end
If you want to do it in the background, you can spawn a new thread to do that.
Metatables
Lua has a feature called metatables. These redefine the way that basic operations work in Lua.
Using the __index and __newindex metamethods, we can take advantage of the getter and setter pattern, but make it look like property of an object (this is more or less how .Changed is implemented in ROBLOX objects)
It looks like this:
local t = {}
local value
function get(obj, property)
assert(property == "value")
return value
end
function set(obj, property, newValue)
assert(property == "value")
if newValue > 1 then
value = 1
elseif newValue < 0 then
value = 0
else
value = newValue
end
end
setmetatable(t, {__index = get, __newindex = set} )
t.value = 5
print(t.value)
t.value = 0.5
print(t.value)
Metamethod + Environment Hack
Pure Lua 5.1 will let you do this more directly. Diito's answer tells you how to get this to work in ROBLOX.
First: do not do this. To an even greater extent than the above, it can be incredibly confusing and frustrating.
Global variables (as opposed to local, not those in _G -- although in vanilla Lua this is essentially the same) are actually properties stored in a table. That table is called the environment, and you can give it a metatable.
Applying the previous lets you do getters and setters on plain variables -- horrifying!
setmetatable( getfenv(), {__index = get, __newindex = set} )
value = 1
print(value)
value = -1.5
print(value)
value = 0.5
print(value)
3 comments
Perhaps a Value object?
Oh I forgot to write that method in, thanks for reminding me. But I really would like to use only Lua for this
Edited