Looking for help creating a widget that can modify object key values in an array

Hello! I have a question about how to write a widget that can dynamically modify the value of an object key. Say I have an array of “players” and they all have the same general template that looks like this.

<<set $players to []>>
<<run $players.push({

        head : {
            health : 100,
            conditions : []
        },

        torso : {
            health :100,
            conditions : []
        },

        leftArm : {
            health :100,
            conditions : []
        },

        rightArm : {
            health :100,
            conditions : []
        },

        leftLeg : {
            health :100,
            conditions : []
        },

        rightLeg : {
            health :100,
            conditions : []
        },


    })>>

Now I want to create a widget, something like “playerAttackTest” that has two arguments, args[0] being the index number of the player being attacked, and _args[1] being the region that will be damaged.
I could do something like this

<<switch _args[1]>>
    <<case "head">>
        <<set $players[_args[0]].head.condition -= 1>>

    <<case "torso">>
        <<set $players[_args[0]].torso.condition -= 1>>

    <<case "leftArm">>
        <<set $players[_arg[0]].leftArm.condition -= 1>>

    <<case "rightArm">>
        <<set $players[_args[0]].rightArm.condition -= 1>>

    <<case "leftLeg">>
        <<set $players[_args[0]].leftLeg.condition -= 1>>

    <<case "rightLeg">>
        <<set $players[_args[0]].rightLeg.condition -= 1>>

<</switch>>

But this feels sort of cumbersome and rigid. I am wondering if there is something that could just take _args[1], use it to look for the object key in the specified object, and then modify its corresponding value. Thank you for any help you can provide!

Yeah, the .leftLeg syntax is just a shortcut: anything you write that way, you can also write as ["head"] (or [_arg[1]]) instead. You can only write it with the dot syntax if the name fits the rules for a JavaScript name (letters, underscores, dollar signs for some reason, numbers after the first character).

So this should do you:

<<set $players [_arg[0]] [_arg[1]] -= 1>>

I put some spaces in there to make it clearer that there’s two groups of brackets one after the other: normally a programmer would leave out the spaces but… IIRC having extra spaces shouldn’t break anything.

2 Likes

Just as a minor point, it’s $args[0] ([1], etc.), with an “s” and with the permanent-variable rather than the temporary-variable sigil. (It used to be _args but that’s deprecated now.)

3 Likes

Thank you so much!