Page 1 of 1

using tables to match items

Posted: Tue Feb 25, 2014 12:29 pm
by noobbotter
I have a question about when and where you can use a table to match items.

Is it possible to use a table of items in an if statement? For example, let's look at this. Suppose I want to keep only the following potions: 203502,203503,203497,203498,203492,203493. How would I do something like this:

Code: Select all

if item:isType("Potions") and item.Id ~= {203502,203503,203497,203498,203492,203493} then
	item:delete()
end
I'm pretty sure that wouldn't work? But not sure? Would I instead have to do something like:?

Code: Select all

keepItems = {203502,203503,203497,203498,203492,203493}

if item:isType("Potions") then
	local dokeep = 0
	for i, mypots in pairs(keepItems) do
		if item.Id == mypots then
			dokeep = dokeep +1
		end
	end
	if dokeep == 0 then
		item:delete()	
	end
end
It just seems like there should be an easier way of doing that. That's how I would normally do it, but I didn't know if there's a much shorter, easier way to do it. Any help would be appreciated. Thanks.

Re: using tables to match items

Posted: Tue Feb 25, 2014 1:09 pm
by Administrator
You can use table.contains to check if a table contains a value. It works almost exactly like you've done in your example, but the work is already done for you and it will be shorter.

Code: Select all

if( not table.contains({1, 2, 3}, item.Id) then
  -- item.Id is not in the table

Re: using tables to match items

Posted: Tue Feb 25, 2014 1:21 pm
by noobbotter
Exactly what I was looking for. Need to add that one to my dictionary. Thanks.

I just noticed there's an inconsistent number of parenthesis in that.

Should it be

Code: Select all

if ( not table.contains({1,2,3}, item.Id)) then
     -- item not in table
end

Re: using tables to match items

Posted: Tue Feb 25, 2014 6:22 pm
by lisa
Correct, the example was just missing 1 bracket.

Code: Select all

Command> if table.contains({1,2,3,4,5},3) then print("yes") end
yes