Just a little help

Hi, sorry but would someone be able to explain why this code runs fine 7 times in a row and then fails on the 8th. Nothing changes.
This is almost certainly not the correct way to code this, but I am still learning.
Thanks, and apologies if this is really stupid.

https://editor.p5js.org/cjstanleywinter/sketches/TKADWBYMT

Your sketch keeps calling currentScreen++;, so the value in currentScreen keeps going up.

This is, essentially, what moves the narrative along.

But then you also do this:

let sentences = narrative.screens[currentScreen].sentences;

This works fine for the first screen, and the second, and a few more.
But eventually it runs into a problem
See, the array narrative.screens has a fixed size. One that currentScreen will eventually exceed. And at that point, you’re trying to access an array element that isn’t there. And that’s a problem.


The issue is similar to this. Here’s my shopping list:

/// SHOPPING LIST:
0) Milk.
1) Eggs.
2) Sugar.
3) Carrots.
4) Ham.

If I asked you for item #0 on the list, you can tell me easily: Milk.

If I asked for item #3 on the list: Carrots.

Clearly this is a list of five things. So what’s the #5 item on this list?

PROBLEM.

The list might be 5 things long, but there’s no #5 item on the list!

Your code is running into exactly the same issue. Except your shopping list is narrative.screens and the item number is currentScreen.

1 Like

Hi,
thank you so much for the reply,

but I’m not sure that particular problem is the reason for this not working.
Because if I comment out the middle ‘else if’ statement it continues through the array as intended.

Something in the if-statement is causing it to not work past index 7 of the array but I don’t see what it could be.

(edited working version)
https://editor.p5js.org/cjstanleywinter/sketches/TKADWBYMT

* 7

* 8

* 9

Cannot read property 'sentences' of undefined (sketch: line 55)

* 10

Okay, fair. Maybe it can’t load a 10th narrative?

but uncomment that else-if statement and it won’t run past the 7th.
I’m stumped

Hi @cjswinter ,

Yes, with the code you provided this is exactly why it fails as explained by @TfGuy44 you are trying to access an element that is not in the array at location 10 (therefore returning undefined in JavaScript).

I tried to debug and understand your code but in my opinion, you shouldn’t mix setTimeout with p5js but rather use the draw() loop as a way to measure time and intervals and schedule your functions.

You are mixing a lot of async calls with timeout and it’s difficult to predict how the program flows.

Note that it doesn’t work past the 7th because it enters in the last else condition and you don’t use a setTimeout to redraw the ellipse… :wink: