-1

Does Lua have any statement equivalent to the "in" statement of python?

Example:

if "word" in variable:
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135

2 Answers2

2

Lua has no equivalent of Python's in operator, but if you know what container type you want to emulate, it's easy to write a function for it.

str

The true argument ensures that the substring is treated literally and not as a pattern. See string.find for details.

local function inString(s, substring)
  return s:find(substring, 1, true)
end

list

local function inArray(array, x)
  for _, v in ipairs(array) do
    if v == x then
      return true
    end
  end
  return false
end

dict

local function inKeys(t, k)
  return t[k] ~= nil
end
luther
  • 5,195
  • 1
  • 14
  • 24
1

Use find

string.find('banana', 'an')

see https://www.lua.org/pil/20.1.html

balderman
  • 22,927
  • 7
  • 34
  • 52