Which methood of creating grid is better?

Hey, today i found out that to detect index of grid tile dependant on 3D position i need to make grid actually placed well, i have two methoods of achieving it:

  1. Nesting
for x = 1, GridSize do
  for z = 1, GridSize do
   for y = 1, GridSize do
      -- Code to create grid
    end
  end
end
  1. One loop
for i = 1, GridSize ^ 3 do
  local Index = i - 1
  local x = Index % GridSize
  local z = math.floor(Index / GridSize) % GridSize ^ 2
  local y = math.floor(Index / GridSize ^ 2)
end

Which one is better?
Also small question, how can i get index based off position, like we have (3, 0, 0) and we want to know what index is it (it should be 3 or 2 dependant on methood)

1 Like

Method 1. It’s easier for debugging, remembering and is just nicer in general

i always used second methood because i thought it’s more mathematically better, for example when trying to find index based off position i need to do:

return math.floor(Position.X / TileSize)

for example, and let’s say when position on X axis will be 3 then index will return 0, instead of 1

Neither is “better”.

Oftentimes there isn’t one optimal solution, but rather multiple solutions each with their own pros and cons. The first method is indeed simpler for someone else to read and debug your code, but if there’s some sort of advantage to using the second method then by all means use that.

If I’m working on a project with other people, though, I’d prefer the first method for maintainability. Otherwise it would be a good idea to document the behaviour of the second method outlining how it works so that someone reading your code for the first time knows what it does without having to waste time analyzing it.

2 Likes

Option 1 is more in-line with our understanding of graphs and dimensions. Option 2 is more space-efficient but harder to read.

I would go with Option 1 just because it’s much easier to debug.

Problem is that both have advantages to thing that i want to do, which are also very, very, very important

See when i use first methood, maintanance is very easy but also getting proper index is hard due to math

While using second indexing is easy but maintanance of grid origin ect becomes magic

At the end i think i’ll combine both, i’ll start loops from 0 like other languages do or simply subtract 1 each time i want to get mathematical index, anyways thx for help

1 Like

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