Skip to content

Getting Started

Once mailbox is placed where crosswalk loads the server modules, you can start using it through any other server modules. Mailbox will automatically load each player data as they entered the game, and save it when they leave.

Opening Mailbox

The first step is to open mailbox by giving it the names of the DataStores to be used.

For example, you can create a new server module that will handle the player's data. Start by opening Mailbox in the Init function.

return function(Modules, ClientModules, Services)
    local module = {}

    function module.Init()
        Modules.Mailbox.Open('game-data', 'player-data')
    end

    return module
end

Data Handlers

Instead of having a centralized place where all the player data is contained and managed, each crosswalk server modules can tell Mailbox what data they need to persist with a player. Mailbox call these decentralized pieces of information data handlers.

Example

If your game needs to handle some type of currency, you will probably have a server module to handle operations related to that. That module can register a data handler to Mailbox to persist data across each player visits.

return function(Modules, ClientModules, Services)
    local module = {}

    local playerDatas = {}

    -- after a player entered a game and Mailbox has
    -- loaded their data, it calls that function and
    -- provides the data table that can be mutated
    local function onLoaded(player, data)
        playerDatas[player] = data
    end

    -- this will be called by Mailbox when a
    -- player is leaving and their data must be
    -- cleaned up
    local function onRemoved(player)
        playerDatas[player] = nil
    end

    -- when Mailbox comes across a player that does
    -- not have data, it will call this function to
    -- obtain a default value
    local function getDefault()
        return {
            gold = 0,
            coins = 100,
        }
    end

    function module.Init()
        Modules.Mailbox.RegisterDataHandler(
            'Currency',
            onLoaded,
            onRemoved,
            getDefault
        )
    end

    function module.GiveCoins(player, amount)
        local data = playerDatas[player]
        data.coins = data.coins + amount
    end

    return module
end