Howdy, Stranger!

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

How to print an array value defined by a variable

Hi everyone! I am new to Twine, and I am trying to do something which probably is very simple, but I can't seem to figure it out.

I have an array called $textsize, and I want to print the value of $textsize that is in the position determined by $sizenumber

I tried to do it like this <<print $textsize[$sizenumber]>> but clearly that's not the proper way to do it.

I am using sugarcube, let me know if I need to provide more information.

Comments

  • SugarCube version?

    That is a proper way to do it, you could also use the naked $variable formatter. The obvious questions are:
    1. How are you constructing the array stored in $textsize?
    2. How are you setting $sizenumber?
    3. What are you trying to print (i.e. what are the values; this will probably be answered by #1)?
  • textsize is a simple array I set it in StoryInit <<set $textsize = ["small", "medium", "large"]>> (I might add more later on);

    $sizenumber is a number variable that varies based on players choices in the game (I set it = 3 in Storyinit, but that changes based on choices throughout the game).

    I am trying to print the text value that "corresponds" to the current value of $sizenumber (if $sizenumber is "2", then it should print "medium"). Since it can change throughout the game, I can't just use <<print $textsize[n]>>, I need to substitute n with the current $sizenumber value.
  • Arrays are 0-based, not 1-based (i.e. the index of "small" is 0). So, you need to adjust $sizenumber when you either set it or use it. Ideally, I'd recommend doing it when you set it (i.e. just set the index properly in the first place).

    When you're setting it:
    <<set $sizenumber to 0>>/* First index. */
    <<set $sizenumber to 1>>/* Second index. */
    <<set $sizenumber to 2>>/* Third index. */
    

    When you're using it:
    <<print $textsize[$sizenumber - 1]>>
    

    Whatever you do, just don't do both.
  • Arrays are 0-based, not 1-based (i.e. the index of "small" is 0). So, you need to adjust $sizenumber when you either set it or use it. Ideally, I'd recommend doing it when you set it (i.e. just set the index properly in the first place).

    When you're setting it:
    <<set $sizenumber to 0>>/* First index. */
    <<set $sizenumber to 1>>/* Second index. */
    <<set $sizenumber to 2>>/* Third index. */
    

    When you're using it:
    <<print $textsize[$sizenumber - 1]>>
    

    Whatever you do, just don't do both.

    Thank you very much, I wasn't aware the array started with 0, and that was causing me an error during my testing (I was looking for the fourth value, which wasn't there, so it didn't print anything), so I thought I was maybe doing something else wrong.
Sign In or Register to comment.