Check the listbox for an item

Started by Gepard, Fri 25/03/2011 17:57:37

Previous topic - Next topic

Gepard

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.
Drink up me 'arties! Yo ho!

monkey0506

It's actually pretty simple:

Code: ags
  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:

Code: ags
// 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);
}

Gepard

#2
Hi, thanks for the answer, what I have now is this:

Code: ags
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.
Drink up me 'arties! Yo ho!

monkey0506

#3
..no. That's not why.

You're checking:

Code: ags
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:

Code: ags
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.

SMF spam blocked by CleanTalk