2006/12/1, Rici Lake <lua@ricilake.net>:
On 1-Dec-06, at 12:31 AM, wang xu wrote:
> Is there a generic way to automatically update one variable when the
> value of another variable is changed?
No. (And why do you want to do that?)
I have a View, the view is a Text Widget, which has an attribute "str",
when the str is modified, the Text widget will update the Screen with
the string.
I also have a Model, which is a table containing many strings, each string is corresponding to one Text Widget.
What I want to do by a linked variable are:
1) when a string in the model changes, the str in the view update automatically.
2) when the str in the Text Widget changes(by the user through GUI), the sting in the Model table update automatically too.
The closest you can do is to implement your own "boxed" values, using
tables with a single key (say, 1):
val1 = {"a"}
val2 = val1
val1[1] = "b"
=val2[1]
You could dress it up in O-O notation:
do
local meta = {}
meta.__index = meta
function meta:set(v) self[1] = v end
function meta:get() return self[1] end
function Box(v)
return setmetatable({v}, meta)
end
end
val1 = Box("a")
val2 = val1
=val2:get()
val1:set("b")
=val2:get()