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

> my favorite question for people who like 1-based is "Given index and length N, how do I create index-1?"

Create index-1? I don't think I've ever needed do that. What does come up all the time in practice in both JS and Lua is "how do I assign past the current end of an array?"

In javascript (if you don't use .push) its arr[arr.length] = x

In Lua its arr[#arr + 1] = x

Even having worked with 0-based indexes for over 20 years, I still doubletake reading that javascript code when it’s embedded in complex code before I can convince myself its inserting. But the lua code is intuitive.

Likewise "read the last element in an array":

JS: arr[arr.length - 1]

Lua: arr[#arr]

I much prefer the lua version in all these cases.

And simplicity is important here because the code gets much worse when the array isn't in a local variable, but instead is some complex expression. confabulate(foo.bar.baz[foo.bar.baz.length - 1]); <-- Simple statement. Absolute mess.



> if you don't use .push

I don't think I've ever needed to avoid .push.

> I still doubletake

Why? "arr[i]" just means "skip i elements and get the next one," which is perfectly intuitive to me. I understand that familiarity is useful, but can you give an intuition for one-indexing that doesn't just appeal to what people are used to?

> the code gets much worse when the array... is some complex expression

Then... don't do that? Rust has "xs.last()", Python has "xs[-1]", and every language has variables. Anyway, even if that code is an "absolute mess" (which is a bit hyperbolic) it's hardly worse than the one-indexed equivalent, which would be

    confabulate(foo.bar.baz[foo.bar.baz.length]);


    confabulate(foo.bar.baz[foo.bar.baz.length]);
The problem I have is that at a glance this looks correct. Even after decades of programming, I would scroll right past this line in JS without noticing the off-by-1 error here. The only saving grace is that this error will occur consistently.

But yes, I'd take Rust's xs.last() in a heartbeat. Especially because you can assign through it with last_mut().

That said, I agree with others in this thread. People fixate on the 1 based indexing of lua but you get used to it pretty quickly once you spend time with the language. Lua's real problem is its sparse standard library and its weak package ecosystem. If history had run its course slightly differently, I could easily see lua ending up inside web browsers instead of javascript. And becoming much more popular as a result. Lua and javascript are remarkably similar languages semantically.




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

Search: