lua-users home
lua-l archive

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


On Tue, Jan 17, 2012 at 12:22, Jak Sprats <jaksprats@gmail.com> wrote:
> 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.
>
> I ran this
>> setmetatable(_G,{__newindex=function(t,x,y)
> print ("overriding "..x.." = "..y)
> rawset(t,x,y) end})
>> y=100
> overriding y = 100
>> y=200
>>
>
> the problem is that _newindex only works on "new" values, so the 2nd time a
> variable is set it doesnt work

You just need to edit the rawset() to store into some other table
instead of t, and create a __index to read from that table. (Maybe
that's what some of those giant ugly code blocks did; I didn't really
read them.) This does incur a bit of a performance hit since now you
invoke metamethods on every read/write, though you can set __index to
the proxy table itself (rather than a function) to speed it up a
little.

-- 
Sent from my toaster.