Gothic Online Forums
Command handler - Printable Version

+- Gothic Online Forums (https://archive.gothic-online.com)
+-- Forum: Scripting (English) (https://archive.gothic-online.com/forum-11.html)
+--- Forum: Tutorials (https://archive.gothic-online.com/forum-13.html)
+--- Thread: Command handler (/thread-2663.html)



Command handler - Sative - 07.08.2019

Hey folks!

Today i wanna show you the simplest method of handling command functions.
You can use it as well for binding another events.

Code:
local COMMANDS = [];

function registerCommand(cmd, fun)
{
    COMMANDS.push({command = cmd, func = fun});
}

addEventHandler("onCommand", function(cmd, params) {
    foreach(item in COMMANDS) {
        if(item.command == cmd) {
            item.func(params);
        }
    }
});
You need only one array to stacking list of bound commands on it.
Function registerCommand(cmd, function) is used only to push bounded command element on commands stack.
Later, in "addEventHandler" we have only simple foreach loop to find correct command on stack, when it find a correct command then calls connected function with params given in the command.


Example of usage:
Code:
registerCommand("hey", function(params) {
    Chat.print(255, 255, 255, "What's your name?");
});

Now, you can add simple command in 3 lines of code, everywhere in your code Smile
Isn't that simple? Have fun!