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
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)