Checking if Player is in Table

So I’m trying to store a player’s name in a table but if the name’s already stored, it doesn’t store another. When I run the code twice and print the contents of the table, you can see the player’s name is stored twice. Is there something I’m doing wrong? (btw Caller is just Player)

if Table[Caller.Name] then
	print(Caller.Name.." is in table")
else
	table.insert(Table,Caller.Name)
	print(Caller.Name.." isn't in table yet; adding")
end
4 Likes

Array Part vs Dictionary Part

Tables in Lua have an array part and a dictionary part. They are not types of tables.

Array Part

The array part is an ordered collection of values.

It looks more or so like this:

local t = {'a', 'b', 'c', 'd'}

You can index for an element with a numerical index. Array starts at index 1, so if you wanted the first value, you can t[1], second, t[2], … t[#t]

local v = t[1] -- better example

Dictionary Part

The dictionary part of a table is an unordered collection of key-value pairs.

It can look like so:

local t = {
    key = "value" -- you can use ["key"] as well, t.k == t['k']
}

You can get the value if you use the key as index.

local v = t.key

You misunderstood how table.insert works.

table.insert(t, i, v) inserts v at position i, in the array part of the table t. If t[i] ~= nil, shift t[i] and everything after it 1 index to the right.

If v is absent it is assumed v = i.

table.insert(t, v) inserts v at position #t + 1.

3 Likes

Arrays can only be indexed with numbers. You can only index tables with strings if the table is a dictionary.

if Table[Caller.Name] then
	print(Caller.Name.." is in table")
else
	Table[Caller.Name] = true
	print(Caller.Name.." isn't in table yet; adding")
end
2 Likes