We are about to switch to a new forum software. Until then we have removed the registration on this forum.
Hello,
I am following the Daniel Shiffman graph tutorial series with p5.js and I wanted to implement the A* algorithm into the maze generator. Then I got a problem :
Firstly, A global var
defined in setup()
is undefined in draw()
(and it makes my programme crash).
Then, I wrote a test programme to see where is that problem from, and I had a strange result : I saw modifications on objects made in draw()
in my setup()
's console.log (see thecurrentCell.visited = true
). I use either sketch.js
(my original programme) or test.js
.
How could I repair that ?
Links (I know that my code isn't optimized neither commented, sorry :-/ ) :
Thanks in advance,
Lugrim
PS: Sorry for my bad English
Answers
It will be great to be able to execute your code. You could host your code in openProcessing, thimbleproject or p5.sketchpad.cc Also it is hard to reproduce your observation without having the proper instructions on how to get that observation. Consider this post: https://stackoverflow.com/help/mcve
Kf
@Lugrim - the console log behaviour is perhaps surprising, but is expected. You've logged a reference to
currentCell
so you see its state at the end of sketch execution, not as it was during setup.Try converting to a string to get around this:
console.log(JSON.stringify(currentCell));
@blindfish thanks, but I always have a problem with my second
console.log(JSON.stringify(currentCell, null, "\t"));
returning undefined :/@Lugrim - test.js works fine. I had to dig through your sketch code to discover you re-declare currentCell in draw:
var currentCell = openSet[winner];
So you've created a locally scoped variable called currentCell that has no relation to the one declared globally. JavaScript's variable hoisting means the code doesn't just throw an error, but instead causes you a hard to find bug #-o
It's considered best practice to always declare variables at the top of functions to make these bugs easier to spot. Or use ES2015+ which now includes block-scoped variables; though in this case the solution is to not re-declare the variable at all ;)