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

So Lua has negative indexes?


It may be better to think of it as a key/value table (a "dict" or "hash") that recognizes when it's being used as an array and optimizes its internal storage accordingly. It always has dict/hash operations, but indices of 1..n are stored more efficiently, and a couple functions reflect this common & algorithmically significant case: the length operator returns the n of 1..n, and "ipairs" iterates over the {1, value}..{n, value} pairs. (The un-ordered {key,value} iterator is "pairs".)

Typically, it's clear upfront whether you're using it as an array or as a table; there isn't much overlap. I understand it being confusing in the beginning, but it's really not a big problem, it's just Lua's version of "oh god, the parens/significant whitespace/etc.". (That and indexing from 1. Not a fan of that personally, but whatever, Lua is handy.)

So yes - you can use negative numbers as indices. Or strings. Or other tables, or arbitrary C pointers. Arrays are just handled better.


It has to do with "holes" in the array. If you have a Lua array like: { 1 , 2 , 3 , nil , 5 }. That "nil" causes problems. I, personally, haven't had an issue with this, but it does come up regularly on the Lua mailing list.




Consider applying for YC's Fall 2026 batch! Applications are open till July 27.

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

Search: