Scripting: Communication between Scripts

The are many times when developing complex systems and classes there is the need to send and receive data between different objects. This could be done by using global variables but would never be practical on a large project where there cold be 1000,s of dynamically controlled objects.
It is far better to have the scripts send and receive data between each other, this way each object can manage its own data.

Options

Calling between Lua scripts is easy to do in skyline. If you have the object name, id or tag of an entity, then you can communicate to its script, action or graph. It is best practice to use the objects tag name as it is always unique in the scene, then using this tag you can grab the id by using the following command.

targetID = entity.getIDFromTag(tagname);

You can also get the description of an entity the same way, which is useful for game mechanics.
To call from one script to another, you have a few options available. Get the target objects ID from the command above.

CallFn() - Call to a specified function

Use lua's entity library for “callFn” which allows you to call a custom function name in another script by an entities id only. e.g.

--| Call in one script with
entity.callFn(objID, targetID, "myCustomFunction", argument );
 
--| Place this function in the targetID script
--| the arg callerID is the id of the object who called this command.
function myCustomFunction( callerID, argument )
    --Do something..
end

publicFn() - call a built in function

Use lua's entity library to to call a function named “publicFn”. This function is a built in function available in all scripts, but will only trigger on the targetID's script.

--| Call in one script with 
entity.callPublicFn(objID, targetID, argument)
 
--| Place the function in the target script
function publicFn( callerID, argument )
    --Do something..
end

globalFn() - Call to all objects global function

And of course a globalFn call which allows you to call every script in the level and receive the event. Its slower so not recommended for every frame. This is received in all scripts that contain the function. This can be used as such:

--| Call in one script with
sky.callGlobalFn(objID, argument);
 
--| Place the function in the target script
function globalFn( callerID, argument )
    --  ...... run code ......
end