If I want to add a completely custom script for use in a passage, what is the best method? I kind of hoped the following would work, but it doesn't seem to (using SugarCube):
<<script>>function dothis(x) { foo }<</script>>
dothis() doesn't seem to be able to be called from anywhere?
I tried just plain old:
<script language="javascript" type="text/javascript">function dothis(x) { foo }</script>
And this is also inaccessible... Any help?
Note that I do not want to create a macro for every custom function. I already have a macro that is designed to call a function (should it exist and be callable...) based on input in the macro. That part works, but if only there were a way to have a function be callable! I know the macro part works because if I put other javascript code directly into the input (such as making the input "alert('hooray!)"), instead of calling another function it works.... its just putting input into it like "dothis(x);" that doesn't work.
Comments
Thank you! That does the trick. I don't quite know why Twine doesn't allow the story .html file to just have a way to compile with a new <script> tag in the head when generated, or why window.var = function is the way to do this (but it is and it works, thanks again!).
I don't know if I will use the widgets, to be honest, because although I am (obviously) not a true master at javascript, I can always peck my way through until I get it to do what it wants... if I wrote it from scratch. I actually do it for a living, and do quite well, believe it or not, but I write everything in my professional framework from the ground up, no using other people's stuff, so I understand it all. I tend to write things in the most straightforward way possible, not like a master of regex and unreadable series of variable type scripts. I am also terrible at reading documentation and so usually miss things jumping into the middle of someone else's framework, as evidenced here.
In any case, all that rambling to say that despite all that, as long as I know where things began and am not missing a chunk of logic in between (as I am with Twine/Sugarcube, obviously) I haven't encountered a js problem yet in a professional setting I couldn't resolve writing it in my way... the widgets seem like they might get in the way of flexibility. Is it really possible to write anything you could in loose Javascript in the widgets? Is there really an advantage over just writing the functions directly in Javascript?
Unless the code in question isn't meant to be used anywhere else, you're probably better off using a script tagged passage to define functions and the like.
As to why you have to specifically attach user functions (which you want to be able to simply call by name) to the global window object, that's a combination of scoping limitations and the fact that the global window object is magical.