ChizWhiz12

Villager
Member
Joined
Dec 14, 2016
Messages
19
Reaction score
2
First Language
Filipino
Primarily Uses
Good day!

I am a JavaScript beginner who's still trying to learn, and I'm having some trouble running a particular plugin I made for an old project I've recently come back to. Originally, this part of my project was a mess of conditional branches, but after finding out about switch statements, I tried changing it entirely. I was originally hoping to put the entire code on a script call, but it did not fit within the max limit. So I tried saving it externally as a plugin, yet I can't seem to get it to work.

Here's what I wrote for the plugin:

JavaScript:
var wellDefined = function() {
   switch ($gameVariables.value(2)) {
   case 1:
     $gameVariables.setValue(21, "primary colors");
     break;
   case 2:
     $gameVariables.setValue(21, "famous dancers");
     break;
   case 3:
     $gameVariables.setValue(21, "all multiples of 5");
     break;
    // 47 more cases...
   }
};

I then do a script call for wellDefined(); , but the Developer Tools windows popup due to an error.

I would be very grateful for any advice as to how I might fix my code, as well as any suggestions as to how I can further optimize it.

Thank you so much :D
 

Nolonar

Veteran
Veteran
Joined
Feb 18, 2018
Messages
504
Reaction score
707
First Language
French, German
Primarily Uses
RMMZ
It would be helpful if you could at least tell us what the error is, but from what I understand:
  • wellDefined() is in a plugin.
  • You are trying to call wellDefined() from a script call.
I'm guessing the error you are getting is something like:
Uncaught ReferenceError: wellDefined is not defined

This might be because of the var in front of wellDefined, which indicates that wellDefined is a local variable that only exists inside your plugin.

You can either make wellDefined a global variable (not recommended, since it can conflict with other plugins trying to define the same global variable), or create a global variable with a unique name (e.g. ChizWhiz12, which nobody else will try to overwrite) and add wellDefined to it.

One way or another, you'll need to know how to define a global variable.
In JavaScript, there are 2 ways to do it:

1. Don't use var, example: bla = 3 creates a global variable named "bla" with value 3.

This is not recommended, because you could get used to not writing var, which would lead to you creating global variables without intending to.

2. Use the document object, example: document.bla = 3

This is recommended, because when you add to the document object, you remain conscious that you're creating a global variable. Also, when you (or someone else) reads the code, you can be sure that the global variable was intended, and not a potential bug.



So to fix your code, we can either do:
JavaScript:
document.wellDefined = function() {
  // code here
};
which you can call simply using wellDefined();

or
JavaScript:
document.ChizWhiz12 = document.ChizWhiz12 || {};

ChizWhiz12.wellDefined = function() {
  // code here
};
which you can call using ChizWhiz12.wellDefined();

As for why I wrote document.ChizWhiz12 = document.ChizWhiz12 || {};, that's for compatibility with other (potential future) plugins.

If you only call document.ChizWhiz12 = {};, then every plugin where you call this will overwrite the global ChizWhiz12 object and replace it with an empty object. To fix that, you would have to ensure only one plugin calls that line, as well as ensure that it gets loaded before any of your other plugins.

But when you use document.ChizWhiz12 = document.ChizWhiz12 || {};, you are replacing the global ChizWhiz12 object with itself (if it exists) or with a new empty object (if it doesn't exist). This means that every one of your plugins can call that line to create the global object if it doesn't exist, and you can load your plugins in any order you wish.

I apologize for the wall of text and hope that my answer was at least somewhat helpful.
 

TheoAllen

Self-proclaimed jack of all trades
Veteran
Joined
Mar 16, 2012
Messages
7,174
Reaction score
10,554
First Language
Indonesian
Primarily Uses
N/A
Personally, if I were to make a global variable, I use window such as window.wellDefined = function(){} instead of document. Not sure what the difference is though.
 

ct_bolt

Creator
Veteran
Joined
May 3, 2012
Messages
1,367
Reaction score
970
First Language
Javascript
Primarily Uses
RMMZ
Good day!

I am a JavaScript beginner who's still trying to learn, and I'm having some trouble running a particular plugin I made for an old project I've recently come back to. Originally, this part of my project was a mess of conditional branches, but after finding out about switch statements, I tried changing it entirely. I was originally hoping to put the entire code on a script call, but it did not fit within the max limit. So I tried saving it externally as a plugin, yet I can't seem to get it to work.

Here's what I wrote for the plugin:

JavaScript:
var wellDefined = function() {
   switch ($gameVariables.value(2)) {
   case 1:
     $gameVariables.setValue(21, "primary colors");
     break;
   case 2:
     $gameVariables.setValue(21, "famous dancers");
     break;
   case 3:
     $gameVariables.setValue(21, "all multiples of 5");
     break;
    // 47 more cases...
   }
};

I then do a script call for wellDefined(); , but the Developer Tools windows popup due to an error.

I would be very grateful for any advice as to how I might fix my code, as well as any suggestions as to how I can further optimize it.

Thank you so much :D
Hmm... not really sure but it works for me exactly as you have it wrote.
...not to ask a silly question but umm... you have the plugin enabled and everything via the plugin manager correct? (F10 key opens plugin manager)
1664323241317.png

if so then yep only thing I can say is really we need to see the error message from the console. That would greatly help figure out the issue.
 

Trihan

Speedy Scripter
Veteran
Joined
Apr 12, 2012
Messages
6,020
Reaction score
6,011
First Language
English
Primarily Uses
RMMZ
Personally, if I were to make a global variable, I use window such as window.wellDefined = function(){} instead of document. Not sure what the difference is though.
window is the very top level, and document is one of window's child elements. When you type "document", it's just shorthand for window.document, as you can see here.

1664323390272.png
 

ATT_Turan

Forewarner of the Black Wind
Veteran
Joined
Jul 2, 2014
Messages
7,694
Reaction score
5,448
First Language
English
Primarily Uses
RMMV
Originally, this part of my project was a mess of conditional branches, but after finding out about switch statements, I tried changing it entirely.
Aside from fixing the scope of your function as Nolonar describes, may I suggest an alternative route? Since the only thing you're doing is setting a predetermined variable to a predetermined value, you really don't need all the extra lines with switch cases and breaks and everything.

You could simply define your phrases in an array and then set the variable equal to the value of that index. Example:
Code:
var arrayPhrases=["", "primary colors", "famous dancers",
                  "all multiples of 5", 47 more things];
$gameVariables.setValue(21, arrayPhrases[$gameVariables.value(2)]);
 

ChizWhiz12

Villager
Member
Joined
Dec 14, 2016
Messages
19
Reaction score
2
First Language
Filipino
Primarily Uses
Hello again. Thank you everyone for the quick response!

You can either make wellDefined a global variable (not recommended, since it can conflict with other plugins trying to define the same global variable), or create a global variable with a unique name (e.g. ChizWhiz12, which nobody else will try to overwrite) and add wellDefined to it.

@Nolonar Thanks for the heads-up about global variables and the document object, I'll definitely keep that in mind! As for changing my plugin with this suggestion, it still returns with "ReferenceError x is not defined." To confirm, I am using the "Script..." Event Command, but I've tried with "Plugin Command..." as well with it not returning anything.

Hmm... not really sure but it works for me exactly as you have it wrote.
...not to ask a silly question but umm... you have the plugin enabled and everything via the plugin manager correct? (F10 key opens plugin manager)

@ct_bolt Yup, I'm quite certain it's on the Plugin Manager window. The plugin is saved as a .js file on the plugins folder, and I have all of my other plugins turned off as I am testing this.

You could simply define your phrases in an array and then set the variable equal to the value of that index. Example:
Code:
var arrayPhrases=["", "primary colors", "famous dancers",
"all multiples of 5", 47 more things];
$gameVariables.setValue(21, arrayPhrases[$gameVariables.value(2)]);

@ATT_Turan Oh wow, this definitely looks cleaner than my original code in my opinion. Thank you so much! However, I run into the same issue as I've had before - "ReferenceError x is not defined."

I have tried combining both @Nolonar and @ATT_Turan 's suggestions, and have attached my plugin files below. Greatly appreciate everyone's help. Thanks again!
 

Attachments

  • QUE_WellDefinedSets_V1.js
    4.2 KB · Views: 2
  • QUE_WellDefinedSets_V2.js
    1.3 KB · Views: 7

Mac15001900

Veteran
Veteran
Joined
Aug 7, 2022
Messages
143
Reaction score
130
First Language
English
Primarily Uses
RMMV
However, I run into the same issue as I've had before - "ReferenceError x is not defined."

This code looks perfectly fine, are you sure it's this plugin causing the error? If you disable it (and remove whatever is calling wellDefined in the project), does the error go away?

ReferenceError in this case means that somewhere, something is trying to use a variable called 'x', but such variable does not exist. You're not using 'x' in this file, so it might be something else.

Another thing you can do is press F8 when you encounter an error. Then select "Console" on top, and look for a red message with the error. There, on the right you can see where the error occurred, and by expanding the message (the small triangle arrow at the start) see more information about what the program was doing when it happened. This should tell you which file (i.e. which plugin) is likely responsible. Also, if you see "Game_Interpreter.command355" in there, the problem was within a script block created in the editor.
 

ATT_Turan

Forewarner of the Black Wind
Veteran
Joined
Jul 2, 2014
Messages
7,694
Reaction score
5,448
First Language
English
Primarily Uses
RMMV
ReferenceError in this case means that somewhere, something is trying to use a variable called 'x', but such variable does not exist. You're not using 'x' in this file, so it might be something else.
Agreed - @ChizWhiz12 we're back to the very first thing Nolonar said in his first reply. Please post an actual screenshot of the error trace from the game. We started out with guessing what the error was and it's led you on a day-long trip down a rabbit hole.
 

TheoAllen

Self-proclaimed jack of all trades
Veteran
Joined
Mar 16, 2012
Messages
7,174
Reaction score
10,554
First Language
Indonesian
Primarily Uses
N/A
window is the very top level, and document is one of window's child elements. When you type "document", it's just shorthand for window.document, as you can see here.

View attachment 241440
Still though, practically what's the difference?
 

ChizWhiz12

Villager
Member
Joined
Dec 14, 2016
Messages
19
Reaction score
2
First Language
Filipino
Primarily Uses
I apologize for the inconvenience, everyone. I should have attached a screenshot from the beginning had I known of the F8 function - I would definitely keep that noted in the future. Sorry about that :/

Here is the Event I've prepared...

001 - Event.png
.
And here is the resulting Error...

002 - Error after interacting with event.png

I've also screenshotted the Error when I have the Yanfly Core Engine plugin ON...

003 - Error interacting with event (Yanfly Core Engine ON).png

ReferenceError in this case means that somewhere, something is trying to use a variable called 'x', but such variable does not exist. You're not using 'x' in this file, so it might be something else.
Also, if you see "Game_Interpreter.command355" in there, the problem was within a script block created in the editor.

@Mac15001900 I apologize for causing a bit of confusion, I simply meant to use 'x' as a stand-in for the example I was giving. Very sorry about that. And yup, I do see Game_Interpreter.command355, though I'm quite the dummy so I can't figure out what the problem is in the editor.

I hope I got everything. Sorry again for the inconvenience.
 

ct_bolt

Creator
Veteran
Joined
May 3, 2012
Messages
1,367
Reaction score
970
First Language
Javascript
Primarily Uses
RMMZ
Sooo right away your plugin isn't actually being loaded into the game.
This is because it doesn't have just the object "chizu" defined.

You can simply fix that by changing your top line to become something like this instead:
JavaScript:
var chizu = chizu || {};

Full code would then be this:
Code:
var chizu = chizu || {};

chizu.wellDefined = function() {

    chizu.arraywellDefined = ["", "primary colors", "famous dancers",
    "all multiples of 5", "all punctual students in 7th grade", "all even numbers", "honest people",
    "letters in the word \"arrange\"", "young politicians", "types of matter", "versatile actresses",
    "all the lakes in our country", "the tastiest fruits", "months containing 31 days", "durable bags",
    "all discovered planets in our galaxy", "tall building", "consonants in the English alphabet",
    "trendy outfits for teens", "grains of sand from a white beach", "nice miniature houses",
    "carpenter's tools", "pretty flowers", "polygonal dice", "expensive gadgets", "spiral seashells",
    "fancy vehicles", "toy soldiers", "well-made furniture", "encyclopedias", "unique painting",
    "golden jewelry", "beautiful pots", "every season in a year", "big dogs", "all the ants in my garden",
    "popular books", "weekdays", "scary insects", "factors of 9", "favorite sculptures", "black birds",
    "the best rock albums", "round bottles", "fragrant candles", "sharp swords", "comfortable cushions",
    "negative integers", "lucky numbers", "prime numbers", "cheap prices"];

    $gameVariables.setValue(21, chizu.arraywellDefined[$gameVariables.value(2)]);
};
That works exactly as it should for me. :)

Sidenote:
You can make it more flexible if you wanted to add parameters to the function like this...
JavaScript:
var chizu = chizu || {};

chizu.wellDefined = function(fromVariable, toVariable) {

    chizu.arraywellDefined = ["", "primary colors", "famous dancers",
    "all multiples of 5", "all punctual students in 7th grade", "all even numbers", "honest people",
    "letters in the word \"arrange\"", "young politicians", "types of matter", "versatile actresses",
    "all the lakes in our country", "the tastiest fruits", "months containing 31 days", "durable bags",
    "all discovered planets in our galaxy", "tall building", "consonants in the English alphabet",
    "trendy outfits for teens", "grains of sand from a white beach", "nice miniature houses",
    "carpenter's tools", "pretty flowers", "polygonal dice", "expensive gadgets", "spiral seashells",
    "fancy vehicles", "toy soldiers", "well-made furniture", "encyclopedias", "unique painting",
    "golden jewelry", "beautiful pots", "every season in a year", "big dogs", "all the ants in my garden",
    "popular books", "weekdays", "scary insects", "factors of 9", "favorite sculptures", "black birds",
    "the best rock albums", "round bottles", "fragrant candles", "sharp swords", "comfortable cushions",
    "negative integers", "lucky numbers", "prime numbers", "cheap prices"];

    $gameVariables.setValue(toVariable, chizu.arraywellDefined[$gameVariables.value(fromVariable)]);
};
Then call it like this
JavaScript:
chizu.wellDefined(21, 2);
Just throwing it out there but totally don't have to of course.

Hope that helps & works as needed for you.
 
Last edited:

ChizWhiz12

Villager
Member
Joined
Dec 14, 2016
Messages
19
Reaction score
2
First Language
Filipino
Primarily Uses
You can simply fix that by changing your top line to become something like this instead:
JavaScript:
var chizu = chizu || {};
Sidenote:
You can make it more flexible if you wanted to add parameters to the function like this...

@ct_bolt It worked! Thank you so much! And yes, adding parameters to the function would definitely be useful since I am making an educational game, and I basically need a RNG that pulls questions out for each section. By having the code written that way, perhaps adding an array parameter as well, I could use this one plugin for everything. Once again, thank you!

Deeply appreciate everyone who helped me out! I have learned a lot from this, rest assured your replies have been noted <3
 

ct_bolt

Creator
Veteran
Joined
May 3, 2012
Messages
1,367
Reaction score
970
First Language
Javascript
Primarily Uses
RMMZ
@ct_bolt It worked! Thank you so much! And yes, adding parameters to the function would definitely be useful since I am making an educational game, and I basically need a RNG that pulls questions out for each section. By having the code written that way, perhaps adding an array parameter as well, I could use this one plugin for everything. Once again, thank you!

Deeply appreciate everyone who helped me out! I have learned a lot from this, rest assured your replies have been noted <3
Yay! Awesome! Glad to hear it's working for ya now :cutesmile:

Happy Game Making! :LZScheeze:
 

Mac15001900

Veteran
Veteran
Joined
Aug 7, 2022
Messages
143
Reaction score
130
First Language
English
Primarily Uses
RMMV
@ct_bolt It worked! Thank you so much! And yes, adding parameters to the function would definitely be useful since I am making an educational game, and I basically need a RNG that pulls questions out for each section. By having the code written that way, perhaps adding an array parameter as well, I could use this one plugin for everything. Once again, thank you!

Deeply appreciate everyone who helped me out! I have learned a lot from this, rest assured your replies have been noted <3

I'm glad it ended up working out :) Here's a bonus JavaScript tip: if you just want to select a random element from an array, you can do so with
JavaScript:
arrayName[Math.floor(Math.random()*arrayName.length)]
.
 

ChizWhiz12

Villager
Member
Joined
Dec 14, 2016
Messages
19
Reaction score
2
First Language
Filipino
Primarily Uses
I'm glad it ended up working out :) Here's a bonus JavaScript tip: if you just want to select a random element from an array, you can do so with
JavaScript:
arrayName[Math.floor(Math.random()*arrayName.length)]
.
Thanks for the tip! I've got something pretty similar running in my plugin, which I guess I'll attach here as well. It's very clunky and is definitely not yet optimized enough to be used on a project other than what I'm working on, but I do owe sharing it to y'all for helping me out <3
 

Attachments

  • CHIZ_RandomQuestionGenerator.js
    13.3 KB · Views: 2

Latest Threads

Latest Posts

Latest Profile Posts

I love this job (as a programmer), coding is fun sometimes. It is just the deadline that needs to CHILL.
Best explanation of "Confirmation Bias": "If you go looking for a fight, you will always find one". If you always look for something, you'll find it. Negativity or Positivity. This is just a reminder to spend time looking for some Positivity today. :D Ya'll have earned it and deserve it.
And now all my attacking skills suddenly heal instead of doing damage...Even kills and revives. Because ofc they do xD
Spend more time building up what you like, and stop tearing down things you don't. If you only tear stuff down, nobody will get to enjoy anything.
Work, work. Streaming in 20 minutes or so.

Forum statistics

Threads
129,931
Messages
1,206,341
Members
171,130
Latest member
thepipa666
Top