[ESX, Lua] adding int value to global variable in EventHandler

Hello,

I have the following problem:

I am declaring a global variable called in client.lua:

local variableName

from server.lua i am getting a int value and i want to set the global variable to the number value from server

RegisterNetEvent('event')
AddEventHandler('event', function(number)
variableName = number
end)

if i now want to use variableName in a function, it prints, that variableName = nil. So I dont understand why the int number is not assigned to the global variable variableName.

Im thankfull for every anwser !

Hey!

I’ve tried something similar just a minute ago. Everything worked for me as intended, I can only assume you have some problem with either environment or declaration.

You should try to:

-Check if variable is declared before any use, in case of global variables, this doesn’t really matter, but it could anyway
-Make sure variable number from server is not nil
-Make sure you are not trying to use this variable in other script
-Make sure you are actually sending the right event to the right client, -1 can be used for testing purposes

And as a last resort. Send here full code(shrinken to max 100 lines), which has server and client. function which prints the value as nil and that’s basically it. We can’t help if we don’t know what you are trying to do exacly.

You could always use Convars or KVP.

You could try something like,
Server:

local VariableToRetrieve = 1
ESX.RegisterServerCallback(‘GetVariable’, function(cb)
cb(VariableToRetrieve)
end)

Client:
local VariableToChange
RegsterNetEvent(‘event’, function()
ESX.TriggerServerCallback(‘GetVariable’, function(VariableRetrieved)
VariableToChange = VariableRetrieved
end)
end)

thank you that worked for me.