+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 (63.1k 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 (68.6k 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.

...