Problem when setting an i <= InventoryItemCount in a for loop

Started by Gal Shemesh, Wed 03/07/2024 12:34:08

Previous topic - Next topic

Gal Shemesh

When using a for loop to adding items to a list, like so:

Code: ags
function sync_list()
{
  mylist.Clear();
  for (int i = 1; i <= Game.InventoryItemCount; i++)

  {
    if (player.InventoryQuantity[i] > 0)
    mylist.AddItem(inventory[i].ScriptName);
  }
}
If the
Code: ags
i <= Game.InventoryItemCount
is replaced with < instead of <=, it does not add the second item to the list when it is triggered.

Khris

Not sure what your point is here? Or question?

If you skip over the last item and you have two inv items in your game, then the second item is not added if you skip over it, yes.

< and <= are two different things that make code behave differently.

When you loop over an array which is zero based, you typically do:
Code: ags
  for (int i = 0; i < length_of_array; i++)
edit: for an array of size 5, this runs the code inside the loop 5 times, with i being 0, 1, 2, 3 and 4.

In the case of the inventory items array, which for some weird reason is one based, you need to start at 1 instead of 0 and consequently count up until length, not length - 1, therefore:
Code: ags
  for (int i = 1; i <= Game.InventoryItemCount; i++)
edit: for an inventory count of 5, this runs the code inside the loop 5 times, with i being 1, 2, 3, 4 and 5.

Snarky

That's my thinking as well, but on Discord @Crimson Wizard had a different take, essentially arguing (if I have it right) that even though inventory[0] is not a valid inventory item, Game.InventoryItemCount should be equal to the size of the inventory[] array (i.e. the highest valid index + 1).

I think the problem here is that the design choice to use 1-based inventory ID numbers but access them through an array (with 0-based indexing) is inherently inconsistent, so there is no truly "correct" way to do it. The proper fix would be to start the IDs from zero.

Khris

@Snarky leaving aside AGS's quirks, I'm reading the OP as "if I use < instead of <= my code breaks" and given there's no further explanation I don't really know which problem to address in the first place.

SMF spam blocked by CleanTalk