On Sat, Feb 29, 2020 at 9:26 PM connor horman wrote:
I’ve used some strongly typed languages that have a “try operator”.
t?[a]?[b]?[c]?[d]?[e] would be equivalent to t[a][b][c][d][e], but if any evaluation preceded by a ? has a false value (false or nil), the result of the entire _expression_ is that value (short circuiting). This only short circuits out of chains of index expressions (of all forms), and function calls.
What about adding "try-version" of every Lua operator? t?[index] = indexing: return nothing if t is nil
t?.field = indexing: return nothing if t is nil
t?:method() = invoking a method, return nothing if t is nil
func?(arg1,arg2,..) = calling a function: return all the arguments if func is nil
a ?+ b = adding: (a or 0)+(b or 0)
?- a = negating: -(a or 0)
a ?~ b = XORing: (a or 0)~(b or 0)
a ?& b = ANDing: (a or -1)&(b or -1)
a ?* b = multiplying: (a or 1)*(b or 1)
a ?/ b = dividing: (a or 0)/(b or 1)
a ?% b = taking modulo: (a or 0)%(b or infinity)
a ?^ b = raising to power: (a or 0)^(b or 1)
a ?< b = comparing: nil is replaced with the minimal possible value of the datatype
a ?== b = comparing: nil is replaced with 0 or empty string depending on the datatype
a ?.. b = concatenating: (a or '')..(b or '')
?# a = taking length: return 0 if a is nil
Many of these, excluding ?# don’t have sensible defaults with operator overloading (which we get from metatables). All forms of indexing and function calls are easy: evaluate the _expression_ if the root (t in this case) is neither false nor nil, otherwise, return the root. Adding the rest would complicate things greatly.