by int_19h · 2y ago · 0 comments
In cases where you really want to fetch the value or else get some default if it doesn't exist, there should be a way to do so that is distinct from regular dereferences and element access.
d["foo"] # exception if missing
d.get("foo") # None if missing
d.get("foo", 42) # 42 if missing
This follows the principle of least surprise - [] is the standard syntax for indexing, so it raises exceptions, and if you forget to check you get an error right there and then, not an unexpected but valid value (that might be saved into a variable etc and then break things much much later!). If you need a market value than you must use get(), and the very act of doing so indicates the intent to both the language and to another person reading your code.assert() also exists for this very reason.
PS: there is a performance penalty between doing d["foo"] v d.foo, one expects an expression, the other does not. So it cannot be compiled. lua also errors on use of a nil value, d.foo() will error, d.foo + 3 will also error. So while it does "silently return a marker" it will crash on runtime.