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:
The only drawback I can think of is:
?
I also oppose the ternary operator for the following reasons:
a
and b or c
already solves 90% of the problems.However, this is quite different from optional chaining:
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.
--
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.