Why is my table being erased to the first index?

I got a script here that replaces a table value from nil to 0.
The table is initialized like this:
local PlayerInv = {40,nil,nil,nil,nil,nil,20,nil,nil,nil,nil,nil,20,nil,nil,nil,nil,nil,20,nil,nil,nil,nil,nil,25,nil,nil,nil,nil,nil,10,nil,nil,nil,nil,nil,10,nil,nil,nil,nil,nil,3,6,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,4,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,nil,4}
I had to do it that way because previously, it would erase every value from index 2 and on. So, i had to manually type out the table like this. And yes, i did use table.insert. Didn’t work

Anyways, im using a module function to replace one of these nils with a 0. The script looks like this:
scriptproblem

at the “set” intent, im trying to replace the nil with a 0. It iterates the inventory perfectly, printing off the correct values. But the moment it gets to Inventory[Data] = number, it will print 20. meaning EVERYTHING but the 1st index was wiped. Idk why it does this, but its really irritating. Any ideas?

here is the print log:
40
nil(x5)
20
nil(x5)
20
nil(x5)
20
nil(x5)
25
nil(x5)
10
nil (x5)
10
nil(x5)
3
6
nil(x13)
4
nil(x13)
4

40

1 Like

Btw, im trying to change the 73rd index. It doesnt exist yet. Is that the problem?

Nil elements don’t exist in tables. The only thing you’ll do when initialising a table like that is increase its initial size (like table.create which will create a table at size n initially). It’s the same thing with a dictionary: keys are nil.

local dictionary = {
    ["foo"] = "bar" -- index "foo" exists with value "bar"
}

-- set the index of "foo" to nil, equivalent to having one of those nils
-- from your PlayerInv table
dictionary["foo"] = nil

print(dictionary["foo"]) -- nil

What I’m trying to say is: your table only contains non-nil elements. So take your PlayerInv table, remove the nils, that’s what the table actually looks like. So that 73rd element you’re expecting to change, assuming it’s non-nil, is actually at a significantly lower index.

Initialise it with something other than nil, otherwise you’ll encounter this error. For example, you can use a literal string “nil” or “N/A”.

But prior to this bug, it worked fine? i was able to fetch values from beyond and they worked fine. However, i did suspect this was the case, which calls for a recode. :sob:

Ill mark your answer right when I test it