4 ms·
I do not know how/why the language should magically know that something should error, if nil is not acceptable as a return then you use || or "this". if the tab
by nmz 2y ago
I do not know how/why the language should magically know that something should error, if nil is not acceptable as a return then you use || or "this". if the table should not have nils then you turn it into a metatable that errors or returns whatever you want it to.
- int_19h 2y agoThe language should not "magically know" anything. It should do the safest thing, which is not to silently return a marker value for which there is no guarantee whatsoever that the caller will remember to check it. If the caller does not want to see an error, then they should use a different method of retrieving the item that is specifically defined as returning a marker value. E.g. in Python: 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.
- nmz 2y agoThis is your opinion on what the default behavior of nil should be, fortunately, We can disagree and you can set a metatable that errors on nil, I will choose to do or not do that depending on the object. 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.