Encapsulated Initialization in Custom Block on Green Flag Without Globals

Cinnapoca's dad here, trying to help her with a "static var" type issue...

I'm building a custom block in Snap! with block variables that act like static variables, persisting across calls within a program run but needing initialization only once per green flag click. The initialization code is expensive, so I want to run it only on the first run after a green flag, not on every block call. I’m currently checking if a variable is uninitialized (e.g., 0) to trigger initialization, but block variables persist across green flag clicks, so the check fails on subsequent runs, and surprisingly even after new block vars are added as I change the code.

How can I encapsulate this initialization within the custom block to maintain exportability, without relying on global variables or timestamps that break encapsulation? I’d like the block to reset its variables automatically on each green flag click, similar to a static variable resetting on program start, but all logic must stay inside the block. I've tried an "on green flag" random session ID, but then I'm adding a dependency on a global var. Is there a way to detect a new green flag run internally, perhaps using events or another mechanism, without external scripts or globals?

If the variable needs to be initialized every green flag click, is the value changing every time? And if so, is there some very small quick value you could check to determine if you need to reinitialize?

If you're banging your head against trying to avoid global variables, just use a global variable; that's what I'd do.

But is this what you want?


... but instead of POSITION and DIRECTION, whatever the lengthy computations are that you want to do, and instead of the SAY, whatever else the block has to do.

huh?

basically "if you're struggling to avoid using global variables, just use global variables to save yourself all that struggle."

Thanks so much, bh! If I had read the docs right, I would have realized that each instance of the block used in the code has its own copy of the block vars, so it's really not a static analog at all. Because your beautiful solution above wrapped the block that contains the block vars with an "outer" function, there's only one "use" of the inner block, so only one copy of the block vars. This was what we were missing. But we liked your solution so much that she put the store/remembered blocks into her personal function library! But we see now that, as you say, trying to avoid globals at all costs here doesn't make sense. Practicality over purism is a good lesson for all students, including me. =)

Thank you again for the thoughtful reply, and for everyone else who chipped in with thoughts!