【问题标题】:What is the Lua equivalent to python's "in" statement?什么是 Lua 等价于 python 的“in”语句?
【发布时间】:2021-02-16 04:04:28
【问题描述】:

Lua有没有等价于python的“in”语句的语句?

例子:

if "word" in variable:

【问题讨论】:

标签: python lua


【解决方案1】:

Lua 没有 Python 的 in 运算符等效项,但如果您知道要模拟的容器类型,则很容易为其编写函数。

str

true 参数确保子字符串按字面意思处理,而不是作为模式处理。详情请见string.find

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

【讨论】:

    【解决方案2】:

    使用查找

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

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

    【讨论】:

      猜你喜欢
      • 2019-09-09
      • 1970-01-01
      • 1970-01-01
      • 2011-01-26
      • 1970-01-01
      • 2019-09-25
      • 2011-02-20
      • 2023-03-03
      • 2018-01-21
      相关资源
      最近更新 更多