Quick question about variables

How would i get a variable outside of the if statement? here’s an example:

for i,item in pairs(workspace.Gear:GetChildren()) do
			if item.Name == option then
				if item.CostType == "Grub" then
					local Type = plr.leaderstats.Grub.Value

				elseif item.CostType == "Survivals" then
					local Type = plr.leaderstats.Survivals.Value
				end
					
				if item.Cost.Value >= Type then -- "Type" is nil because the variable is inside the if statment
					local NewItem = item:Clone()
					NewItem.Parent = plr.Backpack

Also, using local Type before the statement does not work either for some reason

1 Like

create the variable Type outside of the statement first, then assign it inside of the statement.

You can declare the variable before beginning to loop.

local Type
for i,item in pairs(workspace.Gear:GetChildren()) do
			if item.Name == option then
				if item.CostType == "Grub" then
					Type = plr.leaderstats.Grub.Value

				elseif item.CostType == "Survivals" then
					Type = plr.leaderstats.Survivals.Value
				end
					
				if item.Cost.Value >= Type then -- "Type" is nil because the variable is inside the if statment
					local NewItem = item:Clone()
					NewItem.Parent = plr.Backpack

doing this causes this error, despite it being assaigned in the statement it’s outside of
image

i also get the same error by doing this

It’s not an error, it’s a warning. As it same says you can silence it by declaring the variable’s value to nil.

local Type = nil
1 Like

This is just studio telling you to style your code. Have you tried to run it?

Here, if you want it to go away:

local Type = nil
for i,item in pairs(workspace.Gear:GetChildren()) do
			if item.Name == option then
				if item.CostType == "Grub" then
					Type = plr.leaderstats.Grub.Value

				elseif item.CostType == "Survivals" then
					Type = plr.leaderstats.Survivals.Value
				end
					
				if item.Cost.Value >= Type then -- "Type" is nil because the variable is inside the if statment
					local NewItem = item:Clone()
					NewItem.Parent = plr.Backpack

this error appears now when i try to run it, looks like Type is still printed as nil

Variables (roblox.com)

Scope (roblox.com)

2 Likes

Looks like the first and second if statement hasn’t run, so Type stays nil.

1 Like

Probably you forgot to add item.CostType.Value?

The error is produced because none of the statements above are true.

1 Like

Your first conditional statement block to assign a value to Type has a case where it never gets a true result, so Type is never assigned. This is a logic error and you will have to re-structure your code accordingly.

1 Like

Okay, i’ll look into it further and i’ll be right back when i check if this is correct

You could initialize it to 0 instead of nil, if that makes sense in your script logic.