LUA:Gamemode Features

From GMod Wiki

Revision as of 12:24, 14 June 2010 by Zackiller25 (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

This is a simple tutorial, which will add commands to allow user to drop their weapons.

The tutorial

First of all let's create a bool to toggle usage of soon to be commands.

 
local ShouldDropWeapon = true
 

Now let's create the toggle function that will allow/disallow weapon dropping.

 
local function ToggleDropWeapon(ply)
	if ply:IsAdmin() then
		if ShouldDropWeapon then --Because ShouldDropWeapon is a bool, it'll be a true or false.
                        --If true then
			ply:PrintMessage(HUD_PRINTNOTIFY, "Weapon drop disabled") --Tell us if it is enabled.
			ShouldDropWeapon = false
		else --Else do
			ply:PrintMessage(HUD_PRINTNOTIFY, "Weapon drop enabled")
			ShouldDropWeapon = true
		end
	end
end
 

Now let's create the function which will make the magic happen!

 
local function PlayerDropWeapon(ply)
	if ShouldDropWeapon and ply:GetActiveWeapon():IsValid()) then --If weapon dropping is enabled, and player's weapon is valid.
		ply:DropWeapon(ply:GetActiveWeapon()) --Drop active weapon
	end
end
 

Now let's add a hook what will make the player drop his weapon on death.

 
hook.Add("DoPlayerDeath", "Player.DropWeapon", PlayerDropWeapon)
 

Not let's create two commands! One what will make the player using the command drop his weapon. Another, what will toggle usage of the function PlayerDropWeapon.

 
concommand.Add( "player_dropweapon", PlayerDropWeapon) --Make user drop his weapon.
concommand.Add( "player_dropweapon_toggle", ToggleDropWeapon)  --Toggle usage of PlayerDropWeapon
 

That's it!

Full code

Here the full code:

 
local ShouldDropWeapon = true
 
local function ToggleDropWeapon(ply)
	if ply:IsAdmin() then
		if ShouldDropWeapon then --Because ShouldDropWeapon is a bool, it'll be a true or false.
                        --If true then
			ply:PrintMessage(HUD_PRINTNOTIFY, "Weapon drop disabled") --Tell us if it is enabled.
			ShouldDropWeapon = false
		else --Else do
			ply:PrintMessage(HUD_PRINTNOTIFY, "Weapon drop enabled")
			ShouldDropWeapon = true
		end
	end
end
concommand.Add( "player_dropweapon_toggle", ToggleDropWeapon)  --Toggle usage of PlayerDropWeapon
 
local function PlayerDropWeapon(ply)
	if ShouldDropWeapon and ply:GetActiveWeapon():IsValid()) then --If weapon dropping is enabled, and player's weapon is valid.
		ply:DropWeapon(ply:GetActiveWeapon()) --Drop active weapon
	end
end
hook.Add("DoPlayerDeath", "Player.DropWeapon", PlayerDropWeapon)
concommand.Add( "player_dropweapon", PlayerDropWeapon) --Make user drop his weapon.
 

Functions and elements used

If you don't understand something in this tutorial, you should read up on these.

Personal tools
Namespaces
Variants
Actions
Navigation
Lua Scripting
Functions
Hooks
Toolbox