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

local and global glitch?

So I have this part of a script that is a 'if' statement,

if numoflemons == 0 then
		newstand = standmodel:Clone()
		newstand.Parent = game.Workspace
	else
		newstand.screen.SurfaceGui.TextLabel.Text = "Lemonade Stands : "..numoflemons.Value
	end

and when I add

local

in front of

newstand = standmodel:Clone()

the part after else (so this part:)

newstand.screen.SurfaceGui.TextLabel.Text = "Lemonade Stands : "..numoflemons.Value

says 'Unknown global 'newstand'' and when I remove the local, the variable says 'Global 'newstand' is only used in the enclosing function; consider changing it to local' So my question is, is it glitched? Or am I doing something wrong here?

4 comments

0

Put in front of the if statement: "local newstand".

0

That'll mess up what I want it to do

0

Really? How?

0

It'll clone it even if there is already a clone

1 answer

✓ Accepted answer

local scopes a variable to the current block, which ends at end / until / else / elseif.

In the following,

if numoflemons == 0 then
	local newstand = standmodel:Clone()
	newstand.Parent = game.Workspace
else
	newstand.screen.SurfaceGui.TextLabel.Text = "Lemonade Stands : "..numoflemons.Value
end
--after

the scope of local newstand is only between the then and the else -- that's where the block ends.

The reason for this is, at --after, if numoflemons was not 0, then local newstand was never declared.

You can define a local variable just before the if in order to make its scope include both the then and else part, as well as after the end of the if:

local newstand
if numoflemons == 0 then
	newstand = standmodel:Clone()
	newstand.Parent = game.Workspace
else
	newstand.screen.SurfaceGui.TextLabel.Text = "Lemonade Stands : "..numoflemons.Value
end
-- can still use newstand here now!

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