简体   繁体   中英

What is the Lua equivalent to python's "in" statement?

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

Example:

if "word" in variable:

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

Use find

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM