Recap - Simple Event Handler
Part of the Logic & Flow section of Coddy's Lua journey — lesson 15 of 54.
Challenge
EasyWrite 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
registerfunction that takeseventNameandcallback, storing the callback in the events table with the event name as the key - Define a
triggerfunction that takeseventNameandarg, 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
eventNameparameter with thevalueparameter - 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 triggervalue(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
1Advanced Table Iteration
Iterating with pairs()Iterating with ipairs()pairs() vs. ipairs()Recap - Character Sheet2More Table Library Functions
table.concat()table construction & unpack()table.sort()Custom Sorting with FunctionsRecap - High Score Board3Advanced Function Concepts
Returning Multiple ValuesVariadic Functions (...)Functions First-Class ValuesAnonymous FunctionsWhat is a Closure?Recap - Simple Event Handler