Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

[Sugarcube] For loops and Click

So I have some code that doesn't work, and I'm not sure why.
<<for $i to 0; $i < $party.length; $i++>>
    <<click "Delete Member">>
        <<print '<<set $party.deleteAt('+$i+')>>'>>
        <<print '<<goto "' + passage() + '">>'>>
    <</click>>
<</for>>

In theory, this code should loop through all party members and display a button saying "Delete Member" for each which, when clicked, deletes the member at that index.
However, rather than deleting the member at index $i, like it's supposed to, it deletes the member at $party.length resulting in an out-of-bounds error.
Obviously this means that $i is not being "memorized" by the print statement as it should be... Why is that? How can I fix it? I'm at a bit of a loss.

Comments

  • Trying to capture loop values from within the <<click>> body won't work—if it did, you wouldn't need to do it in the first place. You have to capture them before the body of the <<click>>. For example:
    <<for _i to 0; _i < $party.length; _i++>>
    	<<print '<<click "Delete Member">><<run $party.deleteAt(' + _i + ')>><<goto "' + passage() + '">><</click>>'>>
    <</for>>
    
    Also, unless the loop index needs to be stateful, beyond its use as the loop variable, then you should use a temporary variable rather than a story variable—as I did the above example.
  • Ah, so the issue was in that I wasn't using a temporary variable.
    I had tried capturing the entire thing before and it didn't work, hence my confusion.

    Well, that's unfortunate. Temporary variables don't seem to be in SugarCube 1.0.34, so I've switched to 2.6.2 for now.
  • Gorlath wrote: »
    Ah, so the issue was in that I wasn't using a temporary variable.
    I had tried capturing the entire thing before and it didn't work, hence my confusion.

    Well, that's unfortunate. Temporary variables don't seem to be in SugarCube 1.0.34, so I've switched to 2.6.2 for now.
    No. The use of temporary variables simply keeps the story variable store clean. The problem was, as I noted, not printing the whole thing. If it didn't work when you tried it before, then you must have gotten something wrong somewhere.

    Beyond that, the <Array>.deleteAt() method only exists in SugarCube 2, so I'm confused as to how you were supposedly using it in v1 to begin with. That's why I suggested the use of temporary variables—which, yes, are not in v1—since it seemed like you were using v2 already (which is at v2.7.0).
  • Ah, is that so? It must have been the wrong version number that was the source of the error, and I just didn't catch it. I was sure I was on the right documentation page when I was searching, though. So far I haven't run into any version incompatibilities, so I guess I got a little lax.
Sign In or Register to comment.