ANSWER : only use table.* functions on sequences (arrays/list) (tables with only consecutive integer keys starting at 1). Their behavior is undefined on non array-like table: they may or may not work as you could expect.
In Lua 5.1 table.insert( t, index, value ) is supposed to move up values if index already exist in the table, right ?
But it doesn't always do that :
local t = {}
table.insert( t, 4, 5 )
table.insert( t, 5, 6 )
table.insert( t, 4, 4 ) -- this erase the value 5 at key 4
-- t[4] = 4, t[5] = 6, t[6] = nil
local t = {}
table.insert( t, 1 )
table.insert( t, 2 )
table.insert( t, 3 )
table.insert( t, 6, 7 )
table.insert( t, 6, 6 ) -- this erase the value 7 at key 6
-- t[6] = 6, t[7] = nil
But :
local t = {}
table.insert( t, 1 ) -- these two lines were added
table.insert( t, 2 )
table.insert( t, 4, 5 )
table.insert( t, 5, 6 )
table.insert( t, 4, 4 ) -- now it moves the values up
-- t[4] = 4, t[5] = 5, t[6] = 5
local t = {}
table.insert( t, 1 )
table.insert( t, 2 )
table.insert( t, 3 )
table.insert( t, 4 ) -- this line was added
table.insert( t, 6, 7 )
table.insert( t, 6, 6 ) -- now it moves the values up
-- t[6] = 6, t[7] = 7
This works like that in LuaForWindows command line as well an application that runs lua scripts (CraftStudio), both using Lua 5.1.
It seems that it happens when
- (number of entries) < index (for the first example)
- (number of entries) < index-1 (for the second example)
So, is this an expected behavior, a bug of Lua 5.1 ? Is there another formula to predict if this will happens or not ?
Thanks a lot