【问题标题】:Empty variable check [duplicate]空变量检查[重复]
【发布时间】:2012-02-26 19:30:15
【问题描述】:

我只是在学习 lua,这是我第一个使用它的脚本。如何检查变量是否为空或其中是否有换行符之类的内容?

【问题讨论】:

  • Lua 中的“空”变量是值为nil 的变量。也许您指的是“空字符串”,即长度为 0 的字符串?

标签: variables lua


【解决方案1】:

您可以检查该值是否为nil:

if emptyVar == nil then
   -- Some code
end

由于 nil 被解释为 false,你也可以写成如下:

if not emptyVar then
   -- Some code
end

(也就是说,除非你想检查布尔值;))

至于换行:你可以使用 string.match 函数:

local var1, var2 = "some string", "some\nstring with linebreaks"
if string.match(var1, "\n") then print("var1 has linebreaks!") end
if string.match(var2, "\n") then print("var2 has linebreaks!") end

【讨论】:

  • 前 2 个不起作用,但最后一个起作用。谢谢。 if string.match(variable, "\n") then print("found") else print("not found")
  • 你需要明白一个带有换行符的变量不是空的。一个空变量里面什么都没有。这就是前两个失败的原因,因为我假设您使用带有换行符的变量进行了测试。
猜你喜欢
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-28
  • 2020-09-24
  • 2018-07-03
相关资源
最近更新 更多