如何使用条件语句在使用io.write时操纵信息?

我想让玩家能够选择一个角色,因此我打印了四个角色的列表。

   print("选择一个角色")
   print("1. 摇滚手")
   print("2. 主唱")
   print("3. 鼓手")
   print("4. 贝斯手")

然后我使用io.write功能允许玩家在角色1和4之间进行选择。我将选择保存在menu_option变量中。我知道我需要添加一些错误处理代码,但我现在不担心

io.write('你选择哪个角色?')
menu_option = io.read()

现在,我想创建一些条件语句来创建一个变量,该变量将定义玩家选择的角色的标题。

if menu_option == 1 then
character = ("摇滚手")

elseif menu_option == 2 then
character = ("主唱")

elseif menu_option == 3 then
character = ("鼓手")

elseif menu_option == 4 then
character = ("贝斯手")
end

这是我的代码开始失败的地方。写入函数正确地将选择(从1到4)写入menu_option变量,但是我的if语句块没有正确地运行。角色变量保持为空值。

我做错了什么?感谢您们提供的任何帮助。

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

点赞
stackoverflow用户11740758
stackoverflow用户11740758

错误在于 io.read() 始终返回一个字符串。

你在 if 条件语句中期望一个数字。

现在你需要像 @Egor 在评论中所写的那样纠正每个 if,或者让 if 检查数字...

menu_option = tonumber(io.read())

...然后让它检查数字。

在此之后,你可以在输入 NaN(不是数字)或什么也没输入(只按下 RETURN/ENTER 键)的情况下执行以下操作...

io.write('Which character do you choose? ')
local menu_option = tonumber(io.read())

if menu_option == empty then menu_option = math.random(4) end
-- empty == nil 但更好理解

...进行随机选择。

此外,我建议使用更多的本地变量声明,以使其看起来像...

-- 文件: character.lua
local character = ''
print("Choose a character:")
print("[1] the rocker")
print("[2] the vocalist")
print("[3] the drummer")
print("[4] the bassist")

io.write('Which character do you choose? ')
local menu_option = tonumber(io.read())

if menu_option == empty then menu_option = math.random(4) end

if menu_option == 1 then
 character = "the rocker"
elseif menu_option == 2 then
 character = "the vocalist"
elseif menu_option == 3 then
 character = "the drummer"
elseif menu_option == 4 then
 character = "the bassist"
end

print('You choosed:',character:upper())

-- 可能的返回值...
-- return character:upper(), menu_option -- 两个值: 第一个为字符串,第二个为数字
-- return os.exit(menu_option) -- 数字可以在 bash 上使用 ${?} 进行检查
-- ^-> 示例: lua character.lua || printf '%d\n' ${?}
2021-09-13 09:42:33