How to dynamically compare the tags of a target passage and any future passage?

Twine Version:2.12.0
I’m making a game in sugar cube at the moment but I ran into the issue of return looping happening if the player tries to go from one menu to the next without returning to the main game. I wanted to try and solve it using the following code but it didn’t work. Any solutions or ideas?

<<if !tags(previous()).includes("menu")>>
<<script>>
$Return=previous();
<</script>>
<</if>>

<<return “close menu” $Return>>

the idea is to make the Return variable be the string of whatever passage name you were last in that wasn’t a menu, and have $Return only be assigned a passage whenever you entered a menu to begin with to not just unnecessarily update it. Yet it never updates $Return

Your problem is that SugarCube markup doesn’t work in pure Javascript, which means $Return won’t be recognized as a variable inside the <<script>> tag. You can use the <<set>> tag instead:

<<set $Return=previous()>>

Or, if you need to use a variable in Javascript, you can use the State.variables object:

<<script>>
   State.variables.Return=previous();
<</script>>

Having said that, I’d recommend just checking out the arbitrarily long return from the documentation, which does exactly what you’re trying to do.