Hello.
I want something like this:
::StoryInit
<<set $TRACKING["ENEMY_1"] = 40>>
<<set $TRACKING["ENEMY_2"] = 50>>
<<set $enemy["ROOM_1"] = "ENEMY_1">>
<<set $hero_stealth = 10>>
<<set $hero_location = "ROOM_1">>
::Main
You can <<link `"hide (" + get_hide_odds() + "%)"` "Hide"`>><</link>>.
::JS
window.get_hide_odds = function() {
var odds = 0;
stealth = 100 - $TRACKING[$enemy[$hero_location]] + $hero_stealth;
return odds;
}
But "$TRACKING[$enemy[$hero_location]]" and "$hero_stealth" doesn't work in JS. They are not defined.
How can I use variables from SugarCube in JS? I need many small functions like get_hide_odds(). And I want use them without arguments like get_hide_odds(enemy,hero). Is it possible? Or I need big structure like "$game" with properties "enemies", "hero", "rooms" etc? And use it like get_hide_odds($game).
Maybe there is better organization of code for my problem (but without fanatism). Thank you.
Comments
If I understand right there is bad idea to write in the beginning of JS. Need I do this in every function?
On top of that, you should probably use the setup object instead of the window object to create your functions if you have a lot.
If you're asking if you can store a reference to State.variables, the answer is yes, and I don't think it's a bad idea to do so. To make it global though, it'd probably be best to make a function or something:
NOTE: This code is for SugarCube 2.18. You didn't specify a format and version, and you should, especially if you're messing with JS.
At that point, I don't know how much typing you're actually saving yourself, though.
I think you'd be surprised what functionality you can get out of SugarCube macros alone, though, and I still recommend using widgets over functions if at all possible, you can emulate a return value using temporary variables if you need to, which is what I do:
Your example function would look like this using a similar system, and would 'return' the temp variable _odds:
And then in passage:
It is exactly what I need. I try to avoid code duplication. so it is reason why I am trying to use JS.