Code Snippets General
From GMod Wiki
This page contains general purpose code snippets.
Contents |
Mathematical Snippets
Generating Pseudo-Random Numbers
math.random( 3, 9 ) // Generates a random integer between 3 and 9 inclusively. math.Rand( 3, 9 ) // Generates a random real number (floating point) between 3 and 9 inclusively.
Better Rounding
- Because, frankly, Garry's rounding function sucks.
- This allows you to round to a decimal point instead of to a whole number.
/* Rounds to the 3rd decimal point * Usage: math.AdvRound( 1.6443132, 3 ); */ function math.AdvRound( val, d ) d = d or 0; return math.Round( val * (10 ^ d) ) / (10 ^ d); end
Toggling a Boolean
local Boolean = false -- Toggle the boolean. Boolean = not Boolean -- or, in C-style notation: Boolean = !Boolean
Getting the Position of a Point between Two Vectors
This will return the position of a point between two vectors. The count is a percentage.
function LinearCalc(PosA, PosB, Percent) return PosA + (PosB - PosA)*Percent end
or
local percent = 0.5 // 1.0 being 100% LerpVector( percent, pos1, pos2)
Variables
Defining Multiple Variables
-- X = 1, Y = 2, Z = 3. local X, Y, Z = 1, 2, 3
Using OR
-- If Y is non-nil, set X to Y; otherwise, set X to 0. local X = Y or 0
Switching Two Variables without Making a Third
a,b = b,a
Loops and statements
Looping through Every Character in a String
for i = 1, string.len( strToLoop ) do local Character = string.sub( strToLoop, i, i ) -- Do stuff with Character here. end
Using 'repeat, until'
repeat num = math.random( 200 ) Msg( num .. "\n" ) until( num == 25 )
Doing 'if .. then ... else' in One Line
local value = ( x > 1 ) && "X is greater" || "X isn't greater"; --and in STD. Lua notation: local value = ( x > 1 ) and "X is greater" or "X isn't greater"; --basic format for Inline Conditionals: local value = (Condition) and TrueValue or FalseValue;
Returning 'if .. then ... else'
return current < max and func( current + 1, max ) or nil
Miscellaneous
Using an Unlimited Number of Arguments
function takesMultipleArgs( ply, name, ... ) print( name, ply:GetPos() ) callAnotherFunction( "hi there", ... ) for k, v in pairs( {...} ) do print( v .. "\n" ) end end
Fading Between Two Colors
function Fade( a, b, frac, alpha ) local res, me res = Color( 0, 0, 0, alpha ) me = ( 1 - frac ) res.r = ( a.r * me ) + ( b.r * frac ) res.g = ( a.g * me ) + ( b.g * frac ) res.b = ( a.b * me ) + ( b.b * frac ) return res end
Simpler approach, also fades the alpha
function LerpColor(frac,from,to) local col = Color( Lerp(frac,from.r,to.r), Lerp(frac,from.g,to.g), Lerp(frac,from.b,to.b), Lerp(frac,from.a,to.a) ) return col end
Using 'print' Effectively
-- print, as you ought to know, will echo a message to the gmod console. print( "lol" ) -- You can pass multiple arguments to print and it will automatically format them with tabs in between them. print( "lol", "wut?" ) -- It's more useful than that though. Print will automatically call tostring on any argument you throw at it, even userdata. print( 42 ) print( Vector( 1, 2, 3 ) ) print( LocalPlayer() ) -- This makes it great for quick debugging and getting information. for _,ent in pairs( ents.GetAll() ) do print( ent, ent:GetPos() ) end
Finding all the Functions or Variables in an Object
Do PrintTable( FindMetaTable( "ObjectName" ) ) to get the functions, and PrintTable( object:GetTable() ) to get the variables. (Not every object has GetTable defined though.)
e.g.
PrintTable( FindMetaTable( "Entity" ) ) PrintTable( Entity( 1 ):GetTable() )
For more information: Metatable
Posted by TetaBonita on FP Forums.
Adding an Event Hook
The middle parameter is a unique name to give the hook, this assures that you won't spawn multiple hooks for doing the same thing.
hook.Add( "GUIMousePressed", "MorphMouseDown", MouseDownFunction )
Making a Custom SpawnMenu
Adding this to your cl_init.lua on your gamemode will add a custom spawnmenu to your server. Add more to the Table to add your own props.
function proplist() print ("List Opening") local props = {} props[1] = "models/props_junk/garbage_milkcarton002a.mdl" props[2] = "models/props_junk/PopCan01a.mdl" props[3] = "models/props_junk/garbage_takeoutcarton001a.mdl" props[4] = "models/props_junk/watermelon01.mdl" props[5] = "models/props_junk/garbage_metalcan001a.mdl" props[6] = "models/props_lab/box01a.mdl" props[7] = "models/props_lab/box01b.mdl" -- You can add more such as props[8] = "models/path/model.mdl" to add your own. local slframe = vgui.Create("DFrame") local IconList = vgui.Create("DPanelList", slframe) slframe:Center() slframe:SetSize(250,200) slframe:SetTitle("Prop Catalog") slframe:MakePopup() IconList:EnableVerticalScrollbar( true ) IconList:EnableHorizontal( true ) IconList:SetPadding( 4 ) IconList:SetPos(10,30) IconList:SetSize(200,160) for k,v in pairs(props) do local icon = vgui.Create( "SpawnIcon", IconList ) icon:SetModel( v ) IconList:AddItem( icon ) icon.DoClick = function( icon ) surface.PlaySound( "ui/buttonclickrelease.wav" ) RunConsoleCommand("gm_spawn", v) end end end concommand.Add("slist", proplist) function GM:OnSpawnMenuOpen( ply ) LocalPlayer():ConCommand("slist") end
Posted by Noforgivin from Facepunch forums.
Smooth health bar example
This creates a nice smooth health bar that fades from green to red.
-- Created by CowThing local smooth = 0 -- Setting up the variable that will get smoothed. hook.Add("HUDPaint", "HealthBar", function() local health = math.Clamp(LocalPlayer():Health(), 0, 100) -- clamps the health to [0, 100] meaning it will not go above 100 or below 0 smooth = math.Approach(smooth, health, 50*FrameTime()) -- smooth the health value, this looks a lot better than just using the raw health value. -- You should use FrameTime() for things like this so it will look smooth even if your FPS is low. local red = (1 - smooth/100)^(1/2) * 255 -- Create a linear equation for the red value, as health drops red increases. local grn = (smooth/110)^(1/2) * 255 -- same for green, as health drops green decreases. local blu = (smooth/200)^2 * 255 -- and for blue local col = Color(red, grn, blu) -- create a single color object with the values. local w, h = 60, 200 local spacing = 32 local equation = (h-8)*(smooth/100)+8 -- this equation is so the bar will shrink as you lose health. draw.RoundedBox( 4, ScrW() - w - spacing - 2, ScrH() - h - spacing - 2, w + 4, h + 4, Color( 30, 30, 30 ) ) draw.RoundedBox( 4, ScrW() - w - spacing, ScrH() - equation - spacing, w, equation, col ) end)
Getting a player using their SteamID
This extension for the player library has many uses.
function player.GetBySteamID(ID) local PTab = player.GetAll() for p=1,#PTab do if ID == PTab[p]:SteamID() then return PTab[p] end end return false end