How could I move a variable outside a function?

So let’s say for example I had a variable passed through an event as an argument. My script calls that variable in a function but I want to use it outside of the function

event.OnServerEvent:Connect(function(number)
	local num = number
end)

So I have this num variable, but I’d also like to use it outside of the event function. If I used another event, it’d just be in another function. Any ideas?

You could do something like this:

Solution 1

local Number = nil

event.OnServerEvent:Connect(function(NewNumber)
	Number = NewNumber
end)

Solution 2

local NumbersTable = {}

event.OnServerEvent:Connect(function(NewNumber)
	table.insert(NumbersTable, NewNumber)
end)

Solution 3 (Use a RemoteFunctions)

RemoteFunction.OnClientInvoke = function(NewNumber)
    return NewNumber
end
RemoteFunction.OnServerInvoke = function(NewNumber)
	return NewNumber
end
5 Likes

Not that it really matters, but you don’t need to set the variable to nil. You can just do local number and then assign a value to it later. If there’s a variable without a value, it will default as nil.

1 Like

What @Crygen54 said will work fine. But I just wanted to emphasize what’s actually going on here. When you have something that wraps with end at the end, you’re creating what’s called as a “nest”. A local variable/function that’s inside of a given nest will only be visible to that nest and any nest inside that nest, but won’t be visible to any nest above it (or global):

image

But declaring the variable at the highest level you want it accessed in will be readable no matter where it’s set afterwards (as long as it’s at the same nest level or deeper):

image

1 Like

Yeah i know that, but i still prefer writing the “= nil” as it make the script more readable especialy when there is lot of variable to use, but it is just my opinion and my workflow, everyone do like he want ^^

1 Like

This helped it make a lot of sense. Thanks!

1 Like

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