Roblox Studio Lua 问题“Workspace.Ultimate.Script:12:尝试比较数字<字符串”-

问题描述

deb = true
giv = script.Parent.Giver
function touch(part)
    local hum = part.Parent:FindFirstChild("Humanoid")
    if hum then
        local plr = game.Players:FindFirstChild(part.Parent.Name)
        local ls = plr:FindFirstChild("leaderstats")
        local cash = ls:FindFirstChild("Cash")
        if plr then
            if deb == true then
                if cash.Value > 12500 then
                deb = false
                giv.BrickColor = BrickColor.new("Really red")
                    local weapon = game.ReplicatedStorage.Jutsus:FindFirstChild("Fireball")
                local w2 = weapon:Clone()
                w2.Parent = plr.Backpack
                wait(script.Parent.RegenTime.Value)
                giv.BrickColor = BrickColor.new("Bright violet")
                    deb = true
                end
            end
        end
    end
end
script.Parent.Giver.Touched:connect(touch) 

我被困在这一点上,我尝试了很多东西但没有任何效果输出是这样的:

Workspace.Ultimate.Script:12: attempt to compare number < string  -  Server - Script:12

如果有人能为我改进代码,我将不胜感激。

解决方法

显然 cash.Value 是一个字符串,所以你不能做 cash.Value > 12500

在将 cash.Value 与数字进行比较之前,将其转换为数字。

tonumber(cash.Value) > 12500

此解决方案假定 cash.Value 是表示数字的字符串。如果不是这种情况,您必须首先确保这一点。

,

字符串和数字的比较需要提前转换,需要确保casg.Value必须是数字,否则可能会提示比较nil值

然后你就可以写出这样的代码了。

deb = true
giv = script.Parent.Giver
function touch(part)
    local hum = part.Parent:FindFirstChild("Humanoid")
    if hum then
        local plr = game.Players:FindFirstChild(part.Parent.Name)
        local ls = plr:FindFirstChild("leaderstats")
        local cash = ls:FindFirstChild("Cash")
        if plr then
            if deb == true then
                if (tonumber(cash.Value) or 0) > 12500 then
                    deb = false
                    giv.BrickColor = BrickColor.new("Really red")
                    local weapon = game.ReplicatedStorage.Jutsus:FindFirstChild("Fireball")
                    local w2 = weapon:Clone()
                    w2.Parent = plr.Backpack
                    wait(script.Parent.RegenTime.Value)
                    giv.BrickColor = BrickColor.new("Bright violet")
                    deb = true
                end
            end
        end
    end
end
script.Parent.Giver.Touched:connect(touch)