Lua question: Is it possible to get the key from a table...
Lua question: Is it possible to get the key from a table...
Is it possible to search a table by value and return the first key with a matching value?
Re: Lua question: Is it possible to get the key from a table
Code: Select all
function findValueInTable(value, t)
for k,v in pairs(t) do
if v == value then return k end
end
end
Re: Lua question: Is it possible to get the key from a table
I actually just finished writing exactly that helper function, but I suppose I wondered if there was a built-in function. I believe this answers my question nonetheless :] Thank you Anjoanjo wrote:Code: Select all
function findValueInTable(value, t) for k,v in pairs(t) do if v == value then return k end end end
- kikito
- Inner party member
- Posts: 3153
- Joined: Sat Oct 03, 2009 5:22 pm
- Location: Madrid, Spain
- Contact:
Re: Lua question: Is it possible to get the key from a table
I had exactly the same question some time ago. It is kind of incredible that Lua is so 'barebones' in some things. From the top of my head:
- table.findByValue
- lots of functions on string (not regular-expression based!)
- math.round (you can implement it like this: function math.round(x) return math.floor(x + .5) end)
- built-in directory support for require. They say "Lua in Ansi-C, and Ansi-C doesn't include directory support" . But I always found that a very lazy excuse.
When I write def I mean function.
Who is online
Users browsing this forum: No registered users and 2 guests