Tuesday 4 March 2014

Twine Coding

I am going to use this page to post interesting and useful code snippets for Twine. These are all tested in Sugarcane, by the way. There is some difference between the formats, in particular Sugarcube is different.

If Twine cannot find a macro with a given name, it will instead look for a passage and insert that (not with sugarcube, though). This is an easy way to include variables. One passage could then include this text:

<<playername>> attacks the gruesome fiend with <<playerweapon>>.

You can then set up two passages, playername and playerweapon, that will automatically get inserted. Note that these passage names cannot contain spaces (and obviously cannot be the same as an existing macro).

The playername passage might look like this:

<<print $name>> the <<print $rank>>

The playerweapon like this:

<<if $weapon = 1 >>
Sword of Fire
<<elseif $weapon = 2 >>
Spear of Might
<<elseif >>
his fists
<<endif>>


In Sugarcube, you have to do this (it does not support the display shortcut):

<<display "playername">> attacks the gruesome fiend with <<display "playerweapon">>.



You can define functions in a script passage, but you have to attach the function to the window object to make it accessible. Here is how to do that:

window.myFunction = function() {
  alert("Here I am");
};


I am still working on how to access variables and objects defned in a script passage



The <<set>> macro is effectively an eval function; if just runs the text though a JavaScript parser. This means you can call function, concatenate commands, etc.

<<set alert("Here I am"); count += 1 >>

Even:

<<set
n = $fullname.indexOf(' ');
if (n == -1) {
  $name = $fullname;
} else {
  $name = $fullname.slice(0, n);
}
>>


No comments:

Post a Comment