This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
cygnis's profile picture

Creating Table of Unique Items

Started by cygnis, 23 March 2014 - 08:46 PM
cygnis #1
Posted 23 March 2014 - 09:46 PM
I've been searching for a few hours now, and haven't figured out how to go about populating a list within a loop, accepting only unique values.

Test code:

myList = {}
while true do
	 print(“insert:”)
	 item = read()
	 if item ~= nil and ~= myList[item] then
		  table.insert(myList,item)
	 end
	 for i = 0, #myList do
		  print(myList[i])
	 end
end

This obviously doesn't work, but I'm at a loss as to how to check if the item is already in the list or not.
CometWolf #2
Posted 23 March 2014 - 10:02 PM
Just store the items as the key instead of the value, then use a pairs loop to list them all.

myList = {}
while true do
		 print(“insert:”)
		 local item = read()
		 myList[item] = myList[item] or true
		 for k,v in pairs(myList) do
				  print(k)
		 end
end
cygnis #3
Posted 23 March 2014 - 10:20 PM

		 myList[item] = myList[item] or true

What is the 'or true' bit doing?
CometWolf #4
Posted 23 March 2014 - 10:40 PM
it's a quicker way of writing

if not myList[item] then
  myList[item] = true
end
Basically what it does is check myList[item] for a value, if there is none there (nil or false) it will move on to the variable following the or statement, and do the same there. Since it's true, it will be considered a valid value, and be stored in the table.
Bomb Bloke #5
Posted 23 March 2014 - 11:44 PM
That is to say, it's a more complex way of writing:

myList[item] = true

:P/>

(Well, to be clear, it doesn't technically do exactly that - but within the context of the rest of the code block, that'll always be the end result.)
Edited on 23 March 2014 - 10:47 PM
CometWolf #6
Posted 24 March 2014 - 12:10 AM
Lol yeah that's true ,it's not really needed since it's storing the same variable anyways.