Lua入门者求助:如何处理猜拳游戏非法输入以避免报错
Lua剪刀石头布游戏输入验证解决方案
先修正你的代码逻辑,核心是在函数内完成完整的输入校验,处理空输入、非法数字/字符串的情况。以下是调整后的代码:
-- 先定义必要的映射表,确保函数内能访问到 local value = {Scissors = true, Rock = true, Paper = true} local selection = {[1] = "Scissors", [2] = "Rock", [3] = "Paper"} local choice = selection -- 假设choice和selection是同一组选项 UserInput = function() print("Scissors, Rock or Paper?") while true do local input = io.read() -- 处理输入为空(用户直接回车)的情况 if not input then print("输入不能为空,请重新输入!") goto continue end -- 检查是否是合法字符串选项 if value[input] then return input end -- 尝试转为数字并校验是否在1-3范围内 local number = tonumber(input) if number and number >= 1 and number <= 3 then return selection[number] end -- 非法输入的处理:提示后继续循环,或直接返回随机选项 print("输入无效!请输入Scissors/Rock/Paper,或1-3的数字") -- 如果要直接返回随机选项,替换上面的提示为以下两行: -- print("输入无效,将随机选择") -- return choice[math.random(3)] ::continue:: end end
关键修正点:
- 语法错误修复:原代码中
if value[input] = nil then是赋值操作,应改为==,且这部分逻辑必须放到函数内部——因为input是函数的局部变量,外部无法访问。 - 空输入处理:
io.read()在用户直接回车时会返回空字符串,通过not input判断并给出提示。 - 合法范围校验:数字转换后必须检查是否在1-3之间,避免
selection[number]返回nil。 - 循环校验逻辑:用
while true循环确保用户输入合法才退出,也可根据需求直接返回随机选项替代循环提示。
内容的提问来源于stack exchange,提问作者German Code Newbie
相关产品推荐
相关产品推荐

