Problems With Multidimensional Tables

So I am basically creating a tactical RPG game like Advance Wars and Fire Emblem and I’ve created an algorithm that creates a random board using an multidimensional table. What I want to do is to print every member of the WorldList table and delete a random part inside the array and replace it with a different part.

The problem that I’m getting is that the print method is printing the index of the members of the table and my code doesn’t destroy the random part in the table.
If I can get any help, that would be much appreciated.

Here’s the code I have so far:

WorldList = {}
for x = 0,20 do
	WorldList[x] = {}
	for y = 0,20 do
		local partIndex = math.random(1,#Parts:GetChildren())
		local newPart = Parts:GetChildren()[partIndex]:Clone()
		newPart.Name = "Tile" .. x .. "," .. y
		newPart.Parent = workspace.World
		newPart.CFrame = CFrame.new(x*4-25 , 3 , y*4-25)
		newPart.Anchored = true
		WorldList[x][y] = {newPart.Name}
	end
end
--Prints the index instead
for index, value in ipairs(WorldList) do
	print(index, value)
end
--Delete a random part inside WorldList and replace it with the Base Castle
local homeX = math.random(1,#WorldList)
local homeY = math.random(1,#WorldList)
print(WorldList[homeX][homeY])
WorldList[homeX][homeY]:Destroy()
--Makes a castle
local myBase = HomePart:Clone()
myBase.Parent = workspace.World
myBase.CFrame = CFrame.new(homeX *4- 25 , 3 , homeY* 4- 25)
myBase.Anchored = true
WorldList[homeX][homeY] = {myBase}

1 Like

I might be wrong but I’m pretty sure tables start at index 1.

They do, but you can still set an index at 0. Iterating would still work fine for arrays if an index is 0.


I don’t really see an issue with the result. It looks fine?

  1. You cannot use :Destroy() on a table (because WorldList[homeX][homeY] is table {newPart.Name}. To find out 1 table element you need to use WorldList[homeX][homeY][1]
  2. You can either set it to nil or find an instance by name with game.Workspace.World:FindFirstChild(WorldList[homeX][homeY][1] and destroy it (if all names are different, otherwise you need to store the instance itself in the table, not its name) or do it differently (depends on you and your ideas)
2 Likes

Would this not cause an off by one error if used as an index when your first index is 0
local homeX = math.random(1,#WorldList)

I think your indexing method is wrong. Im not good at tables so please correct me if anything is faulty here.

Lets see, you have 20 indexes in WorldList.

local randomX = WorldList[math.random(1, #WorldList)]

This would return a table as we know. The table houses the Y values.

local randomY = randomX[math.random(1, #randomX])

This MIGHT give what you want.

Problem here is what you’re thinking is Y is another X value.

I probably havent understood your question fully if im wrong.

This solved my problem, thanks.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.