Efficiently iterating through 3D array

I have a 3D array which stores voxels in a 3D grid. How do I efficiently iterate through this table, as it is most likely the majority of values in it’s “cubic size” are nil. I do not know the size of this table, as I use an Autotable system that makes its size infinite.

It’d become INCREDIBLY inefficient to have to iterate through it the old fashioned way:

function ClearCave()
	for x = 1,#Array do
		for y = 1,#Array[x] do
			for z = 1,#Array[x][y] do
				
			end
		end
	end
end

As, like I said, I do not know the length of any one dimension, because it is theoretically infinite. That means the game could be going through the loop millions times! Is there no good way to do this? As I could store all the voxels in a 1D array for the purpose of cataloguing, rather than actual use.

1 Like

It would make sense to store chunks. That way you can narrow the search down smaller and smaller. For example, a sector contains say 12 chunks, each chunk contains a 12x Xy 12z area of land.

1 Like

That’s not beneficial and would actually harm other parts of the game. Aswell, I’m not searching, rather I am just simply attempting to “clear out” the table. Any non-nil value, turn to nil.

What do you need a 3D array filled with nil values for? I don’t know a very efficient way to do that, but maybe this would be worth a try.

local tableCreate = table.create
local function clearCave()
    for x, arrayX in ipairs(array) do
        for y, arrayXY in ipairs(arrayX) do
            arrayX[y] = tableCreate(#arrayXY, nil)
        end
    end
end

This includes iteration, but I think using table.create might make this faster than the function you posted.

No, it wouldn’t be faster. However the issue in general has been solved.

Then just overwrite the table. Maybe at runtime generate the template table, then when you need to, just overwrite the table with the template.

I said the issue has been solved.

Yup! Just adding some feedback which is perfectly OK to do :+1: