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

Viewed 8093

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.

10 Answers

The direct answer: Modify the source code of Lua. Change all the operations on lua table to base-0.

Here I'm doing it, along with Lua standard library. Windows binary available.

http://lua-users.org/wiki/CountingFromOne (some comment at the bottom)

https://github.com/farteryhr/lua-base-0 (see the commit history for what have been modified)

Mostly dirty work about +1 -1, and most of them have been done.

Please write some test cases (covering as many details of the language as possible) and report bugs.

(For now it's known there's still something wrong with metatable, but I can't find time to investigate it)

You can fix this lua-flaw by using an iterator that is aware of different index bases:

function iarray(a)
  local n = 0
  local s = #a
  if a[0] ~= nil then
    n = -1
  end
  return function()
    n = n + 1
    if n <= s then return n,a[n] end
  end
end

However, you still have to add the zeroth element manually:

Usage example:

myArray = {1,2,3,4,5}
myArray[0] = 0
for _,e in iarray(myArray) do
  -- do something with element e
end

I've found when interfacing with a 0 indexed language (C for example) it is easiest to just not use index 0. It is wasteful of memory, but changing lua is pretty absurd.

Related