3 ms·
How about this: The empty string and 0 are truthy. Why?
by TedDoesntTalk 6y ago
How about this: The empty string and 0 are truthy. Why?
- cl3misch 6y agoMaybe because all variables are `nil` by default, and checking on undeclared variables does not raise an error. So `if foo then ... end` is often used as an existence check, where `foo = 0` should be truthy.
- anonymoushn 6y agoThis is probably a good thing, if you don't want to have tickets filed about whether midnight (time of day) is truthy, whether Jan 1, 1970 is truthy, why some type of empty collection is truthy but others are not, etc.
- pansa2 6y ago> This is probably a good thing, if you don't want to have tickets filed about whether midnight (time of day) is truthy Agreed. Here is an example of exactly that in Python: https://bugs.python.org/issue13936 https://bugs.python.org/issue13936
- DarkWiiPlayer 6y ago0? Because Lua isn't C. It makes sense for C to treat 0 as falsey, because (void*)0 is Cs way of expressing a nil-value, as well as not having a dedicated boolean value to keep the language simpler. Lua, both has a dedicated nil value and a boolean type, so there's no reason whatsoever to treat zero as falsey, other than the C cargocult. As for empty strings, I really don't see the rationale behind it. An empty string is not nothing. At the very least, it still holds the length-data of 0, so it's conceptually more than just nil and should thus still be truthy.
- pansa2 6y agoIf you make the empty string falsy, surely you need to make all empty collections falsy? Python does this, which leads to people checking whether a list is empty using `if l` rather than `if len(l) > 0`. I‘d rather they stuck with “explicit is better than implicit”.