[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Redefine "=".
- From: "Alexey Zaytsev" <alexey.zaytsev@...>
- Date: Fri, 2 Jun 2006 06:53:05 +0400
On 6/2/06, Jérôme VUARAND <jerome.vuarand@gmail.com> wrote:
t = {}
setmetatable(t, {
__newindex = function(self, key, value)
print("Hello World! ("..key..value..")")
end
})
t["foo"] = "bar"
> Hello World! (foobar)
There is a strong distinction between variables and values in Lua.
Variables are merely references to values. In :
t = "foo"
you are not affecting a value to the above table, you are affecting a
new value to an untyped variable (t). But you cannot set metatable for
variables, only for values. That's a good reason for not having a kind
of __reference or __copy metamethod.
The __reference metamethod would not operate on variable t, but rather on the
value, which is going to be assigned to this variable. like:
t = {}
setmetatable(t, {
__ref = function(table)
return table
}) <- the normal behaviour
setmetatable(t, {
__ref = function(table)
local tmp = {}
for i, j in pairs(table) do
tmp[i] = j
end
return tmp
end
}) <- make "=" behave like copy.
2006/6/1, Alexey Zaytsev <alexey.zaytsev@gmail.com>:
> Hello.
>
> Is it possible to redefine the reference ("=") operator for tables in lua?
> I thougth it is a job for metamethods, but could not find any. Is
> there any reason for not having any __reference (or __copy) metamethod
> in lua?
>