Page 1 of 1

Lua question: Is it possible to get the key from a table...

Posted: Wed Oct 13, 2010 1:16 am
by ninwa
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

Posted: Wed Oct 13, 2010 1:18 am
by bmelts

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

Posted: Wed Oct 13, 2010 1:22 am
by ninwa
anjo wrote:

Code: Select all

function findValueInTable(value, t)
   for k,v in pairs(t) do
      if v == value then return k end
   end
end
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 Anjo

Re: Lua question: Is it possible to get the key from a table

Posted: Wed Oct 13, 2010 6:55 am
by kikito
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.
There are libs that cover some or nearly all of those, but since they are libs they are non-standard so you loose portability :?