You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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永远成立,猜对后循环不会终止

修复步骤

  1. 用tonumber()将用户输入的字符串转换为数字,同时处理非数字输入的情况
  2. 调整判断逻辑为if-elseif-else结构,避免重复判断
  3. 猜对数字时修改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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:37:07