lua-users home
lua-l archive

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




On Saturday, May 17, 2014, Thiago L. <fakedme@gmail.com> wrote:

On 17/05/2014 13:54, Jay Carlson wrote:
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
I want something like |local v = t?t1?t2?t3|... (actually I want |local v = t?.t1?.t2?.t3|...)


I think that an important detail is that both selectors are important, sometimes in the same object. Usually a specific property group or mixin is optional, but not every branch on the tree is. 

Also, ? In an assignment should be error:

A?b = c
--error