How to change the value of a variable inside an AddEventHandler

my idea is simple, I want, through an AddEventHandler, change the value of a global variable in the client that was created previously, as shown in the following example:

local test = false;

RegisterNetEvent("change")
AddEventHandler("change", function(c)
    test = c
end)

print(test)

(assuming the parameter “c” is receiving the value TRUE)

however the value of the variable only changes inside the function, that is, inside the AddEventHandler, it becomes TRUE, but when it leaves the function, it returns to its original value FALSE.

How can I change the value of the variable and leave the function with the changed value?

The value is being changed, but that print() statement is running when the script first starts, so it will always print false since it hasn’t been changed yet. To test this, you can do TriggerEvent('change') before print(test) and you should see that the value actually has changed to true.

1 Like

@OfficialBadger within my real code, an event on the server side is triggering this event on the client side. the idea was to use this variable to check its value within the client with the IF. I am using the TriggerServerEvent, and within the Server, in this event, I am using the TriggerClientEvent to call this other event on the Client.

In short, I am calling the event correctly, and it is being executed, because when I put a PRINT inside the event, it executes, but the variable does not change outside the event, only inside ;-;

Try getting rid of local in front of it, so it’s a true global variable

1 Like

I use local in all my variables just for improvement reasons, but yeah, I tried the first time removing the local to see if that would solve the problem but it didn’t work xD.

honestly the problem is in AddEventHandler. Not even the “return” returns the value of the function outside of it, and I think that with variables it doesn’t happen either, but unfortunately I need to use AddEventHandler

I managed to solve the problem here by creating a separate function and making the event call that function. Within this function I changed the value of the variable and it worked, the problem was AddEventHandler XD

1 Like