lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 3/14/08, Alexandr Leykin <leykina@gmail.com> wrote:
>  I need quick verification function that is the existence of values in
>  the table:
>  is_value(table,value)->boolean

just to make it clear: you want to know if a given _value_ is stored
in a table? not check for a _key_ ?

if so, you have two options:

1) the easy, slow is what you've found, do a full search
2) the efficient one, use an inverted table.  that is, mantain a
second table where you use the values as keys to any value (usually
'true')

so, each time you add a value to your table (t[n]=v) , add t2[v]=true

then, to check if v is in t, just do
function is_value(t,v)
   return t2[v]
end

of course, you have to somehow find t2 given t; and make sure to set
t2[v]=nil when you remove/change v from t.  you can create a 'set
object' using metatables, or....

if you only need a 'set' functionality, instead of storing v as
values, store them as keys, keeping only the 't2' i've used above.
that depends a lot on your program, but it's probably the best
solution.

that is, instead of:

t={'a','b','c'}

use:
t={a=true, b=true,c=true}

then t['a'] is true, but t['f'] is nil (which is as 'untrue' as 'false')

-- 
Javier