MV How to Use Notetags with Parameters?

Hello everyone!

So far, the only thing I managed to discover is what's said at the help files.

I'm trying to alter the code where you inflict status ailments at someone and check if said status ailment already affected the target. If yes, I want to cause another status effect with a notetag in the status effect of the database.

The raw logic is something like:
JavaScript:
// If state "burned" is applied
if (burned == true) {
    // Apply the second state
    burnout == true;
}
else {
    // Apply the first state
    burned == true;
}
The trick here is that by the time you get down to the level of addState(), it only knows the state ID and the battler it's being added to. It no longer has any reference to the skill you're coming from, which is probably where you'd add this.

So your options are:
1 - Add this in at a higher level which will depend on whether you're adding this from an Add State Trait or an Attack State, etc.

2 - You could just make an action sequence for your skill and put it in there. (or, for that matter, in a Yanfly Skill Core Post-Damage Eval or something)
The trick here is that by the time you get down to the level of addState(), it only knows the state ID and the battler it's being added to. It no longer has any reference to the skill you're coming from, which is probably where you'd add this.
So, for short, there's no way to check the state at the moment of applying it?

So your options are:
1 - Add this in at a higher level which will depend on whether you're adding this from an Add State Trait or an Attack State, etc.

2 - You could just make an action sequence for your skill and put it in there. (or, for that matter, in a Yanfly Skill Core Post-Damage Eval or something)

Actually I'm creating my own plugin for this. So I would stick to the 1st method. Any clues on which part of the code I should mess with to achieve this effect?
So, for short, there's no way to check the state at the moment of applying it?
I suppose you could put it into a notetag on the state, yes, I didn't think of that part.

Actually I'm creating my own plugin for this. So I would stick to the 1st method. Any clues on which part of the code I should mess with to achieve this effect?
According to the script call lists and the engine library, states are put onto a battler with the addState() method.

So you can just grep for that in your js folder - you'll find the code of the original function on line 3008 of rpg_objects, and you can see the other functions that come from various skill traits and such and end up calling addState() in the end.

Just add an else:
Code:
Game_Battler.prototype.addState = function(stateId) {
    if (this.isStateAddable(stateId)) {
        if (!this.isStateAffected(stateId)) {
            this.addNewState(stateId);
            this.refresh();
        }
        else
            // Add a state referenced by your notetag here
        this.resetStateCounts(stateId);
        this._result.pushAddedState(stateId);
    }
};
Each of an Item/Skill's effects (e.g. Add State) gets processed via the applyItemEffect method of Game_Action. E.g. you could patch that method to check this.item().meta['tagName'], i.e. the value (string) of the <tagName: value> notetag on the corresponding Item/Skill.

In case it helps, here's an existing MV plugin for specifying effect conditions:
According to the script call lists and the engine library, states are put onto a battler with the addState() method.

ATT_Turan, that's the library I was just looking for all this time! Many thanks for this!

@caethyril , the plugin idea I had in mind was a bit different, but after seeing this one you recommended, you just sparkled a new idea on my mind. Many thanks!
Ok guys, I decided to give a try to the original code idea, but the skill doesn't seem to be working.

Here it is:
Code:
Game_Battler.prototype.addState = function(stateId) {
        if (this.isStateAddable(stateId)) {
            if (!this.isStateAffected(stateId)) {
                this.addNewState(stateId);
                this.refresh();
            }
            else {
                // Adiciona o State referenciado pela notetag "nextStack"
                var nextStack = SdataStates[stateId].meta.nextStack;

                if (this.isStateAddable(nextStack)) {
                    if (!this.isStateAffected(nextStack)) {
                        this.addNewState(nextStack);
                        this.refresh();
                    }
                }

            }
            this.resetStateCounts(stateId);
            this._result.pushAddedState(stateId);
        }
    };

What I'm missing?
It looks like you have "SdataStates" instead of "$dataStates"
Code:
                // Adiciona o State referenciado pela notetag "nextStack"
                var nextStack = SdataStates[stateId].meta.nextStack;
Also, meta.nextStack is a string value, not a number.

Try this instead?
JavaScript:
var nextStack = parseInt($dataStates[stateId].meta.nextStack, 10);
Also, meta.nextStack is a string value, not a number.
That's what I get for stopping at the first error 😔
Hello again!

So, it's really not working and I don't know why.

Here's a print of what I'm trying to do in the Database.
Captura de tela de 2023-01-03 16-41-04.png

Captura de tela de 2023-01-03 16-42-34.png
I did a quick test and your code, after applying the correction for the var nextStack line, seems to work for me on actors and enemies. I put a <nextStack: 5> tag on the default Poison state, added Poison twice to the same target, and they got blinded (state 5).

Based on those screenshots: did you test with the correct skill?

Otherwise: what are you seeing in-game that makes you say it "doesn't work"?

Make sure you've saved your project to apply Plugin Manager changes before testing. Battle test doesn't prompt you to save, so that can be easy to forget.
@caethyril, I've followed all your instructions. Indeed I had to save the project before testing battles in the Database. However, I tried the same you did (add Poison, then Blind) and it's not working the same way it's not working for the other skills.

Now it's appearing a 1.000.000 number after I attack the monster, right after the damage is applied. It happens with both a Poison skill and a Poison Sword I created for this test.

I tested with both parseInt and Number methods. None of them seems to work.

Is there anything else I should include in my plugin for it to work?
Are you using any other plugins? If so, maybe share screenshot(s) of your Plugin Manager.

For testing purposes you can try using console.log to show messages in the dev console. Press F8 to show the console during test. E.g.
Spoiler: your code with test outputs
JavaScript:
Game_Battler.prototype.addState = function(stateId) {
    if (this.isStateAddable(stateId)) {
        // DEBUG: check that it gets this far (e.g. because of State Resist or State Rate)
        console.log('addState: state ' + stateId + ' can be added!');
        if (!this.isStateAffected(stateId)) {
            this.addNewState(stateId);
            this.refresh();
        }
        else {
            // Adiciona o State referenciado pela notetag <nextStack: X>
            var nextStack = parseInt($dataStates[stateId].meta.nextStack, 10);
            // DEBUG: show nextStack value in console
            console.log('addState: nextStack = ' + nextStack);
            if (this.isStateAddable(nextStack)) {
                // DEBUG: notification that it can be added
                console.log('addState: nextStack is addable!');
                if (!this.isStateAffected(nextStack)) {
                    // DEBUG: notification of success
                    console.log('addState: adding next state');
                    this.addNewState(nextStack);
                    this.refresh();
                }
            }

        }
        this.resetStateCounts(stateId);
        this._result.pushAddedState(stateId);
    }
};
As you can see, these can be added wherever you like to check values and identify where the program is going and what is happening. You can remove them or comment them out when you get it working correctly. 👋

(Another, more advanced, option is using breakpoints, which work on the Source tab of the dev tools window: click a line number to define a breakpoint, and the app will pause when it hits that line of code. That tab offers controls to resume or step through subsequent code line by line.)


In case you're interested, here's an alternative implementation that is less likely to clash with other plugins. It works slightly differently to yours: it reapplies the original state (refreshing its turn count) when applying its "next" state. Also, since it's a patch, it will include all addState modifications from other plugins that load before it.
Spoiler: patch plugin code
JavaScript:
// M05) State progression.
void (() => {
'use strict';

    /** Name of notetag. */
    const TAG_NAME = 'nextStack';

    /** Anti-loop device. */
    const chain = [];

    /**
     * @param {string} tag tag value from original state
     * @returns {number} ID of next state to apply (0 = none).
     */
    const getNextState = function(tag) {
        return parseInt(tag, 10) || 0;
    };

    // Store current method for later reference.
    const alias = Game_Battler.prototype.addState;
    // Redefine method.
    Game_Battler.prototype.addState = function(stateId) {
        // If state is already here, also apply its "next" state
        if (this.isStateAffected(stateId)) {
            const next = getNextState(
                $dataStates[stateId].meta[TAG_NAME]
            );
            if (next) {
                chain.push(stateId);
                if (!chain.contains(next))
                    this.addState(next);
            }
        }
        chain.length = 0;
        // And then invoke the original method~
        alias.apply(this, arguments);
    };

})();
This is modified from something I wrote for MZ, but I did a quick test in MV (same as before) and it seems to work. If you're using an old editor version then you may need to replace every const here with var to avoid syntax errors. [Edit: also swap the arrow function () => { for a "proper" function function() { in that case.]
Thanks again @caethyril !

Are you using any other plugins? If so, maybe share screenshot(s) of your Plugin Manager.

No, I'm doing my tests on a raw project. Althought the intention is to add more plugins at it (mostly Yanfly stuff).

I decided to post the entire script code (since it quite simple so far) so you can check to see if I didn't missed anything at the anatomy of it. There are some changes of my own here too.

Spoiler
Code:
(function() {
    // Salvando o código original que checa o State e o aplica
    var default_addState = Game_Battler.prototype.addState;
   
    // Recriando minha própria versão do código
    Game_Battler.prototype.addState = function(stateId) {
        if (this.isStateAddable(stateId)) {
            if (!this.isStateAffected(stateId)) {
                this.addNewState(stateId);
                this.refresh();
            }
            else {
                // Adiciona o State referenciado pela notetag "nextStack"
                var nextStack = $dataStates[stateId].meta.nextStack;
                var nStack = Number(nextStack);
                if (this.isStateAddable(nStack)) {
                    if (!this.isStateAffected(nStack)) {
                        this.addNewState(nStack);
                        this.refresh();
                    }
                }
            }
            this.resetStateCounts(stateId);
            this._result.pushAddedState(stateId);
        }
    };
 });
Ah, I think I see the problem. You've put everything in an anonymous function, but you haven't evaluated that function, therefore the change never gets applied. I.e. you've got this:

(function() { // stuff });
...which defines a function. You'd want this instead:

(function() { // stuff })();
...which defines and immediately evaluates the function. This structure is called an IIFE:

There is nothing special about this case: if you write myFunction it points to that function object, but if you write myFunction() then it calls that function, with whatever arguments you include in the brackets.

What worked for me before was literally just putting the code you posted earlier (plus correction for that 1 line) in a file by itself. If you're not planning to reference that local default_addState variable then you can just not define it (which will also save a tiny bit of RAM), at which point the IIFE is unnecessary.

Note that parseInt is specifically designed to extract an integer value from a string:
Number will work here, but it's typically only needed for non-integer values.
Ah, I think I see the problem. You've put everything in an anonymous function, but you haven't evaluated that function, therefore the change never gets applied. I.e. you've got this:

(function() { // stuff });

...which defines a function. You'd want this instead:

(function() { // stuff })();

...which defines and immediately evaluates the function. This structure is called an IIFE:

If you had a facepalm emoji here I would use it... 😅

Now the whole thing is working almost as intended.
I'm trying to apply a cumulative state now, something like:
If (Burned X == true) {
Apply Burned X+1;
}
Then I can go through something like:
Burned 1
Burned 2
Burned 3
Burned ... and so on...

But this if {} else {} logic won't work for this. If I put another <nextStack: X> notetag and try to add the next state after another, it keeps stuck at Burned 1 and Burned 2.
I'm trying to apply a cumulative state now, something like:
If (Burned X == true) {
Apply Burned X+1;
}
Then I can go through something like:
Burned 1
Burned 2
Burned 3
Yes, you will need a loop/recursion of some kind for this. You can try my "alternative":
Spoiler: patch plugin code
JavaScript:
// M05) State progression.
void (() => {
'use strict';

    /** Name of notetag. */
    const TAG_NAME = 'nextStack';

    /** Anti-loop device. */
    const chain = [];

    /**
     * @param {string} tag tag value from original state
     * @returns {number} ID of next state to apply (0 = none).
     */
    const getNextState = function(tag) {
        return parseInt(tag, 10) || 0;
    };

    // Store current method for later reference.
    const alias = Game_Battler.prototype.addState;
    // Redefine method.
    Game_Battler.prototype.addState = function(stateId) {
        // If state is already here, also apply its "next" state
        if (this.isStateAffected(stateId)) {
            const next = getNextState(
                $dataStates[stateId].meta[TAG_NAME]
            );
            if (next) {
                chain.push(stateId);
                if (!chain.contains(next))
                    this.addState(next);
            }
        }
        chain.length = 0;
        // And then invoke the original method~
        alias.apply(this, arguments);
    };

})();
This is modified from something I wrote for MZ, but I did a quick test in MV (same as before) and it seems to work. If you're using an old editor version then you may need to replace every const here with var to avoid syntax errors.
This invokes addState recursively, e.g. with states that "stack" in the order A -> B -> C:
  • Add A => target has state A.
  • Add A => target has states A and B.
  • Add A => target has states A, B, and C.
The recursion is safe because it remembers which states it has already applied this time via the local chain array, and stops if it is told to apply a state that it has already applied.

Another way to approach it would be to use a loop...untested example:

let id = stateId; while (id) { default_addState.call(this, id); id = parseInt($dataStates[id].meta.nextStack, 10); }
You could add a safety mechanic like in my example to remember which states have been added, otherwise it's possible to set up an endless loop, e.g. A -> B -> A.

[Edit: changed the loop example.]
caethril, that's a great solution and now I'm thinking about a way to "remove" the previous state (to create a sort of cumulative stack, like Burned 1 goes to Burned 2 and so on).

Any hints on how I should proceed?

You could add a safety mechanic like in my example to remember which states have been added, otherwise it's possible to set up an endless loop, e.g. A -> B -> A.

It also kinda interested me, how could I create a limited loop of the same state?
now I'm thinking about a way to "remove" the previous state (to create a sort of cumulative stack, like Burned 1 goes to Burned 2 and so on).
Each step, you have two IDs: the "current" state, and its "next stack". So you could just remove the current state before adding the next one.

Personally I think I'd just put Resist State traits on the "higher" states though, e.g. for A -> B -> C:
  • B resists A
  • C resists B and A.
Regardless, if you want it to still allow stacking, like A + B -> C, then you'd have to adjust the logic. I think that would need another loop for each state added, to check its "next" chain and see if there's one of those states currently on the target. E.g. when adding A, you could check:
  • Does the target have state A?
    • If yes, then add state B (next stack from A).
    • Otherwise, does the target have state B?
      • If yes, then add state C (next stack from B).

It also kinda interested me, how could I create a limited loop of the same state?
I'm not sure what you're asking here. If you want to allow adding the same state a limited number of times, you could track how many times the state has been added and use that to decide when to allow adding it?

Original thread: https://forums.rpgmakerweb.com/threads/how-to-use-notetags-with-parameters.153216/