Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I force Lua's table indexing to start from zero?

Tags:

indexing

lua

I have an issue with Lua. It uses one-based indexing. The language has a feature to set value at index 0, but the value won't be counted as a part of table length, and string manipulations are still one-based. Therefore, I think the feature is something special rather than about indexing.

I don't want a flame about one-based or zero based. I'm just asking is there a feature to force zero-based indexing.

like image 840
eonil Avatar asked Aug 07 '10 13:08

eonil


2 Answers

Working with 0-indexed arrays is actually pretty simple:

local array={
[0]="zero",
    "one",
    "two"
}

for i=0,#array do
    print(array[i])
end

You can use #array without subtracting 1 because the length operator actually returns the highest index (technically, the key before the first nil), not the actual "length" (which wouldn't make sense in Lua anyway).

For string operators, you'll probably have to just create duplicate functions (though there might be a better way)

ipairs() also only supports 1 indexing, so you'll have to define your own function or just use a regular for instead.

like image 151
12Me21 Avatar answered Oct 01 '22 01:10

12Me21


I know this question is already 1 year old, but I thought future seekers would be interested in the fact, that CFF Explorer contains a scripting language (Lua with patches), which has 0-indexed table patch:

http://www.ntcore.com/files/cffscriptv2.htm

Also, in the document above, the author stated that he had to disable most of the standard library functions, because they're incompatible with 0-indexed arrays, so please reiterate your thought process about this issue :)

like image 37
antekone Avatar answered Oct 01 '22 02:10

antekone