Inventory items (as links) on footer

Please specify version and format if asking for help, or apply optional tags above:
Twine Version: 2
Story Format: Sugarcube 2.3

I am building a point-and-click game, with verbs and inventory items on the story’s footer (as links) which the player clicks and combines to form actions.

All good so far. The static verb menu works. The inventory menu, being dynamic, I don’t know how to handle. I can get the inventory items on the footer as links with a <<for>> loop, but they don’t work properly.

When the player clicks on one item link, the variable $currentitem is supposed to take the value of the clicked item (a string) and then another passage (called “Perform Action”) is called.

(Later, I will make inventory items as objects, but for the moment I am trying to make it work with them as strings.)

So, here is my code for that:

<<for _i = 0; _i < $inventory.length; _i++ >>
    <<link $inventory[_i]>>
    <<set $currentitem to $inventory[_i]>>
    <<include "Perform Action">><</link>>
    <br />
<</for>>

I suspect that the problem lies in <<set $currentitem to $inventory[_i]>>. Since this part of the code does not fire unless the links get clicked later on, the local/temp variable _i doesn’t make sense anymore when the player clicks the link.

So, any suggestions on how I can work around this problem? Cheers!

Does it work better if you add “Perform Action” to the <<link>>? That macro will run the script inside the tags before redirecting to the new passage. (Reference)

Try this line instead and see if it gives better results:

    <<link $inventory[_i] "Perform Action">>
        <<set $currentitem to $inventory[_i]>>
    <</link>> 

Edit:
Oh wait… I think there’s a more critical flaw in your loop logic.

If my understanding of how Twine processes this is correct, it will run process the script inside the <<link>> when you click the link and not before. If this is true, the value of _i for every link will always be equal to $inventory.length at that point because the loop will have finished.

It looks like you can get around this using the <<capture>> macro. (Reference)

<<for _i = 0; _i < $inventory.length; _i++ >>
    <<capture _i>>
        <<link $inventory[_i] "Perform Action">>
            <<set $currentitem to $inventory[_i]>>
        <</link>>
    <</capture>>
<</for>>

This is untested but hopefully fixes it.

1 Like

Wow! Thanks, @tayruh!!! Yes, indeed, the <<capture>> macro is exactly what was missing! It works now!

1 Like