+1 vote
by (160 points)
edited by
I've been trying to return an int from a function defined in javascript to variable set in sugarcube 1.0.35:

<<script>>

function testFunction () {

return 10;

}

<</script>>

<<set $testVar to testFunc()>>

However, whenever I test this piece of code I get "Error: <<set>>: bad evaluation: testFunc is not defined"

What am I doing wrong? Why does Twine give a "not defined" error?

Thank you for your help.

1 Answer

0 votes
by (61.6k points)
reshown by
 
Best answer
  1. The name of the function is not the same as the function you call in the <<set>> macro. 
  2. You shouldn't really create functions like this. Putting them in a passage instead of your Story JavaScript can cause problems. 
  3. You're creating a global function; I generally recommend using the setup object. 

Here's an example that should work. First, in story JavaScript, place this: 

setup.testFunction = function () {
    return 10;
};

Then, in passage: 

<<set $var to setup.testFunction()>>

<<print $var>> /% 10 %/

Note. I wrote this code from memory, it may contain errors. 

by (160 points)
It worked! Thank your very much for your help! :)

Thank you also for your advice, I obviously lack the knowledge of how this should be done x) I shall follow these guidelines from now on. Thank you!
by (64.2k points)

3. You're creating a global function; […]

Actually, no.  Their function, testFunction(), was a part of the local scope of the particular <<script>> invocation they defined it within.

Welcome to Twine Q&A, where you can ask questions and receive answers from other members of the community.

You can also find hints and information on Twine on the official wiki and the old forums archive.

See a spam question? Flag it instead of downvoting. A question flagged enough times will automatically be hidden while moderators review it.
...