LevelUpMessage: Here we use the API function Say to show a message to all players.

Activate: The game calls this function when it loads the addon. We want the game to call LevelUpMessage every time a player levels up. To do this we call the API function ListenToGameEvent with "dota_player_gained_level" and LevelUpMessage as arguments.

Here you can use either nil or an object (for example, a table or a function). If you use an object here, then it will be passed as the first argument to your function when the event happens.

Event details

By calling ListenToGameEvent with an event name and a function, you tell the game to call that function every time the event happens. When the game calls the function, it passes a table as an argument to it. This table contains details of the event. On the page Built-In Engine Events you can see which keys the table has. For example, on this page you can see that the table for "dota_player_gained_level" has a key called level (cf. Example 2 above).

Warning: Because Valve sometimes change the events, the list Built-In Engine Events is not always accurate. You can use the pairs function to see which keys a table has:

Replace ? with the object that you want to use as self in your function. Here is an example:

Example 3

When an NPC spawns, we print the total number of times this has happened:

-- scripts/vscripts/addon_game_mode.luaifMyClass==nilthenMyClass=class({})endfunctionMyClass:InitGameMode()self.numSpawned=0ListenToGameEvent("npc_spawned",MyClass.MyFunction,self)endfunctionMyClass:MyFunction()self.numSpawned=self.numSpawned+1print("Number of times an NPC has spawned: "..self.numSpawned)endfunctionActivate()GameRules.MyAddon=MyClass()GameRules.MyAddon:InitGameMode()end

Tip:You can use the RollPercentage function to introduce a drop chance.

FAQ

Question: What does Dynamic_Wrap do?

Answer: Use Dynamic_Wrap if you want the console command "script_reload" to also reload your listeners.

Tip:The source code of Dynamic_Wrap can be found here: /path/to/Steam/SteamApps/common/dota 2 beta/game/core/scripts/vscripts/utils/vscriptinit.lua.

Here are some more details: Suppose you have registered a listener like this:

ListenToGameEvent("some_event_name",MyClass.MyFunction,someObj)

If you change the source code of MyClass.MyFunction and then type "script_reload" in the console, your change will not be visible. It will still be the old version of MyClass.MyFunction that gets called when the event happens. To fix this, you can use Dynamic_Wrap:

Now, every time the event happens, the game will look up the field MyFunction on MyClass and then run the function this field points to. When you change the source code of MyClass.MyFunction and then type "script_reload" in the console, the MyFunction field will be updated. So when the event happens, the game will run the new version of the function.