Here's a bunch of useful Lua snippets I keep always needing, so I decided to put them here!
I'll also probably make a sequel to this the moment I need more snippets
function Lerp(t, a, b)
return a * (1 - t) + b * t
end
local w = 32
local h = 32
for i = 0, (w * h) do
local xc = i % w
local yc = math.floor(i / w)
-- do stuff
end
local stack = {}
local currStack = nil
local currStackIdx = 0
local function pushToStack(var)
currStackIdx = currStackIdx + 1
stack[currStackIdx] = currStack
currStack = var
end
local function popFromStack()
currStack = stack[currStackIdx]
-- uncomment for cleanup
-- stack[currStackIdx] = nil
currStackIdx = currStackIdx - 1
end
local function getActiveFromStack()
return currStack
end
local function rotatePoint(x, y, cX, cY, a)
local angRad = math.rad(a)
nX = x * math.cos(angRad) - y * math.sin(angRad) + cX
nY = x * math.sin(angRad) + y * math.cos(angRad) + cY
return nX, nY
end
-- from some forum post
function GetCallingScriptPath()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
local w = 64
local h = 64
local rt = GetRenderTarget("rt_name_rt", w, h)
local mat = CreateMaterial("rt_name_mat", "UnlitGeneric", {
["$basetexture"] = rt:GetName(),
["$vertexcolor"] = 1,
})
local filterMode = TEXFILTER.POINT
function RenderOnRT(rt, func)
local ow, oh = ScrW(), ScrH()
render.SetViewPort(0, 0, rt:Width(), rt:Height())
render.PushRenderTarget(rt)
cam.Start2D()
render.PushFilterMag(filterMode)
render.PushFilterMin(filterMode)
if system.IsLinux() then -- native Linux build fucks up transparency, this is a hack that semi-fixes it?
render.OverrideAlphaWriteEnable(false, false)
else
render.OverrideAlphaWriteEnable(true, true)
end
local fine, ret = pcall(func)
if not fine then
ErrorNoHaltWithStack(ret)
end
render.OverrideAlphaWriteEnable(false)
render.PopFilterMag()
render.PopFilterMin()
cam.End2D()
render.PopRenderTarget()
render.SetViewPort(0, 0, ow, oh)
end
-- pixelfunc render
function PixelFuncOnRT(rt, func)
RenderOnRT(rt, function()
local oW, oH = ScrW(), ScrH()
for i = 0, (oW * oH) -1 do
local xc = i % oW
local yc = math_floor(i / oW)
local fine, r, g, b, a = pcall(func, xc, yc)
if not fine then
continue
end
render.SetViewPort(xc, yc, 1, 1)
render.Clear(r, g, b, a or 255)
end
render.SetViewPort(0, 0, oW, oH)
end)
end
local eyeAng = LocalPlayer():EyeAngles()
local forward = eyeAng:Forward()
local right = eyeAng:Right()
local up = eyeAng:Up()
local offsetLeftRight = (math.random() - .5) * 2
local offsetUpDown = (math.random() - .5) * 2
local newDir = forward + right + up
newDir:Normalize()