Photon Lua (Corona) Client API

Module loadbalancing.LoadBalancingClient

Implements the Photon LoadBalancing workflow.

Functions

new (serverAddress, appId, appVersion, options) Creates instance of Photon LoadBalancing client.
instance:getGamePeer () Returns peer currently connected to game server or nil.
instance:setUserId (userId) Set user id
instance:getUserId () Returns previously set user id.
instance:service () Call this at least several times per second to keep client functioning.
instance:onStateChange (state) Called on client state change.
instance:onError (errorCode, errorMsg) Called if client error occures.
instance:onOperationResponse (errorCode, errorMsg, code, content) Called on operation response.
instance:onEvent (code, content, actorNr) Called on custom event.
instance:onRoomList (rooms) Called on room list received from Master server (on connection).
instance:onRoomListUpdate (rooms, roomsUpdated, roomsAdded, roomsRemoved) Called on room list updates received from Master server.
instance:onMyRoomPropertiesChange () Called on joined room properties changed event.
instance:onActorPropertiesChange (actor) Called on actor properties changed event.
instance:onJoinRoom (createdByMe) Called when client joins or successfully creates room.
instance:onActorJoin (actor) Called when new actor joins the room client joined to.
instance:onActorLeave (actor, cleanup) Called when actor leaves the room client joined to.
instance:onActorSuspend (actor) Called when actor suspended in the room client joined to.
instance:onFindFriendsResult (errorCode, errorMsg, friends) Called when findFriends request completed.
instance:onLobbyStats (errorCode, errorMsg, lobbies) Called when lobbies statistics update received.
instance:onAppStats (errorCode, errorMsg, stats) Called when application statistics update received.
instance:onGetRegionsResult (errorCode, errorMsg, regions) Called when getRegions request completed.
instance:onWebRpcResult (errorCode, message, uriPath, resultCode, data) Called when webRpc request completed.
instance:initRoom (room) Override with customization of room object if extending LoadBalancingClient class.
instance:initActor (actor) Override with customization of actor object if extending LoadBalancingClient class.
instance:myActor () Returns local actor.
instance:myRoom () Returns client's room.
instance:myRoomActors () Returns actors in room client currently joined including local actor.
instance:myRoomMasterActorNr () Returns actor number of the player who's the master of this Room.
instance:myRoomActorCount () Returns numer of actors in room client currently joined including local actor.
instance:reset (connect) Resets client to initial state
instance:setCustomAuthentication (authParameters [, authType] [, authData]) Enables custom authentication and sets it's parameters.
instance:connect (options) Starts connection to Master server.
instance:connectToNameServer (options) Starts connection to NameServer.
instance:createRoomFromMy (roomName, options) Creates a new room on the server (or fails when the name is already taken).
instance:createRoom (roomName, options) Creates a new room on the server (or fails when the name is already taken).
instance:joinRoom (roomName, options, createOptions) Joins a room by name and sets this player's properties.
instance:joinRandomRoom (options) Joins a random, available room.
instance:disconnect () Disconnects from all servers.
instance:suspendRoom (options) Disconnects client from Game server keeping player in room (to rejoin later) and connects to Master server if not connected.
instance:leaveRoom (options) Leaves room and connects to Master server if not connected.
instance:raiseEvent (eventCode, data, options) Raises game custom event.
instance:changeGroups (groupsToRemove, groupsToAdd) Changes client's interest groups (for events in room).
Note the difference between passing nil and {}: nil won't add/remove any groups, {} will add/remove all (existing) groups.
First, removing groups is executed.
instance:findFriends (friendsToFind) Requests Master server for actors online status and joined rooms.
instance:requestLobbyStats (lobbiesToRequest) Requests Master server for lobbies statistics.
Override onLobbyStats to handle request results.
Alternatively, automated updates can be set up during connect.
instance:getRegions () Requests NameServer for regions list.
instance:webRpc (uriPath, parameters, options) Sends web rpc request to Master server.
instance:connectToRegionMaster (region) Connects to a specific region's Master server, using the NameServer to find the IP.
instance:isConnectedToMaster () Checks if client is connected to Master server (usually joined to lobby and receives room list updates).
instance:isConnectedToNameServer () Checks if client is connected to NameServer server
instance:isInLobby () Checks if client is in lobby and ready to join or create game.
instance:isJoinedToRoom () Checks if client is joined to room.
instance:isConnectedToGame () Deprecated.
instance:availableRooms () Current room list from Master server.
instance:availableRoomsCount () Number of rooms currently available on server.
instance:setLogLevel (level) Sets client logger level
StateToName (state) Converts State element to string name.

Tables

PeerErrorCode Enum for client peers error codes.
State Enum for client states.


Functions

new (serverAddress, appId, appVersion, options)
Creates instance of Photon LoadBalancing client. Override instance methods to handle system or custom events and operation responses.

Parameters:

  • serverAddress string or table Server address:port. Used as Master server or as NameServer address depending on what server connected first (connect or connectToNameServer)
  • appId string Cloud application ID.
  • appVersion string Cloud application version.
  • options optional table Additional options:

    initRoom: (function) Optional method for new room customization: function initRoom(LoadBalancingClient, Room).

    initActor: (function) Optional method for new actor customization: function initActor(LoadBalancingClient, Actor).

    encryptedAuthentication: (boolean) Default is true. Encrypts authentication phase when connects to Master and Game servers.

    crcEnabled: (boolean) Default is false. If enabled, the client and server will add a CRC checksum to every sent package.

Returns:

    LoadBalancingClient instance
instance:getGamePeer ()
Returns peer currently connected to game server or nil.

Returns:

    core.PhotonPeer Current game peer.
instance:setUserId (userId)
Set user id

Parameters:

instance:getUserId ()
Returns previously set user id.

Returns:

    string User id.
instance:service ()
Call this at least several times per second to keep client functioning.
instance:onStateChange (state)
Called on client state change. Override to handle it.

Parameters:

  • state State New client state.
instance:onError (errorCode, errorMsg)
Called if client error occures. Override to handle it.

Parameters:

instance:onOperationResponse (errorCode, errorMsg, code, content)
Called on operation response. Override if need custom workflow or response error handling.

Parameters:

  • errorCode int Server error code.
  • errorMsg string Error message.
  • code byte Operation code.
  • content table Operation response content.

see also:

instance:onEvent (code, content, actorNr)
Called on custom event. Override to handle it.

Parameters:

  • code byte Event code.
  • content table Event content.
  • actorNr int Actor ID event raised by.
instance:onRoomList (rooms)
Called on room list received from Master server (on connection). Override to handle it.

Parameters:

instance:onRoomListUpdate (rooms, roomsUpdated, roomsAdded, roomsRemoved)
Called on room list updates received from Master server. Override to handle it.

Parameters:

instance:onMyRoomPropertiesChange ()
Called on joined room properties changed event. Override to handle it.
instance:onActorPropertiesChange (actor)
Called on actor properties changed event. Override to handle it.

Parameters:

instance:onJoinRoom (createdByMe)
Called when client joins or successfully creates room. Override to handle it.

Parameters:

  • createdByMe boolean True if room is created by client.
instance:onActorJoin (actor)
Called when new actor joins the room client joined to. Override to handle it.

Parameters:

instance:onActorLeave (actor, cleanup)
Called when actor leaves the room client joined to. Also called for every actor during room cleanup. Override to handle it.

Parameters:

  • actor loadbalancing.Actor Actor left the room.
  • cleanup boolean True if called during room cleanup (e.g. on disconnect).
instance:onActorSuspend (actor)
Called when actor suspended in the room client joined to. Override to handle it.

Parameters:

instance:onFindFriendsResult (errorCode, errorMsg, friends)
Called when findFriends request completed.
Override to handle request results.

Parameters:

  • errorCode int Result error code. 0 if request is successful.
  • errorMsg string Error message.
  • friends table Table with actors names as keys and friend statuses as values: {name1 = friendStatus1, name2 = friendStatus2, ... }.

    friendStatus.online: (boolean) Online status.

    friendStatus.roomId: (string) Joined room.

instance:onLobbyStats (errorCode, errorMsg, lobbies)
Called when lobbies statistics update received. Update can be automated by set up during connect or requested explicitly by requestLobbyStats.
Override to handle request results.

Parameters:

  • errorCode int Result error code. 0 if request is successful. For automated updates is always 0.
  • errorMsg string Error message. For automated updates is always empty.
  • lobbies table Array of lobbies statistics: [lobbyStats1, lobbyStats1, ... ].

    lobbyStats.lobbyName: (string) Lobby name.

    lobbyStats.lobbyType: (int) Lobby type.

    lobbyStats.peerCount: (int) The number of players in the lobby (on Master, not playing).

    lobbyStats.gameCount: (int) The number of games in the lobby.

instance:onAppStats (errorCode, errorMsg, stats)
Called when application statistics update received.
Override to handle request results.

Parameters:

  • errorCode int Result error code. Currently is always 0.
  • errorMsg string Error message. Currently is always empty.
  • stats table Application statistics.

    stats.peerCount: (int) Count of players currently online on Game servers.

    stats.masterPeerCount: (int) Count of players on Master server (looking for game).

    stats.gameCount: (int) Count of games currently in use (includes invisible and full rooms, so it doesn't match lobby list).

instance:onGetRegionsResult (errorCode, errorMsg, regions)
Called when getRegions request completed.
Override to handle request results.

Parameters:

  • errorCode int Result error code. 0 if request is successful.
  • errorMsg string Error message.
  • regions table Table with region codes as keys and Master servers addresses as values
instance:onWebRpcResult (errorCode, message, uriPath, resultCode, data)
Called when webRpc request completed.
Override to handle request results.

Parameters:

  • errorCode int Result error code. 0 if request is successful.
  • message string Error message if errorCode ~= 0 or optional message returned by remote procedure.
  • uriPath string Request path.
  • resultCode int Result code returned by remote procedure.
  • data table Data returned by remote procedure.
instance:initRoom (room)
Override with customization of room object if extending LoadBalancingClient class. In case of instantiating LoadBalancingClient directly, pass customization method in new.

Parameters:

see also:

instance:initActor (actor)
Override with customization of actor object if extending LoadBalancingClient class. In case of instantiating LoadBalancingClient directly, pass customization method in new.

Parameters:

see also:

instance:myActor ()
Returns local actor. Client always has local actor even if not joined.

Returns:

    loadbalancing.Actor Local actor.
instance:myRoom ()
Returns client's room. Client always has it's room even if not joined. It's used for room creation operation.

Returns:

    loadbalancing.Room Current room.
instance:myRoomActors ()
Returns actors in room client currently joined including local actor.

Returns:

    table actorNr -> loadbalancing.Actor pairs list of room actors.
instance:myRoomMasterActorNr ()
Returns actor number of the player who's the master of this Room. Note: This changes when the current master leaves the room.

Returns:

    number Master actor number.
instance:myRoomActorCount ()
Returns numer of actors in room client currently joined including local actor.

Returns:

    int Number of actors.
instance:reset (connect)
Resets client to initial state

Parameters:

  • connect boolean Connect after reset
instance:setCustomAuthentication (authParameters [, authType] [, authData])
Enables custom authentication and sets it's parameters.

Parameters:

  • authParameters string This string must contain any (http get) parameters expected by the used authentication service.
  • authType optional constants.CustomAuthenticationType The type of custom authentication provider that should be used. Default is CustomAuthenticationType.Custom
  • authData string or table The data to be passed-on to the auth service via POST.
instance:connect (options)
Starts connection to Master server.

Parameters:

  • options optional table Additional options:

    keepMasterConnection: (boolean) Don't disconnect from Master server after joining room. Default is false.

    lobbyName: (string) Name of the lobby connect to.

    lobbyType: (constants.LobbyType) Type of the lobby.

    lobbyStats: (boolean) If true, Master server will be sending lobbies statistics periodically.
    Override onLobbyStats to handle request results.
    Alternatively, requestLobbyStats can be used.

Returns:

    boolean True if current client state allows connection.
instance:connectToNameServer (options)
Starts connection to NameServer.

Parameters:

  • options optional table Additional options.
instance:createRoomFromMy (roomName, options)
Creates a new room on the server (or fails when the name is already taken). Takes parameters (except name) for new room from myRoom() object. Set them before call.

Parameters:

  • roomName optional string New room name. Assigned automatically by server if empty or not specified.
  • options optional table Additional options:

    lobbyName: (string) Name of the lobby to create room in.

    lobbyType: (constants.LobbyType) Type of the lobby.

instance:createRoom (roomName, options)
Creates a new room on the server (or fails when the name is already taken).

Parameters:

  • roomName optional string The name to create a room with. Must be unique and not in use or can't be created. If not specified or nil, the server will assign a GUID as name.
  • options optional table Additional options:

    isVisible (boolean) Shows the room in the lobby's room list. Default is true.

    isOpen (boolean) Keeps players from joining the room (or opens it to everyone). Default is true.

    maxPlayers (int) Max players before room is considered full (but still listed).

    customGameProperties (table) Custom properties to apply to the room on creation (use string-typed keys but short ones).

    propsListedInLobby (photon.common.type.Array of strings) Defines the custom room properties that get listed in the lobby: require("photon.common.type.Array").new("propName1", "propName2", ... ), plugin: photon.common.type.Array.new(...)

    emptyRoomLiveTime (int) Room live time (ms) in the server room cache after all clients have left the room.

    suspendedPlayerLiveTime (int) Player live time (ms) in the room after player suspended.

    lobbyName: (string) Name of the lobby to create room in.

    lobbyType: (constants.LobbyType) Type of the lobby.

instance:joinRoom (roomName, options, createOptions)
Joins a room by name and sets this player's properties.

Parameters:

  • roomName string The name of the room to join. Must be existing already, open and non-full or can't be joined.
  • options optional table Additional options:

    rejoin: (boolean) Rejoin using current userId.

    createIfNotExists: (boolean) Create room if not exists.

  • createOptions optional table Room options for creation:

    isVisible (boolean) Shows the room in the lobby's room list. Default is true.

    isOpen (boolean) Keeps players from joining the room (or opens it to everyone). Default is true.

    maxPlayers (int) Max players before room is considered full (but still listed).

    customGameProperties (table) Custom properties to apply to the room on creation (use string-typed keys but short ones).

    propsListedInLobby (photon.common.type.Array of strings) Defines the custom room properties that get listed in the lobby: require("photon.common.type.Array").new("propName1", "propName2", ... ), plugin: photon.common.type.Array.new(...)

    emptyRoomLiveTime (int) Room live time (ms) in the server room cache after all clients have left the room.

    suspendedPlayerLiveTime (int) Player live time (ms) in the room after player suspended.

    lobbyName: (string) Name of the lobby to create room in.

    lobbyType: (constants.LobbyType) Type of the lobby.

instance:joinRandomRoom (options)
Joins a random, available room. This operation fails if all rooms are closed or full.

Parameters:

  • options optional table Additional options:

    expectedCustomRoomProperties: (table) If specified, a room will only be joined, if it matches these custom properties.

    expectedMaxPlayers: (int) If specified, filters for a particular maxPlayer setting.

    matchingType: (constants.MatchmakingMode) Selects one of the available matchmaking algorithms. Default is MatchmakingMode.FillRoom

    lobbyName: (string) Name of the lobby to create room in.

    lobbyType: (constants.LobbyType) Type of the lobby.

    sqlLobbyFilter: (string) Basically the "where" clause of a sql statement. Examples: 'C0 = 1 AND C2 > 50'. 'C5 = "Map2" AND C2 > 10 AND C2 < 20'

instance:disconnect ()
Disconnects from all servers.
instance:suspendRoom (options)
Disconnects client from Game server keeping player in room (to rejoin later) and connects to Master server if not connected.

Parameters:

  • options optional table Additional options:

    sendAuthCookie: (boolean) Securely transmit the encrypted object AuthCookie to the web service in PathLeave webhook when available

instance:leaveRoom (options)
Leaves room and connects to Master server if not connected.

Parameters:

  • options optional table Additional options:

    sendAuthCookie: (boolean) Securely transmit the encrypted object AuthCookie to the web service in PathLeave webhook when available

instance:raiseEvent (eventCode, data, options)
Raises game custom event.

Parameters:

  • eventCode byte Identifies this type of event (and the content). Your game's event codes can start with 0.
  • data Event custom data (may be of any base type or table, use nil if none).
  • options optional table Additional options:

    interestGroup: (byte) The ID of the interest group this event goes to (exclusively).

    cache: (constants.EventCaching) Events can be cached (merged and removed) for players joining later on. Default is EventCaching.DoNotCache

    receivers: (constants.ReceiverGroup) Defines to which group of players the event is passed on. Default is ReceiverGroup.Others

    targetActors: (int array) Defines the target players who should receive the event (use only for small target groups).

    sendReliable: (boolean) Default is true. Guarantees event delivery (event repeated if it's lost). Set to false if the event is replaced by a newer rapidly.

    channelId: (byte) Default is 0. The "channel" to which this event should belong. Per channel, the sequence is kept in order.

    webForward: (boolean) Forward to web hook.

instance:changeGroups (groupsToRemove, groupsToAdd)
Changes client's interest groups (for events in room).
Note the difference between passing nil and {}: nil won't add/remove any groups, {} will add/remove all (existing) groups.
First, removing groups is executed. This way, you could leave all groups and join only the ones provided.

Parameters:

  • groupsToRemove array Groups to remove from interest. Nil will not leave Object. A {} will remove all.
  • groupsToAdd array Groups to add to interest. Nil will not add Object. A {} will add all current.
instance:findFriends (friendsToFind)
Requests Master server for actors online status and joined rooms.
Override onFindFriendsResult to handle request results.

Parameters:

  • friendsToFind table Actors names array.
instance:requestLobbyStats (lobbiesToRequest)
Requests Master server for lobbies statistics.
Override onLobbyStats to handle request results.
Alternatively, automated updates can be set up during connect.

Parameters:

  • lobbiesToRequest table Array of lobbies id pairs [ [lobbyName1, lobbyType1], [lobbyName2, lobbyType2], ... ]. If not specified or null, statistics for all lobbies requested.
instance:getRegions ()
Requests NameServer for regions list.
Override onGetRegionsResult to handle request results.
instance:webRpc (uriPath, parameters, options)
Sends web rpc request to Master server.
Override onWebRpcResult to handle request results.

Parameters:

  • uriPath string Request path.
  • parameters table Request parameters.
  • options optional table Additional options:

    sendAuthCookie: (boolean) Defines if the authentication cookie gets sent to a WebHook (if setup)

instance:connectToRegionMaster (region)
Connects to a specific region's Master server, using the NameServer to find the IP.

Parameters:

  • region string Region connect to Master server of.

Returns:

    boolean True if current client state allows connection.
instance:isConnectedToMaster ()
Checks if client is connected to Master server (usually joined to lobby and receives room list updates).

Returns:

    boolean True if client is connected to Master server.
instance:isConnectedToNameServer ()
Checks if client is connected to NameServer server

Returns:

    boolean True if client is connected to NameServer server.
instance:isInLobby ()
Checks if client is in lobby and ready to join or create game.

Returns:

    boolean True if client is in lobby.
instance:isJoinedToRoom ()
Checks if client is joined to room.

Returns:

    boolean True if client is joined to room.
instance:isConnectedToGame ()
Deprecated. Use isJoinedToRoom().
instance:availableRooms ()
Current room list from Master server.

Returns:

    table roomName -> loadbalancing.RoomInfo pairs list of available rooms.
instance:availableRoomsCount ()
Number of rooms currently available on server.

Returns:

    int Available rooms count
instance:setLogLevel (level)
Sets client logger level

Parameters:

StateToName (state)
Converts State element to string name.

Parameters:

  • state State Client state enum element.

Returns:

    string Specified element name or nil if not found.

Tables

PeerErrorCode
Enum for client peers error codes.

Fields:

  • Ok No Error.
  • MasterError General Master server peer error.
  • MasterConnectFailed Master server connection error.
  • MasterConnectClosed Disconnected from Master server.
  • MasterTimeout Disconnected from Master server for timeout.
  • MasterEncryptionEstablishError Master server encryption establishing failed.
  • MasterAuthenticationFailed Master server authentication failed.
  • GameError General Game server peer error.
  • GameConnectFailed Game server connection error.
  • GameConnectClosed Disconnected from Game server.
  • GameTimeout Disconnected from Game server for timeout.
  • GameEncryptionEstablishError Game server encryption establishing failed.
  • GameAuthenticationFailed Game server authentication failed.
  • NameServerError General NameServer peer error.
  • NameServerConnectFailed NameServer connection error.
  • NameServerConnectClosed Disconnected from NameServer.
  • NameServerTimeout Disconnected from NameServer for timeout.
  • NameServerEncryptionEstablishError NameServer encryption establishing failed.
  • NameServerAuthenticationFailed NameServer authentication failed.
State
Enum for client states.

Fields:

  • Error Critical error occurred.
  • Uninitialized Client is created but not used yet.
  • ConnectingToNameServer Connecting to NameServer.
  • ConnectedToNameServer Connected to NameServer.
  • ConnectingToMasterserver Connecting to Master server (includes connect, authenticate and joining the lobby).
  • ConnectedToMaster Connected to Master server.
  • JoinedLobby Connected to Master and joined lobby. Display room list and join/create rooms at will.
  • ConnectingToGameserver Connecting to Game server (client will authenticate and join/create game).
  • ConnectedToGameserver Connected to Game server (going to auth and join game).
  • Joined The client joined room.
  • Disconnected The client is no longer connected.
generated by LDoc 1.3