lua-users home
lua-l archive

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


Perhaps you can use __call args as the default value, if it was not
set by the user. This way, the extra () will be less likely to be
forgotten.

On 8/24/10, Cuero Bugot <cbugot@sierrawireless.com> wrote:
>
>> 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)
>
>
>
>
>
>
>

-- 
Sent from my mobile device