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

General discussion about LÖVE, Lua, game development, puns, and unicorns.
Post Reply
User avatar
ninwa
Party member
Posts: 118
Joined: Tue Oct 12, 2010 1:21 am
Location: Metro Detroit
Contact:

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

Post by ninwa » Wed Oct 13, 2010 1:16 am

Is it possible to search a table by value and return the first key with a matching value?

User avatar
bmelts
Party member
Posts: 380
Joined: Fri Jan 30, 2009 3:16 am
Location: Wiscönsin
Contact:

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

Post by bmelts » Wed Oct 13, 2010 1:18 am

Code: Select all

function findValueInTable(value, t)
   for k,v in pairs(t) do
      if v == value then return k end
   end
end

User avatar
ninwa
Party member
Posts: 118
Joined: Tue Oct 12, 2010 1:21 am
Location: Metro Detroit
Contact:

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

Post by ninwa » Wed Oct 13, 2010 1:22 am

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

User avatar
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

Post by kikito » Wed Oct 13, 2010 6:55 am

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 :?
When I write def I mean function.

Post Reply

Who is online

Users browsing this forum: No registered users and 16 guests