Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

What do you want it to return though?

x = f() or "default value"

or maybe you want it to error

x = f() or error"F failed"

or maybe x is an object in which case you can just

setmetatable(x,{__index = function () return "" --[[default value here]] end})

or maybe you don't want nils, in which case

debug.setmetatable(nil, {}) -- actually this one is complicated, but yeah, you can use this.



The default should be an error, since that's the only way to prevent issues where the wrong value gets passed around a lot before finally blowing up somewhere else (and good luck debugging that).

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.


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.


The 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.


This 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: