lua-users home
lua-l archive

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


Oscar Lazzarino wrote:
> 
> I think a nice solution would be to ADD two tag methods
> "set" and "get" on variables. This methods would substitue the
> getglobal/setglobal pair, because they would work on every variable for
> which the TM is set (local or global, in a table or not).

Intercepting access to locals would be very difficult to implement.

IMHO, get/setglobal was mainly used for two purposes: debugging and
"magic variables" - variables that call functions when accessed.

Debugging is still possible with get/settable tags on the global
table.  It may even be more secure because it catches more kind
of accesses to the global table than get/setglobal did.

And "magic variables": get/setglobal decide by type what function
to call.  Is this really that what most people want?  Isn't it more
that they want to track special names?

See how simple it is to track that:

-------------------------------------------
global_get = {}
global_set = {}

metatable(globals(), {
    index = function(glbl, name)
        return (global_get[name] or rawget)(glbl, name)
    end,
    newindex = function(name, val)
        return (global_set[name] or rawset)(glbl, name, val)
    end
})  

-- That's all.
-- And how to use it:

function global_get.foo(_,name)
    print("getting global foo")
    return 42
end 

function global_set.foo(_,name,val)
    print("setting global foo to", val)
end 

print(foo)
print(globals().foo)      -- getglobal would never catch this!  We do.
foo="Hello"
globals().foo="World!"    -- same here
----------------------------------------------

Ciao, ET.


PS: Iirc, Roberto asked a while ago who really needs set/getglobal and nobody
cared ;-)

PPS: Btw a good example for the nexindex method ;-)