tags:

views:

332

answers:

1
+1  Q: 

Lua table lookup

I know this seems like a dumb question but how do i search a lua table for a given item? let's say i have a table like this:

local table = {
    itemA = 0.8,
    itemB = 1.2,
    itemC = 1
}

is there, say, a function named table.find or something? It's also late here so I'm not thinking too clearly at the moment...

+5  A: 

You can lookup items in the table either using the [] operator:

x=table["itemA"]

or by using the . operator:

x=table.itemA

Edited because original code is now syntax-correct.

Martin B
+1. Note that the dot only works if the key happens to be a string value made up of legal identifier characters. Tables can be indexed by values of any type (except nil) most of which will require the `[]` notation.
RBerteig
Good point (no pun intended ;) ), thanks!
Martin B
Boy i must be tired to not see that, thanks for the help!
RCIX
Just checking, in your example x will be nil if the value does not exist in the table?
RCIX
Yes. http://www.lua.org/pil/2.5.html
Martin B