Changing passage text with custom macro

Is there an easy way to change or add text to a passage with a custom macro?

For example if I have, in the story javascript
macros.add("randText", {
    handler: function(){
        try{
            //code to determine output
        }
        catch(e){
            return this.error("randText error!" + e.message);
        }
    }
});

that would give me a <<randText>> macro
But I can't figure out what to actually put in the function to alter the text in the passage.

Comments

  • edited October 2015
    Why not use the built-in DOM manipulation macros? The DOM Content and DOM Classes macros, and likely some of the Interactive macros like <<click>>, should prove useful.
  • That works if I want a specific output.
    Say I have an array of multiple strings, and I want to pick one and display it. I find it much easier and cleaner to write a function that selects one of those strings and gives it as output, rather than adding a block of code directly to my passages. Especially if it is one that I plan to use multiple times, I can just call that function/macro rather than duplicating the code block every time I want to use it.

    Basically, if I have a passage where the player is at the zoo, I'd like to be able to do something like
    You are looking at a <<ramdomAnimal>>.
    rather than having to put the entire code block for picking a random animal on that page.

    Does that make sense?
  • You don't state which version of SugarCube you are using so I will assume it is the one that comes with Twine 2.0.8

    You may wish to use a widget instead of a custom macro, they basically do the same thing but one allows you to use macros to implement it instead of requiring Javascript.

    1. Initialized a variable named $animals in your StoryInit passage like so:
    <<set $animals to ["monkey","bear", "cat"]>>
    
    2. Create a new passage (I named mine Widgets), assign it a widget tag and place the following in it:
    note: arrays are zero based, meaning the first element has an index of zero not one.
    <<widget "ramdomAnimal">><<print $animals[random(0,$animals.length-1)]>><</widget>>
    
    3. Now try your example in one of your passages:
    You are looking at a <<ramdomAnimal>>.
    
  • Instead of indexing the array, I'd suggest one of the following:
    <<widget "ramdomAnimal">><<print either($animals)>><</widget>>
    
    Or:
    <<widget "ramdomAnimal">><<print $animals.random()>><</widget>>
    

    Other than that, greyelf is on the money.
Sign In or Register to comment.