Lua "or" 语句问题

我非常新于 Lua,并且正在进行一个非常简单的文本冒险游戏,但无法正常工作。我的代码如下:

while input ~= ("leave cave" or "leave") do
print("你想做什么?")
input = io.read()

if input == "inspect" then
        print("你在一个洞穴内")
    elseif input == "leave cave" or "leave" then
        print("你离开了洞穴")
    elseif input == "inv" then
        for i,v in pairs(inv) do
        print(i, v)
    end
  else
    print("你输入了无效的命令...")
  end
end

-- 离开洞穴

input = ""
print("你想做什么?")
input = io.read()
while input ~= "follow path" do
if input == "inspect" then
        print("你在一座山的脚下,这里有一条小路。")
    elseif input ==  "follow path" then
        print("你跟随这条小路,发现了一个大门。")
     elseif input == "inv" then
        for i,v in pairs(inv) do
        print(v)
        end
    else
        print("这不是一个有效的命令...")
    end
end

我的意图是,每当用户键入离开或离开洞穴时,它就会继续到下一个部分(路径部分),然而,当我键入“离开”然后再次键入“inspect”它会说“我在一个洞穴内”,而不是它应该说的,它说你出去了,你看到了一条小路。而当我键入离开洞穴,然后检查时,它会一遍又一遍地无限期地刷出“你在山脚下,那里有一条小路,有一个门”。

当我键入“inv”时,它不会打印我的库存,而是打印“你离开了洞穴”,但实际上没有离开。

点赞
用户2616735
用户2616735

a or b 不能生成一个表示 "a 或者 b" 的值——这会太过复杂。

实际上,如果你让它选择两个字符串,它只会选择第一个:

print("leave cave" or "leave") --> leave cave

or 应该只用于布尔值——你必须将它与多个 完整的条件 结合使用:

while (input ~= "leave cave") and (input ~= "leave") do

在这种情况下,使用 repeat ....... until <condition> 循环会更好:

repeat
    print("What do you want to do?")
    input = io.read()

    -- <do stuff>
until input == "leave" or input == "leave cave"
2017-01-21 21:15:30
用户3979429
用户3979429

虽然 or 无法完成这样复杂的操作,但是通过一些 hacky 的 metatable 代码,你可以重新创建出这种效果。

请注意 _我不建议在任何真正的专业或商业程序中,或者在任何情况下使用这段代码_,这段代码是低效且不必要的,但是它是一段有趣的代码,能够做到你要的效果。这只是一个有趣的方式来实验 Lua 的强大功能。

local iseither
iseither = setmetatable({},{
   __sub = function(arg1,arg2)
      if arg2 == iseither then
         arg2.Value = arg1
         return arg2
      else
         if type(arg2) ~= "table" then
            error("Second operator is -iseither- was not a table",2)
         else
            for i,v in ipairs(arg2) do
               if arg1.Value == v then
                  arg1.Value = nil
                  return true
               end
            end
            arg1.Value = nil
            return false
         end
      end
   end
})

print(1 -iseither- {1,2,3,4,5})
2017-01-21 23:44:48