How do you ACCESS Array Elements using Angelscript?

403 Views Asked by At

I am trying to create a simple inventory system for a game I am creating. The inventory needs 2 pieces of information for each item in the inventory, "item name" and "item description".

The information I read from the Angelscript website says to create

an array of string with 2 elements each.

Apparently this is done by using

string[] inventory(2); 

What does this mean 2 elements?
How do I access those 2 elements inside the array?

The code below seems to work, but doesn't do what I expect it would do.

void Inventory(string item, string description) {
string[] inventory(2); // an array of string with 2 elements each. 

inventory.insertLast(item); // item name

inventory.insertLast(description); //item description

print("ID:"+ inventory[1]);
print("ID:"+ inventory[2]);
print("ID:"+ inventory[3]);
}

Inventory("gold_key",item);

output

ID:
ID:gold_key
ID:Use this gold key to unlock a gold door.
2

There are 2 best solutions below

0
On

I am not sure want you want to do but accessing array can be done using arr_name[index]. While index begin in 0. For example:

{
    string[] inventory(2);
    inventory[0] = "aaa";
    inventory[1] = "bbb";
    cout << "inventory include" << inventory[0] << "and" << inventory[1] << endl;
}
0
On

Your code does the following: Create a string array with two empty strings. Adding two other elements to end the array with insertLast. After that the 2nd, 3rd and 4th element are dereferenced and printed.

It does not do what you expect because: 1) It‘s not a string array with two items each, it‘s a string array with two items. 2) You add item and description at the end of the array, after the two empty strings. 3) The indexing starts at 0 for the first element.

If you really want a two dimensional array try the following:

array<array<string>> inventory;
array<string> elem = {item, description};
inventory.insertLast(elem);
cout << inventory[0][0] << „: “ << inventory[0][1] << endl;