[Date Prev][Date Next][Thread Prev][Thread Next]
- Subject: Re: Long chains of objects (aka tables)
- From: "Thiago L." <fakedme@...>
- Date: Sat, 17 May 2014 14:07:57 -0300
On 17/05/2014 13:54, Jay Carlson wrote:
I want something like |local v = t?t1?t2?t3|... (actually I want |local
v = t?.t1?.t2?.t3|...)
On May 16, 2014, at 6:45 PM, Thiago L. <firstname.lastname@example.org> 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
local v = t and
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.