------ Trace.lua ------ local uisrv = lgs.DarkUISrv local function Report(message, id) uisrv.TextMessage("Message "..message.." received from "..id.." by "..script.objid) end function TurnOn(msg) Report(msg.message, msg.from) return true end function TurnOff(msg) Report(msg.message, msg.from) return true end
This shows using a local function, and also a local variable to hold the script service. Using local variables is faster than globals, and the name is shorter so you can type less.
This script reads some fields from the message table that is passed to your message handler. Message tables can have different fields depending on the message being handled. See Script Messages for complete information about messages.
The example also uses the global script object. The script object has two fields:
|script.ObjId||The ID of the object this script is running on.|
|script.ClassName||The name of this script.|
|script:SendMessage(to,message,…)||Send a message to an object. The method will return after the object has received the message. You can add up to three extra parameters.|
|script:PostMessage(to,message,…)||Sends a message, but doesn’t wait for it to be received. This is the preferred way to send messages because it doesn’t delay the game as much.|
|script:SetTimedMessage(name,time,type (opt),data (opt))||Set a timer on this object. Time is in milliseconds. When the timer expires, a Timer message is sent back to your script. A timer can be "OneShot" or "Periodic", which you pass as the optional third parameter.|
|script:KillTimedMessage(timer)||Stop a previously set timer. Pass the value that was returned from SetTimedMessage.|
|script:IsScriptDataSet(name)||Check if a script variable is set.|
|script:GetScriptData(name)||Return the value of a script variable.|
|script:SetScriptData(name,value)||Set a script variable.|
|script:ClearScriptData(name)||Erase a script variable.|
The use of script variables will be described later.
The TurnOn and TurnOff functions in the example do the same thing. It would be more efficient to use one function for both messages. This is not difficult in Lua. Instead of two functions you can type this:
function TurnOn(msg) Report(msg.message, msg.from) return true end TurnOff = TurnOn
As long as the name is global and a function, it will be considered a message handler.