Can I use a String to name a pointer?

Started by bauldur_rises, Sun 28/08/2022 05:47:16

Previous topic - Next topic

bauldur_rises

So, say I wanted to make an array but I wanted to create a string that would name the array - is that possible?

For instance:

Code: ags


arrayname = String.Format("peter");
int arrayname[5];



in order to produce 5 arrays named peter[0] through peter[4].

I suspect the above won't work, but is it possible to do?

Thanks

Crimson Wizard

#1
No; but why do you need this, what are you trying to achieve with this?

Note that the declaration syntax "int arrayname[5]" means one array with 5 elements, not 5 arrays. Array cannot be named "peter[0]", such expression would mean "take the 0th element of array peter", "peter[4]" would mean "take the 4th element of array peter".

bauldur_rises

It was mostly academic at this point, but I thought I'd ask.

Thanks for the correction that it would be one array with an index of 0 to 4, I'm still getting my head around it all.

Khris

You can use a struct instead:

Code: ags
// in script header
struct NamedArray {
  String name;
  int size;
  int numbers[10];
};


Add this in the main script:
Code: ags
NamedArray namedArrays[6];

int findArrayByName(String name) {
  for (int i = 0; i < 6; i++) {
    if (namedArrays[i].name == name) return i;
  }
  return -1;
}


Now initialize them:
Code: ags
  // e.g. in game_start
  namedArrays[0].name = "peter";
  namedArrays[0].size = 5;
  namedArrays[0].numbers[0] = 123;


And use them:
Code: ags
  int peterIndex = findArrayByName("peter");
  if (peterIndex > -1) namedArrays[peterIndex].numbers[1] = 456;


Characters are zero-indexed, so if you want to assign each character an array you can simply use  namedArray[someCharacter.ID]

Snarky

Yes, you could do what Khris describes, but as Crimson asks, why? It is hard to think of a good reason why this should be necessary (at least for any basic task), so probably you're trying to solve some other problem using the wrong approach.

bauldur_rises

It was originally to solve an issue that I've since realised I can solve other ways, but the thought lingered in my head and I was curious.

SMF spam blocked by CleanTalk