lua-users home
lua-l archive

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


On Mon, Aug 23, 2010 at 1:25 PM, Cuero Bugot <cbugot@sierrawireless.com> wrote:
>> 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.
>
> Indeed this is a way to do it, but it is rather intrusive :) The fact is that I cannot isolate part of the code need this "safe navigation operator" or not, since it is usually embedded in the code here and there.
>
>

If you can live with this syntax (or you are able to use a token
filtering system to transform your ideal syntax - perhaps Groovy's -
into this):

  if safenav(config,'network','server','url') then
    dosomething(config.network.server.url)
  end

...then this should work for you:

  function safenav(v, ...)
    for i = 1, select('#', ...) do
      if (v == nil) then  return nil;  end
      v = v[select(i, ...)]
    end
    return v
  end

-Duncan