Unable to retrieve name from Array

So, I’m able to retrieve a player name from this array manually, but when I put it in a for-loop, it gives me an error with "attempt to index nil with ‘name’ "

Any solutions?

    print(tempPlayerArray[1]["name"]); -- works (prints 'dngbae2')
    print(tempPlayerArray[1].name); -- works (prints 'dngbae2')
    print(player) -- works (prints 'dngbae2')

    for i, v in pairs(tempPlayerArray) do
        if v[i]["name"] == player then -- crashes here with "attempt to index nil with 'name' "
            -- blah blah blah
        end
    end

This is because v[1] here refers to a dictionarie index which doesn’t exist, when you create a dictionarie, indexes are the ones you declare.

local tempPlayerArray = {
	[1] --[[index (1)]] = {name = "foobar"} --[[value (dictionarie)]]
}

print(tempPlayerArray[1]["name"])

for i --[[1]], v --[[dictionarie]] in pairs(tempPlayerArray) do
	print(v[i]) -- nil
	if v[i]["name"] == player.Name then -- v[1] refers to the index of the dictionarie, which doesn't exist
		
	end
end

To solve it, you will need to index v["name"].

local tempPlayerArray = {
	{name = "foobar"}
}

print(tempPlayerArray[1]["name"]) -- foobar

for i, v in pairs(tempPlayerArray) do
	if v["name"] == player.Name then
        print(v["name"]) -- foobar
		-- etc
	end
end
1 Like

Hello again.

What I should’ve added before is that it is unfortunately not possible to loop through a dictionary.

What you could do is every time something is added to the dictionary, add the name to a separate table like so.

local names = {}
table.insert(names, playerName)

Then, when looping through the dictionary…

for _, name in pairs(names) do
    local dictName = tempPlayerArray[name]
    -- You now have the indexed name from the dictionary
end
1 Like