Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

I can't index my 4d array outside of my function. [?]

I created an array inside of a server script called map. I initialize it like so

maps = {}

game.Players.PlayerAdded:Connect(function(player)
		for i = 1, 20 do
    		for k = 1, 20 do
        			maps[player.UserId] = {[i] ={[k] ={["occupied"] = "clear"}}}
        			print(maps[player.UserId][i][k]["occupied"]) --> "clear"
    		end
		end
end)

I know the initialization works because the print() function outputs "clear". However, when I try to use this array outside of the PlayerAdded function, none of my indexes work. I use it in the same script like so

for i = x, x + object.SizeX.Value do
    	for i = y, y + object.SizeY.Value do
            	print(x, y)
                    if maps[player.UserId][x][y]["occupied"] ~= "clear" then
                        	return;
                    end
            end
    end

The error is as follows: ServerScriptService.Main:27: attempt to index field '?' (a nil value) Why on earth is this happening? Am I even setting the indexes to numbers? Help is always appreciated.

Thanks, Connor

1 answer

✓ Accepted answer

The problem with your script is that every time line 6 executes, it completely wipes whatever was previously in the table by setting maps[player.UserId] to a brand new table. To fix this, you'll have to "set it as you go". I've done this below:

local Players = game:GetService("Players")
local Maps = {}

Players.PlayerAdded:Connect(function(Player)
	Maps[Player.UserId] = {} -- Set the initial table to store values in
	for i = 1, 20 do
		Maps[Player.UserId][i] = {} -- Create a new table with index 'i' inside the initial table
		for k = 1, 20 do
			Maps[Player.UserId][i][k] = {occupied = "clear"} -- Add index 'k' to the table with index 'i'
		end
	end
end)

1 comment

0

Thanks, that was the exact issue.

This discussion is preserved as it was. New answers, comments, and votes are closed.