lua-users home
lua-l archive

RE: Metatables

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


Well, I've found a situation for which my 'proxy' object cannot help: operator ==. In the
previously mentioned language (FOOBAR) we can have:
 if state == 0 then
 state = state + 1
 end
Where 'state' need not exist before the boolean expression. If it doesn't exist, it is created
and initialized to zero, so this boolean would evaluate to true.
Without a 'metaevent' for ==, I don't know what to do. The proxy gets me 99% of the way there,
but without this last 1% I'll be forced to use plan B. Plan B is to analyze the FOOBAR source,
trying to guess which variables in which expressions are not initialized. This will be impossible
to do with 100% accuracy, because FOOBAR variables are all global, and the order in which a
project's scripts are run is non-deterministic (event driven). Is 'state = 10' the first-time
initialization of 'state'? It depends on whether the script containing this line executes before a
script that uses 'state' in an expression.
Anyway, any ideas are welcome. I've reposted the proxy code I'm using below.
Cheers,
Eric
-- proxy.lua
local
 proxy_toval,
 proxy_tonum, 
 proxy_tostr, 
 proxy_metatable
function proxy_toval(p,val)
 if type(p) == "table" and metatable(p) == proxy_metatable then
 setglobal (p.name, val)
 return val 
 else
 return p
 end
end
function proxy_tonum(p)
 return proxy_toval(p,0)
end
function proxy_tostr(p)
 return proxy_toval(p,"")
end
proxy_metatable = {
 add = function(l,r) return proxy_tonum(l) + proxy_tonum(r) end,
 sub = function(l,r) return proxy_tonum(l) - proxy_tonum(r) end,
 mul = function(l,r) return proxy_tonum(l) * proxy_tonum(r) end,
 div = function(l,r) return proxy_tonum(l) / proxy_tonum(r) end,
 pow = function(l,r) return proxy_tonum(l) ^ proxy_tonum(r) end,
 unm = function(o) setglobal(o.name, 0) return 0 end, 
 concat = function(l,r) return proxy_tostr(l)..proxy_tostr(r) end,
 settable = function(t,k,v) 
 local nt = {}
 rawset (nt, k, v)
 setglobal (t.name, nt)
 end,
}
metatable (
 globals(), {
 index = function(t,k) 
 local proxy = { name = k }
 metatable (proxy, proxy_metatable)
 rawset (t, k, proxy) 
 return proxy 
 end,
 })
__________________________________________________
Do You Yahoo!?
Try FREE Yahoo! Mail - the world's greatest free email!
http://mail.yahoo.com/

AltStyle によって変換されたページ (->オリジナル) /