lua-users home
lua-l archive

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


On May 16, 2014, at 6:45 PM, Thiago L. <fakedme@gmail.com> wrote:

> So I did some benchmarking: https://gist.github.com/SoniEx2/4b1d9d8e6427cf5a1439
> 
> It seems like pcall is almost the best way to do Groovy's ?. stuff in Lua: http://groovy.codehaus.org/Null+Object+Pattern
> (let me quote it)
> "with the |?.| operator, an expression like |p?.job?.salary| will be equal to null if |salary| is equal to null, or if |job| is equal to null or if |p| is equal to null. You don't need to code a complex nested |if ... then ... else| to avoid a |NullPointerException|."
> (actually pcall is more like catching a NullPointerException but w/e)

If you can stand doing this at statement context, you could macro-transform

    local v ?= t.t1.t2.t3

into either

    local v = t and 
      t.t1 and 
      t.t1.t2 and 
      t.t1.t2.t3

or 

    local v = t
    v = v and v.t1
    v = v and v.t2
    v = v and v.t3

In the case of the (unrealistic) nesting level of that gist, the latter seems about ten times faster. At a depth of 4 it's only ~2.5 times faster.

If there were a way to change the definition of "." inside a lexical scope, that might be interesting. Going after nil's metatable will break code outside the consenting scope.

Jay