Page 1 of 1

how to use basic list or array to see whether an item is in the list?

Posted: Fri May 19, 2023 12:35 am
by caiyaozheng
hey, i want to do:

1. capture item name from a line(i know how to do it ,let's say the captured item is now in matches[2])
2. make an item list. for exmaple apple,banana,cake,rice....
3.verify whether the mathces[2] is the item in the item list

my current scripts:

item_english=matches[3]
if string.find(matches[2], "apple") then send("drop "..item_english) end

but the above script can only do 1 item at a time.

can someone help?

Re: how to use basic list or array to see whether an item is in the list?

Posted: Fri May 19, 2023 2:39 am
by demonnic
Code: [show] | [select all] lua
local fruit = { "apple", "orange", "banana" }
if table.contains(fruit, item) then
  -- item is in the fruit table
end

-- could make a function for it if you may need to check frequently
function isFruit(item)
  return table.contains(fruit, item)
end

test = isFruit("apple")
display(test) --true

Re: how to use basic list or array to see whether an item is in the list?

Posted: Fri May 19, 2023 1:54 pm
by Jor'Mox
Another way, especially if you have different actions to match different words you are looking for, is to use your matched words as keys, and the actions as entries, like this:
Code: [show] | [select all] lua
action_table = {apple = "drop apple", orange = "eat orange", pear = "cast fireball pear"}

-- then you leverage that table like this
action = action_table[matches[2]]
if action then send(action) end
But your mentioning of only being able to do one item at a time makes me think that you are getting a list of items all in a single string, and you want to check for all of the items you care about in that longer string, and deal with each one, all at once. To do that, you'd use an iterator function to modify what you have above, like this:
Code: [show] | [select all] lua
action_table = {apple = "drop apple", orange = "eat orange", pear = "cast fireball pear"}

-- then you iterate through the capture to get each word in turn
-- %a+ will match any set of consecutive upper or lower case letters
for w in string.gmatch(matches[2], "%a+") do
    action = action_table[w]
    if action then send(action) end
end

Re: how to use basic list or array to see whether an item is in the list?

Posted: Wed Jun 14, 2023 1:01 pm
by caiyaozheng
thanks! @demonnic & Jor'Mox!