Proposal: Optional Chaining

158 views
Skip to first unread message

最萌 小汐

unread,
Apr 25, 2024, 4:06:09 AM4/25/24
to lu...@googlegroups.com

I hope Lua can support optional chaining syntax:

v1 = a?.b --> if a ~= nil then v1 = a.b else v1 = nil end v2 = a?[1] --> if a ~= nil then v2 = a[1] else v2 = nil end a?() --> if a ~= nil then a() end a?:f() --> if a ~= nil then a:f() end a?.b = 1 --> if a ~= nil then a.b = 1 end a?[1] = 1 --> if a ~= nil then a[1] = 1 end a[b?] = 1 --> if b ~= nil then a[b] = 1 end

In actual Lua usage, I often encounter situations where I need to chain multiple nil checks, such as when reading from a data table:

local hp = UnitData[id] and UnitData[id].attributes and UnitData[id].attributes.hp

This approach is hard to read, error-prone, and affects performance. If Lua supported optional chaining syntax, it could be written as:

local hp = UnitData[id]?.attributes?.hp

Moreover, I encounter scenarios where I need to check for nil return values from functions and store the result to avoid side effects:

local hp local attributes = Unit.attrModule and Unit.attrModule:makeAttributes() if attributes then    hp = attributes.hp end

This code is verbose, and the actual logic is drowned in the nil-checking code. Using optional chaining can cleanly achieve this functionality:

local hp = Unit.attrModule?:makeAttributes()?.hp

I believe optional chaining offers the following advantages:

  1. Reduces code length and improves code readability
  2. Reduces performance loss caused by manual nil-checking
  3. More rigorous nil-checking; manually written nil-checking may miss certain cases (e.g., when the value is false or when repeated function calls cause side effects)
  4. Fully compatible with existing Lua code
  5. As it is an entirely new syntax, it does not affect the semantics of existing code or introduce additional performance overhead

The only drawback I can think of is:

  1. Introducing new symbols and syntax, such as ?

-- sumneko

bil til

unread,
Apr 25, 2024, 5:58:18 AM4/25/24
to lu...@googlegroups.com
Am Do., 25. Apr. 2024 um 10:06 Uhr schrieb 最萌 小汐 <sum...@hotmail.com>:
>
> I hope Lua can support optional chaining syntax:
>
> v1 = a?.b --> if a ~= nil then v1 = a.b else v1 = nil end

Did you create the ingenious "Sumneko Lua-Add-On" for Visual Studio Code?

If yes, thank you very much for this - this is super-great.

... just please understand that a very good point of Lua is, that the
source code + parser is very compact.

and additionally that the number of keywords / "coding tricks" is very
restricted. This to my experience makes it much easier to learn for
newbees / trainees than C. (just C notation of course has the
advantage, that it has so wide application range, that it is somehow
"common by itself" to many people... just please take care to separate
your own "experienced C programmer" feelings from the feelings of
"newbees" / "sometimes programmers").

Adding new symbols into Lua code like the ? in your proposal for sure
would be a VERY heavy decision - I from my side would not support
this, sorry.

(Did you check the chapter "Booleans" in Roberto's Book "Programming
in Lua" - there the notation "a and b or c" for C notation "a ? b : c"
is clearly described... and to my experience with trainee C training,
the expression "a ? b : c" is better NOT to show to newbees/trainees -
they anyway need some C programming experience before they start to
like this expression...).

Sainan

unread,
Apr 25, 2024, 6:14:23 AM4/25/24
to lu...@googlegroups.com
Sven Olsen published a patch that adds exactly that to Lua[1]. I'm sure
you're also aware of various forks of Lua such as Pluto which offer
syntax sugar like this[2].

[1] See "Safe Navigation" at http://lua-users.org/wiki/SvenOlsen
[2] https://pluto-lang.org/docs/New%20Features/Safe%20Navigation

最萌 小汐

unread,
Apr 25, 2024, 6:37:57 AM4/25/24
to lu...@googlegroups.com

I also oppose the ternary operator for the following reasons:

  1. It introduces 2 new symbols.
  2. The existing a and b or c already solves 90% of the problems.
  3. Its syntax is very unique, requiring an additional learning curve.
  4. It doesn't save much code or reduce cognitive load compared to existing solutions.

However, this is quite different from optional chaining:

  1. It introduces 1 new symbol, which is indeed a drawback.
  2. Existing solutions have their own drawbacks.
  3. Its syntax is not unique; someone familiar with Lua can intuitively guess its meaning.
  4. Compared to existing solutions, it can save a significant amount of code and reduce cognitive load.


发件人: lu...@googlegroups.com <lu...@googlegroups.com> 代表 bil til <bilt...@gmail.com>
发送时间: 2024年4月25日 17:58
收件人: lu...@googlegroups.com <lu...@googlegroups.com>
主题: Re: Proposal: Optional Chaining
 
--
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to lua-l+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/lua-l/CAOnDXmH8g2GpJYrvfbhT0QtUZcxH%3DQuLN2sTrnPuX7Wg0Dq1Rg%40mail.gmail.com.

最萌 小汐

unread,
Apr 25, 2024, 6:44:56 AM4/25/24
to lu...@googlegroups.com
Thank you for providing this information, but I don't like using Lua dialect syntax. I hope PUC Lua can do better.

-- sumneko

发件人: lu...@googlegroups.com <lu...@googlegroups.com> 代表 Sainan <sai...@calamity.gg>
发送时间: 2024年4月25日 18:13

收件人: lu...@googlegroups.com <lu...@googlegroups.com>
主题: Re: Proposal: Optional Chaining
--
You received this message because you are subscribed to the Google Groups "lua-l" group.
To unsubscribe from this group and stop receiving emails from it, send an email to lua-l+un...@googlegroups.com.

Sainan

unread,
Apr 25, 2024, 7:02:06 AM4/25/24
to lu...@googlegroups.com
On 2024-04-25 12:44, 最萌 小汐 wrote:
> Thank you for providing this information, but I don't like using Lua
> dialect syntax. I hope PUC Lua can do better.

I point this out because PUC Lua is not exactly known for syntax sugar.
'break' as a shorthand for 'goto break' might be the only example.

rolf.kal...@kalbermatter.nl

unread,
Apr 25, 2024, 8:08:53 AM4/25/24
to lu...@googlegroups.com
One of the main guiding lines with the Lua creators is to keep it lean and mean in order to let it run on even very resource constrained hardware platforms. Syntactic sugar is the exact opposite to that!
Yes it may shorten some scripts somehow, but each such feature requires extra code in the Lua kernel, that needs to be designed, fit into the existing infrastructure without affecting anything else and of course tested extensively. There is always the chance that halfway through you discover that it has some undesirable effects on the parsing code, either making parsing more complicated or even introducing ambiguities that need to be resolved or worked around.

So it is not something to take easily and introducing such a feature requires a lot of preparation, discussion, controversy and sometimes fighting. :-)

Rolf Kalbermatter

Scott Morgan

unread,
Apr 25, 2024, 9:42:28 AM4/25/24
to lu...@googlegroups.com
On 25/04/2024 13:08, rolf.kal...@kalbermatter.nl wrote:
> One of the main guiding lines with the Lua creators is to keep it lean
> and mean in order to let it run on even very resource constrained
> hardware platforms. Syntactic sugar is the exact opposite to that!

That's only somewhat true, because there is sugar in Lua (function
definitions for example)

So the real question is how much does the proposed sugar cost, in terms
of code support and memory usage, and is it worth it. Which is
ultimately a value judgement.

It's not the first time this (or similar) syntax has been proposed.
Personally, I like it, it fits with a lot of my use cases nicely. But I
know the Lua team have generally been indifferent to it.

Scott

rolf.kal...@kalbermatter.nl

unread,
Apr 25, 2024, 10:23:59 AM4/25/24
to lu...@googlegroups.com


On 25 April 2024 at 15:42:25 +02:00, 'Scott Morgan' via lua-l <lu...@googlegroups.com> wrote:
It's not the first time this (or similar) syntax has been proposed. Personally, I like it, it fits with a lot of my use cases nicely. But I know the Lua team have generally been indifferent to it.
I find this solution indeed quite elegant and if it was possible to be added without making Lua significantly more complex it would be a nice idea. On the other hand I'm not going to sleep one minute less if it never gets into Lua.

Rolf Kalbermatter


Luiz Henrique de Figueiredo

unread,
Apr 25, 2024, 3:57:31 PM4/25/24
to lu...@googlegroups.com
Some of this request is addressed in the thread below without syntax modifications.

Rett Berg

unread,
Apr 25, 2024, 6:04:53 PM4/25/24
to lua-l
I got nerd-sniped here :D

I've written two functions which I (think?) solve this very permanently. I will be including them as part of ds[1]

local keyPath
keyPath = mty.doc[[keyPath(t, 'a', 2, 'c') -> t.a[2].c]]
(function(t, ...)
  if(nil == ...) then return t end
  return keyPath(t[...], select(2, ...))
end)
M.keyPath = keyPath

local tryPath; tryPath = mty.doc[[
tryPath(t, 'a', 2, 'c') -> t.a?[2]?.c
Looks up the values at the path, returning nil if any are nil.
]](function(t, ...)
  if(nil == (...)) then return t end
  local v = t[...]; if v == nil then return end
  return tryPath(v, select(2, ...))
end)
M.tryPath = tryPath


Rett Berg

unread,
Apr 25, 2024, 6:05:24 PM4/25/24
to lua-l
permanently -> performantly (stupid spell check)

Rett Berg

unread,
Apr 25, 2024, 8:09:30 PM4/25/24
to lu...@googlegroups.com
I've modified it slightly to use a for loop instead of recursion. I'm also calling it just "get"

M.get = mty.doc[[
get(t, 'a', 2, 'c') -> t.a?[2]?.c?
get the keys or nil if any are missing.
]]
(function(t, ...)
  local len = select('#', ...)
  for i=1,len-1 do
    t = t[select(i, ...)]
    if t == nil then return end
  end
  return t[select(len, ...)]
end)

--
You received this message because you are subscribed to a topic in the Google Groups "lua-l" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/lua-l/QaSBdasU-Us/unsubscribe.
To unsubscribe from this group and all its topics, send an email to lua-l+un...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/lua-l/13af80d5-b7e4-4214-ae4d-ba8e1017a27dn%40googlegroups.com.
Reply all
Reply to author
Forward
0 new messages