Why do some people use table[index + 1] instead of table.insert?

Technically, with generalized iteration you don’t have to use either

they are both the same, though technically index could be a specific value that needs to be asserted rather than just placing into table with .insert

as for this, I tend to do this when the index isnt a number value like

table[playerInstance] = nil

from what i remember you cant table.remove an instance index? I think its because there is no number value, i could be wrong but that is what I’ve stuck with so I believe this is the case.

You mean you can just use like next() or just:

--Example code

for i,v in t do
   --code here
end

Glad to see this post having a lot of answers.

(This is my new account, previously @AridFights1; OP of the post)

Over the past year, I have learnt a lot, so here’s my ultimate summary of this entire post.

Difference between array and dictionary

Normally, tables look like this:

local Table = {} :: { [any]: any }

When these tables have indices which are numbers, they are known as “arrays”.

local Array = {} :: { [number]: any }

But when tables contain indices which are numbers, strings, objects etc. they are known as dictionaries.

local Dictionary = {} :: { [number | string | any]: any }
table.insert behaviour

If you insert a value using table.insert and remove it using table.remove it will remove the unused index and organize items accordingly.

Code:

local Sample = {}

local function PrintTable(t: {})
	for i, v in t do
		print(`[{i}]: {v}`)
	end
end

for i = 1, 5 do
	table.insert(Sample, i)
end

PrintTable(Sample)

table.remove(Sample, 3)

print("--------\nRemoved\n--------")

PrintTable(Sample)
Normal indexing behaviour

As you can see, after setting the unused index to nil, it does not appear anymore in the output, but the other indexes stay the exact same.


Code:

local Sample = {}

local function PrintTable(t: {})
	for i, v in t do
		print(`[{i}]: {v}`)
	end
end

for i = 1, 5 do
	Sample[#Sample + 1] = i
end

PrintTable(Sample)

Sample[3] = nil

print("--------\nRemoved\n--------")

PrintTable(Sample)

Overall, I’d recommend you use table.insert and table.remove unless you’re working with specific indexes.