Jump to content




get the location of a value in a table


  • You cannot reply to this topic
2 replies to this topic

#1 Varscott11

  • Members
  • 23 posts

Posted 03 July 2016 - 09: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]

#2 Lignum

  • Members
  • 558 posts

Posted 03 July 2016 - 09: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.

#3 KingofGamesYami

  • Members
  • 3,002 posts
  • LocationUnited States of America

Posted 03 July 2016 - 11:42 PM

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,
}






1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users