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]
get the location of a value in a table
Started by Varscott11, Jul 03 2016 09:18 PM
2 replies to this topic
#1
Posted 03 July 2016 - 09:18 PM
#2
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:
Keep in mind that if you have multiple values which are the same, it will pick the first key it can find.
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
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











