Author Topic: multi_events.lua: Register multiple functions on an event  (Read 1124 times)

Christopho

  • Administrator
  • Hero Member
  • *****
  • Posts: 1041
    • View Profile
multi_events.lua: Register multiple functions on an event
« on: October 20, 2016, 03:18:55 pm »
I already talked about the multi_events.lua script in another topic, but let's share it in this forum because most scripts to be shared by the community will need it. Indeed, scripts that use it can be more self-contained, and therefore easier to share, which is the goal of this forum.

Scripts that I will share it on this forum, as well as the ones you can already find in the Zelda OLB Solarus Edition project, almost always use this feature.

So what is it?

This multi_events.lua script allows to register several functions to a single event, for example game:on_started().

Motivation

You often have a lot of scripts: the dialog box, the HUD, the pause menu, the camera manager, etc., and all these components need to do some stuff in the same event, for example they all need to perform some initialization in game:on_started(). One way to do it is to define the game:on_started() event in your game_manager.lua script, and from there, call the initialization code of each component (the dialog box, the HUD, the pause menu, the camera manager, etc). You can guess the problem: whenever you create a new component that also needs to do something in game:on_started(), you need to modify your game_manager.lua script again. This is because game:on_started() can be defined only once (or it would overwrite the previous definition). And then when you want to share your nice new feature on this forum, you need to tell people how to modifiy they game_manager.lua script. Not as easy as just copying a Lua script file. This is only an exemple, the same is true for a lot of other events (not only game:on_started()).

As an example, our previous games all have this issue. Here is the game:on_started() event from Zelda ROTH SE:
Code: Lua
  1. function game:on_started()
  2.  
  3.   dungeon_manager:create(game)
  4.   equipment_manager:create(game)
  5.   dialog_box = dialog_box_manager:create(game)
  6.   hud = hud_manager:create(game)
  7.   pause_menu = pause_manager:create(game)
  8.   camera = camera_manager:create(game)
  9.  
  10.   -- Initialize the hero.
  11.   local hero = game:get_hero()
  12.   game:stop_rabbit()  -- In case the game was saved as a rabbit.
  13.   update_walking_speed()
  14.  
  15.   -- Measure the time played.
  16.   run_chronometer(game)
  17. end
  18.  
As described above, we initialize all components. Components are usually defined in their own separate Lua scripts of course, but there is still this central initialization code needed. It is a bit delicate to share one of these features with you (like for example, the transformation of Link into a rabbit), because you would have not only to copy the rabbit.lua script, but also this initialization code. And actually even more, because in fact, rabbit.lua also needs to do stuff in game:on_game_over_started() and in hero:on_state_changed()… Very easy to miss things and to introduce bugs when you want the feature in your project.

So, it would be great if there was a way to define multiple functions to be called when a single event occurs, right? This is precisely what multi_events.lua script does. By using a different syntax, you can register several functions to the same event. Which means that in our examples above, you no longer need to modifiy existing scripts every time you import a script from some other project! Well, you still need to require() the script somewhere, but that's it.

Now in Zelda OLB SE, one of our new projects, the game_manager.lua script no longer defines game:on_started() at all. Instead, every component (dungeons, equipment, dialog box, HUD, pause menu, camera, rabbit manager, chronometer, etc.) registers its own stuff to be done in game:on_started(). The game manager remains unchanged when features are added or removed from the project. The whole rabbit code is contained in a single script now (and actually I will share it on this forum very soon).

So, this is extremely useful to make scripts as much independent and self-contained as possible. Basically, they become much easier to share.

How to use it?

- Copy the multi_events.lua script below to your project, into the scripts/ folder.
- Just require("scripts/multi_events.lua") at some point in your project (like from main.lua).
- In your scripts for all events, you now have the choice between two approaches: the traditional one or the multi-functions one, using object:register_event(event_name, callback).

Examples:

Code: Lua
  1. -- The traditional way still works:
  2. function my_sprite:on_animation_finished()
  3.   -- blah blah
  4. end
  5.  

Code: Lua
  1. local map = ...
  2.  
  3. require("multi_events")
  4.  
  5. -- This approach allows to register several functions to the same event:
  6. map:register_event("on_started", function()
  7.         -- blah blah
  8. end)
  9.  
  10. map:register_event("on_started", function()
  11.         -- other stuff
  12. end)
  13.  

The code!

Script: scripts/multi_events.lua
License: GPL v3
Author: Christopho
URL: https://github.com/solarus-games/zelda-olb-se/blob/dev/data/scripts/multi_events.lua
Code: Lua
  1. -- This script allows to register multiple functions as Solarus events.
  2. --
  3. -- Usage:
  4. --
  5. -- Just require() this script and then all Solarus types
  6. -- will have a register_event() method that adds an event callback.
  7. --
  8. -- Example:
  9. --
  10. -- local multi_events = require("scripts/multi_events")
  11. --
  12. -- -- Register two callbacks for the game:on_started() event:
  13. -- game:register_event("on_started", my_function)
  14. -- game:register_event("on_started", another_function)
  15. --
  16. -- -- It even works on metatables!
  17. -- game_meta:register_event("on_started", my_function)
  18. -- game_meta:register_event("on_started", another_function)
  19. --
  20. -- The good old way of defining an event still works
  21. -- (but you cannot mix both approaches on the same object):
  22. -- function game:on_started()
  23. --   -- Some code.
  24. -- end
  25. --
  26. -- Limitations:
  27. --
  28. -- Menus are regular Lua tables and not a proper Solarus type.
  29. -- They can also support multiple events, but to do so you first have
  30. -- to enable the feature explicitly like this:
  31. -- multi_events:enable(my_menu)
  32. -- Note that sol.main does not have this constraint even if it is also
  33. -- a regular Lua table.
  34.  
  35. local multi_events = {}
  36.  
  37. local function register_event(object, event_name, callback)
  38.  
  39.   local previous_callbacks = object[event_name] or function() end
  40.   object[event_name] = function(...)
  41.     return previous_callbacks(...) or callback(...)
  42.   end
  43. end
  44.  
  45. -- Adds the multi event register_event() feature to an object
  46. -- (userdata, userdata metatable or table).
  47. function multi_events:enable(object)
  48.   object.register_event = register_event
  49. end
  50.  
  51. local types = {
  52.   "game",
  53.   "map",
  54.   "item",
  55.   "surface",
  56.   "text_surface",
  57.   "sprite",
  58.   "timer",
  59.   "movement",
  60.   "straight_movement",
  61.   "target_movement",
  62.   "random_movement",
  63.   "path_movement",
  64.   "random_path_movement",
  65.   "path_finding_movement",
  66.   "circle_movement",
  67.   "jump_movement",
  68.   "pixel_movement",
  69.   "hero",
  70.   "dynamic_tile",
  71.   "teletransporter",
  72.   "destination",
  73.   "pickable",
  74.   "destructible",
  75.   "carried_object",
  76.   "chest",
  77.   "shop_treasure",
  78.   "enemy",
  79.   "npc",
  80.   "block",
  81.   "jumper",
  82.   "switch",
  83.   "sensor",
  84.   "separator",
  85.   "wall",
  86.   "crystal",
  87.   "crystal_block",
  88.   "stream",
  89.   "door",
  90.   "stairs",
  91.   "bomb",
  92.   "explosion",
  93.   "fire",
  94.   "arrow",
  95.   "hookshot",
  96.   "boomerang",
  97.   "camera",
  98.   "custom_entity"
  99. }
  100.  
  101. -- Add the register_event function to all userdata types.
  102. for _, type in ipairs(types) do
  103.  
  104.   local meta = sol.main.get_metatable(type)
  105.   assert(meta ~= nil)
  106.   multi_events:enable(meta)
  107. end
  108.  
  109. -- Also add it to sol.main (which is a regular table).
  110. multi_events:enable(sol.main)
  111.  
  112. return multi_events
  113.  
  114.  
« Last Edit: October 26, 2016, 03:17:59 pm by Christopho »

llamazing

  • Jr. Member
  • **
  • Posts: 73
    • View Profile
Re: Register multiple functions on an event
« Reply #1 on: October 21, 2016, 08:20:13 am »
On line 39, why do you create the empty function? Isn't that wasteful? Couldn't you just do the following instead? Lines 39 and 41 are modified.

Code: Lua
  1. local function register_event(object, event_name, callback)
  2.  
  3.   local previous_callbacks = object[event_name]
  4.   object[event_name] = function(...)
  5.     return previous_callbacks and previous_callbacks(...) or callback(...)
  6.   end
  7. end

Christopho

  • Administrator
  • Hero Member
  • *****
  • Posts: 1041
    • View Profile
Re: Register multiple functions on an event
« Reply #2 on: October 21, 2016, 08:55:38 am »
Both approaches should be equivalent I think. It is a matter of taste. To me, the and+or version is a bit less readable. It makes one additional test. Also, when defining a recursive algorithm it is nice to show explicitly the an initial value, which is often an empty list, or in this particular case, an empty function. Like in functional programming.
But again, this is equivalent, there is no real problem with your suggestion.

MetalZelda

  • Hero Member
  • *****
  • Posts: 504
    • View Profile
Re: multi_events.lua: Register multiple functions on an event
« Reply #3 on: January 27, 2017, 11:42:29 pm »
Interesting, using the multiple event for game:save() makes the game un-save-able, calling game:save() returns nil

Christopho

  • Administrator
  • Hero Member
  • *****
  • Posts: 1041
    • View Profile
Re: multi_events.lua: Register multiple functions on an event
« Reply #4 on: January 28, 2017, 01:58:57 am »
What do you mean? game:save() is a normal function, not an event.

MetalZelda

  • Hero Member
  • *****
  • Posts: 504
    • View Profile
Re: multi_events.lua: Register multiple functions on an event
« Reply #5 on: January 28, 2017, 03:39:35 am »
Oh right I didn't take that in consideration