HTML [Solved] Sugarcube 2 / twine array splice problem...

esoom

Active Member
Sep 6, 2017
929
1,090
I'm having real trouble trying to compare two ids together and remove when the same inside a for loop. I have managed to get it to work with all but the first match in the array and I can't figure out why. I've tried running the for loop in reverse and even resetting the count values to 0 but the first (or last when running the other way) gets missed.

/* Create siblings excluding themselves from child arr */
<<if $zNPC[$npcid].cset == 1>>
<<for _i = 0; _i < $zNPC[$npcid].children.length; _i++>>
<<set _currchild = $zNPC[$npcid].children[_i]>>
<<set $zNPC[_currchild].sibling to Array.from($zNPC[$npcid].children)>>
<</for>>
<<for _i = 0; _i < $zNPC[$npcid].children.length; _i++>>
<<set _currchild = $zNPC[$npcid].children[_i]>>
<<for _is = $zNPC[_currchild].sibling.length; _is > 0; _is-->>
<<print _currchild>>
<<if _currchild == $zNPC[_currchild].sibling[_is]>>
<<print "match">><br/>
<<print $zNPC[_currchild].sibling[_is]>><br /><br />
<<set $zNPC[_currchild].sibling.splice(_is, 1)>>
<<set _i = 0>>
<<set _is = $zNPC[_currchild].sibling.length>>
<<endif>>
<</for>>
<</for>>
<<endif>>

Any suggestions, it's beginning to piss me off. Basically what this is trying to do its match the current parent child id to the copied array and when both ids are the same remove that part of the array and continue. I've only just figured out I needed to use the Array.from to stop it altering the original array which made me confused for the longest while :).
 
Last edited:

esoom

Active Member
Sep 6, 2017
929
1,090
Never mind I just figured it out I forgot the fucking >= 0 in the second for loop, I've obviously been playing too much Katamari.

I'm such an idiot :cry:. Only took me 2 hours to figure it out.

This is the code that works...

/* Create siblings excluding themselves from child arr */
<<if $zNPC[$npcid].cset == 1>>
<<for _i = 0; _i < $zNPC[$npcid].children.length; _i++>>
<<set _currchild = $zNPC[$npcid].children[_i]>>
<<set $zNPC[_currchild].sibling to Array.from($zNPC[$npcid].children)>>
<<for _is = $zNPC[_currchild].sibling.length; _is >= 0; _is-->>
<<if _currchild == $zNPC[_currchild].sibling[_is]>>
<<set $zNPC[_currchild].sibling.splice(_is, 1)>>
<<endif>>
<</for>>
<</for>>
<<endif>>
 
Last edited:

HiEv

Member
Sep 1, 2017
384
778
I've only just figured out I needed to use the Array.from to stop it altering the original array which made me confused for the longest while :).
FYI, you might want to use the SugarCube instead of , since the former does a deep copy, while the latter only does a shallow copy.