How can I prevent a table/variable from being LOCAL to the function?

My function essentially does this:

It catches a remote event from the server with a table/list of guns.

An already existing table (that has been defined OUTSIDE of the function) is overwritten with the new table from the remote event.

However, I’ve just learned that it’s only local to the function and in the rest of the script the table is still how it was before.

My code:


local gunList

Events.UpdateGunListStC.OnClientEvent:Connect(function(gunlist2)
		
	print('Updated gun list on death/event fire')
	gunList = gunlist2 -- gunList is an already defined table. 
     -- This SHOULD overwrite the already defined table (gunList) with the new one from the remote event.
	print('Set updated gun list as ')
	print(gunList)
		
end)

print(gunList) -- yet this returns NIL

Help would be appreciated.

1 Like

make sure gunlist2 does not equal nil

1 Like

This should work, you will just find that the last print will print nil because it happens before the remote event is fired (since it is printed after you DEFINE the remote connection rather than after)

3 Likes

It does indeed exist. chr limit

1 Like

Show us what gunlist2 parameter is.

1 Like

It returns nil on every other function in my script as well, and these functions do run after the remote event is fired.

1 Like

This is the reason. Here is a modified script:

local gunList

Events.UpdateGunListStC.OnClientEvent:Connect(function(gunlist2)
		
	print('Updated gun list on death/event fire')
	gunList = gunlist2 -- gunList is an already defined table. 
     -- This SHOULD overwrite the already defined table (gunList) with the new one from the remote event.
	print('Set updated gun list as ')
	print(gunList)
		
end)

Events.UpdateGunListStC.OnClientEvent:Wait() — wait for the event to be called

wait() — wait a bit more just in case

print(gunList) -- yet this returns NIL
1 Like

The only thing i can think of is that is this code in a loop?

OnClientEvent doesn’t yield at all, so what’s happening is that you’re declaring gunList and setting it to nil at the beginning with local gunList, connecting an OnClientEvent connection which sets gunList to gunList2, and then printing gunList at the end, not waiting for it to be set to anything.

If you want to yield and wait for a return value, then use a RemoteFunction instead. It would look something like this:

local gunList = Events.UpdateGunListStC:InvokeServer()

print(gunList)

Then on the server:

local function onInvoke()
    return {} -- whatever table you want to return
end
Events.UpdateGunListStc.OnServerInvoke = onInvoke
1 Like

I’m going to have to update the table more than once, I don’t know much about remote functions, will it?

Yes. You can invoke the function as many times as needed. You can also Invoke the client to update the table from the server when necessary.