Global variables resetting on server side

Hello!
I’m quite new to FiveM development and lua in general, so I have question.
I’m creating a project where I have server.lua and client.lua:

server.lua

AreStrippersSpawned = false

RegisterNetEvent('nls:getAreStrippersSpawned')
AddEventHandler('nls:getAreStrippersSpawned', function ()
    return AreStrippersSpawned
end)

RegisterNetEvent('nls:strippersSpawn')
AddEventHandler('nls:strippersSpawn', function ()

    TriggerClientEvent('nls:strippersSpawn', -1)
    AreStrippersSpawned = true
end)

client.lua

Citizen.CreateThread(function ()
    print(areStrippersSpawned)

    if areStrippersSpawned == true then
        return
    end

    local playerServerId = GetPlayerServerId(PlayerId())

    while areStrippersSpawned == false do
        local playerPed = GetPlayerPed(GetPlayerFromServerId(playerServerId))
        local playerCoords = GetEntityCoords(playerPed)
        local distance = GetDistanceBetweenCoords(playerCoords.x, playerCoords.y, playerCoords.z, vanillaUnicornCoords.x, vanillaUnicornCoords.y, vanillaUnicornCoords.z, false)

        if distance < 50 then
            print(distance)
            TriggerServerEvent('nls:strippersSpawn')
            areStrippersSpawned = true
        end

        Citizen.Wait(1000)
    end
end)

The issue that I have is that after I logout and login again AreStrippersSpawned is false. So my question is shouldn’t it be that server.lua script is only executed on server itself? How it works?

Hey, you are missing a point. Server side is saving these variable. You think it doesn’t because you don’t see the difference between client side and server side.

Server-Side

local variable = 0
RegisterNetEvent('override', function(num)
    variable = num
end)
RegisterNetEvent('check', function()
    print(variable)
end)

This server-side code executed correctly and with you disconnecting and joining the server once again will have the same value that you have overridden it with. Client side doesn’t save this info, same with Server side. If you restart your script, unless you have data saved in MySQL or physical *.txt or *.json you will simply just get 0 or false in your case.

Also you cannot return values from server-side, this would have been a Massive security flaw.
(I’m assuming this since you didn’t provide whole client side, at least from what we can see)

1 Like

Okay, I can kinda see what you mean, even after I’ve updated the value on server-side and it’s showing true in the console, on client I am still getting false value.
On reconnecting also true value is still on server side.
So basically is there any workaround so I can pass this updated value to client-side?

Send an event to server requesting update and re-send your variable to client.

Instead of

return AreStrippersSpawned

Do

TriggerClientEvent('event:name', source, AreStrippersSpawned)

On Client register Net event and after that override variable on client from this passed arg

1 Like