MV Pick a random thing from an array parameter

I started to work on making my own plugin, meant to help me give out random rewards to the player. My intention was making it so that each parameter is a separate rarity with various items assosiated with it. After that an NPC is supposed to trigger a function that would pick a random item from the array and put it in variable (atm it's just for testing)
Here's the code (apologies for weird naming):
JavaScript:
/*:
@plugindesc test
@author alex

@param common
@type item[]

@param rare
@type item[]

@param special
@type item[]

@param epic
@type item[]

@param legendary
@type item[]

*/

////GAMBLING STUFF

var alx_parameters = PluginManager.parameters(idiotsFirstPlugin);
var alx_common = alx_parameters.common



(function random_thing() {
    
    x = JSON.parse(alx_common);
    //x = Math.randomInt(alx_orbs.length);
    //x = Math.randomInt(alx_orbs.length);
    $gameVariables.setValue(83, x[0]);
    $gameMessage.add("It's \\v[83].");
    })();
And here's the script on NPC
JavaScript:
random_thing();

Notihng works as intented. When I try to interact with the npc, no message is displayed. How to fix it?
To start: this is not how you define reusable functions. Often plugins need to do a bunch of things only once when loaded (such as modifying the engine in some way), and that's what this syntax is for. So your code only gets run once, when your plugin is loaded, resulting in nothing happening since game message doesn't work yet.

If you want to create a function that gets called during the game, you'd just do this:
JavaScript:
function random_thing() {   
    x = JSON.parse(alx_common);
    //x = Math.randomInt(alx_orbs.length);
    //x = Math.randomInt(alx_orbs.length);
    $gameVariables.setValue(83, x[0]);
    $gameMessage.add("It's \\v[83].");
}
Just to add to what @Mac15001900 said - you may want to read up on scope.


Where and how you declare your variables matters. Right now you have stuff going into the global scope that is, at best, bad coding practice; and, at worst, can interfere with your code or someone else's.

For example, just saying x with no declaration automatically makes it global, and that's a very common, simple name that's quite likely to have conflicts.
Some more points:
  1. PluginManager.parameters expects the plugin's filename (without .js), e.g.
    JavaScript:
    var alx_parameters = PluginManager.parameters("ALX_FirstPlugin");

  2. Rather than parsing the parameters every time you need them, it's more efficient to parse the parameters once, when the plugin loads, e.g.
    JavaScript:
    var alx_common = JSON.parse(alx_parameters.common);
    Then it's already an array when you run the function, so you don't need to parse it there:
    JavaScript:
    function random_thing() {
      var x = alx_common;

  3. Like Turan says, the variables alx_parameters and alx_common don't really need to be global. You could restructure the code like:
    JavaScript:
    (function() {  // for local scope
      var alx_parameters = PluginManager.parameters("ALX_FirstPlugin");
      var alx_common = alx_parameters.common
    
      // Define this on `window`, which makes it global.
      window.random_thing = function() {
        // your code here
      };
    })();
    This still lets you call the function as random_thing() in a script call.

  4. If a plugin errors out while loading, it may be rejected silently, causing it to have absolutely no effect in-game. You can open the dev tools window (F8 or F12 during playtest) and check the Console tab of that window for any errors, usually in red text.
If you want to create a function that gets called during the game, you'd just do this:
JavaScript:
function random_thing() {  
    x = JSON.parse(alx_common);
    //x = Math.randomInt(alx_orbs.length);
    //x = Math.randomInt(alx_orbs.length);
    $gameVariables.setValue(83, x[0]);
    $gameMessage.add("It's \\v[83].");
}
I changed the code however the NPC isn't activating the function
var alx_common = alx_parameters.common
also this wont work, as you use JSON.parse(alx_parameters["common"])
to target the parameter if its a array or object.

you also need a "forEach" function, .map or .some to iterate the array.
Edit: wait no I may have misunderstood...

alx_parameters is an object. Its properties can be accessed as usual: bracket notation is only necessary for unusual identifiers, e.g. including space, hyphen, ., etc.

JSON.parse(alx_parameters.common) will return an array of string values. So @ShadowDragon is correct that you would want to loop over the array to parse those into numbers, e.g.
JavaScript:
var alx_common = JSON.parse(alx_parameters.common).map(
  function(v) { return parseInt(v, 10); }
);
This uses a built-in array method, map, to transform each element of the input array.
Transformed the code to
JavaScript:
(function() {  
    var alx_parameters = PluginManager.parameters("idiotsFirstPlugin");
    var alx_common = JSON.parse(alx_parameters.common).map(
        function(v) { return parseInt(v, 10); }
      );
 
    window.random_thing = function() {
        $gameVariables.setValue(83, alx_common[0]);
        $gameMessage.add("It's \\v[83].");
    };
  })();
NPC still does nothing?
for reference, the npc settings:
settings

(wrote it twice since i couldn't remember which one was right.)
It's random_thing().

Things to check:
  1. Is your plugin file named idiotsFirstPlugin.js (case-sensitive)?

  2. Have you turned on the plugin in the Plugin Manager?

  3. For now, make sure you have turned off any other plugins.

  4. Did you save your project to apply Plugin Manager changes before testing?

  5. That event should error out at the first Script command ("$random_thing is not defined"). But if it does nothing, not even show the "test" message, then that suggests the event isn't even running. When testing, select New Game from the title screen. Maybe you're activating a different event?

  6. Have you checked the console for errors, like I suggested?
Have you checked the console for errors, like I suggested?
Almost forgot about it! After checking it, it says that random_thing is not defined
1710512017471.png

Just to be sure I checked it with plugins turned off - in which case it just throws out an error on screen.
Because the plugin didn't load, as indicated by the first error in the console:

console.png

The problem is that the parameters are blank by default, and JSON.parse doesn't work with empty strings. You can temporarily fix that by simply editing the parameter (double-click) then clicking OK. The value should now be [] (unless your editor version is really outdated for some reason).

To actually fix it, you can add a safety check, so the plugin never tries to parse an empty string:
JavaScript:
var alx_common = JSON.parse(alx_parameters.common || "[]").map(
  function(v) { return parseInt(v, 10); }
);
I also suggest setting a default value for each parameter, e.g.

@param common @type item[] @desc Optional description~ @default []

Regardless, with that problem solved, the plugin works for me. Note that you have to have at least 83 game variables defined for $gameVariables.setValue(83, value) to do anything. You can change the maximum number of variables in the editor:

variables.png

JavaScript:
    window.random_thing = function(type) {
        switch(type) {
            case "common":
                $gameVariables.setValue(83, alx_common[0]);
                $gameMessage.add("It's \\v[83].");
                break;
            case "epic":
                $gameVariables.setValue(83, alx_epic[0]);
                $gameMessage.add("It's \\v[83].");
                break;
            default:
                 consol.log("type does not exist")
        }
    };

this is a alternate way if you want random from a pool.
so you can do: random_thing("common") to get something from the common,
you can extend the list.

this can make it more efficient as well.
Thank you! It works now!
I think that solves my problem, but before I go I wanted to thank everyone for help. I probably gonna post here again some time in the future, so I hope you won't get mad, lol.
Almost forgot about it! After checking it, it says that random_thing is not defined
Just as a tip, as you saw in this thread - it's a bad idea to crop your screenshots and pick and choose what information people see.

For some reason, you cropped out the actual line that says the plugin was incomplete and not loaded at all - if caethyril hadn't taken the time to save your code and test the plugin herself, we wouldn't have known.

Any time you show a screenshot - of the console, a database item, event, whatever - just post the entire relevant window.

Good luck!
so I hope you won't get mad, lol.
why would we?
we try to help when we are able and your free to ask for help.
just don't expect to get answers on the fly as we are volunteers ^^

Original thread: https://forums.rpgmakerweb.com/threads/pick-a-random-thing-from-an-array-parameter.166819/