lua-users home
lua-l archive

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

On Wed, Mar 12, 2008 at 3:06 PM, Alexandr Leykin <> wrote:
>  How to know to be a key in lua table? Without use pairs/ipairs/next?
>  a = {a,b,c,d}
>  a.a => nil, but key "a" present in table!
>  a.f => nil, but key "f" not in table!
>  Than differ a.a and a.f??? (a.a - key in the table a, a.f - not)

Your terminology is a bit confused.  In this case, a b c and d are
values in the table, not keys.  The above constructor is equivalent to
a = {[1] = a, [2] = b, [3] = c, [4] = d}.  In this case, 1, 2, 3 and 4
are the keys, while a, b, c and d are the values.

That being said, you can test if something is a key in the table by
simply indexing the table:

if type(tbl[key]) ~= nil then
  -- The key exists in the table.

There is no fast way to check to see if a value is used in a table.
You would need to resort to the following search, or design a better
data structure using tables:

function valueExists(tbl, value)
  for k,v in pairs(tbl) do
    if value == v then
      return true

  return false

Perhaps you could be more specific about your concern or problem.

- Jim