Table.insert is removing values?

I’m trying to use table.insert to add values to a pre-made table.

local drops = {
    [3] = "Sword",
    [6] = "Sword +1",
    [7] = "Shield"
}

for i = 1, 2 do
    table.insert(drops, i, "Gold")
end

for i = 4, 5 do
    table.insert(drops, i, "Gold")
end

print(drops)

However, any index before the pre-made index is being removed (ex table.insert(drops, 2, “Gold”) will remove [3] = “Sword”) and index 6 and 7 are being shifted up by 1, leaving index [3] and [6] “void”, or nil.
This is what the output shows:
image

and can be tested using this code:

local test = {
    [3] = "Three"
}

table.insert(test, 2, "Two")

print(test) -- [3] = "Three" is suddenly missing

I’ve already thought about using table[index] = value instead as shown below which works properly, but I was wondering if this is a problem with my coding, roblox engine, or the function itself. Can anyone else get the same result, or give me insight on this? If this is really a bug, then could someone else report this issue because I do not have permission to post there.

local drops = {
    [3] = "Sword",
    [6] = "Sword +1",
    [7] = "Shield"
}

for i = 1, 2 do
    drops[i] = "Gold"
end

for i = 4, 5 do
    drops[i] = "Gold"
end

print(drops)
2 Likes

I think the Roblox table.insert() documentation could lead one to not realize
the shifts–See:
https://www.lua.org/manual/5.1/manual.html#pdf-table.insert

Probably contributing to your confusion is how # in Lua actually works–
It often confuses people, as what it actually does is not what one might think:
https://www.lua.org/manual/5.1/manual.html#2.5.5

“I’ve already thought about using table[index] = value instead as shown below which works properly…”
Yes do this instead, as this appears to be what you are trying to accomplish.

I know that shifting works properly in Roblox:

local tab = {
    [4] = "Hi"
}

table.insert(tab, 4, "New")

print(tab) -- [4] = "Hi" has been shifted to [5] = "Hi" and [4] = "New" now exists

The problem here is that it is shifting the value when i = i - 1 which somehow also deletes the value.

local tab = {
    [4] = "Hi"
}

table.insert(tab, 3, "New")

print(tab) -- [4] = "Hi" has been shifted to "void" and no longer exists. [3] = "New" now exists by itself.

I do not believe this is intended behavior, or am I missing something here?

1 Like

I’m not good at tables but is your script replacing tables Edit: I don’t think it’s possible that happens

Or wait, is it because [3] = nil so when table.insert is called, [3] = nil is being shifted to [4] = “Hi” which causes it to become nil? That makes much more sense to me.

Nvm so it’s possible your replacing the tables with nil so try to fix that

When you have a table that’s like an array, but really isn’t, it can be quite a mess to deal with.
A proper array starts at index 1 and has no holes in it.