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

Is it possible to define a variable from one function to another?

 local UIS = game:GetService("UserInputService")

local player = game.Players.LocalPlayer
local char = player.Character
local humanoid = char.Humanoid

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.Space then
		
	local p = Instance.new("Part")
	p.Transparency = 0.5
	p.CanCollide = false
	p.Anchored = false
	p.Size = Vector3.new(20.05, 1.59, 0.05)
	p.Name = "Box"
	p.Parent = char

    local Weld = Instance.new("Weld")
    Weld.Part0 = char.LowerTorso
    Weld.Part1 = p
    Weld.C0 = CFrame.new(0,0,0)
    Weld.Parent = char.LowerTorso

	end
end)

	p.Touched:Connect(function(hit) 
		if hit.Parent:FindFirstChild("Humanoid") then
			print("human")
		end
	end)

If i do this, the p used in the touched function will no longer be a part because it's in a separate function but is there a way that'll make it so that even if they're in separate functions, p used in the touched function can be defined to be the same as in the input function? I know it's a bit illogical to do this when i can just put it all in one function and what not but it's important for what i'm trying to make.

2 comments

0

Remove the keyword local before p

0

Removing the local will work but only do so if you are certain the variable will be defined by the first function before it's called, otherwise the script will error.

2 answers

✓ Accepted answer

If you want the variable p to be used elsewhere in the script, then you have to make it a global variable by removing "local". Local would make it where it could only be accessed by that function you defined it under. This link should help you: https://www.lua.org/pil/1.2.html

2 comments

0

why did they remove scopes from wiki and put it in robloxdev???

0

thanks, at first i thought adding the local was a must

Yes, define the variable outside the function.

local p

function a()
p = "lol"
end
a()
function b()
print(p)
end
b()

--Prints "lol"

1 comment

0

Please use proper indentation, reading that makes me cringe.

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