I hope Lua can support optional chaining syntax:
v1 = a?.b -->ifa ~=nilthenv1 = a.belsev1 =nilendv2 = a?[1] -->ifa ~=nilthenv2 = a[1]elsev2 =nilenda?()-->ifa ~=nilthena()enda?:f()-->ifa ~=nilthena:f()enda?.b =1-->ifa ~=nilthena.b =1enda?[1] =1-->ifa ~=nilthena[1] =1enda[b?] =1-->ifb ~=nilthena[b] =1end
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].attributesand 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:
localhp = 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:
localhplocalattributes =Unit.attrModuleandUnit.attrModule:makeAttributes()ifattributesthenhp = attributes.hpend
This code is verbose, and the actual logic is drowned in the nil-checking code. Using optional chaining can cleanly achieve this functionality:
localhp =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.