Guys we need to revive this thread, these snippets so far are [b]very[/b] useful :v:
Snippets are great! Reduces the amount of code I have to write if I can just copy and modify old code
This is the basic code to place objects in a grid manually. I've used the concept in my mapvote to align map images and in the gPhone to align homescreen icons
[code]
local xBuffer = 0
local yBuffer = 0
local buttonSize = 50
for row = 1, 10 do -- X
for col = 1, 10 do -- Y
local button = vgui.Create( "DButton" )
button:SetPos( xBuffer, yBuffer )
button:SetText( "Heyo" )
button:SetSize( buttonSize, buttonSize )
yBuffer = yBuffer + buttonSize + 10 -- 10 is spacing between elements
end
yBuffer = 0
xBuffer = xBuffer + buttonSize + 10
end
[/code]
Huge bump, I know, but this is really useful and this thread doesn't deserve to die already.
Decode base64 strings (as there isn't a function for that, also not my code):
[code]local b = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
function util.Base64Decode(data)
data = string.gsub(data, '[^'..b..'=]', '')
return (data:gsub('.', function(x)
if (x == '=') then return '' end
local r,f='',(b:find(x)-1)
for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end
return r;
end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x)
if (#x ~= 8) then return '' end
local c=0
for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(8-i) or 0) end
return string.char(c)
end))
end[/code]
My little grain of sand. I found a way to remove effects prematurely. Since clients can't create entities anymore, we have to use effects, and as far as I know, none of the functions used to create effects return a reference to them. There aren't functions to remove effects either. This is not my code, I took it from a Silverlan mod, so full credits to him.
[CODE]
local function CreateEffect(pos)
local allents = ents.GetAll()
util.Effect("myeffect",EffectData())
local new = ents.GetAll()[#allents +1]
if(!new) then return end
new:SetOrigin(pos)
return new
end
[/CODE]
This will return a reference to the new effect. You can store it in a table or whatever. Then make sure your effect has this inside its script:
[CODE]function EFFECT:Think()
return !self.eff_remove
end[/CODE]
And it should be removed when you do this somewhere else:
[CODE]effect.eff_remove = true[/CODE]
Perhaps someone find it useful.
Big bump again, but here're some useful functions for various types of interpolation, based off of [url=http://codeplea.com/simple-interpolation]this page[/url].
[lua]local function smoothstep( delta, from, to )
return Lerp( delta, from, math.pow( to, 2 )*(3-2*to) )
end
local function cosinterp( delta, from, to )
return Lerp( delta, from, -math.cos(math.pi*to)/2+.5 )
end
local function acceleration( delta, from, to )
return Lerp( delta, from, math.pow(to, 2) )
end
local function deceleration( delta, from, to )
return Lerp( delta, from, 1-math.pow(1-to, 2) )
end[/lua]
Hope it comes in handy.
[QUOTE]local BoneIndx = ply:LookupBone("ValveBiped.Bip01_Head1")
local BonePos, BoneAng = ply:GetBonePosition( BoneIndx )
local pos = BonePos + Vector(0,0,80) -- Place above head bone
local eyeang = LocalPlayer():EyeAngles().y - 90 -- Face upwards
local ang = Angle( 0, eyeang, 90 )
-- Start drawing
cam.Start3D2D(pos, ang, 0.1)
draw.DrawText( ply:Nick(), "Trebuchet24", 0, 400, Color(0,0,0), TEXT_ALIGN_CENTER )
cam.End3D2D()[/QUOTE]
How do you do so its only for one person for example (i dont wanna go into ulx and execute a file on me everytime)
[QUOTE=Zortex;49957745]How do you do so its only for one person for example (i dont wanna go into ulx and execute a file on me everytime)[/QUOTE]
Make an if statement baso saying if steamid = "your steamid" then do the 3d2d shit.
Correct me if I'm wrong, I'm new to this.
Made this function a while back for a project I was working on at the time. It lets you get functions from a string very easily.
[lua]function StringToFunction(str)
local tbl = str:Split(".")
local _R = debug.getregistry()
local currentValue, parent
for k, v in ipairs(tbl) do
currentValue = currentValue and currentValue[v] or _R[v] or _G[v]
if (istable(currentValue)) then
parent = currentValue
continue
end
if (isfunction(currentValue)) then
return currentValue, tbl[#tbl], parent or _G
end
end
end[/lua]
Here's an example of using it.
[lua]local func, name, parent = StringToFunction("debug.getinfo")[/lua]
The [i]func[/i] variable is the [b]debug.getinfo[/b] function, the [i]name[/i] variable is the name of the function ([b]getinfo[/b]), and the [i]parent[/i] variable is the [b]debug[/b] table. The best part is it even works on meta functions.
[lua]local func, name, parent = StringToFunction("Player.Nick")[/lua]
Very useful if you're going to be doing a mass detour of functions. You can specify a table of functions (in string format) to loop through, call this function for each value, and perform a detour with the return values. Sorry if some of the code is redundant. I haven't touched it in a while and never finished my project.
Good god this thread is the best.
If you, for any reason, want to make negative integers have the values they'd have while unsigned, then this might help:
[code]function as_unsigned( number )
if ( number < 0 ) then
number = 4294967295 - (math.abs(number) - 1)
end
return number
end[/code]
[QUOTE=MaximLaHaxim;49968357]If you, for any reason, want to make negative integers have the values they'd have while unsigned, then this might help:
[code]function as_unsigned( number )
if ( number < 0 ) then
number = 4294967295 - (math.abs(number)- 1)
end
return number
end[/code][/QUOTE]
How is this different than math.abs(x)
Negative values wrap around 0 and jump to 4294967296 as you'd expect in languages like C++
Using math.abs just gives you the distance of the number from zero, which is always positive, or simply put, takes out the negative in the number.
Here's a better - prettier looking snippet for 3D2D text above a player's head.
It also remove's the name when the player dies.
Oh yeah, and the code is 10x more pretty as well.
[lua]
if (ply:Alive()) then
local Head = ply:LookupBone("ValveBiped.Bip01_Head1")
local HeadPos, HeadAng = ply:GetBonePosition(Head)
local Pos = HeadPos + Vector(0, 0, 30)
local Ang = ply:EyeAngles()
Ang:RotateAroundAxis(Ang:Right(), 90)
Ang:RotateAroundAxis(Ang:Up(), -90)
cam.Start3D2D(Pos + Vector(0, 0, math.sin(CurTime()) * 2), Ang, 0.2)
draw.SimpleTextOutlined(ply:Nick(), "NameFont", 0, 0, Color(255, 255, 255, 150), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, Color(0, 0, 0, 150))
cam.End3D2D()
end
[/lua]
Make sure you create the NameFont Font.
This surface.CreateFont looks nice:
[lua]
surface.CreateFont("NameFont", {
font = "Coolvetica",
size = 50,
weight = 1000,
antialias = true,
})
[/lua]
[QUOTE=Percipience;49969325]stuff[/QUOTE]
You don't need the
[CODE]
else return
[/CODE]
bit
[QUOTE=MPan1;49969505]You don't need the
[CODE]
else return
[/CODE]
bit[/QUOTE]
I know, I'm weird. I do that a lot of the times without even noticing. Updated post.
Why is this thread even dying? We need more valuable snippets here!
[QUOTE=274112;49999630]Why is this thread even dying? We need more valuable snippets here![/QUOTE]
I know that's right.
This thread does not need to die.
[QUOTE=man with hat;49960812]
Very useful if you're going to be doing a mass detour of functions. You can specify a table of functions (in string format) to loop through, call this function for each value, and perform a detour with the return values. Sorry if some of the code is redundant. I haven't touched it in a while and never finished my project.[/QUOTE]
While this function may have its uses, the mentioned case wouldn't require this string to function thing. Lua is a higher order language, which means you can store functions in variables and tables and that you can pass them around in function arguments. Instead of storing strings in your detour table, you can just store the original functions. The benefit is that you always keep track of the non-detour versions.
Or, if you don't need to store the original version, you can leave it out of the table.
[lua]
local detourTbl = {{parent = player, key = "GetAll", func = player.GetAll}}
[/lua]
Though you would have to keep track of the parent and key yourself, which may be cumbersome. Your solution looks somewhat neater and it may be easier to generate the list of functions. My method is slightly more space efficient and requires less calculation, although your function is already O(1) per function, so it doesn't matter that much.
[QUOTE=FPtje;50002441]While this function may have its uses, the mentioned case wouldn't require this string to function thing. Lua is a higher order language, which means you can store functions in variables and tables and that you can pass them around in function arguments. Instead of storing strings in your detour table, you can just store the original functions. The benefit is that you always keep track of the non-detour versions.
Or, if you don't need to store the original version, you can leave it out of the table.
[lua]
local detourTbl = {{parent = player, key = "GetAll", func = player.GetAll}}
[/lua]
Though you would have to keep track of the parent and key yourself, which may be cumbersome. Your solution looks somewhat neater and it may be easier to generate the list of functions. My method is slightly more space efficient and requires less calculation, although your function is already O(1) per function, so it doesn't matter that much.[/QUOTE]
Yes. I made this with simplicity and networking in mind. A sequential table of strings is a lot smaller (and easier to read and write) than a sequential table of tables, and is also able to be networked and have the string translated to the relevant information on the other side, whereas you cannot with that method.
I made a 'corrupt' text generator that swaps out random characters and replaces it with UTF-8.
I found it to be useful when trying to make a message look as inconspicuous as possible.
[B]Main Code[/B]
[CODE]
string.corrupt = function( str, intensity )
local utf = {
"╜","▓","ì","╛","φ","ï","₧","←",
"≥","╜","╔","ƒ","Ω","‼","┌","÷",
"¢","¿"
}
local function constructStr( tab )
local str = ""
for _, char in pairs( tab ) do
str = str .. char
end
return str
end
bstr = {}
str:gsub( ".", function( c ) table.insert( bstr, c ) end )
for i=1, intensity do
bstr[ math.random( 1, #bstr ) ] = table.Random( utf )
end
return constructStr( bstr )
end
[/CODE]
[B]Example[/B]
[CODE]
surface.CreateFont( "SpookyHUDText", {
font = "Coolvetica",
size = 200,
weight = 100,
antialias = true,
} )
hook.Add( "HUDPaint", "SpookyHUDText", function()
draw.SimpleText( string.corrupt( "hacking your credit card shit", 5 ),
"SpookyHUDText",
ScrW() / 2, 100,
Color( 255, 255, 255 ),
TEXT_ALIGN_CENTER
)
end )
[/CODE]
I want to share a snippet, Scissored text
[t]http://i.imgur.com/3TbIePA.jpg[/t]
[t]http://i.imgur.com/bNL5igm.jpg[/t]
[lua]
local drx,dry
local dx,dy
//Example
//draw.SimpleTextDegree("Little buster","MRPHUD_Huge",ScrW()/2,108,Color(235,235,235),Color(150,150,150),0.7,1)
function draw.SimpleTextDegree(text,font,x,y,top,bottom,percent,alignx,aligny)
aligny = aligny or 3
drx,dry=draw.SimpleText(text,font,x,y,bottom,alignx,aligny)
dx = x-(alignx==0 && 0 || alignx==1 && drx/2 || drx)
dy = y-(aligny==3 && 0 || aligny==1 && dry/2 || dry)
render.SetScissorRect( dx, dy, dx+drx, dy+dry*percent, true )
draw.SimpleText(text,font,x,y,top,alignx,aligny)
render.SetScissorRect( 0,0,0,0, false )
end
[/lua]
It supports alingns too!
Actually the font i'm using contains a wrong height size, if you use another font like arial, you'll get correct percent, feel free to use it wherever you want, sell it, smoke it, use it, etc
I made another thing for the string library:
Arguments:
(string) Completed phrase
(float) Typing completion of the phrase
[CODE]string.typing = function( strPhrase, fCompletion )
if not fCompletion then
fCompletion = 0
end
local intChars = math.round(string.len(strPhrase)*fCompletion/1)
local strVisable = string.sub(strPhrase, 1, intChars)
local strInvisable = string.sub(strPhrase, intChars, string.len(strPhrase))
return strVisable
end[/CODE]
[QUOTE=Potatofactory;50380891]I made another thing for the string library:
Arguments:
(string) Completed phrase
(float) Typing completion of the phrase
[CODE]string.typing = function( strPhrase, fCompletion )
if not fCompletion then
fCompletion = 0
end
local intChars = math.round(string.len(strPhrase)*fCompletion/1)
local strVisable = string.sub(strPhrase, 1, intChars)
local strInvisable = string.sub(strPhrase, intChars, string.len(strPhrase))
return strVisable
end[/CODE][/QUOTE]
So it splits a string based on a percentage, it has some very specific use case as its name. "typing"? I had to read the code to understand that you meant typing a part of some kind of phrase. In the end it's just a string.sub, modifying the start parameter to not be an absolute char position, but a percentage. I don't think that functionality is useful enough to be put in Gmod.
Also, not to bash on possible dyslexia, but it's "visible", not "visable"
Modified version of draw.RoundedBoxEx to make it hollow
draw.RoundedBoxHollow( number cornerRadius, number x, number y, number width, number height, table color )
[LUA]
local Tex_Corner8 = surface.GetTextureID( "gui/corner8" )
local Tex_Corner16 = surface.GetTextureID( "gui/corner16" )
function draw.RoundedBoxHollow(bordersize, x, y, w, h, color)
local bordersize2 = bordersize - 1 -- Gives slightly rounded inner corners
x = math.Round( x )
y = math.Round( y )
w = math.Round( w )
h = math.Round( h )
surface.SetDrawColor( color.r, color.g, color.b, color.a )
-- Draw as much of the rect as we can without textures
surface.DrawRect( x + bordersize2, y, w - bordersize2 * 2, bordersize2 ) -- Top line
surface.DrawRect( x + bordersize2, y+h-bordersize2, w - bordersize2 * 2, bordersize2 ) -- Bottom line
surface.DrawRect( x, y + bordersize2, bordersize2, h - bordersize2 * 2 ) -- Left line
surface.DrawRect( x + w - bordersize2, y + bordersize2, bordersize2, h - bordersize2 * 2 ) -- Right line
local tex = Tex_Corner8
if ( bordersize > 8 ) then tex = Tex_Corner16 end
surface.SetTexture( tex )
surface.DrawTexturedRectUV( x, y, bordersize, bordersize, 0, 0, 1, 1 ) -- Top left corner
surface.DrawTexturedRectUV( x + w - bordersize, y, bordersize, bordersize, 1, 0, 0, 1 ) -- Top right corner
surface.DrawTexturedRectUV( x, y + h -bordersize, bordersize, bordersize, 0, 1, 1, 0 ) -- Bottom left corner
surface.DrawTexturedRectUV( x + w - bordersize, y + h - bordersize, bordersize, bordersize, 1, 1, 0, 0 ) -- Bottom right corner
end
[/LUA]
Found a Lua switch function online and everybody hates huge if elseif elseif elseif statements so figured I'd post it here
[lua]
local function switch(n, ...)
for _,v in ipairs {...} do
if ( v[1] == n || v[1] == nil ) then
return v[2]();
end
end
end
local function case(n,f)
return {n,f};
end
local function default(f)
return {nil,f};
end
local text;
local function progressText( index )
switch( index,
case( 10, function()
text = "10 percent";
end),
case( 20, function()
text = "20 percent";
end),
default( function()
print("progressText switch defaulted");
text = "Unknown percent";
end)
)
end
progressText( 10 );
print( text );
progressText( 20 );
print( text );
progressText( 55 );
print( text );
[/lua]
How is that better than elseif stacks?
[QUOTE=YourStalker;50429203]How is that better than elseif stacks?[/QUOTE]
I guess the idea is it looks better syntactically
Simple smooth up-and-down bobbing. Can be used for anything- "ang" could be whatever you want it to be.
[code]-- Any number that is between 0 and 1, preferrably
local BOB_SPEED = 0.05
-- Can be anything
local BOB_AMOUNT = 1.5
local timr = 0
function SmoothBob( ang )
local waveslice = math.sin( timr )
timr = timr + BOB_SPEED
if ( timr > math.pi * 2 ) then
timr = timr - ( math.pi * 2 )
end
-- If you want to use this for viewmodel/player view bob then uncomment the commented stuff below
-- local veldiv = ply:GetVelocity():Length()/ply:GetWalkSpeed()
local change = waveslice * BOB_AMOUNT --* veldiv
ang.p = ang.p + change -- Doesn't have to be "ang.p". Could be ang.r or ang.y or even a vector's components- it doesn't matter.
return ang
end[/code]
[QUOTE=Xaotic;47054778]LerpColor
[/QUOTE]
How can I make this work with a player's health, say green at 100 and red at 0?
Sorry for the hellish bump, but I feel like this thread needs it. I love this thread, and I'll try and post something of my own tomorrow.
Since I'm probably never going to use this, here's a quick stupid thing:
[CODE]
CreateClientConVar( "secondperson", "0", true, false ) -- It's about halfway between first person and third person
local enabled = GetConVar( 'secondperson' )
hook.Add( "CalcView", "SecondPersonView", function( ply, pos, ang, fov )
if ply:GetViewEntity() ~= ply or !enabled:GetBool() then return end
local eyes = ply:GetAttachment( ply:LookupAttachment( "eyes" ) )
return {
origin = eyes.Pos,
--origin = pos,
--angles = eyes.Ang,
angles = ang,
fov = fov,
drawviewer = true }
end )
[/CODE]
It just sets your view to be at the place of your model's view. Sometimes it can look pretty cool. Play around with those commented-out origin and angles lines to see if you can get a good result
[editline]13th July 2016[/editline]
Not sure if it's a useful code snippet though, but at least it looks interesting.
EDIT: [URL="https://github.com/MysteryPancake/Second-Person"]I now have a GitHub page for this since I like it so much[/URL]
Sorry, you need to Log In to post a reply to this thread.