<<capture>> in a <<for>> loop

Hi,
I have a nested array called $fighters that holds info’s about fighters using an arrays called $person
inside the $person array are details such as $person.name or $person.strenght
Now I want to create a dynamic display using a for loop that should show each person using a dialog box. I have tried multiple ways, each not successful.

   <<for _i = 0; _i lt $fighters.length; _i++>>
      <<set _currentFighterID = $fighters[_i]>>
        <<capture _i>>
            <<link "<<print State.variables[_currentFighterID].name>>">>
                <<dialog "Fighter Details">>
                    <strong>Name:</strong> <<print State.variables[_currentFighterID].name>><br>
                    <strong>Strength:</strong> <<print State.variables[_currentFighterID].strength>><br>
                <</dialog>>
            <</link>>
        <</capture>>
    <</for>>

The issue is that the links created end up getting the appropriate name (the name of each fighter) but the dialog box that opens when any link is clicked is based on the information of the last fighter in the $fighters array. The result stays the same when I remove the <<capture>> macro. Also I tried using Dialog.open instead of the dialog api macro by chapel but that did not help either.

Thanks for your time!

Basically you’re capturing the wrong variable, but I see TME is about to explain in greater detail.

2 Likes

You have a couple of issues going on here.

  1. Your primary issue is that you’re capturing the wrong variable. Nowhere within the capture do you use _i. You do use _currentFighterID, which is what you should be capturing.
  2. Your argument to <<link>> is badly overcomplicated. All you need there is a backquote expression.

Try the following:

<<for _i = 0; _i lt $fighters.length; _i++>>
	<<set _currentFighterID = $fighters[_i]>>
	<<capture _currentFighterID>>
		<<link `State.variables[_currentFighterID].name`>>
			<<dialog "Fighter Details">>
				<strong>Name:</strong> <<print State.variables[_currentFighterID].name>><br>
				<strong>Strength:</strong> <<print State.variables[_currentFighterID].strength>><br>
			<</dialog>>
		<</link>>
	<</capture>>
<</for>>

 

Additionally. You can simplify your <<for>> loop a bit by using its range form. For example, replace the following:

<<for _i = 0; _i lt $fighters.length; _i++>>
	<<set _currentFighterID = $fighters[_i]>>

With:

<<for _currentFighterID range $fighters>>
3 Likes

Thanks a lot! It is incredible what you two have done for the community. Whenever I look for a solution to a problem, I run into your guys’ threats from as late back as 2015 :ok_hand: