Easily add chat commands in your game

edited January 2017 in Tutorials

I started trying out dota2 modding a few days ago and created a class that allows you to add a command to any function with only one line of code.

By using this code you won't need to execute all functions that are linked with player_chat and check whether the chat contained the command or not, nor do you have to create one superclass containing all the commands and going through them with if..else.
These links are also dynamically evaluated at runtime, so they won't break when you use script_reload.

One function is called every chat. This one calls the function linked with the command. Simple, nice and easy.
EDIT: Some help from Discord made it the Simplest, nicest and easiest

First you'll need to add chatcommand.lua and split.lua to your project.

Create a function that should be executed when the command triggers
example 1: function MyFunction(keys) ...
example 2: function anotherClass:MyFunction(keys) ...
keys is the same you'll get from the player_chat event

  • keys.teamonly(bool)
  • keys.userid(short)
  • keys.text(string)

Place somewhere (preferably above your function)
in case of example 1: ChatCommand:LinkCommand("-some_command_without_spaces", "MyFunction")
in case of example 2: ChatCommand:LinkCommand("-some_command_without_spaces", "MyFunction", anotherClass)
"MyFunction" as a string, anotherClass as an object

That's it! When you start your chat with the specified command the function will be triggered.

TIP: You can easily add some arguments after your command : e.g. -gold 322
In your code you can get those arguments easily with
splitted = split(keys.text," ")
local gold = tonumber(splitted[2])