lua-users home
lua-l archive

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


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

I got this to work though, it is actually dead simple and whoever wrote the core of lua did so w/ the subtlety of genius
-- START CODE
IndexedElement = { x = true; }
ShadowTable    = { x = 11; }
function setter(tbl, name, value)
  if (IndexedElement[name] ~= nil) then
    print ('Firing update: old: ' .. ShadowTable[name] .. ' new: ' .. value)
  end
  rawset(ShadowTable, name, value) 
end

function luaSet(a)
  print ('luaSet START: a.x: ' .. a.x);
  a.x=44;
  print ('luaSet SUCCESS: a.x: ' .. a.x);
end

a={}
setmetatable(a, {__index=ShadowTable, __newindex=setter})

print ('START: a.x: ' .. a.x);
luaSet(a);

print ('updateSet START: a,x: ' .. a.x);
a.x=999;
print ('updateSet SUCCESS: a,x: ' .. a.x);

luaSet(a);

print ('FINAL: a.x: ' .. a.x);

print ('SET NON-INDEXED Field');
a.y=22;
-- END CODE

Works like a charm and has all the dynamic properties I need ... i.e. I could very easily make "a.y" into an Index :)

Thanks