【问题标题】:New to LUA, i have question about my scriptLUA 新手,我对我的脚本有疑问
【发布时间】:2021-01-15 02:50:58
【问题描述】:

您好,我是 LUA 新手,一般来说是脚本/编码新手 这是我在说的脚本

print("Type a Number!")
repeat
input = io.read()
if input == "10" then 
    print("Ten")
elseif input == "7" then
        print("Seven")

elseif input == "1" then
    print("One!")
elseif input == "exit" or input == "Exit" then
    print("Exiting...")  
else
     print("incorrect")  
end
until input == "Exit" or input == "exit"

我觉得 elseif 太多了,但我不想在输入 exit 或 Exit 时打印“不正确”,所以我的解决方案是在 else 命令之前添加另一个 elseif。这可以更简化,还是我无能为力,它很好

还有一个问题,为什么这不起作用

num = 10
input = io.read()
If input == num then 
     print("Ten")
end

或者这个代码

num = 10
input = io.read()
If input == 10 then 
     print("Ten")
end

为什么上面的代码在 if 之后我有字符串的布尔值,才有效

【问题讨论】:

  • 1) If 与 if 不同。 2) 10 与"10" 不同 3) io.read() 返回字符串,需要tonumber() 将其转换为数字,然后才能与另一个数字进行比较

标签: lua


【解决方案1】:
  1. 定义你的行为
local actions = {
   [1] = function() print("One");
   -- Same for any other numbers you want
   ["exit"] = function() os.exit() end; -- Close the whole program
}
  1. 获取您的意见
local input = io.read() -- This returns a string
  1. 规范化您的输入
input = input:lower() -- Make the whole string lowercase
input = tonumber(input) or input -- Try converting to number
  1. 获取与您的输入匹配的操作
local action = actions[input]
  1. 如果找到,则运行该操作
if action then
   action()
else
   print("Error! Could not handle input: ", input)
end

【讨论】:

  • 哦,实际上其他 2 个代码示例不起作用是有道理的,我不知道 io.read() 仅适用于字符串...是否有类似的数字类型或我总是必须将其转换为数字吗?感谢您的回答非常有帮助:))))
【解决方案2】:
local inputs = {
     ['1'] = 'One!'
  ,  ['7'] = 'Seven'
  , ['10'] = 'Ten'
  , exit   = 'Exiting...'
  , Exit   = 'Exiting...'
}
local input
print 'Type a Number!'
repeat
    input = io.read ()
    print (inputs [input] or 'incorrect') -- Lua 'nullsafe' operator.
until input == 'Exit' or input == 'exit'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-30
    • 2017-02-22
    • 2019-05-06
    • 1970-01-01
    • 2011-08-31
    • 2022-12-12
    相关资源
    最近更新 更多