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

How to get global variables to work outside of a function?

I'm currently working on an animation which plays, and stops for a brief moment. However, the variable "track" does not exist by the track:AdjustSpeed(0).

I tried to remove the "local" in the variable declaration, but then when I do, it shows an error.

Here's the script:

local button = script.Parent
local otherdoorbutton = script.Parent.Parent.DoorR
local db = false

button.MouseButton1Click:Connect(function()
	local train = workspace[tostring(game.Players.LocalPlayer) .."Train"]
	local dooropened = train.DoorOpened
	for i = 1,6,1 do
		local door = train["DoorL" ..tostring(i)]
		local anim = door.OpenClose
		local controller = door.AnimationController
		local track = controller:LoadAnimation(anim)
		if db == false then
			if  dooropened.Value =="NO" then
				track:Play()
			end
		end
	end
	wait(3.5)
	track:AdjustSpeed(0) --this does not work
end)

Any help will be appreciated!

1 answer

✓ Accepted answer

Simply put the local variable before the block like this

local button = script.Parent
local otherdoorbutton = script.Parent.Parent.DoorR
local db = false

button.MouseButton1Click:Connect(function()
	local train = workspace[tostring(game.Players.LocalPlayer) .."Train"]
	local dooropened = train.DoorOpened

	local track -- before loop it is still in this scope so all good	
	
	for i = 1,6,1 do
		local door = train["DoorL" ..tostring(i)]
		local anim = door.OpenClose
		local controller = door.AnimationController

		--/changes the track variable from outer scope
		track = controller:LoadAnimation(anim)

		if db == false then
			if  dooropened.Value =="NO" then
				track:Play()
			end
		end
	end
	wait(3.5)
	track:AdjustSpeed(0) --this does work
end)

The thing when you said gives you 'error' when you remove local is not an error but warning, i am glad you counted this as an error as it prevented you from doing the stupid thing like that, assigning global variable like this without local will allow the whole script to have access to it, no matter in what scope you are, this is generally bad because your script is not supposed to have access to it.

Also using not keyword is a lot better than == false because it's a lot better to type and faster too.

if not db then
	...

1 comment

0

Ah I see. Thank you for your help!

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