User Tools

Site Tools


events
no way to compare when less than two revisions

Differences

This shows you the differences between two versions of the page.


events [2020/05/22 12:23] (current) – created maxime
Line 1: Line 1:
 +====== Events ======
 +
 +Some core types use events. These events can be used to run a function when a certain trigger happens on a specific object.
 +
 +===== Triggering events =====
 +
 +To trigger an event on an object, call this event from the chosen object. Events are designed to be triggered by their owner, and listened to by other objects.
 +
 +For example, if you create a new component type extending ''COMP_WORKPLACE'', you can do the following in one of this type's function:
 +
 +<code lua>
 +myCustomWorkplace.registerVillager = function(villager)
 +    ...
 +    self.ON_ASSIGNED_WORKER_CHANGED(villager)
 +    ...
 +end
 +</code>
 +
 +===== Registering to events =====
 +
 +When you create a custom type, objects of this type can listen to event triggers, and run functions when those events are triggered. For this, you use three new event-specific functions in the ''event'' table.
 +
 +==== register ====
 +
 +Register to an event triggered on a specific target object.
 +
 +''void **event.register**(//target//, //objectEvent//, //callback//)''
 +
 +^ Name ^ Type ^ Description ^
 +| //''target''// | ''userdata'' | ''the target custom-type object'' |
 +| //''objectEvent''// | ''event'' |  |
 +| //''callback''// | ''function'' | Must have the same parameters as the event |
 +
 +<code lua>
 +local compMainGameLoop = getLevel():find("COMP_MAIN_GAME_LOOP")
 +event.register(self, compMainGameLoop.ON_NEW_DAY, function()
 + myMod:log("New day!")
 +end)
 +
 +local parentBuilding = getOwner():findFirstObjectWithComponentUp("COMP_BUILDING")
 +event.register(self, parentBuilding.ON_CUSTOM_NAME_CHANGED, function(newName)
 + myMod:log("Building name changed to " .. newName)
 +end)
 +</code>
 +
 +==== unregister ====
 +
 +Stops listening to an event registered on a specific target object.
 +
 +''void **event.unregister**(//target//, //objectEvent//)''
 +
 +^ Name ^ Type ^ Description ^
 +| //''target''// | ''userdata'' | ''the target custom-type object'' |
 +| //''objectEvent''// | ''event'' |  |
 +
 +<code lua>
 +local compMainGameLoop = getLevel():find("COMP_MAIN_GAME_LOOP")
 +event.unregister(self, compMainGameLoop.ON_NEW_DAY)
 +</code>
 +
 +==== clear ====
 +
 +Stops listening to all events registered on the target object
 +
 +''void **event.clear**(//target//)''
 +
 +^ Name ^ Type ^ Description ^
 +| //''target''// | ''userdata'' | ''the target custom-type object'' |
  
events.txt · Last modified: 2020/05/22 12:23 by maxime

Donate Powered by PHP Valid HTML5 Valid CSS Driven by DokuWiki