lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


2012/1/17 steve donovan <steve.j.donovan@gmail.com>:
> On Tue, Jan 17, 2012 at 8:27 AM, Jak Sprats <jaksprats@gmail.com> wrote:
>> So I need to do something like override the assignment operator for a
>> variable, but I cant figure out how.
>>
>> Anyone got any magic on this one?
>
> Strictly speaking, you can't override assignment to a single variable.
>  However, assignments of the form 't.v' will cause __newindex to fire,
> if 'v' is not already present in t.  So the solution is a variation on
> the proxy trick;  t does not directly have your variables, but
> __newindex can redirect the lookup to some hidden table within t,
> _and_ fire a notification.
>

This works:

Lua 5.2.0  Copyright (C) 1994-2011 Lua.org, PUC-Rio
> setmetatable(_ENV,{__newindex=function(t,x,y)
>> print ("overriding "..x.." = "..y)
>> rawset(t,x,y)
>> end})
> y=100
overriding y = 100

And if you want to override assigments only to some variables, the
function could look up `x` in a table.

But the OP's example was:  `local var = 34`

I can't figure out how to overrride assigment to a local variable.