空变量检查。

我只是在学习 Lua,这是我在其中编写的第一个脚本。我该如何检查变量是否为空或其中是否有换行符等内容?

原文链接 https://stackoverflow.com/questions/9141217

点赞
stackoverflow用户570336
stackoverflow用户570336

你可以检查一个变量是否为 nil:

if emptyVar == nil then
   -- 一些代码
end

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

if not emptyVar then
   -- 一些代码
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
2012-02-04 14:15:01