Double Dimension arrays.

I found a solution on one of my major issues I had, while I was thinking of implementing an idea into an actual game.

Here goes the solution on the thread I opened for your reference:

So far I know:
  • I can set values using script commands.
  • I can set as a value a one dimension array.
  • I can read values using script commands from normal variables and one dimension arrays.

Still using Script Event Command:
  1. Can I turn an RPG Maker built in variable into a two dimension array?
  2. Can I set the data?
  3. Can I access the data?
  4. If so, we need a valid example.
I found the solution and I share it now on this thread to save you some time.

Yes we can do this!
Control Variables 1, 2 and 5 get value using the Script option.


◆Control Variables:#0001 = [2,2,3]
◆Control Variables:#0020 = 2
◆Script:$gameVariables.value(1)[1] = 1;
◆Script:$gameVariables.setValue(2, $gameVariables.value(1)[1]);
◆Script:$gameVariables.setValue($gameVariables.value(20), 'Hello');
◆Control Variables:#0005 = [[1,2,3],[4,5,6],[7,8,9]]
◆Script:$gameVariables.setValue(2, $gameVariables.value(5)[2][1]);

◆Comment:Should return 8 on second row
◆Text:None, Window, Bottom
:Text:\V[1]
:Text:\V[2]
:Text:\V[4]

But this command is really messy. I mean...
◆Control Variables:#0005 = [[1,2,3],[4,5,6],[7,8,9]]
it is kinda bleh!
What if the array has 9001 rows?
So... it seems we can use a multi-line syntax with no problem!
You shall use though a Script Event Command to set the multi dimension Array.


THIS is what you should study, if you wanna play with csv-like data:

◆Control Variables:#0001 = [2,2,3]
◆Control Variables:#0020 = 2

◆Script:$gameVariables.value(1)[1] = 1;
◆Script:$gameVariables.setValue(2, $gameVariables.value(1)[1]);
◆Script:$gameVariables.setValue($gameVariables.value(20), 'Hello');
◆Control Variables:#0005 = [[1,2,3],[4,5,6],[7,8,9]]
◆Script:$gameVariables.setValue(2, $gameVariables.value(5)[2][1]);
◆Comment:Should return 8 on second row
◆Script:$gameVariables.setValue(10, [
: :['Hi!', 'Bye', 'Lie'],
: :['Try','Die','Spy'],
: :['My','Why','Shy']
: :]);
◆Script:$gameVariables.setValue(9, $gameVariables.value(10)[1][0]);
◆Text:None, Window, Bottom
: :\V[1]
: :\V[2]
: : \V[4]
: : \V[9]

◆Comment:4th row should... try!



Moderator note: Opened it for possible questions that may arise.
as much as I use array for a long time
now I more use object instead
because I always forgot what index 1/2/3 is
now I more to use
var Buster_sword = {}
Buster_sword.name = 'Buster sword'
var Mc = {}
Mc.weapon_equip = [
Buster_sword ,
Double_edge
]

Mc.weapon_equip[1].name = 'Buster sword'
You can always use objects. but what if someone wants to keep things simple?
You might not need to remember what the index of the items in the array is.
There are cases, that are just let's say different colors and sizes of balls.
Still all of them are balls and it's not important which ball is witch.
Thus you really need a neat and simple way to play with your data fast and efficient.
Everyone is using what is better to have your job done.

For instance, what if you want NPCs to say random stuff each time?
Oh! You can get a random number from 1 to N and have an array of N items.
You get a random line, and show it. It doesn't matter which is which.

P.S. I think arrays are objects too. I might be wrong though.
Cool csv solution!
Yes, arrays are objects, but what's commonly called objects in javascript are like associative arrays in other languages. So it's the convention to say objects for {} and arrays for [] even if they're technically both objects... and arrays.
umm... I didn't say array is wrong...
sorry if my poor English make you feel offend
just say that now a day I use object more
because I like to know the name more than [1][2][3]
it make my little brain confusing

and I think what we should do is use them in the right spot
or even combo them...

and yes array and object
they are similar in many ways
if you dig down
they can do many same thing
the only blockade is our knowledge

well... haha...
who am I to said that line
as someone who just start learn JavaScript...
@pasunna no no no! It is all right! I wasn't offended at all! And you are absolutely right! I just explained why I wanted to use an array instead of an object here. 🙂
By the way, I am a rookie on JS myself too, so... yeah! Feel free to speak.

Cool csv solution!
Yes, arrays are objects, but what's commonly called objects in javascript are like associative arrays in other languages. So it's the convention to say objects for {} and arrays for [] even if they're technically both objects... and arrays.

Ah! Makes sense. I am a rookie on JS really, sometimes it is not obvious because I know how to code on other languages, but still, I consider myself a completely noob case.
I started asking for a csv manipulation solution.
I figured out it was complex to make one.
Then someone told me that since the data will be in a csv, it would be the same thing if I would implement them into a plugin.
I was like wait WHAT? That was a brilliant idea.
And then it hit me.
No need for plugin.
Just set the data using a Script Event Command and you are ready to go!!!
I just needed to gather information on how to access the data after this.
And voila!
I am rookie too I just fake it 'til I make it 😊

I do like this straightforward solution you've come up with, sometimes the cleanest approach is the best one.
If you wanna go the extra mile you could probably use my file system plugin to read an actual excel exported csv file and use JSON.parse() to put it into an array
You seem more fluent than me though. I mean at least you made a plugin.
And you did a great job. I left a few comments.
You are surely more fluent in JS than me or that's how it looks!
omg it worked!
JavaScript:
csv = file.read("", "Book1.csv");
csv = JSON.parse('[["' + csv.split(";").join('","').split(/(?:\r\n|\r|\n)/g).join('"],["') + '"]]');
csv // Output => [Array[4], Array[4], Array[4], Array[4]]


Thank you, I don't know, I still am figuring things out and learning all the time.
You're welcome~
Welp, that looks like how I usually doing my eventing. I also sux at coding actually. That's how I'm started to think of covering my weakness, and making more advanced stuff through eventing. It's pretty fun, like exploiting things on minecraft without modding. Hehe, the more you know there are still lot of things that can be exploit...

It's cool that game variables are flexible and not just limited to integer. Also datas stored on it will also be saved on game system, so you don't have to worry bout game save / load.

Other than databasing, I also use it to store stories and dialogues. This GREATLY improve dialog input in the game as you can edit em via text editor. Editing em, even exporting em to other languages will be much easier.
1588827476924.png


I even stopped using window message and make my own message call using show pictures...
Ah, yes. Show pictures is also as much powerful. Technically, if you can control graphics and datas, you can do anything! Mwahahaha!
omg it worked!
JavaScript:
csv = file.read("", "Book1.csv");
csv = JSON.parse('[["' + csv.split(";").join('","').split(/(?:\r\n|\r|\n)/g).join('"],["') + '"]]');
csv // Output => [Array[4], Array[4], Array[4], Array[4]]


Thank you, I don't know, I still am figuring things out and learning all the time.
I shall give this a try someday.
This is really really promising and it seems like a good solution if I end up using a csv or something someday.
I really would like to make it that way, so someone would have an executable file and a csv alongside, thus editing the csv would update the whole game without any code knowledge.
That could be a great teaching tool.
I once used nodeJS script to convert CSV, but later I moved to use python since the pandas lib can help me resolve all datasheet in one excel file in one run.

csv parsing is tricky:
"hello, world", hello, world
should be seen as three columns

JavaScript:
const fs = require("fs");
const path = require("path");
const _ = require("lodash");

const parseCol = (name, col) => {
  const list = col.split(";").filter(Boolean);
  const head = _.head(list);
  if (["id", "name", "note"].includes(name)) return col;
  if (/^.+:.+$/.test(head)) {
    return list.map((item) => {
      const pairs = item.split(":");
      return {
        name: pairs[0],
        note: pairs[1],
      };
    });
  } else if (/^.+[(].+[)]$/.test(head)) {
    return list.map((item) => {
      const [_, id, params] = item.match(/^(.+)[(](.+[,]?)+[)]$/);
      return {
        id,
        params: params.split(","),
      };
    });
  } else if (/^\[.+\]$/.test(col)) {
    return col.split(",");
  }
  return col;
};
const parseFile = async (src, dst, filename) => {
  const data = await fs.promises.readFile(path.resolve(src, filename), "utf-8");
  const lines = data.split("\r\n").map((item) => {
    let flag = true;
    const list = [0];
    const subStrings = [];
    item.split("").forEach((v, i) => {
      if (v === '"') return (flag = !flag);
      if (v === "," && flag) {
        list.push(i);
        subStrings.push(item.substring(list[0], list[1]).replace(/^["](.*)["]$/, "$1"));
        list.shift();
        list[0] += 1;
      }
    });
    subStrings.push(item.substring(list[0]).replace(/^["](.*)["]$/, "$1"));
    return subStrings;
  });
  const head = lines.shift();
  const obj = lines.map((line) => _.fromPairs(line.map((col, index) => [head[index], parseCol(head[index], col)])));
  await fs.promises.writeFile(path.resolve(dst, filename.replace(/csv$/, "json")), JSON.stringify(obj));
};

const src = "./data/Cards/CSV";
const dst = "./data/Cards/JSON";
const filenames = fs.readdirSync(src, "utf-8");
filenames.forEach((item) => {
  parseFile(src, dst, item);
});

I am trying to parse format like "action(param1,param2);" into my defined data shape or "key:value;key:value" to a key value pairs. I don't like 2D arrays since they are meaningless.

Original thread: https://forums.rpgmakerweb.com/threads/double-dimension-arrays.121213/