Just a quick correction: …probably not, but… according to the dev hub, PublishAsync
does not provide return values like a function call would; you would have to subscribe to a different topic that would send the data specifying the JobId, or you could specify a different action within that topic that gets the data.
I made my own variation of your code that gathers all the data published from a player-specific message topic into an array, sorts it by player count, and chooses the one with the least players.
-- stuff to detect requests
local function onMessageGot(msg)
--[[ get the topic from the data sent
msg = {
Sent = -- the time when the message was sent
Data = -- message sent over by the developer
}
--]]
local msgTopic = msg.Data
local amountOfPlayers = #Players:GetPlayers()
if amountOfPlayers < Players.MaxPlayers then
-- the table to send
local sendTable = {
Count = amountOfPlayers,
JobId = game.JobId
}
-- send the table back to specified topic
MessagingService:PublishAsync(msgTopic, sendTable)
end
end
MessagingService:SubscribeAsync(MESSAGING_TOPIC, onMessageGot)
-- requesting an open server
-- open a new player-specific topic
local newMessagingTopic = string.format("ReturnEmptyServersFor-%d", Player.UserId)
-- make a table to store any responses
local openServers = {}
local function onReturnMessageGot(msg)
-- insert the data into the table
openServers[#openServers + 1] = msg.Data
end
local retSubscription = MessagingService:SubscribeAsync(newMessagingTopic, onReturnMessageGot)
MessagingService:PublishAsync(MESSAGING_TOPIC, newMessagingTopic)
-- wait for all the servers to respond
-- might be shorter, I don't know
wait(5)
-- disconnect from the topic since it's not being used anymore
retSubscription:Disconnect()
if #openServers > 0 then -- at least 1 server is open
-- sort servers by player count
table.sort(openServers, function(a, b)
return a.Count < b.Count
end
-- choose the one with the lowest count
local foundJobId = openServers[1].JobId
TeleportService:TeleportToPlaceInstance(game.PlaceId, foundJobId, Player)
else
print("sorry, no open servers")
end
One could also receive just the first server to respond and get the player to teleport them there as soon as possible, you would just disconnect the subscription from inside the callback:
--[[ requesting an open server ]]
local retSubscription
local function onReturnMessageGot(msg)
local foundJobId = msg.Data.JobId
retSubscription:Disconnect()
TeleportService:TeleportToPlaceInstance(game.PlaceId, foundJobId, Player)
end
getConnection = MessagingService:SubscribeAsync(newMessagingTopic, onReturnMessageGot)
MessagingService:PublishAsync(MESSAGING_TOPIC, newMessagingTopic)
You might also want to wrap your PublishAsyncs
in a pcall
since this is a networking function that can error, but you can also use Promises for this!