Hacker News new | ask | show | jobs
by aethy 1341 days ago
Yeah; the indexing is weird when you're not used to it; but honestly I find starting arrays at 1 is actually incredibly useful for business logic. It's terrible for math, but it allows you to use things like truthiness really effectively for compound statements that return indices and stuff.

Like, for example, `string.find` returns the index where something's found. You can just do `if str:find("a")` if you want to test to see whether a string contains "a", whereas in most other languages that test for location you're required to check that the result isn't equal to `string::npos`, `null` (if your langauge supports that), `-1`, or some other value that's not 0. Lua, you can assume that it's truthy if it's found, because 1 is the start of the string, not 0.

Took me a while to get used to, but I really like the idiom now for things that just high-level string stuff, and glue code.

1 comments

I don't mean to screw up the whole vibe of your comment, but...

    if 0 then
        print('0 is true')
    else
        print('0 is false')
    end
prints "0 is true". The reason why "you can just do `if str:find('a')`" is because it returns nil.

string.find never returns 0.

That's what I mean. It never returns 0, so is thus always truthy if it finds something.

If you do `if (str.indexOf("a"))` in javascript; you'll miss out on the case where the string starts with "a", because the index returned 0, which is falsy.

EDIT: Oh, sorry, I see what you mean. You're right, my bad.

EDIT2: I guess, let me rephrase. 0 is rarely returned for things, so the falsiness of it doesn't usually enter into the equation. So you can do things like that, regardless of the truthiness of 0, because it's not used, whereas in other langauges, you usually have to check, unless they have 0 as truthy as well. (though I guess this isn't much of an argument in favour of 1-indexes)

Some additional context for us lua noobs:

>Conditionals (such as the ones in control structures) consider false and nil as false and anything else as true. Beware that, unlike some other scripting languages, Lua considers both zero and the empty string as true in conditional tests.

https://www.lua.org/pil/2.2.html

>The basic use of string.find is to search for a pattern inside a given string, called the subject string. The function returns the position where it found the pattern or nil if it could not find it.

https://www.lua.org/pil/20.1.html