How to tell if a given value is inside a specified table

1

I want to identify if a name is within a list.

lista = {"name","name2","name3"}

In python I could do if name in lista: , but in moon is otherwise, which I do not know how it is.

    
asked by anonymous 23.08.2018 / 03:54

1 answer

2

You can do a function to iterate:

function Set (list)
  local set = {}
  for _, l in ipairs(list) do set[l] = true end
  return set
end

And so use

local items = Set { "apple", "orange", "pear", "banana" }

if items["orange"] then
  -- faz algo
end

Or, iterate through the list

local items = { "apple", "orange", "pear", "banana" }

for _,v in pairs(items) do
  if v == "orange" then
    -- do something
    break
  end
end
  

Original: link

Alternative, indexing by names:

local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
    ...
end
  

Original: link

    
23.08.2018 / 03:57