### General Server Script Setup with AddCSLuaFile and include
Source: https://wiki.facepunch.com/gmod/Understanding_AddCSLuaFile_and_include~diff%3A563178
This example shows a typical setup in an init.lua file, where clientside scripts are sent to the client and shared scripts are included for server-side use.
```lua
AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
```
--------------------------------
### Premake5.lua Project Setup
Source: https://wiki.facepunch.com/gmod/Binary_Modules_Detouring_Functions~diff%3A561096
Example of how to set up your premake5.lua file to include the detouring and scanning submodules.
```lua
CreateWorkspace({
name = "[Your Project]",
abi_compatible = false
})
CreateProject({
serverside = [true or false],
manual_files = false
})
[Your includes ...]
IncludeHelpersExtended()
IncludeDetouring()
IncludeScanning()
```
--------------------------------
### Complete DPanel Setup Example
Source: https://wiki.facepunch.com/gmod/Introduction_To_Using_Derma~diff%3A564592
This example demonstrates creating a DPanel, setting its size, position, background color, and ensuring it's visible. Note that `SetPaintBackground(true)` is required for `SetBackgroundColor` to take effect.
```lua
-- Create the DPanel
local myFirstPanel = vgui.Create( "DPanel" )
-- Set its size (Width: 200px, Height: 100px)
myFirstPanel:SetSize( 200, 100 )
-- Set its position (X: 300px from left, Y: 200px from top)
-- (Trying slightly different coords for visibility)
myFirstPanel:SetPos( 300, 200 )
-- Make it paint its background
myFirstPanel:SetPaintBackground( true )
-- Set the background color to blue (R=0, G=0, B=255, Alpha=255)
myFirstPanel:SetBackgroundColor( Color( 0, 0, 255, 255 ) )
-- Make sure it's v
```
--------------------------------
### Player:StartSprinting Example
Source: https://wiki.facepunch.com/gmod/Player%3AStartSprinting~diff%3A527166
Provides an alternative implementation for starting a sprint. It uses a hook to detect forward movement and a timer to enable sprinting after a delay.
```lua
local vDelay = 0
local prevDown = 0
hook.Add( "StartCommand", "TestFunc", function( ply, cmd )
if ( cmd:KeyDown( IN_FORWARD ) and prevDown == false ) then
vDelay = CurTime() + 0.4
elseif ( cmd:KeyDown( IN_FORWARD ) ) then
if ( vDelay < CurTime() )then
cmd:SetButtons( bit.bor( cmd:GetButtons(), IN_SPEED ) )
end
end
prevDown = cmd:KeyDown(IN_FORWARD)
prevDown = cmd:KeyDown( IN_FORWARD )
end )
```
--------------------------------
### UGCPublishWindow:Setup
Source: https://wiki.facepunch.com/gmod/UGCPublishWindow%3ASetup~diff%3A561793
The Setup function initializes the UGCPublishWindow panel for publishing Workshop items. It takes arguments specifying the UGC type, the file to publish, an associated image file, and a handler object.
```APIDOC
## UGCPublishWindow:Setup
### Description
Initializes the UGCPublishWindow panel for publishing Workshop items.
### Method
panelfunc
### Arguments
- **ugcType** (type) - The type / namespace of the WorkshopFileBase that created this panel
- **file** (string) - The File to publish
- **imageFile** (string) - The Image
- **handler** (WorkshopFileBase) - The WorkshopFileBase that created this panel
```
--------------------------------
### Basics - Getting Started
Source: https://wiki.facepunch.com/gmod/~pagelist?p=0&sort=
Introductory tutorial for getting started with Garry's Mod development.
```APIDOC
## Beginner_Tutorial_Intro
### Description
Introduction to Garry's Mod development.
### Endpoint
N/A (Internal API/Concept)
```
--------------------------------
### Get Sequence Ground Speed for Movement
Source: https://wiki.facepunch.com/gmod/Entity%3AGetSequenceGroundSpeed
This example demonstrates how to get the ground speed of a walking animation and set it as the desired speed for an entity's locomotion. It first looks up the sequence ID for 'walk_all', then starts the ACT_WALK activity, sets the sequence, and finally uses the retrieved ground speed to configure the entity's movement. Ensure the sequence ID is valid before proceeding.
```lua
local sequence = self:LookupSequence( "walk_all" ) if ( sequence ) then self:StartActivity( ACT_WALK ) self:SetSequence( sequence ) self.loco:SetDesiredSpeed( self:GetSequenceGroundSpeed( sequence ) ) end
```
--------------------------------
### Setup Data Tables with NetworkVars
Source: https://wiki.facepunch.com/gmod/Entity%3ANetworkVar~diff%3A564533
Use Entity:NetworkVar within ENTITY:SetupDataTables to define network variables for an entity. You can specify the type, slot, and name for each variable. Slots can be omitted, and arguments will shift accordingly. Examples show setting and getting values for these variables.
```lua
function ENT:SetupDataTables()
self:NetworkVar( "Float", 0, "Amount" )
self:NetworkVar( "Vector", "StartPos" ) -- note arguments shift if slot is omitted
sself:NetworkVar( "Vector", "EndPos" )
end
-- Code...
-- Setting values on the entity
self:SetStartPos( Vector( 1, 0, 0 ) )
self:SetAmount( 100 )
-- Code...
-- Getting values
local startpos = self:GetStartPos()
```
--------------------------------
### Basic Render Target Setup and Drawing
Source: https://wiki.facepunch.com/gmod/render_rendertargets~diff%3A561324
This example demonstrates creating a Render Target, a corresponding Material, and then drawing both 2D and 3D content onto it before displaying it on screen. Ensure you have the necessary models and materials available.
```lua
-- Create the Render Target we'll be using throughout this example
local renderTarget = GetRenderTarget(
"RenderTargetExample", -- The name of the Render Target's Texture
1024, 1024 -- The size of the Render Target
)
-- Create a Material that corresponds to the Render Target we just made
local renderTargetMaterial = CreateMaterial(
"RenderTargetExampleMaterial", -- All Materials need a name
"UnlitGeneric", -- This shader will work great for drawing onto the screen, but can't be used on models
-- To use this material on a model, this would need to use the "VertexLitGeneric" shader.
{
["$basetexture"] = renderTarget:GetName(), -- Use our Render Target as the Texture for this Material
["$translucent"] = "1", -- Without this, the Material will be fully opaque and any translucency won't be shown
}
)
-- Used later for some 3D rendering
local clientsideModel = ClientsideModel( "models/props_lab/huladoll.mdl", RENDERGROUP_OPAQUE )
clientsideModel:SetNoDraw( true )
-- An all-white material is built-in to the game
local colorMaterial = Material( "color" )
-- This function just gives us something to draw that uses a 2D context
-- It can be replaced with any other 2D drawing operation(s)
local function DrawSomething2D()
surface.SetMaterial( colorMaterial )
surface.SetDrawColor( Color( 255, 0, 255, 200 ) )
surface.DrawTexturedRectRotated( ScrW()/2, ScrH()/2, 500, 500, ( CurTime() * 200 ) % 360 )
end
-- Same as DrawSomething2D, but with 3D content
local function DrawSomething3D()
-- To brighten the model without setting up lighting
render.SuppressEngineLighting( true )
-- By default, 3D rendering to a Render Target will put the Depth Buffer into the alpha channel of the image.
-- I do not know why this is the case, but we can disable that behavior with this function.
render.SetWriteDepthToDestAlpha( false )
render.Model( {
model = "models/props_lab/huladoll.mdl",
-- You can ignore this math, it's just to make the hula doll do a little dance
pos = Vector( 20, -math.sin( CurTime() * 7.5 ) * 0.35, -3.5 ),
angle = Angle( 0, 180 + math.sin( CurTime() * 7.5 ) * 7, math.sin( CurTime() * 7.5 ) * 15 )
}, clientsideModel )
render.SetWriteDepthToDestAlpha( true )
render.SuppressEngineLighting( false )
end
-- In a hook that runs every frame, draw to the Render Target
-- Note: You could use any hook for this.
hook.Add( "PreDrawEffects", "DrawingToExampleRenderTarget", function( isDrawingDepth, isDrawingSkybox, isDrawing3dSkybox )
-- Start drawing onto our render target
render.PushRenderTarget( renderTarget )
-- Remove the Render Target's contents from the previous frame so we can draw a new one on a fresh "canvas"
render.Clear( 0, 255, 0, 200, true, true )
-- Start drawing in a 2D context
-- By default this hook provides a 3D context, so we need to change it.
```
--------------------------------
### Get Entity Model Scale
Source: https://wiki.facepunch.com/gmod/Entity%3AGetModelScale
Retrieves the model scale of an entity. This example shows how to get the model scale of entity with ID 1.
```Lua
print( Entity(1):GetModelScale() )
```
--------------------------------
### Get Player Color Example
Source: https://wiki.facepunch.com/gmod/Entity%3AGetColor~diff%3A527749
Loops through all players on the server and prints their color to the console. This example demonstrates retrieving and displaying entity colors.
```lua
for key, ply in pairs( player.GetAll( ) ) do -- Loop through all players on the server
local col = ply:GetColor( ); -- Gets the players color and assigns it to local variable col
for key, ply in ipairs( player.GetAll() ) do -- Loop through all players on the server
local col = ply:GetColor() -- Gets the players color and assigns it to local variable col
print( "Printing " .. ply:Nick() .. "'s color!" ); -- Say we are printing the players name's color
PrintTable( col ); -- Pass col into PrintTable to print to contents of col
print( "Printing " .. ply:Nick() .. "'s color!" ) -- Say we are printing the players name's color
PrintTable( col ) -- Pass col into PrintTable to print to contents of col
end
```
--------------------------------
### Example .properties file content
Source: https://wiki.facepunch.com/gmod/Addon_Localization~diff%3A528216
This is an example of a .properties file used for localization. Lines starting with '#' are comments. Each line is a key-value pair separated by '='.
```properties
spawnmenu.content_tab=Spawnlists
spawnmenu.category.npcs=NPCs
spawnmenu.category.addons=Addons
spawnmenu.category.weapons=Weapons
spawnmenu.category.postprocess=Post Process
spawnmenu.category.your_spawnlists=Your Spawnlists
spawnmenu.category.addon_spawnlists=Addon Spawnlists
spawnmenu.category.games=Games
spawnmenu.category.browse=Browse
spawnmenu.category.entities=Entities
spawnmenu.category.vehicles=Vehicles
spawnmenu.category.creations=Creations
spawnmenu.category.dupes=Dupes
spawnmenu.category.saves=Saves
```
--------------------------------
### Premake5 Command-Line Execution Examples
Source: https://wiki.facepunch.com/gmod/Creating_Binary_Modules%3A_Premake~diff%3A561069
These commands demonstrate how to invoke Premake5 to generate project files for different platforms and IDEs. Ensure you replace placeholders like `vs2022` with your specific IDE version.
```bash
premake5.exe --os=windows --gmcommon=./garrysmod_common vs2022
```
```bash
./premake5 --os=linux --gmcommon=./garrysmod_common gmake2
```
```bash
./premake5 --os=macosx --gmcommon=./garrysmod_common xcode4
```
--------------------------------
### Hook GM:StartChat Example
Source: https://wiki.facepunch.com/gmod/GM%3AStartChat
This example demonstrates how to hook into the GM:StartChat event to detect when a player starts typing in team chat or regular chat.
```lua
hook.Add( "StartChat", "HasStartedTyping", function( isTeamChat ) if ( isTeamChat ) then print( "Player started typing a message in teamchat." ) else print( "Player started typing a message." ) end end )
```
--------------------------------
### Basic Render Target Setup and Usage
Source: https://wiki.facepunch.com/gmod/render_rendertargets~diff%3A563150
This example demonstrates creating a Render Target, a corresponding material, and setting up a basic 2D drawing context. It's a foundational snippet for using Render Targets.
```lua
-- Create the Render Target we'll be using throughout this example
local renderTarget = GetRenderTarget( "RenderTargetExample", -- The name we'll call new Render Target's Texture
1024, 1024 -- The size of the Render Target
)
-- Create a Material that corresponds to the Render Target we just made
local renderTargetMaterial = CreateMaterial( "RenderTargetExampleMaterial", -- All Materials need a name
"UnlitGeneric", -- This shader will work great for drawing onto the screen, but can't be used on models
-- To use this material on a model, this would need to use the "VertexLitGeneric" shader.
{
["$basetexture"] = renderTarget:GetName(), -- Use our Render Target as the Texture for this Material
["$translucent"] = "1", -- Without this, the Material will be fully opaque and any translucency won't be shown
}
)
-- Used later for some 3D rendering
local clientsideModel = ClientsideModel( "models/props_lab/huladoll.mdl", RENDERGROUP_OPAQUE )
clientsideModel:SetNoDraw( true )
-- An all-white material is built-in to the game
local colorMaterial = Material( "color" )
-- This function just gives us something to draw that uses a 2D context
-- It can be replaced with any other 2D drawing operation(s)
local function DrawSomething2D()
surface.SetMaterial( colorMaterial )
surface.SetDrawColor( Color(
```
--------------------------------
### Example: Styling a Scrollbar
Source: https://wiki.facepunch.com/gmod/DScrollPanel%3AGetVBar~diff%3A524895
An example demonstrating how to get the vertical scroll bar using DScrollPanel:GetVBar and customize its appearance, as well as the appearance of its buttons and grip.
```APIDOC
## Example: Styling a Scrollbar
### Description
This example shows how to retrieve the vertical scroll bar of a DScrollPanel and customize the painting of the scroll bar itself, its up button, down button, and grip.
### Code
```lua
local DFrame = vgui.Create("DFrame")
DFrame:SetSize(500, 500)
DFrame:Center()
DFrame:MakePopup()
DFrame:SetTitle("Scrollbar Example")
function DFrame:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(0, 100, 100))
end
local DScrollPanel = vgui.Create("DScrollPanel", DFrame)
DScrollPanel:SetSize(400, 250)
DScrollPanel:Center()
local sbar = DScrollPanel:GetVBar() -- Get the vertical scroll bar
-- Customize the painting of the scroll bar
function sbar:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(0, 0, 0, 100))
end
-- Customize the painting of the up button
function sbar.btnUp:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(200, 100, 0))
end
-- Customize the painting of the down button
function sbar.btnDown:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(200, 100, 0))
end
-- Customize the painting of the grip
function sbar.btnGrip:Paint(w, h)
draw.RoundedBox(0, 0, 0, w, h, Color(100, 200, 0))
end
-- Add some content to the scroll panel
local str = ""
for i = 1, 50 do
str = str .. "more space!\n"
end
local DLabel = vgui.Create("DLabel", DScrollPanel)
DLabel:SetText(str)
DLabel:Center()
DLabel:SizeToContents()
```
### Output
This example will produce a scrollable panel within a frame, with custom-styled scroll bar elements. The output images referenced in the original documentation are `scrollbar_style_example.png`.
```
--------------------------------
### UGCPublishWindow:Setup( string ugcType, string file, string imageFile, WorkshopFileBase handler )
Source: https://wiki.facepunch.com/gmod/UGCPublishWindow
Updates the Workshop items list with the provided details.
```APIDOC
## UGCPublishWindow:Setup( string ugcType, string file, string imageFile, WorkshopFileBase handler )
### Description
Updated the Workshop items list.
### Method
`UGCPublishWindow:Setup( string ugcType, string file, string imageFile, WorkshopFileBase handler )`
### Parameters
#### Path Parameters
- **ugcType** (string) - Required - The type of UGC.
- **file** (string) - Required - The path to the UGC file.
- **imageFile** (string) - Required - The path to the image file.
- **handler** (WorkshopFileBase) - Required - The workshop file handler.
```
--------------------------------
### DButton Example
Source: https://wiki.facepunch.com/gmod/DButton
Example demonstrating how to create and configure a DButton.
```APIDOC
## DButton Example
### Description
The DButton is exactly what you think it is - a button!
### Code
```lua
local frame = vgui.Create( "DFrame" )
frame:SetSize( 300, 250 )
frame:Center()
frame:MakePopup()
local DermaButton = vgui.Create( "DButton", frame ) -- Create the button and parent it to the frame
DermaButton:SetText( "Say hi" ) -- Set the text on the button
DermaButton:SetPos( 25, 50 ) -- Set the position on the frame
DermaButton:SetSize( 250, 30 ) -- Set the size
DermaButton.DoClick = function()
-- A custom function run when clicked ( note the . instead of : )
RunConsoleCommand( "say", "Hi" ) -- Run the console command "say hi" when you click it
end
DermaButton.DoRightClick = function()
RunConsoleCommand( "say", "Hello World" )
end
```
```
--------------------------------
### freezecam_started Game Event
Source: https://wiki.facepunch.com/gmod/gameevent/freezecam_started~edit
This event is called on the Client and Menu realms when the freeze camera starts spectating something. An example cause is when a player starts spectating in OBS_MODE_FREEZECAM.
```APIDOC
## freezecam_started Game Event
### Description
Called when the freeze cam starts spectating something.
### Realm
Client and Menu
### Example Cause
```lua
local ply = Entity( 1 )
ply:Spectate( OBS_MODE_FREEZECAM )
ply:SpectateEntity( ply )
```
### Usage Example
```lua
gameevent.Listen( "freezecam_started" )
hook.Add( "freezecam_started", "freezecam_started_example", function( data )
-- Called when the freeze cam starts spectating something.
end )
```
```
--------------------------------
### Example .properties File Content
Source: https://wiki.facepunch.com/gmod/Addon_Localization~diff%3A547814
This is an example of a `.properties` file used for localization. Keys and values are separated by '=', and lines starting with '#' are comments. The first line must be empty.
```properties
# This is a comment
spawnmenu.content_tab=Spawnlists
spawnmenu.category.npcs=NPCs
spawnmenu.category.addons=Addons
spawnmenu.category.weapons=Weapons
spawnmenu.category.postprocess=Post Process
spawnmenu.category.your_spawnlists=Your Spawnlists
spawnmenu.category.addon_spawnlists=Addon Spawnlists
spawnmenu.category.games=Games
spawnmenu.category.browse=Browse
spawnmenu.category.entities=Entities
spawnmenu.category.vehicles=Vehicles
spawnmenu.category.creations=Creations
spawnmenu.category.dupes=Dupes
spawnmenu.category.saves=Saves
```
--------------------------------
### Example Usage
Source: https://wiki.facepunch.com/gmod/DColorButton
This example demonstrates how to create and configure a DColorButton.
```APIDOC
## Example
Creates a DColorButton button.
```lua
local frame = vgui.Create( "DFrame" )
frame:SetSize( 500, 500 )
frame:Center()
frame:MakePopup()
local DColorButton = vgui.Create( "DColorButton", frame )
DColorButton:SetPos( 1, 28 )
DColorButton:SetSize( 100, 30 )
DColorButton:Paint( 100, 30 ) -- Note: Paint is usually called internally by the VGUI system.
DColorButton:SetText( "DColorButton" )
DColorButton:SetColor( Color( 0, 110, 160 ) )
function DColorButton:DoClick()
-- Callback inherited from DLabel, which is DColorButton's base
print( "I am clicked! My color is ", self:GetColor() )
end
```
_Note: The `Paint` method is typically handled by the VGUI system and might not need to be called directly in most cases. The example shows it for completeness based on the source text._
```
--------------------------------
### Complete DPanel Example
Source: https://wiki.facepunch.com/gmod/Introduction_To_Using_Derma~diff%3A564595
This example demonstrates creating a `DPanel`, setting its size, position, background color, and ensuring it is visible.
```lua
-- Create the DPanel
local myFirstPanel = vgui.Create( "DPanel" )
-- Set its size (Width: 200px, Height: 100px)
myFirstPanel:SetSize( 200, 100 )
-- Set its position (X: 300px from left, Y: 200px from top)
-- (Trying slightly different coords for visibility)
myFirstPanel:SetPos( 300, 200 )
-- Make it paint its background
myFirstPanel:SetPaintBackground( true )
-- Set the background color to blue (R=0, G=0, B=255, Alpha=255)
myFirstPanel:SetBackgroundColor( Color( 0, 0, 255, 255 ) )
-- Make sure it's visible (usually is by default if not parented to
```
--------------------------------
### Get Sequence Duration - Garry's Mod Lua
Source: https://wiki.facepunch.com/gmod/Entity%3ASequenceDuration
Retrieve the length of a specific animation sequence for an entity. This example demonstrates selecting a weighted sequence and then getting its duration.
```lua
local ply = Entity( 1 )
local seq = ply:SelectWeightedSequence( ACT_GMOD_TAUNT_CHEER )
local len = ply:SequenceDuration( seq )
print( ply, seq, len )
```
--------------------------------
### Example Usage
Source: https://wiki.facepunch.com/gmod/DMenu
This example demonstrates how to create a DMenu with options, submenus, icons, and spacers, and then open the menu.
```APIDOC
## Example
__local Menu = DermaMenu() -- Add a simple option. Menu:AddOption( "Simple option" ) -- Simple option, but we're going to add an icon local btnWithIcon = Menu:AddOption( "Option with icon" ) btnWithIcon:SetIcon( "icon16/bug.png" ) -- Icons are in materials/icon16 folder -- Adds a simple line spacer Menu:AddSpacer() -- Add a submenu local SubMenu = Menu:AddSubMenu( "A Sub Menu" ) SubMenu:AddOption( "Sub Option #1" ):SetIcon( "icon16/group.png" ) -- Add a submenu with icon local Child, Parent = Menu:AddSubMenu( "A Sub Menu with Icon" ) Parent:SetIcon( "icon16/arrow_refresh.png" ) Child:AddOption( "Sub Option #2" ):SetIcon( "icon16/group.png" ) -- Open the menu Menu:Open()
```
--------------------------------
### Get Return Value from Lua Function
Source: https://wiki.facepunch.com/gmod/C_Lua%3A_Functions~diff%3A561070
Retrieves the return value of a Lua function called from C++. This example specifically shows how to get the return value of the 'math.abs' function.
```cpp
LUA->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); // Push the global table
LUA->GetField( -1, "math" ); // Get the math table
LUA->GetField( -1, "abs" ); // Get the abs function from the mat
```
--------------------------------
### Create and Configure a DButton with Click Action
Source: https://wiki.facepunch.com/gmod/DButton%3ADoClick~diff%3A546542
This example demonstrates how to create a DButton, set its text, size, and position, and define its behavior when clicked. The button will print 'Hello World!' to the chat and then remove itself from the screen.
```lua
local DermaButton = vgui.Create( "DButton" ) -- Creates our button
DermaButton:SetText( "Click me!" )
DermaButton:SetSize( 100, 100 )
DermaButton:Center()
DermaButton:SetMouseInputEnabled( true ) -- We must accept mouse input
function DermaButton:DoClick() -- Defines what should happen when the label is clicked
chat.AddText("Hello World!")
self:Remove()
end
```
--------------------------------
### Get Return Value from Lua Function
Source: https://wiki.facepunch.com/gmod/C_Lua%3A_Functions~diff%3A551360
Shows how to retrieve the return value of a Lua function called from C++. This example specifically calls 'math.abs' and prepares to get its result.
```cpp
LUA->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); // Push the global table
LUA->GetField( -1, "math" ); // Get the math table
LUA->GetField( -1, "abs" ); // Get the abs function from the math table
```
--------------------------------
### PANEL:Init Example
Source: https://wiki.facepunch.com/gmod/PANEL%3AInit~diff%3A510992
Demonstrates how PANEL:Init is called recursively for each base type a panel has. Ensure the panel is created after registration.
```lua
local BASE = {}
function BASE:Init()
print("Base Init Called")
end
local PANEL = {}
function PANEL:Init()
print("Panel Init Called")
end
vgui.Register("MyBase", BASE, "DFrame")
vgui.Register("MyPanel", PANEL, "MyBase")
local panel = vgui.Create("MyPanel")
```
--------------------------------
### DMenu:GetChild
Source: https://wiki.facepunch.com/gmod/DMenu%3AGetChild~diff%3A550402
Gets a child panel from a DMenu by its index. The index starts at 1.
```APIDOC
## DMenu:GetChild
### Description
Gets a child by its index. Unlike Panel:GetChild, this index starts at 1.
### Method
panelfunc
### Arguments
* **childIndex** (number) - The index of the child to get. Note: Unlike Panel:GetChild, this index starts at 1.
### Realm
Client and Menu
```
--------------------------------
### Run Garry's Mod Dedicated Server (Linux)
Source: https://wiki.facepunch.com/gmod/Downloading_a_Dedicated_Server~diff%3A529596
Starts the Garry's Mod dedicated server on Linux from the installation directory. Configures maximum players and the starting map.
```bash
cd ~/gmodds/
./srcds_run -game garrysmod +maxplayers 32 +map gm_construct
```
--------------------------------
### Example .properties File Content
Source: https://wiki.facepunch.com/gmod/Addon_Localization~diff%3A547812
This is an example of a `.properties` file used for localization. Keys and values are separated by an equals sign, and lines starting with '#' are comments. The first line must be empty.
```properties
# File | Edit | Selection | Find | View | Goto | Tools | Project | Preferences | Help |
---------------------------------------------------------------------------------------
<>| spawnmenu.properties |_________________________________________________________ + V
1| H
2| spawnmenu.content_tab=Spawnlists H
3| spawnmenu.category.npcs=NPCs H
4| spawnmenu.category.addons=Addons H
5| spawnmenu.category.weapons=Weapons H
6| spawnmenu.category.postprocess=Post Process H
7| spawnmenu.category.your_spawnlists=Your Spawnlists H
8| spawnmenu.category.addon_spawnlists=Addon Spawnlists H
9| spawnmenu.category.games=Games |
10| spawnmenu.category.browse=Browse |
11| spawnmenu.category.entities=Entities |
12| spawnmenu.category.vehicles=Vehicles |
13| spawnmenu.category.creations=Creations |
14| spawnmenu.category.dupes=Dupes |
15| spawnmenu.category.saves=Saves |
16|
```
--------------------------------
### Complete Panel Example
Source: https://wiki.facepunch.com/gmod/Introduction_To_Using_Derma
This example demonstrates creating a DPanel, setting its size, position, background color, and ensuring it is visible.
```lua
-- Create the DPanel
local myFirstPanel = vgui.Create( "DPanel" )
-- Set its size (Width: 200px, Height: 100px)
myFirstPanel:SetSize( 200, 100 )
-- Set its position (X: 300px from left, Y: 200px from top)
-- (Trying slightly different coords for visibility)
myFirstPanel:SetPos( 300, 200 )
-- Make it paint its background
myFirstPanel:SetPaintBackground( true )
-- Set the background color to blue (R=0, G=0, B=255, Alpha=255)
myFirstPanel:SetBackgroundColor( Color( 0, 0, 255, 255 ) )
-- Make sure it's visible (usually is by default if not parented to hidden)
myFirstPanel:SetVisible( true )
```
--------------------------------
### Example: Creating a basic DFrame
Source: https://wiki.facepunch.com/gmod/DFrame
This example demonstrates how to create and configure a basic DFrame, setting its position, size, title, and making it a popup window.
```APIDOC
## Example: Creating a basic DFrame
### Description
Creates a basic DFrame.
### Code
```lua
__concommand.Add( "open_frame", function()
local DFrame = vgui.Create( "DFrame" ) -- The name of the panel we don't have to parent it.
DFrame:SetPos( 100, 100 ) -- Set the position to 100x by 100y.
DFrame:SetSize( 300, 200 ) -- Set the size to 300x by 200y.
DFrame:SetTitle( "Derma Frame" ) -- Set the title in the top left to "Derma Frame".
DFrame:MakePopup() -- Makes your mouse be able to move around.
end )
```
```
--------------------------------
### Example .properties file content
Source: https://wiki.facepunch.com/gmod/Addon_Localization~diff%3A547577
This is an example of a .properties file used for localization. Keys and values are separated by an equals sign, and lines starting with '#' are comments. Keys must not contain spaces.
```properties
spawnmenu.content_tab=Spawnlists
spawnmenu.category.npcs=NPCs
spawnmenu.category.addons=Addons
spawnmenu.category.weapons=Weapons
spawnmenu.category.postprocess=Post Process
spawnmenu.category.your_spawnlists=Your Spawnlists
spawnmenu.category.addon_spawnlists=Addon Spawnlists
spawnmenu.category.games=Games
spawnmenu.category.browse=Browse
spawnmenu.category.entities=Entities
spawnmenu.category.vehicles=Vehicles
spawnmenu.category.creations=Creations
spawnmenu.category.dupes=Dupes
spawnmenu.category.saves=Saves
```
--------------------------------
### Listen to client_beginconnect Event
Source: https://wiki.facepunch.com/gmod/gameevent/client_beginconnect~diff%3A549452
This example demonstrates how to listen for the client_beginconnect event using a binary module. It's necessary to use a module because the game event system is not directly available in the Menu state.
```lua
require("gameevent") -- using a Binary Module because the Menu State doesn't has gameevent.Listen
gameevent.Listen( "client_beginconnect" )
hook.Add( "client_beginconnect", "client_beginconnect_example", function( data )
local address = data.address // The Server address.
local ip = data.ip // The Server IP. Use the address instead!
local port = data.port // The Server Port.
local source = data.source // The Source, why the client is connecting to the Server.
// Called when trying to connect to aServer.
end
)
```
--------------------------------
### Get and Print ConVar Integer Value
Source: https://wiki.facepunch.com/gmod/ConVars
Retrieve a ConVar object using `GetConVar` and then use `GetInt()` to get its integer value. This example prints the current value of the `sbox_maxprops` ConVar.
```lua
local sbox_maxprops = GetConVar( "sbox_maxprops" )
print( sbox_maxprops:GetInt() )
```
--------------------------------
### Premake Command-Line Execution Examples
Source: https://wiki.facepunch.com/gmod/Creating_Binary_Modules%3A_Premake~diff%3A547592
These commands demonstrate how to invoke Premake to generate project files for different operating systems and IDEs. Ensure you replace placeholders like 'vs2022' with your specific IDE version.
```bash
premake5.exe --os=windows --gmcommon=../garrysmod_common vs2022
```
```bash
./premake5 --os=linux --gmcommon=../garrysmod_common gmake2
```
```bash
./premake5 --os=macosx --gmcommon=../garrysmod_common xcode4
```
--------------------------------
### GetCount - CRecipientFilter Example
Source: https://wiki.facepunch.com/gmod/CRecipientFilter%3AGetCount~diff%3A514181
This example demonstrates how to use CRecipientFilter:GetCount to retrieve the number of players in a filter after adding all players. It also shows how to get the list of players using GetPlayers.
```lua
local rf = RecipientFilter()
rf:AddAllPlayers()
print( rf:GetCount() )
PrintTable( rf:GetPlayers() )
```
--------------------------------
### Player:StartSprinting Alternative Example
Source: https://wiki.facepunch.com/gmod/Player%3AStartSprinting~diff%3A524927
This example demonstrates an alternative approach to simulating sprint functionality by hooking into the StartCommand event. It checks for forward input and a delay to trigger the sprint button.
```lua
local vDelay = 0
local prevDown = 0
hook.Add( "StartCommand", "TestFunc", function( ply, cmd )
if ( cmd:KeyDown( IN_FORWARD ) and prevDown == false ) then
vDelay = CurTime() + 0.4
elseif ( cmd:KeyDown( IN_FORWARD ) ) then
if ( vDelay < CurTime() )then
if ( vDelay < CurTime() )then
cmd:SetButtons( bit.bor( cmd:GetButtons(), IN_SPEED ) )
end
end
prevDown = cmd:KeyDown(IN_FORWARD)
end
end )
```
--------------------------------
### Example premake5.lua Configuration for Detouring
Source: https://wiki.facepunch.com/gmod/Binary_Modules_Detouring_Functions
This is an example of how your premake5.lua file should look after including the detouring and scanning submodules. Replace '[Your Project]' and '[Your includes ...]' with your specific project details.
```lua
__CreateWorkspace({name = "[Your Project]", abi_compatible = false})
CreateProject({serverside = [true or false], manual_files = false})
[Your includes ...]
IncludeHelpersExtended()
IncludeDetouring()
IncludeScanning()
```
--------------------------------
### QC Compiler Instructions Example
Source: https://wiki.facepunch.com/gmod/Important_Filetypes~edit
This example demonstrates common QC commands used to instruct the StudioMdl compiler. Understand the structure of commands prefixed with '$' and their parameters.
```qc
$modelname "props_sdk\myfirstmodel.mdl"
$body mybody "myfirstmodel-ref.smd"
$surfaceprop combine_metal
$cdmaterials "models\props_sdk"
$sequence idle "myfirstmodel-ref.smd" // no animation wanted, so re-using the reference mesh
$collisionmodel "myfirstmodel-phys.smd" {
$concave
}
```
--------------------------------
### Get Player UniqueID
Source: https://wiki.facepunch.com/gmod/Player%3AUniqueID
Retrieves the Unique ID of a player entity. This is a basic usage example.
```lua
Entity( 1 ):UniqueID()
```
--------------------------------
### Create and Configure DProperty_Combo
Source: https://wiki.facepunch.com/gmod/DProperty_Combo~diff%3A516949
Demonstrates creating a DFrame, adding a DProperties panel, and then creating two DProperty_Combo rows with different configurations and choices. The first combo uses default text, while the second customizes the placeholder text and adds various data types as choices. It also shows how to set up a callback for when the data changes.
```lua
local Panel = vgui.Create( "DFrame" )
Panel:SetSize( 500, 500 )
Panel:MakePopup()
local DP = vgui.Create( "DProperties", Panel )
DP:Dock( FILL )
local choice = DP:CreateRow( "Choices", "Combo #1: Default" )
choice:Setup( "Combo", {} )
choice:AddChoice( "Allow", true )
choice:AddChoice( "Disallow", false )
local choice = DP:CreateRow( "Choices", "Combo #2: Custom default text" )
choice:Setup( "Combo", { text = "Select type..." } )
choice:AddChoice( "Table", {} )
choice:AddChoice( "Function", function() end )
choice:AddChoice( "String", "Hello world" )
choice.DataChanged = function( self, data )
print( "You selected: ", data )
end
```
--------------------------------
### Panel:GetChild
Source: https://wiki.facepunch.com/gmod/Panel%3AGetChild~diff%3A510542
Gets a child by its index. This index starts at 0, except when used on a DMenu.
```APIDOC
## Panel:GetChild
### Description
Gets a child element from a Panel by its index.
### Method
Class Function
### Arguments
* **childIndex** (number) - Required - The index of the child to retrieve. Note: This index starts at 0, except when used on a DMenu.
```
--------------------------------
### Panel:GetChild
Source: https://wiki.facepunch.com/gmod/Panel%3AGetChild~diff%3A517672
Gets a child by its index. This index starts at 0, except when used on a DMenu.
```APIDOC
## Panel:GetChild
### Description
Gets a child by its index.
### Method
Class Function
### Parameters
#### Arguments
* **childIndex** (number) - The index of the child to get. This index starts at 0, except when you use this on a DMenu.
```
--------------------------------
### Create and Use a Basic Render Target
Source: https://wiki.facepunch.com/gmod/render_rendertargets~diff%3A561412
Demonstrates setting up a Render Target, drawing 2D and 3D elements onto it, and then displaying it on screen. Ensure the material uses the correct shader for its intended use (e.g., UnlitGeneric for screen display, VertexLitGeneric for models).
```lua
-- Create the Render Target we'll be using throughout this example
local renderTarget = GetRenderTarget( "RenderTargetExample", -- The name we'll call new Render Target's Texture
1024, -- The size of the Render Target
1024 -- The size of the Render Target
)
-- Create a Material that corresponds to the Render Target we just made
local renderTargetMaterial = CreateMaterial( "RenderTargetExampleMaterial", -- All Materials need a name
"UnlitGeneric", -- This shader will work great for drawing onto the screen, but can't be used on models
-- To use this material on a model, this would need to use the "VertexLitGeneric" shader.
{
["$basetexture"] = renderTarget:GetName(), -- Use our Render Target as the Texture for this Material
["$translucent"] = "1" -- Without this, the Material will be fully opaque and any translucency won't be shown
}
)
-- Used later for some 3D rendering
local clientsideModel = ClientsideModel( "models/props_lab/huladoll.mdl", RENDERGROUP_OPAQUE )
clientsideModel:SetNoDraw( true )
-- An all-white material is built-in to the game
local colorMaterial = Material( "color" )
-- This function just gives us something to draw that uses a 2D context
-- It can be replaced with any other 2D drawing operation(s)
local function DrawSomething2D()
surface.SetMaterial( colorMaterial )
ssurface.SetDrawColor( Color( 255,
```
--------------------------------
### Start Garry's Mod Server
Source: https://wiki.facepunch.com/gmod/Linux_Dedicated_Server_Hosting~diff%3A526769
Launch the Garry's Mod dedicated server using the srcds_run script. This example starts a server with 12 player slots on the 'gm_flatgrass' map.
```bash
~/server_1/srcds_run -game garrysmod +maxplayers 12 +map gm_flatgrass
```
```bash
~/server_1/srcds_run -game garrysmod +maxplayers 12 +map gm_flatgrass +sv_setsteamaccount
```
--------------------------------
### Listen to client_beginconnect Event
Source: https://wiki.facepunch.com/gmod/gameevent/client_beginconnect~diff%3A549445
This example demonstrates how to listen for the client_beginconnect event using a Binary Module, as the Menu state does not have direct access to gameevent.Listen. It shows how to access and use the provided data fields.
```lua
require("gameevent") -- using a Binary Module because the Menu State doesn't has gameevent.Listen
gameevent.Listen( "client_beginconnect" )
hook.Add( "client_beginconnect", "client_beginconnect_example", function( data )
local address = data.address // The Server address.
local ip = data.ip // The Server IP. Use the address instead!
local port = data.port // The Server Port.
local source = data.source // The Source, why the client is connecting to the Server.
// Called when trying to connect to aServer.
end )
```
--------------------------------
### Create a Simple DGrid with Buttons
Source: https://wiki.facepunch.com/gmod/DGrid~edit
This example demonstrates how to create a DGrid and populate it with DButtons. Note that DGrid's automatic sizing can conflict with Panel:Dock.
```lua
local frame = vgui.Create( "DFrame" )
frame:SetPos( 500, 500 )
frame:SetSize( 200, 300 )
frame:SetTitle( "Frame" )
frame:MakePopup()
local grid = vgui.Create( "DGrid", frame )
grid:SetPos( 10, 30 )
grid:SetCols( 5 )
grid:SetColWide( 36 )
for i = 1, 30 do
local but = vgui.Create( "DButton" )
but:SetText( i )
but:SetSize( 30, 20 )
grid:AddItem( but )
end
```
--------------------------------
### Get Return Value from Lua Function
Source: https://wiki.facepunch.com/gmod/C_Lua%3A_Functions~diff%3A526488
Explains how to retrieve the return value from a Lua function call. This example specifically gets the return value of math.abs and stores it in a C++ integer variable.
```cpp
LUA->PushSpecial( GarrysMod::Lua::SPECIAL_GLOB ); // Push the global table LUA->GetField( -1, "math" ); // Get the math table LUA->GetField( -1, "abs" ); // Get the abs function from the math table LUA->PushNumber( -666 ); // Push our argument LUA->Call( 1, 1 ); // Call the function and get 1 return value int iReturnValue = (int)LUA->GetNumber( -1 ); LUA->Pop( 3 ); // Pop the global table, the math table, and the return value off the stack
```
--------------------------------
### Listen to server_spawn Event
Source: https://wiki.facepunch.com/gmod/gameevent/server_spawn~diff%3A549450
This example demonstrates how to listen for the server_spawn event using a binary module. It includes all available data fields for the event.
```lua
require("gameevent") -- using a Binary Module because the Menu State doesn't has gameevent.Listen
gameevent.Listen( "server_spawn" )
hook.Add( "server_spawn", "server_spawn_example", function( data )
local hostname = data.hostname // The hostname of the Server.
local address = data.address // The Server address.
local ip = data.ip // The Server IP. Use the address instead!
local port = data.port // The Server Port.
local game = data.game // The Game the Server is hosting. Should always be garrysmod.
local mapname = data.mapname // The Mapname the Server is currently on.
local maxplayers = data.maxplayers // The amount of slots the Server has.
local os = data.os // The os the Server is running on.
local dedicated = data.dedicated // true if the Server is a dedicated Server.
local password = data.password // true if the Server is password protected.
// Called while connecting to the Server.
end )
```