Adventure Game Studio

AGS Support => Beginners' Technical Questions => Topic started by: Gepard on Fri 25/03/2011 17:57:37

Title: Check the listbox for an item
Post by: Gepard on Fri 25/03/2011 17:57:37
Yes, I searched the forums. Basically when a player enters a room, I need the script to check a certain listbox for an item and IF there is no such item in that listbox, I want to add that item into that listbox. Is there any easy way of doing this? Thank you very much for helping me.
Title: Re: Check the listbox for an item
Post by: monkey0506 on Fri 25/03/2011 18:22:10
It's actually pretty simple:

  int i = 0;
  while (i < lstListbox.ItemCount)
  {
    if (lstListbox.Items[i] == "some item")
    {
      // do something here..
      i = lstListbox.ItemCount; // break out of the loop
    }
    i++;
  }


If you need to do this more than once, you could even make a handy extender method:

// Script.ash

import int IndexOf(this ListBox*, String item, bool caseSensitive=true);

// Script.asc

int IndexOf(this ListBox*, String item, bool caseSensitive)
{
  if (item == null) return -1;
  int i = 0;
  while (i < this.ItemCount)
  {
    if (this.Items[i].CompareTo(item, caseSensitive) == 0) return i;
    i++;
  }
  return -1;
}

// some other script

int index = lstListbox.IndexOf("some item");
if (index == -1)
{
  Display("Item not found in ListBox!");
}
else
{
  Display("Item found at index %d!", index);
}
Title: Re: Check the listbox for an item
Post by: Gepard on Fri 25/03/2011 18:39:37
Hi, thanks for the answer, what I have now is this:

function CheckTopics (String topicname) {
 int i = 0;
 while (i < topics.ItemCount)
 {
   if (topics.Items[i] == "topicname")
   {
     topics.AddItem (topicname);
     i = topics.ItemCount; // break out of the loop
   }
   i++;
 }
}


But it doesnt work :( Why?

Oh I know why! I had to change the == into != and there needs to be at least one item in the listbox, otherwise it wont work... Thanks for the help.
Title: Re: Check the listbox for an item
Post by: monkey0506 on Fri 25/03/2011 18:55:08
..no. That's not why.

You're checking:

if (topics.Items[i] == "topicname")

You're checking against a string-literal, not against the variable named topicname.

In my first code-snippet I intentionally was checking against a string-literal because I hadn't defined a variable for the item's value. In my second code snippet I used the String.CompareTo function to allow optional case-sensitivity, but I then used the variable, not a string-literal. Your code should look like this:

function CheckTopics (String topicname)
{
  int i = 0;
  while (i < topics.ItemCount)
  {
    if (topics.Items[i] == topicname)
    {
      topics.AddItem (topicname);
      i = topics.ItemCount; // break out of the loop
    }
    i++;
  }
}


Note that all I did was remove the quotes to change the string-literal into the variable.