Tutorial:Script interfaces

From Official Factorio Wiki
Revision as of 16:57, 4 April 2013 by FreeER (talk | contribs) (Discovering interfaces)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

Script interfaces allow direct communication between simultaneously running scripts. This is done in form of defining a public interface with given functions. All the code regarding the interfaces communication is in the remote namespace.

Defining interfaces

The interface is defined as follows:

 remote.addinterface("myinterface", {
   mygetter = function()
     -- you can return 1 or more variables from the script
     return "foo"
   -- the values can be only primitive type or (nested) tables
   mysetter = function(foo, bar)
     glob.foo = foo
     glob.bar = bar

The interface functions can take only primitive types and tables as variables. The same holds for return values. The reason for this is that the scripts are running in different lua states and there is no easy way of passing more elaborate data (functions, rich Factorio objects - Lua Entity, etc.) around. Passing simple function callbacks is very powerful mechanism and might be implemented in some way in the future.

The interfaces are not serialised. Therefore it is a good idea to put them into the global scope of the script. In that way they are run everytime the script file is loaded (no matter whether it is the first run or game being loaded).

At the moment the interface is identified solely by its name. There is no vesion mechanism yet. It is a good idea to prefix the name of the interface with the name of the mod / map where it is defined.

Calling interface functions

The interface can be used for calling functions from a different script.

Example (in the different script than the one above):

 -- calls the myinterface.mygetter from the script above and prints the returning value
 print(remote.call("myinterface", "mygetter"))

This remote.call can be used in the global scope as well. However then the script in which it is called has to be invoked after the script which defined the interface. The ordering of the scripts is: first the map script and then the mod scripts in order defined by the mod ordering.

 -- set values in the other script
 -- remote call takes the name of the interface, name of the function and then variable amount of parameters
 remote.call("myinterface', "mysetter", 5, {bar=baz})

Discovering interfaces

The script can check for expected interfaces and its functions via the remote.interfaces table. This is a table indexed by interface names where the values are set of functions for particular interfaces.


 -- check whether there is the "myinterface" interface and whether it contains the "mygetter" function
 if remote.interfaces.myinterface and remote.interfaces.myinterface.mygetter then
   -- the remote call for the function is safe to use