Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Why is my if statement not being run even if it's true?

level = 1
xp = 0
minxp = 10
local textLabel = script.Parent
textLabel.Text = level

function levelUp()
	level = level + 1
	textLabel.Text = level
end

function recieveXp()
	print("Recieved EXP")
	if (xp >= minxp) then
		levelUp()
		print("You are now level " .. level .. "!")
		minxp = math.floor(minxp * 1.2)
		print("Next level up at " .. minxp .. " EXP")
	end
end

for xp = 0, 1000, 1 do
	print(xp .. "/" .. minxp)
	recieveXp()
	wait(1)
end

I have this simple leveling system here that lets players infinitely level and each level beyond requires more xp. My problem is with my function recieveXp. The for loop below is just to add xp every second. I'm getting a received exp message but the if statement after seems to be showing as false or ignored even when it is true (xp is greater than minimum xp for level up)

The if statement works flawlessly when placed in the for loop in place of the function line but I'd rather make it a function as there will be several events that add exp. I'm relatively new to this, so if you have any suggestions for the best logic for something like this or anything at all, it'd really help.

1 comment

0

If mattscy's answer helped you and you acknowledge that you should accept his answer.

1 answer

This is only occurring because the for loop does not update the xp variable the way you would expect. The loop only creates a version of the variable local to the loop itself. For example:

local Banana = 0
local function Foo()
	print(Banana)
end

for Banana = 0,10 do
	Foo()
end

While you would expect this to print numbers 0 to 10, it only prints 0. To solve this, you could instead try something like this:

local Banana = 0
local function Foo()
	print(Banana)
end

for i = 0,10 do
	Banana = i
	Foo()
end

This will update the original Banana variable, letting you use it in the function.

Don't forget that you should also keep track of each players' levels and experience on the server rather than entirely from a local script, otherwise your levelling system will be vulnerable to exploitation.

Hope this helps!

1 comment

0

Alright, awesome! Thank you so much, I didn't expect someone to reply so quickly :)

This discussion is preserved as it was. New answers, comments, and votes are closed.