4 ms·
Lua’s arrays can start at index 0 if you like, there’s no real reason why the first line wouldn’t work. Starting at 1 is a convention: array = {“hello”, “worl
by teamonkey 3y ago
Lua’s arrays can start at index 0 if you like, there’s no real reason why the first line wouldn’t work.
Starting at 1 is a convention:
array = {“hello”, “world”}
print(array[1]) —- displays “hello”
array[0] = “why”
array[2] = “there”
for i=0,2 do print(array[i]) end —- “why” “hello” “there”
- dicytea 3y agoIt's cute that you can do this, but it's not a practical solution, so I don't really know why people keep bring this up. As shown by your example, arrays constructed the native way will start at 1. So you're going to need to make your own custom constructor which means additional overhead. Also, all built-in functions that expects 1-based arrays will completely break: for _, value in ipairs({[0]="foo", [1]="bar"}) do print(value) end This will print "bar" And even if you still insist on pushing through all of this friction by handrolling your own stdlib, everything is out of the window once you interact with any external library that you don't control. There's a very good reason why no one is using this trick. Anything other than 1-based indexing is just undefined behavior.
- andrewmcwatters 3y agoThere are different uses for `for’, and you’re supposed to use `for i=0, n do’ for the use case you’re describing. People absolutely do this, and you have to for things like using LuaJIT’s FFI and doing work across C.