Roblox Lua代码报错‘attempt to compare string and number’原因咨询
Problem Description
I wrote this Roblox Lua script to handle rebirth functionality, but I'm getting an error attempt to compare string and number on line 2. Here's my code:
script.Parent.Yes.MouseButton1Click:connect(function() if game.Players.LocalPlayer.leaderstats.Stage.Value < 20 and db then db = false script.Parent.Question.Text = "YOU NEED ATLEAST 20 STAGES TO REBIRTH!" wait(3) script.Parent.Visible = false open = false db = true elseif db then game.ReplicatedStorage.Rebirth:FireServer() script.Parent.Visible = false open = false end end)
Answer
Hey there, let's break down this error for you clearly.
The attempt to compare string and number error pops up on line 2 because you're trying to compare game.Players.LocalPlayer.leaderstats.Stage.Value (which is a string data type) with the number 20 using the < operator. Lua doesn't let you directly compare different data types—you can't check if a text string is "less than" a number.
Root Cause
The most common reason this happens is that your Stage value in the leaderstats folder was created as a StringValue instead of a numeric value type (like IntValue or NumberValue). Since stages track numerical progression, they should always use a numeric value type to store their data.
Fixes
Correct the Value Type in Roblox Studio
- Enter play mode and find the
leaderstatsfolder under your test player instance. - Delete the existing
StageStringValue. - Create a new
IntValue(perfect for whole-number stage counts) and name itStage. - Make sure any server-side code that sets or updates the
Stagevalue uses this numeric type instead of a string.
- Enter play mode and find the
Add a Safety Check in Your Script (Optional)
To guard against accidental type mismatches later, you can convertStage.Valueto a number before comparing it. This acts as a fallback if the value ever gets messed up:script.Parent.Yes.MouseButton1Click:connect(function() local stageNum = tonumber(game.Players.LocalPlayer.leaderstats.Stage.Value) or 0 if stageNum < 20 and db then db = false script.Parent.Question.Text = "YOU NEED ATLEAST 20 STAGES TO REBIRTH!" wait(3) script.Parent.Visible = false open = false db = true elseif db then game.ReplicatedStorage.Rebirth:FireServer() script.Parent.Visible = false open = false end end)The
tonumber()function turns a string that represents a number into an actual number, andor 0ensures you get a valid number (0) if the conversion fails (like if the value is a non-numeric string).
That should fix the error and get your rebirth system working as intended!
内容的提问来源于stack exchange,提问作者Anthony K.




