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

"if var > 0 then" [script] not working even though variable is bigger than 0. Why?

My script starts off with 0 oats. People drop off oats to the part and the oat variable goes up by 1. That bit works. But then the give function doesn't work when I try to pick up a tool. Before I added the "if oats > 0 then," I could pick up the tool so I know that bit works. Here is my script:

oats = 0
print(oats)

function tch(h)
if (h.Parent.Oats.Name == "Oats") then
	oats = oats + 1
	h.Parent:Destroy()
	script.Parent.Parent.OatCount.SurfaceGui.TextLabel.Text = oats
	print(oats)
end
end

script.Parent.Touched:connect(tch)

function onClicked()
if oats > 0 then -- the following does not run
function give(dough)
	local y = dough.Backpack
	local z = game.Lighting["Handful of Oats"]
	z:Clone().Parent = y
end
end
end

script.Parent.ClickDetector.MouseClick:connect(give)
script.Parent.ClickDetector.MouseClick:connect(onClicked)

2 answers

✓ Accepted answer

You put the function inside a function, and then called the function as if it were a global.

oats = 0
print(oats)

function tch(h)
if (h.Parent.Oats.Name == "Oats") then
    oats = oats + 1
    h.Parent:Destroy()
    script.Parent.Parent.OatCount.SurfaceGui.TextLabel.Text = oats
    print(oats)
end
end

script.Parent.Touched:connect(tch)

local Allowed = false

function give(dough)
	if Allowed == true then
	   	local y = dough.Backpack
	    local z = game.Lighting["Handful of Oats"]
	    z:Clone().Parent = y
	end
end

function onClicked()
if oats > 0 then -- the following does not run
	Allowed = true
end
end

script.Parent.ClickDetector.MouseClick:connect(give)
script.Parent.ClickDetector.MouseClick:connect(onClicked)

2 comments

0

It works! Thank you for help, I really appreciate it!

0

No problem.

The lesser the line and the less the spacing, the better, so the script runs faster. I don't recommend you put too much spacing :)

local oats = 0
print(oats)
local Clicked = false -- Add a Debounce so player don't spam

function tch(h)
	if (h.Parent.Oats.Name == "Oats") then
	    oats = oats + 1
	    h.Parent:Destroy()
	    script.Parent.Parent.OatCount.SurfaceGui.TextLabel.Text = oats
	    print(oats)
	end
end

script.Parent.Touched:connect(tch)

function onClicked()
	if Clicked == false then
		if oats > 0 then -- I don't think you can put 2 functions in one another so please don't.
			Clicked = true
			local y = dough.Backpack
			local z = game.Lighting["Handful of Oats"]
			z:Clone().Parent = y
			Clicked = false
		end
	end
end

script.Parent.ClickDetector.MouseClick:connect(onClicked)

1 comment

0

the spaces do nothing. their actually more visual appealing.

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