using tables to match items

Runes of Magic/Radiant Arcana (http://www.runesofmagic.com)
Post Reply
Message
Author
noobbotter
Posts: 527
Joined: Fri Aug 31, 2012 1:15 pm

using tables to match items

#1 Post 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.
User avatar
Administrator
Site Admin
Posts: 5344
Joined: Sat Jan 05, 2008 4:21 pm

Re: using tables to match items

#2 Post 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
noobbotter
Posts: 527
Joined: Fri Aug 31, 2012 1:15 pm

Re: using tables to match items

#3 Post 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
User avatar
lisa
Posts: 8332
Joined: Tue Nov 09, 2010 11:46 pm
Location: Australia

Re: using tables to match items

#4 Post 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
Remember no matter you do in life to always have a little fun while you are at it ;)

wiki here http://www.solarstrike.net/wiki/index.php?title=Manual
Post Reply