+1 vote
by (230 points)

Hello!

I am currently using sugarcube and I am attempting to figure out how I can let the user select a certain index of an array of strings by using buttons to cycle through the indeces of that array.

This is what my code looks like...

<<set $haircolor = [ "black", "blonde", "brown", "auburn", "red", "ginger", "grey", "white"]>> 

<<set $haircolor_choice >= 0 >>
<<button "<-">>
<<set $haircolor_choice-->><<replace "#pc_haircolor">><</replace>>		
<</button>>

<span id = "pc_haircolor"><<print $haircolor[$haircolor_choice]>></span>

<<button "->">> 
	<<set $haircolor_choice++>><<replace "#pc_haircolor">><</replace>>	
<</button>>

I know I am close but Im not sure what I am missing, any help would be greatly appreciated!

1 Answer

+1 vote
by (44.7k points)
selected by
 
Best answer

A couple of minor bugs.  This line:

<<set $haircolor_choice >= 0 >>

is basically meaningless.  You want this instead:

<<set $haircolor_choice = 0 >>

Then, inside the <<replace>> macro you need to put whatever it is that you want to replace the current contents with.

Finally, you need to put in some checks to prevent $haircolor_choice from going out of bounds of the $haircolor array.

Once you've done all of that you'll get something like this:

<<set $haircolor = [ "black", "blonde", "brown", "auburn", "red", "ginger", "grey", "white" ]>> 

<<set $haircolor_choice = 0>>
<<button "<-">>
	<<set $haircolor_choice-->>
	<<if $haircolor_choice < 0>>
		<<set $haircolor_choice = $haircolor.length - 1>>
	<</if>>
	<<replace "#pc_haircolor">>$haircolor[$haircolor_choice]<</replace>>
<</button>>

<span id = "pc_haircolor">$haircolor[$haircolor_choice]</span>

<<button "->">> 
	<<set $haircolor_choice++>>
	<<if $haircolor_choice >= $haircolor.length>>
		<<set $haircolor_choice = 0>>
	<</if>>
	<<replace "#pc_haircolor">>$haircolor[$haircolor_choice]<</replace>>
<</button>>

Additionally, you might want to replace the "<-" and "->" in the buttons with "←" and "→".

Hope that helps!  :-)

by (230 points)
Thank you so much! It works perfectly. I knew I had to set constraints so that $haircolor_choice wouldn't leave the bounds of the $haircolor array but I wasn't sure how to go about it. Thank you!!
...