Thread Tools Display Modes
07-13-10, 06:35 PM   #1
Chibi
A Cyclonian
 
Chibi's Avatar
AddOn Author - Click to view addons
Join Date: Jul 2005
Posts: 43
Use table index as value?

If you have a table you're iterating through, is it possible to return the key as a literal value? example, if you have a table that looks like {1="a", 2="b", 3="c"} can you run through the table to see if a variable == "b" and then have it return 2?
__________________
Perhaps...
  Reply With Quote
07-13-10, 06:37 PM   #2
cloudwolf
A Black Drake
AddOn Author - Click to view addons
Join Date: Mar 2008
Posts: 87
Code:
for k, v in pairs (table) do
   if v==check then
   print(v)
   end
end
  Reply With Quote
07-13-10, 07:01 PM   #3
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
Unless you have a specific reason to use an indexed table, it would be more efficient to use a "dictionary style" table with key/value pairs:

Code:
local t = { ["a"] = true, ["b"] = true, ["c"] = true, }
Then, instead of interating over the whole table, you can just do:
Code:
local v = "a"
if t[v] then print("Found!") else print("Not found.") end
Result: the value is in the table, so "Found!" is output.
Code:
local v = "x"
if t[v] then print("Found!") else print("Not found.") end
Result: the value is not in the table, so "Not found." is output.

Edit:
You don't necessarily need to use the boolean true as your value, but it's the simplest way to go if the only thing you're going to use the table for is checking "is this value in this table?".
  Reply With Quote
07-13-10, 07:05 PM   #4
Jzar
A Chromatic Dragonspawn
 
Jzar's Avatar
AddOn Author - Click to view addons
Join Date: Jun 2007
Posts: 158
Code:
for i = 1, #table do
  if table[i] == val then print i end
end
  Reply With Quote

WoWInterface » Developer Discussions » Lua/XML Help » Use table index as value?


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off