Event System in STDLIB

Place to get help with not working mods / modding interface.
Nexela
Smart Inserter
Smart Inserter
Posts: 1828
Joined: Wed May 25, 2016 11:09 am
Contact:

Re: Event System in STDLIB

Post by Nexela »

Slightly branching from the on tick discussion the best use of STDLIB Event is registering multiple handlers for something like this

control - requires scriptA and scriptB

script A and B both have on_build events for different things (or even on_init events etc)

Without the events system you would have a big IF block or for loop in control since calling script.on a second time would overwrite the first one. With STDLIB you can register the on_build in both scriptA and scriptB, essentially keeping all of your scripts separated instead of intermingling them making changes and updates harder. And also you can selectively enable or disable each event handler as needed. Basically treat Event.register the same you would Script.on just with the added feature of more then 1 function per event.

Another area where it REALLY shines is with the GUI stuff (might not be the exact syntax but from the top of my head)

GUI.on_click("Name-of-gui-widget", functiontodo()") is a LOT easier then writing one huge monolithic IF clicked then block for every element with a clickie"

User avatar
aubergine18
Smart Inserter
Smart Inserter
Posts: 1264
Joined: Fri Jul 22, 2016 8:51 pm
Contact:

Re: Event System in STDLIB

Post by aubergine18 »

I'd been doing stuff like this for gui events (this is pseudo code for clarity, obviously I'm not storing functions in `global` objects) to avoid massive nested if-elseif-else-end statements...

Code: Select all

global.onClick = {}

global.onClick['element1Name'] = fnHandler1
global.onClick['element2Name'] = fnHandler2

script.on_event( defines.events.on_gui_click, function(event)
  local name = event.element.valid and event.element.name or nil
  return name and global.onClick[name] and global.onClick[name](event)
end )
What I would really love is if the API had two functions - one for registering event handlers and one for unregistering them, for example:

Code: Select all

script.on_event( <eventId>, <function>[, <filter>] )

script.clear_event( <eventId>[, <function>][, <filter>] )
This way I could register multiple handler functions for same event, optionally filtering them. And if I have ref to the function and/or filter, I can clear specific handler.
Better forum search for modders: Enclose your search term in quotes, eg. "font_color" or "custom-input" - it prevents the forum search from splitting on hypens and underscores, resulting in much more accurate results.

Post Reply

Return to “Modding help”