So I have a “stack level too deep” error, and I’m pretty sure I know what’s causing it. I am working on a tile based game, and I have all the tiles, and for convenience (to save looking it up every time I need to use pathfinding), each tile has a “nearby” array containing the 8 neighbours.
However, when I go to print out some objects for debugging, I am frequently running into the “stack level too deep” error. I think that it is because each tile has neighbouring tiles in the “nearby” array, which then refer back to the original tile, creating a loop when trying to print all objects.
I can live with this, but it would be much nicer if I could have my cake and eat it too. I can avoid it by referring to tiles by id or coordinates, instead of direct reference to object. Disadvantage is this means searching for the object every time.
So, is there a way to maintain my current code but prevent the “nearby” array from being printed in output so that it stops sanely?
Hope that’s clear! Current code:
class Tile
attr_accessor :type, :x, :y, :z, :nearby, :t_id
@type = 0
@@count = 0
def initialize(x, y, z, type)
@x = x
@y = y
@z = z
@t_id = @@count
@@count += 1
@nearby = []
@type = type
end
end
Ruby prints the return of the inspect method of an object when you pass it to p. You can override inspect on your class to make it return a string with only the information that would be useful for you.
For instance:
When you print it: