遍历不同文件位置选项

本质上我正在尝试创建一个函数,它测试我给出的第一个位置,形如:

 myComputer.referenceLookup("/address/x/text")

并返回该位置的字符串(如果它不为空或不是“None”或“”(空))。

如果不是,则希望测试下一个可能的位置:

 myComputer.referenceLookup("/address/1/x/text")

否则,我希望它返回一个空字符串(“”)。

我试图在[Lua手册](http://www.lua.org/manual/5.3/manual.html#3)中寻找帮助,但没有找到,同时在repl.it中测试不同的表单,但不幸的是,我无法像通常测试时那样复制相似的例子。

function firstLine(x)

if myComputer.referenceLookup("/Address/ .. (x) .. /text") != NULL or "None" or "" then

    return myComputer.referenceLookup("/Address/ .. (x) .. /text")

elseif myComputer.referenceLookup("/Address/1/ .. (x) .. /text") !=  NULL or "None" or "" then

    return myComputer.referenceLookup("/Address/1/ .. (x) .. /text")

else

    return ""

end

end

myComputer.out.firstHouseNumber = firstLine(housenumber)

值得注意的是,我通常会引用以下事实:

myComputer.out.firstHouseNumber= myComputer.referenceLookup("/Address/housenumber/text")

myComputer.out.firstHouseNumber= myComputer.referenceLookup("/Address/1/housenumber/text")

我使用的平台不会抛出错误,而会返回空白,而不是运行lua脚本,因此我无法调试(因此通常使用repl.it)。

我知道这使问题有点抽象,但如果有人知道我可以做我所描述的事情的方法,那么将不胜感激。

点赞
用户4984564
用户4984564

假设

通过查看你的答案,我假设:

  1. myComputer.referenceLookup 在其他地方已经定义并且正常工作(不是这个问题的一部分)
  2. NULL 也在其他地方定义,并且表示某种 nil 值。

回答

以下代码:

if myComputer.referenceLookup("/Address/ .. (x) .. /text") != NULL or "None" or "" then

不起作用,因为 or 运算符不是这样使用的。

Lua 会按以下方式解释它:

if (myComputer.referenceLookup("/Address/ .. (x) .. /text") != NULL) or "None" or ""

因为 "None" 是一个字符串值,因此被视为 truthy,if条件将始终成立,因此它始终需要返回第一个位置。此外,Lua 中没有 != 运算符,应使用 ~=

至于解决方案,则需要三个类似以下的比较:

if myComputer.referenceLookup("/Address/" .. x .. "/text") ~= NULL
and myComputer.referenceLookup("/Address/" .. x .. "/text") ~= "None"
and myComputer.referenceLookup("/Address/" .. x .. "/text") ~= "" then

显然,多次调用函数是一个不好的主意,因为它既会降低性能,还可能具有副作用,因此最好先将其保存在变量中,如下所示:

local result = myComputer.referenceLookup("/Address/" .. (x) .. "/text")
if result ~= NULL and result  ~= "None" and result  ~= "" then
  return result
end

额外内容

如果您希望使您的程序更易于扩展,还可以使用 string.format 从模板中构建位置。假设您有一个包含所有位置的表,如下所示:

local locations = {
  "/Address/%s/text";
  "/Address/1/%s/text";
}

然后,您可以使用 ipairs 迭代所有条目,并使用 string.format 构建每个位置:

for index, template in ipairs(locations) do
  local result = myComputer.referenceLookup(template:format(x))
  if result ~= NULL and result  ~= "None" and result  ~= "" then
    return result
  end
end

请注意,只要模板是字符串,您可以将 string.format(template, x) 写为 template:format(x)。(进一步阅读

2019-06-19 08:23:45