0

How would one check if a word is NOT in an array... example:

fruits = { 'apple', 'banana' }
value = "carrot"
if not value == fruits then
  print ( value .. " is not a fruit" )
end

or something like that? I would prefer pure Lua.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
user3392846
  • 65
  • 1
  • 7
  • Sorry, I disagree. "Table" contains a value is slightly different than "array". Because for this question I can give two advises, none of which is acceptable for tables. 1. If it is a hardcoded array, like config, you can do this: `({apple = 1, banana = 1})[value]`. 2. If it is an array, there is quite beautiful but ineffecient method: `utils.swapKV(array)[value]` – Konstantin Nikitin Aug 01 '17 at 10:56

1 Answers1

1

The direct way:

local found = false
for _, v in ipairs(fruits) do
  if v == value then
    found = true
    break
  end
end

if not found then
  print ( value .. " is not a fruit" )
end
Yu Hao
  • 119,891
  • 44
  • 235
  • 294