Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

local and global glitch?

Asked by 7 years ago

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?

0
Put in front of the if statement: "local newstand". GoldenPhysics 474 — 7y
0
That'll mess up what I want it to do theawesome624 100 — 7y
0
Really? How? GoldenPhysics 474 — 7y
0
It'll clone it even if there is already a clone theawesome624 100 — 7y

1 answer

Log in to vote
2
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
7 years ago
Edited 7 years ago

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!
Ad

Answer this question