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

get the location of a value in a table

Started by Varscott11, 03 July 2016 - 08:18 PM
Varscott11 #1
Posted 03 July 2016 - 10:18 PM
I've been working with tables, and have created a for loop what looks like this:

for key,value in pairs do

blah, blah, blah.

Is there a way to find the key value that equals the actual value?

kind of like this but in reverse:

local list={ [1] = "hello"}

local value=list[1]
Lignum #2
Posted 03 July 2016 - 10:23 PM
Go through the table using pairs and compare the current value with the one you're looking for. Once you've found your value, return the current key.

That'd look something like this in Lua:

local list = { "hello" }

local function findKey(tbl, value)
   for k,v in pairs(tbl) do
	  if v == value then
		 return k
	  end
   end
end

local helloIndex = findKey(list, "hello")
print(helloIndex) --# prints 1

Keep in mind that if you have multiple values which are the same, it will pick the first key it can find.
KingofGamesYami #3
Posted 04 July 2016 - 12:42 AM
If you do this a large number of times, or depending on your application, it may be worthwhile to simply invert the table's keys and values. For example, if I wanted to allow only certain people to enter my base, I might use a table like this:

{
  ["KingofGamesYami"] = true,
  ["Lignum"] = true,
}