Message Handler - Silverfeelin/Starbound-MessageHandling-Demo GitHub Wiki

The handler argument to the message.setHandler function (see Receiving Messages) should be a function with the below parameters.

function myHandler(messageType, isLocal, ...)
  • messageType

This value matches the messageName in your message.setHandler function.
This may be useful if you bind the same function to multiple messages (for whatever reason).

  • isLocal

A bool indicating whether this message was sent locally or not.
For example, this value will be true when sending a message from your tech to your interface, but false when another player sends the message to your interface.

  • args

All arguments after that are optional, and represent the data sent together with the message. Make sure this data is parsed correctly, as any data could be sent by any client.
For example, when a local message "multiply" is sent with the arguments 10 and 20, the handler will be called like such:

handler("multiply", true, 10, 20)
  • Return Value

The value you return will be the sent back to the sender of the message. This is the result of the promise.

You can only return one value (opposed to the indefinite amount of arguments received). To return multiple values, they should be encapsulated in a Lua object.

Just like with sending messages, all returned data must be serializable. Returning a function will throw an error, crashing your script.

Some examples of valid return values: "15", 15 or {answer = 15, message = "3 * 5 = 15"}.

Example

function init()
  -- Since the messageType is not important to us, we ignore it by using `_`.
  message.setHandler("multiply", function(_, isLocal, a, b)
    -- Check argument validity
    if type(a) ~= "number" or type(b) ~= "number" then
      return "Those aren't numbers!"
    end

    -- Check if the message was locally sent
    if isLocal then
      -- Send myself the right answer.
      return (a * b)
    else
      -- We'll mess with cheaters by sending them a wrong answer!
      return (a + b)
    end
  end
end