lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


The "Programming in Lua" book says:
> we can start the indices of an array with any number that pleases us

These words seem to be very misleading.
Sometimes Lua has a terrible performance problem with 0-based arrays.
In the following simple example 0-based array is 1000+ times slower than 1-based array!

$ cat program.lua
local game_field = {}
local game_size = 1000000
local base_index = tonumber(arg[1])
print("Array indices start with "..base_index)

local function initialize_game_field()
   for j = base_index, base_index + game_size - 1 do
      game_field[j] = "white"
   for j = base_index + game_size, base_index + 2*game_size - 1 do
      game_field[j] = nil
   for j = base_index + 2*game_size, base_index + 3*game_size - 1 do
      game_field[j] = "black"


$ lua -v
Lua 5.4.2  Copyright (C) 1994-2020, PUC-Rio

$ time lua program.lua 1
Array indices start with 1

real    0m0.400s
user    0m0.360s
sys     0m0.036s

$ time lua program.lua 0
Array indices start with 0

real    24m12.488s
user    24m8.532s
sys     0m2.376s

Is it a bug that will be fixed in the next bugfix release of Lua?
Or is it an inherent Lua feature every Lua programmer should be aware of?