[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: Safe navigation operator
- From: Cuero Bugot <cbugot@...>
- Date: Tue, 24 Aug 2010 00:52:48 -0700
> If you don't mind adding a pair of parenthesis (or quotes) to the end
> of the expression, you can get something pretty nice with __call :
Using Jerome's idea of trailing "()", I came to a minimalist way doing safe navigation:
local meta = {}
meta.__index=function(t, key)
return setmetatable({path=t.path.."."..key}, meta)
end
meta.__newindex=function(t, key, value)
print ("setter", t.path.."."..key, value)
end
meta.__call=function(t)
return "getter "..t.path
end
config = setmetatable({path=""}, meta)
> =config.network.server.url()
getter .network.server.url
> config.network.server.url = "someurl"
setter .network.server.url someurl
Of course then it still need the setter and the getter that will actually do the reading/writing in the actual config table, but that's easy :)
--------------------------------
Same, but does not even create a new table for each traversal level...
Drawback is that it is not 'thread safe', and '()' must not be forgotten or next access will be corrupted...
local meta = {}
meta.__index=function(t, key)
t.path = t.path.."."..key
return t
end
meta.__newindex=function(t, key, value)
print ("setter", t.path.."."..key, value)
t.path = ""
end
meta.__call=function(t)
local p
p, t.path = t.path, ""
return "getter "..p
end
config = setmetatable({path=""}, meta)