1

In lua, if we try to index a series of nested table (any of which can be nil), we might write code like this:

-- try to get a.b.c

local ret
if a then
    local b = a.b
    if b then
        ret = b.c
    end
end

Which I think is lenthy and ugly. There are also simpler ways:

-- method 1
local ret = a and a.b and a.b.c

-- method 2
local ret = ((a or {}).b or {}).c

I know I'm splitting hairs, but these two methods are still not perfect, method 1 causes more index operations (do a.b twice), method 2 create some unnecessary tables.

So I wonder if there is a way with no side-effect like '?.' in C#? Or '?.' operator violates lua's design philosophy?

2
  • 1
    Lua doesn't even have ++ or +=, yet you ask for null conditional operator? This is too ahead of its time. Commented Jan 18 at 9:30
  • isn't a and a.b equivalent to a?.b in C#? Commented Jan 18 at 13:41

1 Answer 1

1

Just write a function:

local function nestedIndexOrNil(t, ...)
  for _, k in ipairs{...} do
    if not t then
      return nil
    end
    t = t[k]
  end
  return t
end

nestedIndexOrNil(a, 'b', 'c')
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.