Is there a way to access something in one function, in another?

Is there a way to access something in one function, in another?

1 Like

could you elaborate because youre not exactly clear on what you mean

I think you’re talking about nesting functions in another.

function foo()
	local input = "Hi!"
	
	local function bar(newString: string)
		input = newString -- rewrites input variable
	end
	
	bar("Hi!!!!!!!")
	
	return input
end

local new = foo()
print(new) -- Output: Hi!!!!!!!

But please explain your question more.

Sorry, I didn’t explain it well but for example

local function partSpawn()
	local part = Instance.new("Part")
    part.Parent = workspace
end

UIS.InputBegan:Connect(function(inp, gpe)
	if inp.KeyCode == Enum.KeyCode.F then
        print(part.Position) -- I know this wouldn't work but is there a way I could reference something inside of the function
    end
end)

Hopefully my other reply explains it more, I’m basically trying to reference something inside of one function in a seperate function.

Just create a reference outside of the function.

local part

local function partSpawn()
	part = Instance.new("Part")
    part.Parent = workspace
end

UIS.InputBegan:Connect(function(inp, gpe)
	if inp.KeyCode == Enum.KeyCode.F then
        print(part.Position) -- I know this wouldn't work but is there a way I could reference something inside of the function
    end
end)

You could also do something like this:

local function partSpawn()
	local part = Instance.new("Part")
    part.Parent = workspace
    return part
end

local part = partSpawn()

UIS.InputBegan:Connect(function(inp, gpe)
	if inp.KeyCode == Enum.KeyCode.F then
        print(part.Position) -- I know this wouldn't work but is there a way I could reference something inside of the function
    end
end)
2 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.