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

Post Reply
caiyaozheng
Posts: 16
Joined: Sat Mar 18, 2023 5:34 am

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

Post 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?

User avatar
demonnic
Posts: 886
Joined: Sat Dec 05, 2009 3:19 pm

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

Post 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

Jor'Mox
Posts: 1153
Joined: Wed Apr 03, 2013 2:19 am

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

Post 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

caiyaozheng
Posts: 16
Joined: Sat Mar 18, 2023 5:34 am

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

Post by caiyaozheng »

thanks! @demonnic & Jor'Mox!

Post Reply