lua-users home
lua-l archive

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





On Sat, May 17, 2014 at 1:50 PM, Andrew Starks <andrew.starks@trms.com> wrote:


On Saturday, May 17, 2014, Roberto Ierusalimschy <roberto@inf.puc-rio.br> wrote:
> I want something like |local v = t?t1?t2?t3|... (actually I want
> |local v = t?.t1?.t2?.t3|...)

Another option:

   local v = (((t or E).t1 or E).t2 or E).t3

(where E={} is defined somewhere in your code...)


For practical use cases that I've run into, where it's only one or two points in the chain, this solution would work for me. 

Thank you! 

-Andrew 
-- Roberto



After playing with this:

```
local empty 
empty = setmetatable({}, {
__index = function()
return empty
end

})

local a = {b ={c = {d = nil}}}
print(((a.b.c.d or empty).e.f or empty).g )
```

I don't like it as much. Maybe someone has some ideas. Most often I'm  checking to see if something exists or if it does it could be a table. With this, I'd have to say:


```
local ((a.b.c.d or empty).e.f or empty).g  = test_val
if  not (test_val == nil or test_val == empty) then

end


I'm not sure that that is all that much pretty or clearer than:

-- check for g, but first check if d as there and it has a valid f.
if a.b.c.d and a.b.c.d.e.f and a.b.c.d.e.f.g then

I'd much prefer:

if a.b.c?d.e?f.g then -- (or the .?)


but that's just me.But it's not a giant pain, either.


-Andrew