Menu
Coddy logo textTech

Recap - Simple Event Handler

Part of the Logic & Flow section of Coddy's Lua journey — lesson 15 of 54.

challenge icon

Challenge

Easy

Write a function createEventSystem that creates a simple event system with pre-registered events and triggers one based on input parameters.

Logic:

  • Create an empty table to store events inside createEventSystem
  • Define a register function that takes eventName and callback, storing the callback in the events table with the event name as the key
  • Define a trigger function that takes eventName and arg, looks up the callback in the events table, and calls it with the argument if it exists
  • Pre-register three events:
    • "double": takes a number and returns it multiplied by 2
    • "square": takes a number and returns it squared
    • "increment": takes a number and returns it plus 1
  • Trigger the event specified by the eventName parameter with the value parameter
  • Return the result of the triggered event, or "Event not found" if the event doesn't exist

Parameters:

  • eventName (string): The name of the event to trigger
  • value (number): The value to pass to the event callback

Returns:

  • The result of the callback function (number), or "Event not found" if the event doesn't exist (number|string)

Try it yourself

function createEventSystem(eventName, value)
    -- Write code here
end

All lessons in Logic & Flow