Trouble with arrays and adding items

Twine Version: V2.3.5
Story Format: SugarCube 2.30.0

I’m trying to set up an array that I can add items to. I want it to appear in my sidebar so I created a “StoryMenu” passage and added a link to my “Inventory”.
In this “Inventory” passage, I’ve typed:

<<silently>><<set $bag =["notebook"]>><<endsilently>>
You have <<print $bag.length>> item(s).
You are carrying <<print $bag>>

In my story, there is a passage where you acquire an apple and add it to your inventory so the passage is written like this:

<<set $bag.push("apple")>> You got an apple.

[[You exit this area]]

When I play the story, the inventory shows up on the sidebar, and everything prints correctly. When I continue through the story and get to the passage where you get the apple, I get this error message:

Error: <<set>>: bad evaluation: undefined is not an object (evaluating 'State.variables.bag.push')

I’ve tried all the different resources and I still can’t seem to figure out what’s going wrong.

My secondary question (provided I can get this first part to work) is am I able to link an item in the array to a description passage? The notebook has several pages in it that I’d like the player to be able to reference throughout the game if needed.

Thanks in advance!

The error is indicating that the $bag variable wasn’t initialised at the time you tried to call the <array>.push() function.

Generally Story Variables that need to exist for the entirety of a story play-through are initialised within the StoryInit special Passage.
eg. If your project doesn’t already have a StoryInit passage then add one, and then place code like the following in it.

<<set $bag to []>>

note: If the ‘bag’ is meant to start out containing the ‘notebook’ then change the above code to the following…

<<set $bag to ["notebook"]>>

I added a StoryInit passage, added the code and it’s not giving me the error code anymore (Thank you!!), but when I go to check my inventory after the passage where I get the apple, it doesn’t show in my inventory it says there is 1 item in the inventory (the notebook). Do I need to change the code in the “Inventory” passage so that it registers that the apple was pushed to the array?

-hanks so much, I’ve been struggling with this for a while

If you haven’t done so already, you need to remove the $bag variable initialisation line from your Inventory Passage, because that initialisation is now being done in StoryInit.
eg. remove the following…

<<silently>><<set $bag =["notebook"]>><<endsilently>>

You’re a lifesaver, thank you! :raised_hands: