lua-users home
lua-l archive

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


On 23 August 2010 13:11, Cuero Bugot <cbugot@sierrawireless.com> wrote:
> Hi all,
>
> I came across a case where I found no short way to write it in Lua. This case could be solved with a "Safe navigation operator" (at least it is the way it is called in Groovy).
>
> The problem happens (for example) when you use multiple level tables to store configurations. For example, you store something like:
>        config.network.server.url = "xxx"
> If the parameter is optional, or if you do not want bad surprise, when you want to use it you need to write:
>        if confg.network and config.network.server and config.network.server.url then
>                dosomething(config.network.server.url)
>        End
>
> This is quite verbose, and it could be nice if it returned nil if one of the level of "config.network.server.url" is nil...
> (See Safe navigation operator in groovy)
>
> So the next step was "Well Lua is wonderful, it'll be easy to implement that 'specific' behavior with metamethods!". But after a little though and tries out, I realized that this use case was not coverable with __index / __newindex, because those metamethods lacks a 'context'.
>

Actually it is:

   debug.setmetatable(nil, { __index = {} })

You could turn this into a function to turn the feature on and off for
certain sections of code.

Matthew