Manual:Functions vs expandAlias
Why use functions vs expandAlias()
Often times when adding functionality to Mudlet for your game, you'll make an alias, and then end up deciding you want to do the same thing from a trigger. It's not uncommon at this point to consider using expandAlias() with the alias you would use to run it from the command line. There are a few reasons to avoid using expandAlias() however.
- expandAlias() has the potential to cause infinite loops by an alias calling itself
- using expandAlias() complicates the workflow by calling out to the alias engine rather than just executing lua in the initial trigger. With expandAlias() you go from lua execution -> alias matcher -> lua execution, whereas using functions it is all just lua execution.
- Getting in the habit of using functions helps make your code reusable and consistent, rather than functions for some things and expandAlias() for those things you've made aliases for.
- Using functions also discourages using the command line separator in your scripts, as this is something which can be changed that can break your entire script if you're making use of it with expandAlias().
- Using functions in scripts allows you to group functionality together, editing the code that accomplishes the tasks side by side rather than in different aliases or triggers.
Ok, so how do I use a function instead?
I'm glad you asked! Let's say you have an alias to repeat something every X seconds. `doEvery <timeToWait> <thingToSend>`. For the below examples, Alias: means create an alias in the mudlet editor with the following name. IE ` Alias: doEvery ` means to make an alias named doEvery. Script: means the same, but a script instead of an alias.
- ^doEvery (\d+) (.*)$
expandAlias("stopEvery") send(matches) doEveryTimer = tempTimer(tonumber(matches), function () expandAlias("doEvery " .. matches .. " " .. matches) end)
if doEveryTimer and exists(doEveryTimer, "timer") then killTimer(doEveryTimer) end
Using functions instead
function doEvery(timeToWait, action) if doEveryTimer then stopEvery() end send(action) doEveryTimer = tempTimer(timeToWait, function () doEvery(timeToWait,action) end) end function stopEvery() if exists(doEveryTimer,"timer") then killTimer(doEveryTimer) end end
- ^doEvery (\d+) (.*)$