Lua报错‘attempt to compare string with number’问题求助
问题分析与修复方案
报错原因
io.read()默认读取用户输入的字符串,而你生成的number2是数字类型,Lua不允许直接对字符串和数字进行比较操作,这就是报错"attempt to compare string with number"的根源。
另外你的代码还有两个隐性问题:
- 三个
if语句独立执行,就算猜对数字,后面的"too high"或"too low"提示仍会输出 - 循环条件
until (hi)==2永远成立,猜对后循环不会终止
修复步骤
- 用
tonumber()将用户输入的字符串转换为数字,同时处理非数字输入的情况 - 调整判断逻辑为
if-elseif-else结构,避免重复判断 - 猜对数字时修改
hi的值,让循环正常终止
修复后的完整代码
local number2 = math.random(1,100) local hi = 2 repeat print("pick a number, 1-100") local input = io.read() local number = tonumber(input) -- 处理非数字输入 if not number then print("请输入有效的数字!") goto continue -- 跳过后续判断,重新循环 end if number == number2 then print("you got it!! congrats") hi = 1 -- 修改hi的值,终止循环 elseif number > number2 then print("too high!") else print("too low!") end ::continue:: until hi ~= 2
内容的提问来源于stack exchange,提问作者cutecats34543
相关产品推荐
相关产品推荐

