MZ Need Help Understanding Behavior of Arrays in Scripts, Console Logging

Sincere request for education or at the very least some pointers in the right direction or reading material:

Hi all, I'm very new to RPG Maker but have been working hard at it for a few weeks. I've finally ended up here after a lot of lurking, learning, and trying to solve things myself. There are so many helpful posts! I am a beginner with JS and don't have an enormous comp sci background, so please bear with me when possible. I have really been trying to upgrade and round out my knowledge, though.

Background: I've been trying to create a simple storage system in my game project- turning an event into a container for some items. I am trying to keep everything simple, direct, and explicitly written. I'm avoiding things that seem too advanced because I won't be able to service them well. I settled on using arrays to make these containers. There were a lot of unexpected pitfalls, mainly stemming from turning variables into objects/arrays and then manipulating or copying those arrays in various ways. Once I learned how to view and use the console, and to use console.log() in my scripts to see what was really going on in my operations, things that had seemed to give a satisfactory result were revealed to be doing weird things I didn't understand in the console.

Remember, I am trying -not- to get out of my depth here.

This led me down a whole chain of reading about object references, shallow cloning vs. deep cloning, how to copy arrays without just making another reference to the same object, the spread (...) syntax, the slice method, Object.create(), JSON.parse(JSON.stringify()), etc. etc. Stuff that honestly, I can read about and use, but not understand the full implications of. Things that would make it difficult for me to expand on the foundation I created.

Where I'm at right now and what's causing a problem for me: I am working on a Sort feature for my storage container (they are small, not too many slots) that finds and grabs any "Empty" slots in the container (read: the array) and throws them all toward the back of the array, leaving all your items stacked in a row at the front of the container (the array). After some weird behavior, I made a small Test event just to test the basic idea on a small scale.

Here's the idea/algorithm (beginner level!): You use Control Variable to declare a game variable as a new Array([7, 7, "first"]). Call it $gV181. But we want "first" to be first, and the 7's to follow it at the back. We start a script, and declare an empty "memory array" to hold the 7 values. Using a for loop, we comb through $gV181, and if we find a 7, we push() that into the memory array. Then using splice(), we remove the 7 from $gV181. When the for loop ends, $gV181 is just ["first"], and the memory array is [7, 7]. While using setValue, we concatenate the two arrays, and $gv181 becomes ["first", 7, 7]. Then the script ends, the memory array essentially goes away, and we have $gv181 the way we want it.

Here's the problem- at the end of the script, $gV181 seems to be correct, as predicted, revealed by console.log()- ["first", 7, 7]. But.. I am also logging the memory array and $gV181 throughout the script, and when the script starts, the console logs them as though they have both already been partially manipulated. This is extremely confusing to me. I will show you. I realize the writing may be in some places superfluous but I am trying to keep things explicit and simple:

Within the events sheet, Control Variables: #0181 arrayConcatTest = new Array(7, 7, "first");
then, script:

console.log("Var 181 is currently:"); console.log($gameVariables.value(181)); var memoryArray = new Array(); console.log("var memoryArray is currently:"); console.log(memoryArray); for (var i = 0; i < $gameVariables.value(181).length; i++) { if ($gameVariables.value(181)[i] == 7) { memoryArray.push($gameVariables.value(181)[i]); $gameVariables.value(181).splice(i, 1); console.log("Var 181 is currently:"); console.log($gameVariables.value(181)); i = i - 1; } } console.log("Var 181 is currently:"); console.log($gameVariables.value(181)); console.log("var memoryArray is currently:"); console.log(memoryArray); $gameVariables.setValue(181, $gameVariables.value(181).concat(memoryArray)); console.log("Var 181 is now:"); console.log($gameVariables.value(181)); console.log("var memoryArray is now:"); console.log(memoryArray);

According to the console, things end up fine, but the logs at the beginning make no sense. If you look at the attached picture, you can see that the two arrays appear to be normal, 3 length and [7, 7, "first"] for Var 181 and just an empty array of length 0 for the other one. However, if you open the dropdown menus, you see that Var 181 is logging as an array of length 1 with element 0 as "first", and the memory array shows as length of 2 with the two elements being the value 7. It is as though they had both been partially manipulated by the for loop, before the final concatenation??

Running the script with the for loop and everything below it commented out printed the logs on the right- the logs I would expect. Length 3, [7, 7, "first"] and length 0, [].

Can someone please talk to me about what's happening in my game? And why? Does the engine try to evaluate the script in some way before running it, as a failsafe, so it doesn't make the engine poo itself or something, and that's messing with the object references before the script is totally run, or something to that effect?

Is this time wizardry? Is this the quantum superposition of variable 181? I can learn how to choreograph move routes at 60 hz. I can read about notetags. I can learn about variable scope. But I think time wizardry is a little bit beyond my grasp.

This concerns me regarding my ability to correctly interpret the logs, and thereby properly debug my game and make it safe to other users so it doesn't break on them, or if it does, I'll know how to fix it. Please help if you can, and remember I'm a beginner so I may not fully understand your references. Thank you so much in advance.
Did you click on the dropdown of the arrays only after the entire code ran, i.e., after the for loop? If you hover your mouse on the little blue icon to the right of the arrays (e.g., to the right of (3) [7, 7, 'first'] in the second line) you'll see it says "Value below was evaluated just now."

That is, it's evaluating the variable at the time that you clicked on the dropdown, so the arrays have already been changed from the initial value.

If you want to test that your initial array is correct, you can try
JavaScript:
console.log($gameVariables.value(181)[i])
in the first line of your for loop, to print out each element.

Hope this helps! I do remember getting confused by this when I first started using the console too.

Edit: Had to put the console code in the CODE tag to avoid italics.
The reason for what you're experiencing is as SeaPhoenix said. If you'd like a little more explanation for why it is that way:

In short, neither $gV181 nor memoryArray *actually* contain an array. What they contain is the numerical address to the memory location where the array starts. When you click that arrow, it goes to the block of memory that the variable points to, in order to populate the dropdown information. Since the contents of that block of memory have already changed by the time that you clicked the arrow, the dropdown is going to contain the new information, rather than the information that existed at the time when you initially called console.log().

Spoiler: Note about your sorting algorithm
On another note, your sorting algorithm is not a very good one. I don't mean that as an insult. Just, since you seem to be interested in learning, I figured that I should let you know. I mean, since you're a beginner, it's not a bad attempt--you used the tools that are available to you in order to accomplish your goal, so that is a win in a way. However, you did it in a way that is extremely wasteful in terms of performance.

You're shrinking one array by one element each time, until it only contains one element. And you're also growing another array by one element each time. Then you're growing the first array back to its original size. The problem with that is that, depending on how optimized the JavaScript engine that is running your code is, it's potentially having to reallocate memory for the entire array, every time you add or remove an element. Allocating memory is one of the slower things that a program can do, so if your end goal is to wind up with an array of the exact same size that you started with, it's ideal to try avoid constantly shrinking and regrowing the array, let alone yet a whole other temporary array as well.

It's probably not good for a beginner to be overly concerned about optimization, but I suppose it's also probably not good for a beginner to get too comfortable with bad habits either. Luckily, sorting algorithms aren't really something that you have to think too hard about, because plenty of other smart people have already done that thinking for you, and there is no shortage of widely known sorting algorithms that you can look up and put to use whenever you need one. The Bubble Sort is maybe a good one to start with, since it's a fairly simple one to understand and implement.

But also, just to let you know, JavaScript does have a built-in sorting function as well. I have no clue what algorithm it uses under the hood, but it's easy to use and pretty flexible. For example, if you just want to move any "first" elements to the beginning of the array, and you don't care about the order of the other elements (as long as they all come after the "first" elements), here is how you could implement it with JavaScript's built-in sort:

JavaScript:
var testArray = [7, 7, "first"];

testArray.sort((a, b) => {
    if (b === "first") return 1;
    return 0;
});

console.log(testArray);

As you can see, the actual sorting portion is only 3 lines of code, and it avoids all that unnecessary memory allocation, and also avoids using a second array like you were doing. And supposing that we want to move all the "first" elements to the beginning of the array, and then sort all the remaining elements in ascending order, it's almost just as easy:

JavaScript:
var testArray = [7, 7, "first", 8, "first", 7];

testArray.sort((a, b) => {
    if (b === "first") return 1;
    if (a === "first") return -1;
    return a - b;
});

console.log(testArray);
Thank you guys both so much for your illuminating responses. I'm really grateful to be able to receive such high quality guidance at that resolution of detail, and for free at that. I've been working really hard to master these tools the past few weeks, and this particular problem was really getting me down- the first roadblock I really didn't know how to make sense of.

Hi @SigmaSuccour I see you there! 🙂 I found your videos on YouTube during my journey the past few weeks and am looking forward to seeing more. 👍

@SeaPhoenix That makes perfect sense, and funny you went through some similar confusion as well. I see that line there now. It's good to have the Time Wizardry theory debunked. Also, I saw your ads in your sig, and bought The Lost Art of Innkeeping. It's awesome! I would like to talk more soon. What you made is very much along the lines of the things I am working on doing- little village environments with social aspects, plots, and upgrades- no battles. I really like the way you delivered tutorial information and used the menus to track progression. Let's talk more once I've finished it!

@Arthran Thanks so much for the detailed information, and the advice about algorithms- no I don't take it personally, you were so kind and thorough in your advice. It's really funny, when I started the Sort project, I had been sitting there with my eyes closed and imagined something very close to the Bubble Sort you linked.. and my immediate next thought was, "Yeah, but with my level of understanding right now, how the hell would I begin to go about doing that? 🤣

I actually do care to some degree about the efficiency- though my first guiding principle at the moment is "Use commands you know and understand, write it so you can read it easily a few days from now, and make it -not break-." The name for this project I imagined, I called "Hands-On Storage." The concept being that the system designs would be guided by what you would do in the physical world with your hands. You'd probably have a drawer you could manipulate with a few things in there, either 4 items or 8 items for easy display and manipulation. So no "Infinite Bag of Holding" inventory which is often the typical format, if there is no encumbrance system.

Optimization does matter though- I made a working solution for the sort before I made this post just to have something functioning (not the code posted above). In fact it was about 2 to 4 times less efficient than what you see above. Just for fun I decided to make the containers have 48 slots and more, and then run the crappy sort to see what the consequences would be (I like to kick these things and see if they're falling apart so that they don't fall apart on someone else later). Whoo boy, was it fun watching the game drop from 144 fps down into the 90s at the push of a button! ☺️

So I will continue to study what you described and the links you posted, and keep trying to gain better command over the array methods. I played a lot of Factorio, and also some of the Zachtronics titles- SpaceChem, Infinifactory, and especially Opus Magnum. It was fun to try solving different problems with different design goals- as fast and efficient as possible, fast and efficient but still with a compact design, or even lengthy or "wasteful" solutions whose design had an aesthetic appeal, or were visually easy to understand the logic of at first glance. I like understanding it all, and why. So thanks very much and I will take your advice to heart!
@ClockworkFigure, thanks for letting me know you bought my game, and glad you enjoyed it! Good luck on your own project too - will be interested in seeing it once you're done!

Original thread: https://forums.rpgmakerweb.com/threads/need-help-understanding-behavior-of-arrays-in-scripts-console-logging.149250/