Difference between revisions of "Interacting with the game: Event-based programming"

From PioneerWiki
Jump to: navigation, search
m (More events: fixup)
m (More events)
 
Line 115: Line 115:
 
If you register an event more than once in the same file only the last instance will be registered and you will see a log warning on the command line and in output.txt.
 
If you register an event more than once in the same file only the last instance will be registered and you will see a log warning on the command line and in output.txt.
  
Example - test_module_1.lua:
+
Example: '''test_module_1.lua'''
 
  Event.Register("onGameStart", function ()
 
  Event.Register("onGameStart", function ()
 
     print("Only the first instance of onGameStart() will be registered")
 
     print("Only the first instance of onGameStart() will be registered")

Latest revision as of 12:03, 8 June 2026

Events

The Lua scripts are all executed at startup. If you were to add a single file named hello_world.lua to the data/modules directory containing the following:

print("Hello, World!")

you would literally see the words, "Hello, World!" appear in Pioneer's output (if running in a terminal) shortly before the main menu appears. You would also see it in the Lua console, if you were to open it.

All file-scoped imperative statements in all Lua files are executed at that time. The way to get Lua code to interact with the game itself, beyond that time, is to write functions and to connect them to event handlers. Many events are triggered by Pioneer during the course of play, all of which will cause any functions which are connected to them, to run. Most will provide those functions with arguments.

Here is a quick list of some of the more commonly used events:

  • onGameStart is triggered when the player clicks on a new game button in the main menu, or when the player loads a game.
  • onEnterSystem is triggered whenever any ship arrives in the current star system after a hyperspace journey.
  • onLeaveSystem is triggered whenever any ship leaves the current star system by hyperspacing.
  • onShipDestroyed is triggered whenever any ship is destroyed.
  • onShipDocked is triggered whenever any ship docks at a starport.

There are many more. All are fully documented in the Pioneer Codedoc. Of the five that I have listed, only onGameStart does not provide the function with any arguments. The other four provide a reference to the ship in question, and the latter two each also provide an additional argument (a reference to the attacker, and the starport, respectively).

Writing a function for an event

An event handling function does not have to return anything. It will be passed any arguments specified in the documentation, which it can either deal with, or ignore. It has access to any variables that are declared in the same file scope, including named functions and tables.

Here is an adaptation of the 'Hello World' message above to be event driven. It's now triggered on game start and will still turn up on the command line, but now much later in the start sequence, pretty much when the game starts and you find yourself docked at a starport.

local Event = require 'Event'

local welcome = function ()
    print("Hello, World!")
end

Event.Register("onGameStart", welcome)

We move on. The same function again but now instead the message is presented on the player's ship console and is now welcoming them to Pioneer. We need to add the 'Comms' module to the script and the function name has changed to 'onGameStart' , same as the event, which is common practice in Pioneer.

local Comms = require 'Comms'
local Event = require 'Event'

local onGameStart = function ()
    Comms.Message ('Welcome to Pioneer!')
end

Event.Register("onGameStart", onGameStart)

The latest code may not work as intended. The reason is that 'onGameStart' is not when the game starts but when it is being launched after pressing the button on the main menu to start on Mars, or whatever location you prefer. Let's see if there is an event that better suits our purpose. 'onShipDocked'?. This will make the message trigger every time we dock at a space station, on the ground or in orbit. 'onShipDocked' will not trigger on launching a saved game or when we start a new game, docked at a starport. Now the script works just fine and will launch the message the next time you land or dock with a space station.

local Comms = require 'Comms'
local Event = require 'Event'

local onShipDocked = function ()
    Comms.Message ('Welcome to Pioneer!')
end

Event.Register("onShipDocked", onShipDocked)

If you look at the comms log after docking/landing, you may see the greeting posted more than once. This is because the same function is triggered for all ships in the vicinity, not only the player's. The Pioneer universe is populated by ships and characters and they follow pretty much the same rules as the player. To fix this we need to test if the ship is the player first. Modify the 'onShipDocked' function in the previous example like this:

local onShipDocked = function (ship)
    if ship:IsPlayer() then
        Comms.Message ('Welcome to Pioneer!')
    end
end

An alternative solution to the last code snippet would be to test for if the ship is not the player:

local onShipDocked = function (ship)
    if not ship:IsPlayer() then return end
    Comms.Message ('Welcome to Pioneer!')
end

Setting a timer

Yet another way to avoid the problem with 'onGameStart' missing your function initially is to place a Timer to delay the event for a short while. Just a second or so to allow the game to load completely. CallAt takes two arguments, the time of action and a function to be carried out. Example form the Timer documentation:

Timer:CallAt(Game.time+30, function ()
    Comms.Message("Special offer expired, sorry.")
end)

A complete example of the welcome message reworked with a timer. 'Game.time' gives us the game time right now so if we call the timer with 'Game.time + 1' we give it a second to think things through.

local Comms = require 'Comms'
local Game = require 'Game'
local Event = require 'Event'
local Timer = require 'Timer'

local onGameStart = function ()
    if not Game.player then return end

    Timer:CallAt(Game.time + 1, function ()
        Comms.Message ('Welcome to Pioneer!')
    end)
end

Event.Register("onGameStart", onGameStart)

Event arguments

As mentioned before onShipDocked passes two arguments to the function. A reference to the ship and a reference to the spacestation.

local onShipDocked = function (ship, station)

Through these arguments we also get access to some of the 'ship' and 'station' methods without having to include any modules. 'ship:IsPlayer()' is for free. Unlimited power is now at your fingertips! 'Comms.Message' takes a second argument for the sender of the message. 'station.label' gives us the name of the space station.

Comms.Message ("Congratulations! Your ship has been upgraded for free!", station.label)
ship:SetShipType('xylophis')

More events

An event can be registered only once per file. If you need more than one function called by the same event you must wrap them in a function.

Example from /data/modules/MusicPlayer.lua:

Event.Register("onGameStart", function ()
    MusicPlayer.rebuildSongList()
    if Game.player:GetDockedWith() and music["docked"] then
        MusicPlayer.playRandomSongFromCategory("docked")
    else)
        playAmbient()
    end
end)

If you register an event more than once in the same file only the last instance will be registered and you will see a log warning on the command line and in output.txt.

Example: test_module_1.lua

Event.Register("onGameStart", function ()
    print("Only the first instance of onGameStart() will be registered")
end)

Event.Register("onGameStart", function ()
    print("Only the last instance of onGameStart() will be registered")
end)

Output. Warning and message:

...
Info: Loading [00%]: Sound::Init took 11.47ms
Info: Loading [08%]: Lua::InitModules() started
Warning: Module modules.test_module_1 overwriting event callback function: 0x57d5ed8b5d50
Info: Loading [08%]: Lua::InitModules() took 84.46ms
Info: Loading [17%]: GalaxyGenerator::Init() started
Info: Creating new galaxy generator 'legacy' version  
...
Info: building follow-on industry distillery after surface_aquaponics at station Pluto Research Base
Info: PROFILE | Economy.PrecacheSystem("Sol") took 2.4609ms
Info: Only the last instance of onGameStart() will be registered
Warning: lodos_shield.model: no materials defined!
Info: CreateCollisionMesh for : (lodos_shield)
...

Use instead:

local message1 = function ()
	print("This is message1 calling!")
end

local message2 = function ()
	print("This is message2 calling!")
end

Event.Register("onGameStart", function()
	message1()
	message2()
end)

output:

...
Info: building follow-on industry distillery after surface_aquaponics at station Pluto Research Base
Info: PROFILE | Economy.PrecacheSystem("Sol") took 2.4510ms
Info: This is message1 calling!
Info: This is message2 calling!
Warning: skipjack_shield.model: no materials defined!
Info: CreateCollisionMesh for : (skipjack_shield)
...

Events can be registered anytime and anywhere in a file but typically they are grouped at the end of a file/module.

If you need to redirect an event to another function you need to first deregister the event.

local Game = require 'Game'
local Event = require 'Event'

local message1 = function ()
    print("This is message1 calling!")
end

local message2 = function ()
    print("This is message2 calling!")
end

Event.Register("onGameStart", message1)

print("Now deregistering 'onGameStart message1' and registering 'onGameStart message2'")
print("No warning message will be given below")
Event.Deregister("onGameStart", message1)
Event.Register("onGameStart", message2)
print("See!?")

output:

...
Info: Loading [00%]: Sound::Init took 10.81ms
Info: Loading [08%]: Lua::InitModules() started
Info: Now deregistering 'onGameStart message1' and registering 'onGameStart message2'
Info: No warning message will be given below
Info: See!?
Info: Loading [08%]: Lua::InitModules() took 99.92ms
Info: Loading [17%]: GalaxyGenerator::Init() started
...
Info: building follow-on industry distillery after surface_aquaponics at station Pluto Research Base
Info: PROFILE | Economy.PrecacheSystem("Sol") took 2.4787ms
Info: This is message2 calling!
Warning: storeria_shield.model: no materials defined!
Info: CreateCollisionMesh for : (storeria_shield)
...