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

How can I use conditional statements to manipulate information while using io.write?

我希望玩家能够选择一个角色,所以我打印了一个包含四个角色的列表。

   print("Choose a character")
   print("1. the rocker")
   print("2. the vocalist")
   print("3. the drummer")
   print("4. the bassist")

然后我使用 io.write 函数让玩家在角色 1 和 4 之间做出选择。我将选择保存在 menu_option 变量中。我知道我必须添加一些错误处理代码,但我现在并不担心

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

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

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

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

我做错了什么?感谢大家给我的帮助。

错误是 io.read() 总是返回一个字符串。
您在 if 条件中期望一个数字。
现在你必须更正每一个如果像@Egor 在评论中写的那样或者做...

menu_option = tonumber(io.read())

...然后让 if' 检查数字

之后你可以在 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 but better (human) readable

...随机选择。

此外,我建议使用更多的局部变量声明,这样看起来...

-- File: 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())

-- Possible return values...
-- return character:upper(), menu_option -- Two values: first=string second=number
-- return os.exit(menu_option) -- Number can examined on bash with ${?}
-- ^-> Example: lua character.lua || printf '%d\n' ${?}