• Useful Code Snippets
    232 replies, posted
What the fuck is this shit [url]http://gamerpaddy.bplaced.net[/url]
[QUOTE=StonedPenguin;46700704]I wouldn't be hard to just take a look at your clientside code and spam the shit out of your site. You'd be better off querying a key to a database and sending it to the client for verification instead.[/QUOTE] It would likely be considerably easier to throttle the requests server-side and block detected spammers. Just my two cents.
Have you tried sending screenshots through net? We're throttled to 20KB/sec meaning any messages that get sent are delayed until the screenshot is delayed, so you have to make the packets small enough to allow all networking to go through, but large enough that they don't take forever. On top of that, you need to ensure you queue them / give them a delay so you can send one after the previous one has been fully sent, or arrived ( dtime *2 ). I limit my packets to 10KB and space them apart with a little bit of a buffer ( 0.25 seconds on top of messagei * time to send 10kb ) in a loop. timers are still broken, they can fail without releveling but they don't give an error message if that happens. Honestly, the easiest way is to leave it how it is, but have the server generate a one-time-use key that it sends to the client and to the website ( SERVER via http.Fetch / Post ensuring the sending ip is correct and another "master" key is sent with it ). The client receives the one time use key which the server had inserted into the db and let it expire in 1 minute or whatever. The client then posts the photo with the key, the key is removed and done. If no key is sent in the form reject data and if no valid key is sent then don't send either. Regardless of how you network the data to the server, if you clog one method up ( net / umsg / concommand ) then other messages are delayed... [url]https://dl.dropboxusercontent.com/u/26074909/tutoring/networking/networking_channels_and_the_order_things_are_sent.lua[/url] It isn't meant for that much data unfortunately.
[QUOTE]Honestly, the easiest way is to leave it how it is, but have the server generate a one-time-use key that it sends to the client and to the website ( SERVER via http.Fetch / Post ensuring the sending ip is correct and another "master" key is sent with it ). The client receives the one time use key which the server had inserted into the db and let it expire in 1 minute or whatever. The client then posts the photo with the key, the key is removed and done. If no key is sent in the form reject data and if no valid key is sent then don't send either. [/QUOTE] That would be the easiest and best way. i was trying to do it like this, but never finished it.
[lua]local blur = Material("pp/blurscreen") local function DrawBlurPanel(panel, amount, heavyness) local x, y = panel:LocalToScreen(0, 0) local scrW, scrH = ScrW(), ScrH() surface.SetDrawColor(255,255,255) surface.SetMaterial(blur) for i = 1, heavyness do blur:SetFloat("$blur", (i / 3) * (amount or 6)) blur:Recompute() render.UpdateScreenEffectTexture() surface.DrawTexturedRect(x * -1, y * -1, scrW, scrH) end end -- Use this on a panel in it's paint hook. or just use the one below, really doesnt matter local function DrawBlurRect(x, y, w, h, amount, heavyness) local X, Y = 0,0 local scrW, scrH = ScrW(), ScrH() surface.SetDrawColor(255,255,255) surface.SetMaterial(blur) for i = 1, heavyness do blur:SetFloat("$blur", (i / 3) * (amount or 6)) blur:Recompute() render.UpdateScreenEffectTexture() render.SetScissorRect(x, y, x+w, y+h, true) surface.DrawTexturedRect(X * -1, Y * -1, scrW, scrH) render.SetScissorRect(0, 0, 0, 0, false) end end -- To draw blur rectangles in HUD elements, etc[/lua] thanks to [url=https://github.com/Chessnut/NutScript/blob/097c611c19f093a7a9d9a5d45f2fd73ac7d68309/gamemode/derma/cl_charmenu.lua#L8]chessnut[/url] for the blur code, [B]not netheous[/B]
My bad, my bad. Misplaced credit.
Kind of a late bump but these can still be quite relevant. Going to add this topic to my link package! Generalized Lua Help ( Links to Wikis, Answers the question of "Where do I post a simple question or DarkRP Specific question", links to other resources compiled by forum members ) [url]https://dl.dropboxusercontent.com/u/26074909/tutoring/___welcome_docs/_welcome_general_lua_learning.lua.html[/url] Useful Programs ( SteamCMD, Autosizer, Desktops, Process Explorer ) and Notepad++ Upgrades [url]https://dl.dropboxusercontent.com/u/26074909/tutoring/___welcome_docs/_welcome_useful_programs_and_notepadpp_upgrades.lua.html[/url] Anyways; I have a lot of snippets available in my dev-base and I'm adding more. Just worked up a few angle differences today ( hopefully they're right; only the last one reports the same output regardless of location ) [code]// // Calculates the 2 unknown angles of a right-triangle so the sum adds up to -180 or 180 - Acecool - See AcecoolDev_Base // function math.OmegaAngleDifference( _pos, _pos2 ) local _rad = math.atan( ( _pos.y - _pos2.y ) / ( _pos2.x - _pos.x ) ); local _deg = math.deg( _rad ); local _deg2 = 180 - ( 90 + math.abs( _deg ) ); _deg2 = ( _deg < 0 ) && _deg2 * -1 || _deg2; return _deg, _deg2, _rad, math.rad( _deg2 ); end [/code] And another new useful one I finished recently for my in-game environment system ( time from the sun position - shared )... [code]// // Calculates "Time" from the position of the in-game sun - Acecool - See AcecoolDev_Base // function math.TimeFromSun( _ang ) local _sun = util.GetSunInfo( ); local _ang = _ang || _sun.direction:Angle( ).p; local _seconds = ( ( ( _ang + 180 + 90 ) * ( 86400 / 360 ) ) % 86400 ); local _output = ( math.formattime ) && math.formattime( _seconds ) || string.FormattedTime( _seconds, "%02i:%02i:%02i" ); return _output; end [/code]
LerpColor [CODE]LerpColor = function(tr,tg,tb,from,to) tg = tg || tr tb = tb || tr return Color(Lerp(tr,from.r,to.r),Lerp(tg,from.g,to.g),Lerp(tb,from.b,to.b)) end [/CODE] tr=fraction red tg=fraction green (nil = tr) tb=fraction blue (nil = tr) from=Color from to=Color to Example: [CODE]_col = Color(0,0,0) hook.Add("HUDPaint","LerpTest",function() _col = LerpColor(0.03,0.003,0.007,_col,Color(255,255,255)) draw.RoundedBox( 3, ScrW()/2, ScrH()/5, 60, 60, _col) end)[/CODE] Turns from black to redish then it slowly goes pinkish and slowly goes whitish after.
A little gun/tool I made to help visualize vectors and paths that I made for my mugger nextbot on Scriptfodder. You basically just place down points and it draws lines between them in the order they are in the table and you can press R to print the table of vectors to console. [t]http://images.akamai.steamusercontent.com/ugc/35244412488772993/A01FE5B1905C15D86AABF760D23DFFB16337C17A/[/t] [code] if SERVER then AddCSLuaFile() end SWEP.PrintName = "Vector Tracker" SWEP.Author = "Exho" SWEP.Contact = "" SWEP.Purpose = "" SWEP.Instructions = "Left click to place vector, right click to remove vector, reload to print to console" SWEP.Slot = 3 SWEP.SlotPos = 1 SWEP.DrawAmmo = false SWEP.DrawCrosshair = true SWEP.HoldType = "normal" SWEP.Spawnable = false SWEP.AdminSpawnable = true SWEP.ViewModel = "models/weapons/v_pistol.mdl" SWEP.WorldModel = "models/weapons/w_pistol.mdl" SWEP.ViewModelFlip = false SWEP.points = {} function SWEP:PrimaryAttack() if not IsFirstTimePredicted() then return end local tr = self.Owner:GetEyeTrace() -- Add a point table.insert( self.points, tr.HitPos ) end function SWEP:SecondaryAttack() local tr = self.Owner:GetEyeTrace() local pos = tr.HitPos -- Remove points close to where we right clicked for k, v in pairs( self.points ) do if v:Distance( pos ) < 10 then table.remove( self.points, k ) end end end function SWEP:Reload() if SERVER then return end if not IsFirstTimePredicted() then return end -- Print all the points to console as a table of vectors print( string.format( '["%s"] = {', game.GetMap() ) ) for _, pos in pairs( self.points ) do print( string.format( '\tVector( %s, %s, %s ),', pos.x, pos.y, pos.z ) ) end print("},") end function SWEP:DrawHUD() local ID = Material( "cable/redlaser" ) hook.Add( "PostDrawOpaqueRenderables", "vector_connector", function() if not self.points or #self.points == 0 then return end for i = 1, #self.points do local pos = self.points[i] local pos2 = Vector( 0, 0, 0 ) -- Either draw the beam to the next point or back to the start if self.points[i+1] then pos2 = self.points[i+1] else pos2 = self.points[1] end -- Draw a beam across each point render.SetMaterial( ID ) render.DrawBeam( pos, pos2, 30, 0, 3, Color(255,255,255) ) -- Draw a beam showing where this point is render.SetMaterial( ID ) render.DrawBeam( pos, pos + Vector( 0, 0, 20 ), 30, 0, 3, Color(0,255,255) ) end end) end [/code]
You know how you always create print statements then forget which file you put them in and then your addon spams the console with prints and you're like crap now i need to find them and then it sucks cuz you have to do work... [CODE] local fileColors = {}; local fileAbbrev = {}; local MsgC , print = _G.MsgC , _G.print local incr = SERVER and 72 or 0 -- server side version of file gets different color from client... way less confusing like that function dprint(...) local info = debug.getinfo(2) if not info then print(...) return end local fname = info.short_src; if fileAbbrev[fname] then fname = fileAbbrev[fname]; else local oldfname = fname; fname = string.Explode('/', fname); fname = fname[#fname]; fileAbbrev[oldfname] = fname; end if not fileColors[fname] then incr = incr + 1; fileColors[fname] = HSVToColor(incr * 100 % 255, 1, 1) end MsgC(fileColors[fname], fname..':'..info.linedefined); print( ' ', ... ) end [/CODE] Basically takes the file name the dprint command was called from, assigns it it's very own super special color, and prefixes the last part of file name to the line that gets printed. Because it contains a call to the legacy print function you're guarantied the same behavior, just with a sexy and colorful file name in front.
Now I can finally hunt down all of those strange prints I have
I made this to make it easier to get door and entity positions. [lua] concommand.Add( "GetEntPos", function(ply) local tr = ply:GetEyeTrace() local ent = tr.Entity if IsValid( ent ) then print(ent:GetPos()) ply:ChatPrint("Entity information is in your console.") end end ) function GetEntPosCMD( pl, text, teamonly ) if text == "/entpos" then pl:ConCommand( "GetEntPos") return "" end end hook.Add( "PlayerSay", "Chat", GetEntPosCMD ) [/lua]
Do you use an autohotkey script that types a random amount of spaces when you press spacebar?
Small library to process HTML Entities. [url]https://gist.github.com/Starfox64/f63f5df5907770e83519[/url]
[QUOTE=_FR_Starfox64;47705301]Small library to process HTML Entities. [url]https://gist.github.com/Starfox64/f63f5df5907770e83519[/url][/QUOTE] You could simplify the code a tiny tiny bit (and make it compatible with stock Lua) by using code similar to [url]https://github.com/garrynewman/garrysmod/blob/master/garrysmod/lua/includes/extensions/string.lua#L68[/url].
[lua] function CheckArguments( FunctionName, ... ) local Good = true; for _, argument in ipairs( {...} ) do local Given = argument[ 1 ]; local RequiredType = argument[ 2 ]; if ( not RequiredType ) then continue; end if ( Given == nil or type( Given ) ~= RequiredType ) then print( Format( "Error calling %s, Argument %u expected type %s, got %s", FunctionName, _, RequiredType, type( Given ) ) ); Good = false; end end return Good; end [/lua] Example use [lua] CheckArguments( "MyFunction( sFilename, sNature )", { sFilename, "string" }, { sNature, "string" } ); [/lua]
[QUOTE=James xX;47705682] CheckArgs [/QUOTE] and in Luaer error format: [lua] function CheckArgs(...) local funcname = debug.getinfo(2).name local valid = true for i, arg in ipairs({...}) do local got = type(arg[1]) local expected = arg[2] if not expected then continue end if got == nil or got ~= expected then print(string.format("bad argument #%u to '%s' (%s expected, got %s)", i, funcname, expected, got)) valid = false end end return valid end [/lua]
[code]function TextWrap( str, width, font ) local str_pieces = {} surface.SetFont( font ) local xsz,ysz = surface.GetTextSize( str ) if xsz < width then return { str } end local str_table = string.Explode( " ", str ) local cur_string = "" for i = 1,#str_table do surface.SetFont( font ) local text = i > 1 and cur_string.." "..str_table[ i ] or str_table[ i ] local xsz,ysz = surface.GetTextSize( text ) if string.find( str_table[ i ], "/n", string.len( str_table[ i ] )-2, string.len( str_table[ i ] ) ) then str_pieces[ #str_pieces+1 ] = cur_string cur_string = str_table[ i ] elseif xsz >= width then str_pieces[ #str_pieces+1 ] = cur_string cur_string = str_table[ i ] else cur_string = text end if i == #str_table then str_pieces[ #str_pieces+1 ] = cur_string end end return str_pieces end [/code] Text wrap function. Sorry it it's terrible <3
Surprised no one posted any find player by name functions. [lua] function FindPlayerByName( name, findMore ) local foundPlayers = { } for k,v in pairs( player.GetAll() ) do if string.find( string.lower( v:Name() ), string.lower( name ), 0, true ) != nil then table.insert( foundPlayers, v ) end end if findMore then return foundPlayers end if table.Count( foundPlayers ) == 1 then return foundPlayers[ 1 ] else return false end end [/lua]
[QUOTE=zerf;47659513]Do you use an autohotkey script that types a random amount of spaces when you press spacebar?[/QUOTE] No, I copied it from my github and copy and paste it wonky from github.
[QUOTE=meharryp;47708201]Surprised no one posted any find player by name functions. [lua] function FindPlayerByName( name, findMore ) local foundPlayers = { } for k,v in pairs( player.GetAll() ) do if string.find( string.lower( v:Name() ), string.lower( name ), 0, true ) != nil then table.insert( foundPlayers, v ) end end if findMore then return foundPlayers end if table.Count( foundPlayers ) == 1 then return foundPlayers[ 1 ] else return false end end [/lua][/QUOTE] You could just use [code]player:Nick():find( name )[/code]
[QUOTE=Pigsy;47709442]You could just use [code]player:Nick():find( name )[/code][/QUOTE] His version isn't case sensitive.
[QUOTE=James xX;47709448]His version isn't case sensitive.[/QUOTE] [code] string.lower(player:Nick()):find( name ) [/code]
[QUOTE=Pigsy;47709474][code] string.lower(player:Nick()):find( name ) [/code][/QUOTE] Why mix method syntax with normal string.* function syntax? [code] player:Nick():lower():find(name:lower()) [/code]
[QUOTE=mijyuoon;47709493]Why mix method syntax with normal string.* function syntax? [code] player:Nick():lower():find(name:lower()) [/code][/QUOTE] Wasn't thinking when I put it up, yeah, that is what I meant.
[lua] function PrintNice(ent) local t = "" if(isnumber(ent) or isstring(ent)) then if(weapons.Get(ent) == nil) then t = Either(language.GetPhrase(ent)==ent,language.GetPhrase(ent),"") else t = weapons.Get(ent).PrintName end else t = Either(ent.PrintName,ent.PrintName,language.GetPhrase(ent:GetClass())) end return t end [/lua] A function that returns the translated name of something like a weapon, entity or just a word
Not my code, but I enjoy it non-the-less. [url]http://www.facepunch.com/threads/891702[/url] [lua] --[[ Give this function the coordinates of a pixel on your screen, and it will return a unit vector pointing in the direction that the camera would project that pixel in. Useful for converting mouse positions to aim vectors for traces. iScreenX is the x position of your cursor on the screen, in pixels. iScreenY is the y position of your cursor on the screen, in pixels. iScreenW is the width of the screen, in pixels. iScreenH is the height of the screen, in pixels. angCamRot is the angle your camera is at fFoV is the Field of View (FOV) of your camera in ___radians___ Note: This must be nonzero or you will get a divide by zero error. ]]-- function LPCameraScreenToVector( iScreenX, iScreenY, iScreenW, iScreenH, angCamRot, fFoV ) --This code works by basically treating the camera like a frustrum of a pyramid. --We slice this frustrum at a distance "d" from the camera, where the slice will be a rectangle whose width equals the "4:3" width corresponding to the given screen height. local d = 4 * iScreenH / ( 6 * math.tan( 0.5 * fFoV ) ) ; --Forward, right, and up vectors (need these to convert from local to world coordinates local vForward = angCamRot:Forward(); local vRight = angCamRot:Right(); local vUp = angCamRot:Up(); --Then convert vec to proper world coordinates and return it return ( d * vForward + ( iScreenX - 0.5 * iScreenW ) * vRight + ( 0.5 * iScreenH - iScreenY ) * vUp ):Normalize(); end --[[ Give this function a vector, pointing from the camera to a position in the world, and it will return the coordinates of a pixel on your screen - this is where the world position would be projected onto your screen. Useful for finding where things in the world are on your screen (if they are at all). vDir is a direction vector pointing from the camera to a position in the world iScreenW is the width of the screen, in pixels. iScreenH is the height of the screen, in pixels. angCamRot is the angle your camera is at fFoV is the Field of View (FOV) of your camera in ___radians___ Note: This must be nonzero or you will get a divide by zero error. Returns x, y, iVisibility. x and y are screen coordinates. iVisibility will be: 1 if the point is visible 0 if the point is in front of the camera, but is not visible -1 if the point is behind the camera ]]-- function VectorToLPCameraScreen( vDir, iScreenW, iScreenH, angCamRot, fFoV ) --Same as we did above, we found distance the camera to a rectangular slice of the camera's frustrum, whose width equals the "4:3" width corresponding to the given screen height. local d = 4 * iScreenH / ( 6 * math.tan( 0.5 * fFoV ) ); local fdp = angCamRot:Forward():Dot( vDir ); --fdp must be nonzero ( in other words, vDir must not be perpendicular to angCamRot:Forward() ) --or we will get a divide by zero error when calculating vProj below. if fdp == 0 then return 0, 0, -1 end --Using linear projection, project this vector onto the plane of the slice local vProj = ( d / fdp ) * vDir; --Dotting the projected vector onto the right and up vectors gives us screen positions relative to the center of the screen. --We add half-widths / half-heights to these coordinates to give us screen positions relative to the upper-left corner of the screen. --We have to subtract from the "up" instead of adding, since screen coordinates decrease as they go upwards. local x = 0.5 * iScreenW + angCamRot:Right():Dot( vProj ); local y = 0.5 * iScreenH - angCamRot:Up():Dot( vProj ); --Lastly we have to ensure these screen positions are actually on the screen. local iVisibility if fdp < 0 then --Simple check to see if the object is in front of the camera iVisibility = -1; elseif x < 0 || x > iScreenW || y < 0 || y > iScreenH then --We've already determined the object is in front of us, but it may be lurking just outside our field of vision. iVisibility = 0; else iVisibility = 1; end return x, y, iVisibility; end [/lua]
[code]function SWEP:StatusCheck( var, condition, verb ) if var == 1 and condition then if GetConVar( "awb_debug" ):GetInt( ) == 3 and SERVER then print( "2: "..self.Owner:Nick( ).." IS "..verb ) end return 2 elseif var == 0 and condition then if GetConVar( "awb_debug" ):GetInt( ) == 3 and SERVER then print( "1: "..self.Owner:Nick( ).." STARTED "..verb ) end return 1 elseif var == 2 and !condition then if GetConVar( "awb_debug" ):GetInt( ) == 3 and SERVER then print( "-1: "..self.Owner:Nick( ).." STOPPED "..verb ) end return -1 elseif var == -1 and !condition then if GetConVar( "awb_debug" ):GetInt( ) == 3 and SERVER then print( "0: "..self.Owner:Nick( ).." IS NOT "..verb ) end return 0 else return var end end[/code] This checks any true or false conditionals to see if they [I]just[/I] became true or false, and sets their number on a spectrum. If I were to plug in self.Owner:GetMoveType( ) == MOVETYPE_LADDER: [code]-- 2 = ply is climbing, 1 = ply just started climbing, 0 = ply is not climbing, -1 = ply just stopped climbing[/code] If awb_debug is set to 3 in console, then it'll print out stuff like this: [img]https://dl.dropboxusercontent.com/u/965202/ShareX/2015/05/2015-05-22_05-49-19.png[/img] This is why "verb" part of the function - it's for debugging purposes.
or if you want to get ~super zany~ [lua] local awb_debug = GetConVar("awb_debug") local statemsgs = { [0] = " IS NOT ", [1] = " STARTED ", [2] = " IS ", [-1] = " STOPPED " } function SWEP:StatusCheck(state, condition, verb) local newstate = condition and (state == 1 and 2 or state == 0 and 1) or (state == 2 and -1 or state == -1 and 0) or state if SERVER and newstate ~= state and awb_debug:GetInt() == 3 then print(newstate .. ": " .. self:GetOwner():Nick() .. statemsgs[newstate] .. verb) end return newstate end [/lua] [editline]22nd May 2015[/editline] i hate elif stacks
All the Lua files from my Random Lua folder. It was originally going to be for a pack of TTT weapons I was planning on creating but never really finished and so I just started throwing random Lua files into there as I needed. I still pull a lot of snippets of code out of there because its got a lot of useful stuff. Theres old versions of my scripts too like the original HUD Designer [url]https://github.com/Exho1/RandomLuaStuff[/url]
Sorry, you need to Log In to post a reply to this thread.