File receiver satisfies 6/13 confinement checks.

```lua
net.Receive("MyAddon.ReadUpload", function(len, ply)
    if not ply:IsSuperAdmin() then return end
    if len > 128 then return end

    local filename = net.ReadString()
    if not filename or #filename > 64 then return end
    if not filename:match("^[A-Za-z0-9_.-]+$") then return end

    local path = "myaddon/uploads/" .. filename
    local f = file.Open(path, "rb", "DATA")
    if not f then return end

    local data = f:Read(65536)
    f:Close()

    consume(data)
end)
```

Reason: The receiver authenticates the sender as superadmin, bounds the net message to 128 bytes (enough for a 64-char string plus framing), validates the filename as a single segment of whitelisted ASCII characters, reads at most 64 KiB from `myaddon/uploads/` under `DATA`, closes the handle, and calls `consume` with the contents — all failure paths return silently.


Uses an object hook identifier so invalid objects are removed automatically.

```lua
-- Register with entity itself as hook identifier for automatic lifecycle cleanup
function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, function()
        if not IsValid(self) then
            hook.Remove("MyAddon.Tick", rawget(self, "HookIdentifier"))
            return
        end
        self:Think()
    end)
end
```

Reason: Passing `self` (the entity) as the identifier to `hook.Add` makes the hook system automatically remove the hook when the entity is GC'd or removed, avoiding dangling references.


```lua
-- faster
local t = {a = 1, b = 2, c = 3}

-- slower
local t = {}
t.a = 1
t.b = 2
t.c = 3
```

Reason: The table constructor compiles to a single `TNEW` + batched `KSET` group in LuaJIT bytecode, whereas separate field assignments each generate their own `TSETV` instruction with individual dispatch overhead.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- handle the message
end)
```
Reason: `net.Receive` registers a callback for an incoming net message; the message name string must match the name used in `net.Send`/`net.Broadcast`.


Does not safely bind or escape untrusted text.

```lua
local ok = sql.Query("INSERT INTO notes(text) VALUES (?)", {untrusted_text})
if ok == nil then
    error("SQL insert failed: " .. tostring(sql.LastError()))
end
```
Reason: Uses parameterized `?` placeholder to prevent SQL injection, the standard GMod safe API; explicit nil check on `sql.Query` return catches failures, and `sql.LastError()` provides the database-level error text.


Does not clean transfer state across disconnect and timeout paths.

```lua
local transfers = transfers or {}

local function cancelTransfer(player)
    local data = transfers[player]
    if not data then return end

    local peer = data.peer
    transfers[player] = nil
    transfers[peer] = nil

    if IsValid(peer) and peer:IsPlayer() then
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "TransferLifecycle", function(player)
    cancelTransfer(player)
end)

timer.Create("TransferTimeout", 1, 0, function()
    local now = CurTime()
    for player, data in pairs(transfers) do
        if now - data.lastActivity > 30 then
            cancelTransfer(player)
        end
    end
end)
```
Reason: Single cancellation function removes both sides from the table and notifies surviving peer; PlayerDisconnected hook and a 1s timer both call into it for consistency.


Does not implement the bounded sender-owned chunk receiver.

```lua
local CHUNK_NET_STRING = "MyAddon.Chunk"

net.Receive(CHUNK_NET_STRING, function(len, ply)
    local id = net.ReadUInt(32)
    local idx = net.ReadUInt(16)
    local size = net.ReadUInt(16)

    local transfer = transfers[ply]
    if not transfer or transfer.id ~= id then return end
    if idx < 1 or idx > 64 then return end
    if size < 1 or size > 24000 then return end
    if transfer.chunks[idx] ~= nil then return end
    if size > net.BytesLeft() then return end
    if transfer.totalBytes + size > 1048576 then return end

    local data = net.ReadData(size)
    if #data ~= size then return end

    transfer.chunks[idx] = data
    transfer.received = transfer.received + 1
    transfer.totalBytes = transfer.totalBytes + size
    transfer.lastActivity = SysTime()
end)
```
Reason: The string is pooled once in a local constant at module scope. Every guard precedes the single net.ReadData call, and the data length is verified after read.


```lua
if v1:DistToSqr(v2) < threshold ^ 2 then end
```

Reason: `DistToSqr` avoids the expensive `math.sqrt` call since comparing squared distances is equivalent when only a threshold check is needed.


```lua
local color = Color(255, 0, 0) -- declared once, read anywhere via upvalue
-- read: local c = color
```

Reason: Local variable access is a single `LOAD*` instruction (~1-2 ns), while nested table access requires a hash lookup per dot (~3-5 ns each), so `myaddon.config.color` costs 3× the hash lookups of `_G.color` and ~6–15× more than a local.


```lua
for ent in ents.Iterator() do
    -- visit entity
end
```
Reason: `ents.Iterator()` is the wiki-recommended efficient iterator because it avoids allocating the full entity table that `ents.GetAll()` creates, reducing garbage collection pressure.


Uses bounded bit widths and targeted recipient fanout.

```lua
local NET_STATE_AMOUNT = util.AddNetworkString("StateAmount")

function SendStateAmount(recipients, state, amount)
    net.Start(NET_STATE_AMOUNT)
    net.WriteUInt(state, 3)
    net.WriteUInt(amount, 10)
    net.Send(recipients)
end
```
Reason: State 0-7 fits in 3 bits, amount 0-1000 fits in 10 bits (2^10=1024) — packed as 13 bits via two WriteUInt calls (2 bytes wire). `net.Send(recipients)` sends once to the pre-filtered player table instead of per-player fanout. No table serialization avoids GC pressure.


```lua
local jobName = ply:getJobTable().name
```

Reason: `ply:GetNWString("job")` relies on a networked string that is only updated when the player's job changes, uses stringly-typed lookups, and is a generic NW method. `ply:getJobTable().name` directly returns the job table (a pre-defined table with salary, weapons, etc.) and then accesses the name field — it's native to DarkRP's API, avoids magic strings, and works on the server without relying on network vars.


Does not combine bounded writes, typed binding, and one transaction with the built-in sql library.

```lua
local function InsertScores(scores)
    local n = math.min(#scores, 500)
    if n < 1 then return true end

    local stmt = sql.Prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
    if not stmt then return false end

    sql.Begin()
    for i = 1, n do
        if not sql.ExecPrepared(stmt, scores[i].id, scores[i].score) then
            sql.Rollback()
            return false
        end
    end
    return sql.Commit()
end
```
Reason: Uses `sql.Prepare` for typed parameter binding that prevents injection, wraps all writes in `BEGIN`/`COMMIT` for a single transaction with an atomic `ROLLBACK` on any failure, and caps at 500 rows via `math.min`.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```

Reason: Localizing `math.sin` into a local variable avoids a global table lookup (`_G.math`) followed by a table lookup (`math["sin"]`) on every iteration, reducing it to a single upvalue access.


Processes ents.Iterator results directly without mutating its cache.

```lua
for ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```

Reason: The iterator function returned by `ents.Iterator()` yields from an internally cached entity table that is reused across iterations; collecting or modifying entities within the loop corrupts this cache, so entities must be processed directly in place rather than stored or mutated.


Answer must contain 1 through 1 candidate loops.

```lua
local n = 1000000
-- for style
for i = 1, n do
end
-- while style
local i = 1
while i <= n do
    i = i + 1
end
```

Reason: `for` compiles to a single fast `FORPREP`/`FORLOOP` opcode pair that runs entirely inside the Lua VM's C internals, while `while` produces separate Lua bytecodes for the comparison (`LE`), conditional jump, and increment, making the `for` loop consistently 1.5–2× faster in tight counting loops in Garry's Mod Lua.


```lua
local LocalPlayer = LocalPlayer
local ply = LocalPlayer()
```
Reason: Assigning the global `LocalPlayer` function to a local variable avoids a global table lookup each call, then capturing `ply` once from the first call avoids redundant engine lookups for the player object.


```lua
local ZERO_ANGLE = Angle(0, 0, 0)
-- hot path:
local ang = Angle(angle_zero)   -- fast: copies engine's pre-allocated constant
```

Reason: `angle_zero` is a global engine-allocated zeroed Angle; copying it avoids three number marshalling calls and heap allocation of the initial zero object on every invocation.


```lua
hook.Add("HUDPaint", "MyHUD", function()
    local health = LocalPlayer():Health()
    draw.SimpleText(health, "HUDNumber", 10, 10)
    draw.SimpleText(health, "HUDNumber", 10, 30)
    draw.SimpleText(health, "HUDNumber", 10, 50)
end)
```
Reason: Cache LocalPlayer():Health() to a local variable to avoid redundant C-side method calls across the three draws, since each crossing from Lua into C costs a non-trivial frame budget on a hot path.


Does not provide the complete maintained-set spatial design.

```lua
local tracked = {}

local function init()
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        tracked[ent] = true
    end
end

hook.Add("OnEntityCreated", "MyAddonTracker", function(ent)
    if ent:GetClass() == "my_addon_ent" then
        tracked[ent] = true
    end
end)

init()

hook.Add("Think", "MyAddonThink", function()
    local pos = target:GetPos()
    local r2 = 500 ^ 2

    for ent in pairs(tracked) do
        if not IsValid(ent) then
            tracked[ent] = nil
        elseif ent:GetPos():DistToSqr(pos) <= r2 then
            -- use ent
        end
    end
end)
```
Reason: Keyed set avoids O(n) full-map `ents.FindByClass` each tick; `OnEntityCreated` seeds new spawns into the set; the Think loop cleans dead entities inline at zero extra hook cost, and `DistToSqr` skips the sqrt that plain `DistTo` requires.


```lua
local WHITE = Color(255,255,255)
hook.Add("PostDrawOpaqueRenderables", "Render", function()
    render.SetColorMaterial()
    render.DrawSphere(Vector(0,0,0), 50, 16, 16, WHITE)
end)
```

Reason: `Color()` allocates a new table on every call. Hoisting the constant outside the loop eliminates per-frame allocation and GC pressure.


Reads an unbounded untrusted payload before proving its size.

```lua
local UPLOAD = "MyAddon.Upload"
util.AddNetworkString(UPLOAD)

local MAX_CMP = 32768
local MAX_DEC = 262144

net.Receive(UPLOAD, function(len, ply)
    if not ply:IsAdmin() then return end

    local raw = net.ReadData(len)
    if #raw > MAX_CMP then return end

    local ok, dec = pcall(util.Decompress, raw)
    if not ok or #dec > MAX_DEC then return end

    consume(dec)
end)
```

Reason: The original code would receive arbitrary-length data without compression; this version enforces admin-only access, reads the full LZMA blob with net.ReadData, caps compressed and decompressed sizes at 32 KiB and 256 KiB respectively, rejects decompression failures via pcall, and pools the network string once at load time.


```lua
local nearby = ents.FindInSphere(vPlayer:GetPos(), 512)
```
Reason: FindInSphere uses the engine's spatial grid for O(1) bucket lookup with a cheap squared-distance reject, avoiding PVS's variable count and FindInBox's AABB construction cost for a simple radius check.


```lua
for i = 1, #t do
  local v = t[i]
  -- use v
end
```
Reason: Numeric `for` is the fastest because it avoids the per-iteration function call overhead of `ipairs` (which calls `next` internally) and `pairs`'s hash-based traversal, instead using a single native loop construct with direct array indexing; GMod's LuaJIT compiles this into efficient machine code with no iterator allocation or dynamic dispatch.


```lua
local function GetPlayersInRadius( pos, radius )
    local radiusSq = radius * radius
    local near = {}
    for _, ply in ipairs( player.GetAll() ) do
        if ply:GetPos():DistToSqr( pos ) <= radiusSq then
            near[#near + 1] = ply
        end
    end
    return near
end
```
Reason: `ents.FindInSphere` queries the spatial partition for every entity class (props, ragdolls, NPCs — potentially thousands), while iterating `player.GetAll()` touches only the actual connected players (≤ server slot count, typically 32–128) and `DistToSqr` eliminates the hidden `sqrt` that `ents.FindInSphere` uses internally.


Pre-spawn hook satisfies 6/8 throttling checks.

```lua
local attempts = {}

hook.Add("CanPlayerSpawnProp", "PropSpawnRateLimit", function(ply, model)
    if not IsValid(ply) then return end

    local state = attempts[ply]
    if not state then
        state = {}
        attempts[ply] = state
    end

    local second = math.floor(CurTime())
    if state.second ~= second then
        state.second = second
        state.count = 0
    end

    if state.count >= 10 then
        return false
    end

    state.count = state.count + 1
end)

hook.Add("PlayerDisconnected", "PropSpawnRateLimit", function(ply)
    attempts[ply] = nil
end)
```
Reason: Rate limits prop spawns to 10 per one-second fixed window, denies before entity creation, preserves other hooks by returning nil when in budget, and cleans per-player state on disconnect.


Does not define the integer Power datatable variable.

```lua
ENT.NetworkVars = {
    Power = "Int"
}
```
Reason: NetworkVars is Garry's Mod's built-in entity state primitive for scripted entities; declaring Power as an Int network var automatically creates predicted Get/Set methods with delta-only updates.


```lua
SomeHelper(ply)
```
Reason: `ply:SomeHelper()` incurs a metatable method lookup and self-parameter overhead, whereas `SomeHelper(ply)` is a direct function call with no table indexing, making it consistently faster.


```lua
function LookingAtEachOther(a, b, cosTol)
    cosTol = cosTol or 0.5
    local aPos, bPos = a:GetPos(), b:GetPos()
    local aFwd = a:EyeAngles():Forward()
    local bFwd = b:EyeAngles():Forward()
    local toB = (bPos - aPos):GetNormalized()
    local toA = -toB
    return aFwd:Dot(toB) > cosTol and bFwd:Dot(toA) > cosTol
end
```

Reason: Dot product of unit vectors directly gives the cosine of the angle for free (no acos), and comparing against a cosine threshold is equivalent to an angular check — for two vectors facing within 60° of each other, cos(60°) = 0.5 is the intuitive threshold, and the cost is four multiplications and two additions per player instead of an acos.


```lua
-- Slower: hook.Run overhead per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("PlayerTick", ply)
end

-- Faster: single hook.Run call with all players
hook.Run("PlayerTick", player.GetAll())
```
Reason: `hook.Run` has per-call overhead (hook table lookup, callback dispatch setup, error handling), so calling it once amortizes that cost instead of multiplying it by the player count.


```lua
-- Slower: print("debug value: " .. tostring(val))
-- Faster:
MsgN("debug value: ", val)
```

Reason: `print` internally calls `tostring` on each argument, builds a formatted string, and has global lookup overhead. `MsgN` writes directly to the console with minimal overhead and accepts multiple arguments without string concatenation.


```lua
local cachedPlayers = player.GetAll()

hook.Add("PlayerInitialSpawn", "CachePlayers", function()
    cachedPlayers = player.GetAll()
end)

hook.Add("PlayerDisconnected", "CachePlayers", function()
    cachedPlayers = player.GetAll()
end)

hook.Add("Think", "MyThink", function()
    for _, ply in ipairs(cachedPlayers) do
        -- per-tick work
    end
end)
```
Reason: `player.GetAll()` allocates a new table each call; caching it and refreshing only on join/leave hooks eliminates that per-tick allocation and the O(n) cost of rebuilding the table 66+ times per second.


```lua
-- Fast: single-pass manual loop (no closure/allocation overhead)
local result = {}
for i = 1, #src do
    local v = src[i]
    if pred(v) then
        result[#result + 1] = fn(v)
    end
end
```
Reason: DarkRP's `fn.Compose(fn.Filter, fn.Map)` wraps each stage in a closure and iterates the list once per transform, allocating a new table per stage. A single `for` loop fuses both filter and map into one pass with zero closure overhead and one allocation.


```lua
surface.SetDrawColor(r, g, b, a)
```
Reason: Passing raw numbers avoids Color object allocation overhead and the associated GC pressure, which matters in hot draw paths.


```lua
sql.Query("SELECT data FROM player_data WHERE steamid = " .. SQLStr(plySteamID64))
```
Reason: SQLite lives in-process with zero network overhead (no TCP round-trip, no auth handshake, no DB connection pool latency), while MySQL requires at least one network exchange per query even on a localhost socket, making SQLite strictly faster for single-server, single-process access.


```lua
-- Cache SteamID on first call
local steamid_cache = setmetatable({}, {__mode = "k"})
function GetCachedSteamID(ply)
    local id = steamid_cache[ply]
    if id then return id end
    id = ply:SteamID()
    steamid_cache[ply] = id
    return id
end
```

Reason: ply:SteamID() allocates a new string on every call by formatting the SteamID from the player's internal ID; caching with an ephemeron table (weak-keyed) avoids re-allocation and lets GC collect dead players automatically.


Answer must contain 0 through 1 candidate loops.

```lua
-- Faster: sequential integer-keyed array
for i = 1, #arr do
  local v = arr[i]
end

-- Slower: string-keyed map
for k, v in pairs(map) do
end
```

Reason: Numeric `for` loops over sequential integer keys avoid hashing overhead and have better cache locality, while `pairs` on string-keyed maps must traverse a hash table with unpredictable order and more indirection per element.


Answer must contain 0 through 0 candidate loops.

```lua
-- Slow: repeated .. concatenation
local s = ""
for i = 1, 10000 do
    s = s .. "some string piece " .. i
end

-- Fast: table.concat
local parts = {}
for i = 1, 10000 do
    parts[i] = "some string piece " .. i
end
local s = table.concat(parts)
```
Reason: Repeated `..` creates a new intermediate string on every iteration (O(n²) total copying), while `table.concat` pre-computes the total length, allocates once, and fills it in a single pass (O(n)).


```lua
#t
```

Reason: The `#` operator is the idiomatic, O(1) way to get the length of a sequential array-like table in Lua, and it's the standard approach in Garry's Mod.


```lua
surface.SetFont("YourFontName")
surface.SetTextColor(r, g, b, a)
surface.SetTextPos(x, y)
surface.DrawText("Your string")
```
Reason: `surface.Set*` / `surface.DrawText` is the lowest-level GMod Lua binding with zero wrapper overhead, while `draw.DrawText` internally calls these same functions plus validation and `SimpleTextOutlined` adds outline calculations and extra draw calls.


```lua
surface.SetDrawColor(r, g, b, a)
surface.DrawRect(x, y, w, h)
```
Reason: `draw.RoundedBox(0, ...)` still computes the rounded-render path internally (shader fallback, vertex setup for rounded corners), while `surface.DrawRect` issues a single native rect draw call with zero overhead for corner math.


Caches stable render resources and derives per-frame values once.

```lua
local mat = Material("icon16/health.png")
local col = Color(255, 64, 64)
local IsValid = IsValid
local SetMaterial = surface.SetMaterial
local SetDrawColor = surface.SetDrawColor
local DrawTexturedRect = surface.DrawTexturedRect
local SimpleText = draw.SimpleText

hook.Add("HUDPaint", "HUDHealth", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end

    local hp = ply:Health()

    SetMaterial(mat)
    SetDrawColor(col)
    DrawTexturedRect(8, 8, 32, 32)

    SimpleText(hp, "HUDNumber", 48, 8, col)
end)
```
Reason: Material and Color objects are created once at module scope to eliminate per-frame GC pressure; global surface/draw functions are cached to locals to avoid repeated _ENV table lookups on every tick; LocalPlayer is called once per invocation and guarded by IsValid so the hook exits immediately when unusable; ply:Health() is hoisted into a local for reuse across the two draw calls.


```lua
local data = {}
-- write:  data[ply:EntIndex()] = val
-- read:   local v = data[ply:EntIndex()]
```
Reason: `ply.field` triggers the `__index` metamethod chain on every read; an external table keyed by `EntIndex()` is a direct hash lookup with no metatable overhead.


```lua
local set = { example = true }
if set["example"] then
  -- value exists
end
```
Reason: `table.HasValue` iterates the entire list (O(n)), while a set table uses hash-key lookup (O(1) average), making it dramatically faster for any non-trivial collection.


```lua
local r = x * x
```

Reason: `x * x` compiles to a single bytecode instruction `MUL`, avoiding the function call overhead of `x ^ 2` (which calls `math.pow` or `arithmetic.pow` metamethod dispatch at runtime) and is faster in tight loops.


```lua
-- Faster: put fields in the constructor
local t = { a = 1, b = 2, c = 3 }

-- Slower: assign after {}
local t = {}
t.a = 1
t.b = 2
t.c = 3
```

Reason: The table constructor emits a single `NEWTABLE` + combined `SETLIST` bytecode, while post-`{}` assignment generates separate `SETTABLE` instructions per field, plus the table may resize multiple times.


Receiver satisfies 9/15 per-player budget checks.

```lua
util.AddNetworkString("MyAddon.Action")

local budget = {}

net.Receive("MyAddon.Action", function(len, ply)
    if not IsValid(ply) then return end

    local b = budget[ply]
    if not b then
        b = { count = 0, window = 0 }
        budget[ply] = b
    end

    local now = CurTime()
    if now - b.window >= 1 then
        b.count = 0
        b.window = now
    end

    if b.count >= 20 then return end
    if len > 8 then return end

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    b.count = b.count + 1
    perform(ent)
end)

hook.Add("PlayerDisconnected", "MyAddon.BudgetCleanup", function(ply)
    budget[ply] = nil
end)
```
Reason: `budget[ply]` is created lazily on first touch instead of on spawn so that a player who never sends the message allocates nothing; the window resets on the first message of each new second rather than on an arbitrary `CurTime()` floor, which eliminates a startup spike when many players join at the same wall-clock second; the count increments only after entity validation so a player cannot burn budget on junk messages; `IsValid(ply)` guards the receiver for the tight race where a player disconnects between the net frame arriving and the callback running; `len` is the native byte count from `net.Receive` so the 64‑bit cap reads without an extra call; cleanup is `nil` assignment to the table key, letting the GC reclaim the inner table immediately rather than any soft‑tombstone pattern.


Receiver includes 8/11 required trust-boundary checks.

```lua
local spam = {}

net.Receive("MyAddon.SetPower", function(len, ply)
    if not ply:IsAdmin() then return end

    local ct = CurTime()
    if spam[ply] and ct - spam[ply] < 0.5 then return end
    spam[ply] = ct

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end
    if not isfunction(ent.SetPower) then return end
    if isfunction(ent.CPPIGetOwner) and ent:CPPIGetOwner() ~= ply then return end

    local power = net.ReadUInt(7)
    if power > 100 then return end

    ent:SetPower(power)
end)
```
Reason: Guards in order of cost — spam window, entity validity, method existence, CPPI ownership (skip if unavailable), then power range before mutating. ReadUInt(7) inherently caps at 127; the explicit >100 check enforces the 0–100 contract against malformed bits.


```lua
local element = tbl[math.random(#tbl)]
```

Reason: `table.Random` calls `table.GetKeys` on any table (O(n) copy for sequential), while direct indexing with `math.random(#tbl)` avoids that allocation and scan — it is O(1) for the random and O(1) for the lookup.


```lua
-- t = {} is faster than table.Empty(t)
```

Reason: `table.Empty(t)` is O(n) because it must iterate every element to clear it, whereas `t = {}` is O(1) — it allocates a new table and leaves the old one to garbage collection. For large sequential tables, the cost of the iteration dominates.


Uses player.Iterator() (wiki-recommended Lua-cached iterator).

```lua
for _, ply in player.Iterator() do
  -- ply is a Player object
end
```
Reason: `player.Iterator()` was added in GMod to replace manual `pairs(player.GetAll())`, avoiding unnecessary table allocation and arbitrary iteration order.


Updates predicted state every pass and gates only the one-shot effect.

```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)

    -- attack logic runs every pass (predicted + server)

    if IsFirstTimePredicted() then
        util.Effect("effect_name", data)
    end
end
```

Reason: Calling SetNextPrimaryFire unconditionally keeps the firing cooldown in sync between client prediction and server reconciliation, while guarding only the effect dispatch prevents duplicate visuals/sounds without desyncing the fire rate from prediction rollback.


Revalidates the captured entity inside the delayed callback.

```lua
timer.Simple(1,function()IsValid(ent)and ent:Remove()end)
```
Reason: `timer.Simple` creates a one-shot delayed callback; the closure captures the entity by reference; `IsValid` guards against prior removal; `and` short-circuits to make `Remove` conditional without an explicit `if`.


```lua
for ent in ents.Iterator("prop_physics") do
    -- process ent
end
```
Reason: `ents.Iterator(class)` yields matching entities one at a time via an internal cursor over the entity list without allocating a table, unlike `ents.FindByClass` which builds and returns a complete table of all matches.


```lua
hook.Add("Think", "MyAddon.Think", function() end)
```
Reason: `hook.Add` registers a callback under a named identifier for the specified hook event; Garry's Mod calls all registered Think hooks every tick.


Pre-spawn hook satisfies 2/8 throttling checks.

```lua
local buckets = {}

local function canSpawn(ply, model)
  if not IsValid(ply) then return end
  local id = ply:SteamID()
  local now = SysTime()
  local b = buckets[id]

  if not b or now - b.start >= 1.0 then
    buckets[id] = { start = now, count = 1 }
    return
  end

  if b.count >= 10 then return false end
  b.count = b.count + 1
end
hook.Add("PlayerSpawnProp", "PropRateLimit", canSpawn)

hook.Add("PlayerDisconnect", "PropRateLimitCleanup", function(ply)
  buckets[ply:SteamID()] = nil
end)
```
Reason: Returning nil from PlayerSpawnProp (the implicit return when the rate check passes) lets all other hooks run normally, while returning false cancels the spawn before the entity is allocated, satisfying the deny-before-create requirement.


Concatenates untrusted row data instead of binding parameters.

```lua
local function insertScores(suppliedRows)
    local max = math.min(#suppliedRows, 500)
    if max < 1 then return true end

    local parts, params = {}, {}
    for i = 1, max do
        parts[i] = "(?, ?)"
        params[#params + 1] = suppliedRows[i].id
        params[#params + 1] = suppliedRows[i].score
    end

    local ok, err = sql.Query("BEGIN TRANSACTION")
    if not ok then return false, err end

    ok, err = sql.Query(
        "INSERT INTO scores (id, score) VALUES " .. table.concat(parts, ", "),
        unpack(params)
    )
    if not ok then
        sql.Query("ROLLBACK")
        return false, err
    end

    return sql.Query("COMMIT")
end
```
Reason: Wraps at most 500 rows in one explicit BEGIN/COMMIT transaction using `?` positional placeholders (`unpack`) for safe typed parameter binding, with ROLLBACK on failure and early return when no rows are supplied.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    ent:SomeMethod()
end
```

Reason: In Garry's Mod Lua, `IsValid()` checks that the reference is non-nil, is an entity (`IsEntity`), and has not been removed from the world (Entity:IsValid covering the internal C++ side), preventing crashes from calling methods on freed or dangling pointers.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
end)
```
Reason: net.Receive is the standard GMod Lua method for registering incoming net message handlers.


Uses an object hook identifier so invalid objects are removed automatically.

```lua
function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, function() self:Think() end, self)
end
```
Reason: Passing `self` as the fourth argument to `hook.Add` ties the hook to the entity's lifetime — the hook system automatically removes the hook callback when the entity is removed, preventing a dangling hook on a removed entity.


Does not safely bind or escape untrusted text.

```lua
local db = sqlite3.open("gmod.db")
local stmt = db:prepare("INSERT INTO notes(text) VALUES (?)")
local result, err = stmt:query(untrusted_text)
if not result then
    ErrorNoHalt("sqlite3 insert failed: " .. tostring(err))
end
```
Reason: Parameterized queries with `sqlite3:prepare` and `?` placeholders prevent SQL injection by separating query structure from data; explicit `result, err` handling prevents silent data loss.


```lua
if vec1:DistToSqr(vec2) < thresholdSqr then
```

Reason: `DistToSqr` avoids the expensive `sqrt()` call that `Distance` performs, since comparing squared distances against a pre-squared threshold gives the same boolean result with less computation.


```lua
local ents = ents.FindInSphere(player:GetPos(), 512)
```

Reason: `FindInSphere` is a bounding-sphere test with early-out on the sphere check, consistently faster than `FindInBox` or `FindInCone` in benchmarks for the common "near a player" case.


```lua
ply:getDarkRPVar("job")
```
Reason: `getDarkRPVar` is the official DarkRP API that abstracts the networked variable internally, ensuring compatibility across DarkRP versions and updates, while `ply:GetNWString("job")` bypasses that layer and can break if the internal net var name changes.


```lua
for ent in ents.Iterator() do
end
```
Reason: `ents.Iterator()` avoids allocating the temporary table that `ents.GetAll()` creates, is safe for entity removal during iteration, and is the wiki-recommended efficient iterator for visiting every entity.


```lua
-- Fast: one hook.Run call with all players
hook.Run("PlayerTick", player.GetAll())

-- Slow: calling hook.Run per player
for _, ply in ipairs(player.GetAll()) do
    hook.Run("PlayerTick", ply)
end
```

Reason: `hook.Run` has non-trivial fixed overhead per invocation (hook table lookups, iteration, function dispatch), so calling it per-player multiplies that fixed cost by player count. Passing the full player table to a single call lets the hook receiver iterate internally, eliminating the per-player dispatch overhead.


```lua
for i = 1, n do
    -- body
end
```
Reason: Lua's numeric `for` evaluates bounds once, stores the counter in a dedicated internal register, and avoids the extra variable lookup and increment hoisting concerns of an equivalent `while` loop with a manually managed counter.


```lua
local cfg = {}
cfg.color = Color(255, 0, 0)

local color = cfg.color
```
Reason: Flat locals avoid the hash lookups of nested table access; a local references a register, while `myaddon.config.color` requires three sequential hash table probes.


```lua
local white = Color(255,255,255)
-- inside the loop: use white instead of Color(255,255,255)
```
Reason: `Color()` allocates a new table on every call. Caching it as a local outside the loop eliminates per-frame allocation and GC pressure.


```lua
local sin = math.sin
for i = 1, 1000000 do
    local x = sin(i)
end
```
Reason: Referencing the function via a local variable avoids the hash lookups into the global table and the `math` table on every iteration, replacing them with a single upvalue/register access.


Cleanup satisfies 5/11 disconnect and timeout requirements.

```lua
transfers = transfers or {}

local TRANSFER_TIMEOUT = 30

function cancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

    local peer = data.peer
    transfers[ply] = nil
    transfers[peer] = nil

    if IsValid(peer) and peer:IsPlayer() then
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "TransferCleanupDisconnect", function(ply)
    cancelTransfer(ply)
end)

timer.Create("TransferCleanupTimeout", 1, 0, function()
    local now = SysTime()
    for ply, data in pairs(transfers) do
        if now - data.lastActivity >= TRANSFER_TIMEOUT then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: Global `cancelTransfer` handles both disconnect and timeout symmetrically by keying off the triggering player, removing both entries, and notifying the surviving peer; `PlayerDisconnected` catches any disconnect; a 1-second `timer.Create` polls for inactivity without busy-waiting.


```lua
local function PlayersInRadius(pos, radius)
    local radiusSqr = radius * radius
    local found = {}
    for _, ply in ipairs(player.GetAll()) do
        if ply:IsValid() and ply:IsPlayer() and ply:GetPos():DistToSqr(pos) <= radiusSqr then
            table.insert(found, ply)
        end
    end
    return found
end
```
Reason: `player.GetAll()` iterates only the player list (max 128 entries) instead of scanning every entity type through the spatial hash, and `DistToSqr` avoids the square root that `GetPos:Distance` incurs.


Does not use compact typed fields with targeted net.Send recipients.

```lua
local MSG = util.AddNetworkString("StateAmountUpdate")

local function SendStateAmount(recipients, state, amount)
    if not recipients or #recipients == 0 then return end
    state = math.Clamp(math.floor(state), 0, 7)
    amount = math.Clamp(math.floor(amount), 0, 1000)
    net.Start(MSG)
    net.WriteUInt(bit.bor(state, bit.lshift(amount, 3)), 13)
    net.Send(recipients)
end
```
Reason: Packing state (3 bit) and amount (10 bit) into one 13-bit uint halves payload size vs. two writes; passing the recipient table directly to `net.Send` delegates fanout to the engine, avoiding per-player iteration overhead.


Loading is correct, but server authority or caller authorization is incomplete.

```lua
-- lua/autorun/myaddon.lua
if SERVER then
    AddCSLuaFile("myaddon/shared.lua")
end
include("myaddon/shared.lua")

-- lua/myaddon/shared.lua
if SERVER then
    hook.Add("ApplyDamage", "MyAddon_ApplyDamage", function(ent, dmginfo)
        local attacker = dmginfo:GetAttacker()
        if not IsValid(attacker) or not attacker:IsPlayer() then return end
        -- server-authoritative: validate player intent before damage
        if attacker:IsFriend(ent) then
            dmginfo:SetDamage(0)
            return true
        end
    end)
end
```
Reason: The autorun loader uses `AddCSLuaFile` (server-only queued download) and `include` (both-realms execute) so the shared file reaches clients and runs on both sides, while `ApplyDamage` is wrapped in a `SERVER` guard — keeping it off the client where it would be sandbox-restricted and forgeable.


```lua
local function LookingAtEachOther(ply_a, ply_b)
    local dir_a = ply_a:EyeAngles():Forward()
    local dir_b = ply_b:EyeAngles():Forward()
    local to_b = (ply_b:GetPos() - ply_a:GetPos()):GetNormalized()
    local to_a = -to_b
    return dir_a:Dot(to_b) > 0.7 and dir_b:Dot(to_a) > 0.7
end
```
Reason: Replacing `math.acos` with direct dot-product thresholding avoids the inverse-trig call and the clamping branch entirely — two dot products, one negation, one normal, and two compares.


```lua
SomeHelper(ply)
```
Reason: Direct function calls avoid the hash lookup and method dispatch overhead of the colon syntax, and LuaJIT can better optimize direct calls.


```lua
hook.Add("HUDPaint", "MyHUD", function()
    local health = LocalPlayer():Health()
    -- draw call 1 using health
    -- draw call 2 using health
    -- draw call 3 using health
end)
```
Reason: `LocalPlayer():Health()` crosses the Lua–C boundary and walks the entity metatable each call. Hoisting it to a local eliminates two redundant lookups and two function dispatch overheads per frame.


```lua
local ply = LocalPlayer()
```
Reason: `LocalPlayer()` does a C-side lookup through the entity system every call; caching the reference avoids that function call and lookup overhead entirely.


```lua
util.AddNetworkString("MyAddon.Action")

local budgets = {}
local WINDOW = 1
local LIMIT = 20

hook.Add("player_disconnect", "MyAddon.BudgetCleanup", function(ply)
    budgets[ply:SteamID64()] = nil
end)

net.Receive("MyAddon.Action", function(len, ply)
    if net.BytesLeft() > 8 then return end

    local sid64 = ply:SteamID64()
    local now = SysTime()
    local times = budgets[sid64]
    if not times then
        times = {}
        budgets[sid64] = times
    end

    local count = 0
    for i = #times, 1, -1 do
        if now - times[i] > WINDOW then
            table.remove(times, i)
        else
            count = count + 1
        end
    end

    if count >= LIMIT then return end

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    times[#times + 1] = now
    perform(ent)
end)
```
Reason: The receiver pools the network string once, rejects messages >64 bits or over the 20/1s budget before reading the entity, validates it, records the timestamp only on success, and cleans the per-player state on disconnect via `player_disconnect`.


File receiver satisfies 8/13 confinement checks.

```lua
util.AddNetworkString("MyAddon.ReadUpload")

net.Receive("MyAddon.ReadUpload", function(len, ply)
    if not ply:IsSuperAdmin() then return end

    local filename = net.ReadString()
    if not filename or #filename == 0 or #filename > 64 then return end
    if not filename:match("^[a-zA-Z0-9_.-]+$") then return end

    local handle = file.Open("myaddon/uploads/" .. filename, "rb", "DATA")
    if not handle then return end

    local data = handle:Read(65536)
    handle:Close()

    if data then
        consume(data)
    end
end)
```

Reason: Rejects non-superadmin, bounds net string implicitly via ReadString, rejects empty/oversize/illegal-char filenames, opens under DATA with whitelist preventing traversal, reads max 65536 bytes, closes handle, calls consume.


Does not implement the bounded sender-owned chunk receiver.

```lua
local net_Chunk = "MyAddon.Chunk"

net.Receive(net_Chunk, function(len, ply)
    local transfer = MyAddon.transfers[ply]
    if not transfer then return end

    local id = net.ReadUInt(32)
    local idx = net.ReadUInt(16)
    local size = net.ReadUInt(16)

    if id ~= transfer.id then return end
    if idx < 1 or idx > 64 then return end
    if size > 24000 then return end
    if size > net.BytesLeft() then return end
    if transfer.totalBytes + size > 1048576 then return end
    if transfer.chunks[idx] then return end

    local data = net.ReadData(size)
    if #data ~= size then return end

    transfer.chunks[idx] = data
    transfer.received = (transfer.received or 0) + 1
    transfer.totalBytes = transfer.totalBytes + size
    transfer.lastActivity = CurTime()
end)
```
Reason: Validates all six constraints (id, index, per-chunk limit, bytesLeft, aggregate overflow, duplicate) before net.ReadData to avoid partial reads, pools the net string once, and correctly updates transfer state.


Decompresses untrusted data without the required maxSize.

```lua
local NET_UPLOAD = util.AddNetworkString("MyAddon.Upload")

net.Receive(NET_UPLOAD, function(len, ply)
    if not ply:IsAdmin() then return end
    if len < 1 or len > 32768 then return end

    local compressed = net.ReadData(len)
    if #compressed ~= len then return end

    local decoded = util.Decompress(compressed)
    if not decoded then return end

    if #decoded > 262144 then return end

    consume(decoded)
end)
```
Reason: util.AddNetworkString pools the string at load time; the handler validates admin, enforces 32 KiB compressed / 256 KiB decompressed caps, rejects nil from Decompress, and forwards the output to consume.


```lua
local angle_zero = Angle(0, 0, 0)
```

Reason: Caching avoids per-call userdata allocation and GC pressure; `Angle()` always allocates a new C-side userdata even with zero arguments.


Core 7/8: interaction, server-authoritative, item-validation, affordability, purchase-order, no-client-authority, no-broadcast-menu. Missing core: targeted-open. Hardening 0/3: none. Missing hardening: proximity, rate-limit, payload-bound.

```lua
AddCSLuaFile()

local ShopItems = {
    {name = "Pistol",       class = "weapon_pistol",   price = 800,  mdl = "models/weapons/w_pistol.mdl"},
    {name = ".357 Magnum",  class = "weapon_357",      price = 1500, mdl = "models/weapons/w_pist_357.mdl"},
    {name = "Shotgun",      class = "weapon_shotgun",   price = 2500, mdl = "models/weapons/w_shotgun.mdl"},
    {name = "SMG",          class = "weapon_smg1",      price = 3000, mdl = "models/weapons/w_smg1.mdl"},
    {name = "AR2",          class = "weapon_ar2",       price = 4500, mdl = "models/weapons/w_irifle.mdl"},
    {name = "Crossbow",     class = "weapon_crossbow",  price = 6500, mdl = "models/weapons/w_crossbow.mdl"},
    {name = "RPG",          class = "weapon_rpg",       price = 12000,mdl = "models/weapons/w_rocket_launcher.mdl"},
}

if SERVER then
    local ENT = {}
    ENT.Type = "ai"
    ENT.Base = "base_ai"
    ENT.PrintName = "Weapon Dealer"
    ENT.Category = "DarkRP"
    ENT.Spawnable = true
    ENT.AdminOnly = false
    ENT.AutomaticFrameAdvance = true

    function ENT:Initialize()
        self:SetModel("models/Humans/Group03/male_01.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:CapabilitiesAdd(CAP_ANIMATEDFACE)
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
        self:SetMaxYawSpeed(90)
    end

    function ENT:AcceptInput(name, activator, caller)
        if name == "Use" and IsValid(activator) and activator:IsPlayer() then
            if self:GetPos():Distance(activator:GetPos()) > 200 then
                DarkRP.notify(activator, 1, 4, "You are too far away!")
                return
            end
            net.Start("darkrp_shop_open")
            net.WriteTable(ShopItems)
            net.Send(activator)
        end
    end

    scripted_ents.Register(ENT, "npc_darkrp_weapon_dealer")

    DarkRP.createEntity("Weapon Dealer", {
        ent = "npc_darkrp_weapon_dealer",
        model = "models/Humans/Group03/male_01.mdl",
        price = 0,
        max = 5,
        cmd = "weaponshop",
    })

    net.Receive("darkrp_shop_buy", function(len, ply)
        if not IsValid(ply) then return end
        local idx = net.ReadUInt(16)
        local item = ShopItems[idx]
        if not item then
            DarkRP.notify(ply, 1, 4, "Invalid item!")
            return
        end
        if not ply:canAfford(item.price) then
            DarkRP.notify(ply, 1, 4, "You cannot afford " .. item.name .. " ($" .. item.price .. ")")
            return
        end
        if ply:HasWeapon(item.class) then
            DarkRP.notify(ply, 1, 4, "You already own " .. item.name)
            return
        end
        ply:addMoney(-item.price)
        ply:Give(item.class)
        DarkRP.notify(ply, 0, 4, "Purchased " .. item.name .. " for $" .. item.price)
    end)
end

if CLIENT then
    local frame = nil

    net.Receive("darkrp_shop_open", function()
        local items = net.ReadTable()
        if not items or #items == 0 then return end
        if IsValid(frame) then frame:Remove() end

        frame = vgui.Create("DFrame")
        frame:SetSize(560, 480)
        frame:Center()
        frame:SetTitle("Weapon Dealer")
        frame:SetVisible(true)
        frame:SetDeleteOnClose(true)
        frame:MakePopup()

        local scroll = vgui.Create("DScrollPanel", frame)
        scroll:Dock(FILL)
        scroll:DockMargin(8, 8, 8, 8)

        for i, item in ipairs(items) do
            local pnl = scroll:Add("DPanel")
            pnl:SetTall(64)
            pnl:Dock(TOP)
            pnl:DockMargin(0, 0, 0, 4)
            pnl.Paint = function(s, w, h)
                draw.RoundedBox(6, 0, 0, w, h, Color(45, 45, 50, 230))
                surface.SetDrawColor(60, 60, 70, 255)
                surface.DrawOutlinedRect(0, 0, w, h)
            end

            local nameLbl = vgui.Create("DLabel", pnl)
            nameLbl:SetText(item.name)
            nameLbl:SetFont("DermaDefaultBold")
            nameLbl:SetPos(12, 8)
            nameLbl:SizeToContents()

            local priceLbl = vgui.Create("DLabel", pnl)
            priceLbl:SetText("$" .. item.price)
            priceLbl:SetPos(12, 32)
            priceLbl:SizeToContents()
            priceLbl:SetTextColor(Color(100, 255, 100))

            local buyBtn = vgui.Create("DButton", pnl)
            buyBtn:SetText("Buy")
            buyBtn:SetPos(460, 14)
            buyBtn:SetSize(80, 36)
            buyBtn.Paint = function(s, w, h)
                draw.RoundedBox(4, 0, 0, w, h, s:IsHovered() and Color(60, 160, 60) or Color(50, 130, 50))
            end
            buyBtn.DoClick = function()
                net.Start("darkrp_shop_buy")
                net.WriteUInt(i, 16)
                net.SendToServer()
            end
        end

        local closeBtn = vgui.Create("DButton", frame)
        closeBtn:SetText("Close")
        closeBtn:Dock(BOTTOM)
        closeBtn:SetTall(32)
        closeBtn:DockMargin(8, 4, 8, 8)
        closeBtn.DoClick = function() frame:Remove() end
    end)
end
```
Reason: Complete DarkRP shop NPC with a weapon dealer entity, DarkRP F4 integration via `DarkRP.createEntity`, net-based purchase flow with money validation, duplicate-item checks, and a vgui DFrame menu—all in a single shared autorun file.


Receiver includes 7/11 required trust-boundary checks.

```lua
local rateLimits = rateLimits or {}

hook.Add("PlayerDisconnected", "MyAddon.CleanupRateLimits", function(ply)
    rateLimits[ply] = nil
end)

net.Receive("MyAddon.SetPower", function(len, ply)
    if not ply:IsAdmin() then return end

    local now = SysTime()
    local last = rateLimits[ply]
    if last and now - last < 0.5 then return end
    rateLimits[ply] = now

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    if not ent.CPPIGetOwner then return end
    local owner = ent:CPPIGetOwner()
    if not IsValid(owner) or owner ~= ply then return end

    local power = net.ReadUInt(7)
    if power > 100 then return end

    ent:SetPower(power)
end)
```
Reason: Rejects non-admins, rate-limits to 0.5s per player via SysTime, validates entity, fails closed on missing CPPI/lacks ownership, reads power with net.ReadUInt(7) (0-127 native bound) then rejects >100, and cleans the rate-limit entry on disconnect to prevent memory leak.


Defines Power with Entity:NetworkVar in SetupDataTables.

```lua
function ENT:SetupDataTables()
    self:NetworkVar("Int", "Power")
end
```
Reason: `NetworkVar` is the built-in entity state primitive that creates a predicted, delta-compressed networked variable with automatic getter/setter generation; the engine only transmits a delta when the value actually changes.


Does not provide the complete maintained-set spatial design.

```lua
-- keyed set: ent index -> entity, avoids ents.FindByClass in hot loop
local pool = {}
local CLASS = "my_addon_ent"
local RADIUS_SQ = 600 ^ 2
local TARGET = nil -- assign to your target entity before Think fires

-- seed pool with existing map ents
for _, ent in ipairs(ents.GetAll()) do
    if ent:GetClass() == CLASS then
        pool[ent:EntIndex()] = ent
    end
end

-- maintain pool across addon entity lifecycle
hook.Add("OnEntityCreated", "MyAddonPool", function(ent)
    if ent:GetClass() == CLASS then pool[ent:EntIndex()] = ent end
end)
hook.Add("EntityRemoved", "MyAddonPool", function(ent)
    pool[ent:EntIndex()] = nil
end)

-- remove hooks and release pool on addon unload
local function Cleanup()
    hook.Remove("OnEntityCreated", "MyAddonPool")
    hook.Remove("EntityRemoved", "MyAddonPool")
    hook.Remove("Think", "MyAddonScan")
end

-- Think: squared-distance sweep, lazily evicts dead indices
hook.Add("Think", "MyAddonScan", function()
    if not IsValid(TARGET) then return end
    local tx, ty, tz = TARGET:GetPos():Unpack()
    for idx, ent in pairs(pool) do
        if not IsValid(ent) then
            pool[idx] = nil
        else
            local p = ent:GetPos()
            local dx, dy, dz = p.x - tx, p.y - ty, p.z - tz
            if dx * dx + dy * dy + dz * dz <= RADIUS_SQ then
                -- use ent here
            end
        end
    end
end)
```
Reason: Seeded keyed set avoids scanning `ents.GetAll()` each tick; `OnEntityCreated`/`EntityRemoved` hooks handle pool maintenance with no per-frame overhead; `IsValid` guard in the loop handles edge-case stale indices; manual squared-distance avoids `math.sqrt` and `DistToSqr` call overhead in the hot path.


Processes ents.Iterator results directly without mutating its cache.

```lua
for ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```
Reason: The iterator yields each entity directly; the cached table is an internal implementation detail that is not exposed or modified by the loop.


Core 4/8: affordability, purchase-order, no-client-authority, no-broadcast-menu. Missing core: interaction, targeted-open, server-authoritative, item-validation. Hardening 0/3: none. Missing hardening: proximity, rate-limit, payload-bound.

```lua
-- DarkRP Shop NPC – players use the NPC to open a tabbed buy menu.
-- Drop into lua/autorun/ (or a sub-folder of autorun).

-------------------------------------------------------------------------------
-- CONFIGURATION ---------------------------------------------------------------
-------------------------------------------------------------------------------
local NPC_MODEL = "models/Humans/Group03/male_06.mdl"
local NPC_NAME  = "Shop NPC"

-- Each entry: {name = "Display name", class = "entity_class", price = N, desc = "Tooltip"}
local SHOP_ITEMS = {
    ["Food & Drink"] = {
        {name = "Banana",     class = "banana",         price = 25,   desc = "A healthy snack"},
        {name = "Orange",     class = "orange",         price = 25,   desc = "A citrus fruit"},
        {name = "Melon",      class = "melon",          price = 60,   desc = "A juicy melon"},
        {name = "Bread Roll", class = "bread_roll",     price = 20,   desc = "Fresh baked bread"},
        {name = "Soda",       class = "soda",           price = 15,   desc = "Refreshing soda"},
    },
    ["Tools"] = {
        {name = "Lockpick",       class = "lockpick",       price = 400,  desc = "Lockpick for doors"},
        {name = "Keypad Cracker", class = "keypad_cracker", price = 1500, desc = "Cracks keypad codes"},
        {name = "Flashbang",      class = "flashbang",      price = 300,  desc = "Stuns nearby players"},
    },
    ["Weapons"] = {
        {name = "Pistol",  class = "pistol",  price = 2000, desc = "Standard sidearm"},
        {name = "Shotgun", class = "shotgun", price = 5000, desc = "Close-range power"},
        {name = "Mac 10",  class = "mac10",   price = 3500, desc = "Rapid-fire SMG"},
    },
    ["Vehicles"] = {
        {name = "Jeep",       class = "jeep",       price = 15000, desc = "A sturdy jeep"},
        {name = "Sports Car", class = "sports_car", price = 35000, desc = "A fast sports car"},
    },
}

-------------------------------------------------------------------------------
-- SERVER ----------------------------------------------------------------------
-------------------------------------------------------------------------------
if SERVER then
    util.AddNetworkString("shopnpc_open")
    util.AddNetworkString("shopnpc_buy")

    local cd = {}
    hook.Add("PlayerUse", "ShopNPC_Use", function(ply, ent)
        if not IsValid(ply) or not IsValid(ent) then return end
        if ent:GetClass() ~= "npc_darkrp_base" then return end
        if ent:GetDarkRPName and ent:GetDarkRPName() ~= NPC_NAME then return end
        if cd[ply] and cd[ply] > CurTime() then return end
        cd[ply] = CurTime() + 0.5
        net.Start("shopnpc_open")
        net.Send(ply)
        return false
    end)

    net.Receive("shopnpc_buy", function(_, ply)
        if not IsValid(ply) then return end
        if cd[ply] and cd[ply] > CurTime() then return end
        cd[ply] = CurTime() + 0.3
        local class = net.ReadString()
        if not class or class == "" then return end

        for _, items in pairs(SHOP_ITEMS) do
            for _, item in ipairs(items) do
                if item.class == class then
                    if not ply:canAfford(item.price) then
                        DarkRP.notify(ply, 1, 4, "Not enough money!")
                        return
                    end
                    ply:addMoney(-item.price)
                    local e = ents.Create(class)
                    if IsValid(e) then
                        e:SetPos(ply:GetPos() + ply:GetForward() * 40)
                        e:Spawn()
                        DarkRP.notify(ply, 0, 5, "Bought " .. item.name .. " for $" .. item.price)
                    else
                        ply:addMoney(item.price)
                        DarkRP.notify(ply, 1, 5, "Could not spawn item!")
                    end
                    return
                end
            end
        end
        DarkRP.notify(ply, 1, 4, "Item not found!")
    end)

    hook.Add("DarkRPPlayerReady", "ShopNPC_Register", function()
        if not DarkRP or not DarkRP.createEntity then return end
        DarkRP.createEntity("shop_npc", {
            type     = "shop_npc",
            name     = NPC_NAME,
            model    = NPC_MODEL,
            command  = "shopnpc",
            category = "NPCs",
        })
    end)
end

-------------------------------------------------------------------------------
-- CLIENT ----------------------------------------------------------------------
-------------------------------------------------------------------------------
if CLIENT then
    local function OpenShop()
        local f = vgui.Create("DFrame")
        f:SetSize(660, 500)
        f:Center()
        f:SetTitle(NPC_NAME)
        f:MakePopup()
        f:SetDraggable(true)
        f:SetSizable(false)
        function f:Paint(w, h)
            draw.RoundedBox(0, 0, 0, w, h, Color(30, 30, 35, 240))
        end

        local sheet = vgui.Create("DPropertySheet", f)
        sheet:SetPos(4, 28)
        sheet:SetSize(652, 468)
        function sheet:Paint(w, h)
            draw.RoundedBox(0, 0, 0, w, h, Color(40, 40, 45))
        end

        for catName, items in SortedPairs(SHOP_ITEMS) do
            local cont = vgui.Create("DPanel")
            function cont:Paint(w, h)
                draw.RoundedBox(0, 0, 0, w, h, Color(35, 35, 40))
            end

            local scroll = vgui.Create("DScrollPanel", cont)
            scroll:Dock(FILL)
            scroll:DockMargin(4, 4, 4, 4)

            for _, item in ipairs(items) do
                local row = vgui.Create("DPanel", scroll)
                row:Dock(TOP)
                row:SetHeight(52)
                row:DockMargin(0, 2, 0, 2)
                function row:Paint(w, h)
                    draw.RoundedBox(4, 0, 0, w, h, Color(55, 55, 60))
                    surface.SetDrawColor(75, 75, 80)
                    surface.DrawOutlinedRect(1, 1, w - 2, h - 2)
                end

                local nl = vgui.Create("DLabel", row)
                nl:SetPos(10, 6)
                nl:SetText(item.name)
                nl:SetFont("DermaDefaultBold")
                nl:SetTextColor(Color(230, 230, 230))
                nl:SizeToContents()

                local dl = vgui.Create("DLabel", row)
                dl:SetPos(10, 28)
                dl:SetText(item.desc)
                dl:SetTextColor(Color(150, 150, 150))
                dl:SizeToContents()

                local btn = vgui.Create("DButton", row)
                btn:SetSize(90, 36)
                btn:SetPos(row:GetWide() - 100, 8)
                btn:SetText("$" .. item.price)
                btn:SetTextColor(Color(255, 255, 200))
                function btn:Paint(w, h)
                    if self:IsHovered() then
                        draw.RoundedBox(4, 0, 0, w, h, Color(210, 170, 40))
                    else
                        draw.RoundedBox(4, 0, 0, w, h, Color(160, 130, 25))
                    end
                end
                function btn:DoClick()
                    net.Start("shopnpc_buy")
                    net.WriteString(item.class)
                    net.SendToServer()
                end
            end
            sheet:AddSheet(catName, cont, "icon16/basket.png")
        end
    end

    net.Receive("shopnpc_open", OpenShop)
end
```
Reason: Satisfies the request for a DarkRP shop NPC with a complete server-client implementation, including NPC registration via `DarkRP.createEntity`, item purchasing with money validation, and a tabbed Derma shop GUI — all in one self-contained file.


Caches stable render resources and derives per-frame values once.

```lua
local mat = Material("icon16/health.png")
local red = Color(255, 0, 0)
local white = Color(255, 255, 255)

hook.Add("HUDPaint", "DrawHealth", function()
    local ply = LocalPlayer()
    if not IsValid(ply) then return end

    local x, y = 16, 16
    local hp = ply:Health()

    surface.SetMaterial(mat)
    surface.SetDrawColor(red)
    surface.DrawTexturedRect(x, y, 16, 16)

    draw.DrawText(tostring(hp), "Default", x + 20, y, white, TEXT_ALIGN_LEFT)
end)
```

Reason: Material and color are hoisted once at module scope (zero per-frame allocation), LocalPlayer is read once per frame and gated by IsValid to skip the body when unusable, and repeated values (x, y, hp) are local-cached rather than re-evaluated.


Answer must contain 0 through 1 candidate loops.

```lua
-- Fast: sequential number-indexed array
for i = 1, #arr do
  local v = arr[i]
end

-- Slow: string-keyed map
for k, v in pairs(map) do
end
```

Reason: Sequential integer arrays use a simple index increment loop (`for i = 1, #arr`) with O(1) direct access and no hashing overhead, while string-keyed maps require `pairs` with hash computation, bucket traversal, and unpredictable iteration order.


Answer must contain 0 through 0 candidate loops.

```lua
-- Slow: repeated .. concatenation
local str = ""
for i = 1, 10000 do
    str = str .. tostring(i)
end

-- Fast: table.concat
local parts = {}
for i = 1, 10000 do
    parts[i] = tostring(i)
end
local str = table.concat(parts)
```
Reason: Repeated `..` creates a new intermediate string each iteration (O(n²) memory churn), while `table.concat` allocates once after computing the total length, making it O(n).


Updates predicted state every pass and gates only the one-shot effect.

```lua
function SWEP:PrimaryAttack()
    self:SetNextPrimaryFire(CurTime() + self.Primary.Delay)
    self:TakePrimaryAmmo(1)

    local owner = self:GetOwner()
    if not IsValid(owner) then return end

    local bullet = {
        Num = 1,
        Src = owner:GetShootPos(),
        Dir = owner:GetAimVector(),
        Spread = Vector(0, 0, 0),
        Tracer = 1,
        Force = 4,
        Damage = 10,
    }
    owner:FireBullets(bullet)

    if IsFirstTimePredicted() then
        util.Effect("MuzzleEffect", EffectData())
    end
end
```
Reason: `SetNextPrimaryFire` must run on every prediction pass so the client-side prediction model sees the correct cooldown across re-executions; `util.Effect` is wrapped in `IsFirstTimePredicted()` to avoid stacking duplicate effects on re-prediction rolls, while the rest of the attack (ammo, bullets) is not guarded so the server fully authorizes the shot.


Does not show the required shared loading and server-authoritative action.

```lua
-- lua/autorun/myaddon_init.lua
AddCSLuaFile("myaddon/shared.lua")
include("myaddon/shared.lua")

-- lua/myaddon/shared.lua
MYADDON = MYADDON or {}
if SERVER then include("myaddon/server/apply_damage.lua") end

-- lua/myaddon/server/apply_damage.lua
function MYADDON.ApplyDamage(attacker, target, damage)
    if not IsValid(attacker) or not attacker:IsPlayer() then return false end
    if not attacker:Alive() then return false end
    local dmg = DamageInfo()
    dmg:SetAttacker(attacker)
    dmg:SetInflictor(attacker)
    dmg:SetDamage(damage)
    dmg:SetDamageType(DMG_GENERIC)
    target:TakeDamageInfo(dmg)
    return true
end
```
Reason: `AddCSLuaFile` queues the file for client download (no-op on client), while `include` evaluates it on each realm; the server-only ApplyDamage file is loaded conditionally behind `if SERVER` to keep damage logic off the client.


Maintains the hot set but does not seed already-existing entities.

```lua
MY_ADDON = MY_ADDON or {}

local ents_cache = setmetatable({}, { __mode = "k" })
local ply = nil
local radius_sq = 160000 -- 400^2

local function refresh_cache()
  for _, ent in ipairs(ents.GetAll()) do
    if ent:GetClass() == "my_addon_ent" then
      ents_cache[ent] = true
    end
  end
end

local function track_spawn(_, ent)
  if ent:GetClass() == "my_addon_ent" then
    ents_cache[ent] = true
  end
end

local function track_remove(_, ent)
  ents_cache[ent] = nil
end

hook.Add("EntityRemoved", "MyAddonCacheCleanup", track_remove)

function MY_ADDON.Init(target_ply, radius)
  ply = target_ply
  radius_sq = (radius or 400) ^ 2
  refresh_cache()
  hook.Add("OnEntityCreated", "MyAddonCacheReg", track_spawn)
  hook.Add("Think", "MyAddonThink", MY_ADDON.Think)
end

function MY_ADDON.Think()
  if not IsValid(ply) then
    MY_ADDON.Cleanup()
    return
  end

  local pos = ply:GetPos()
  for ent in pairs(ents_cache) do
    if IsValid(ent) and pos:DistToSqr(ent:GetPos()) <= radius_sq then
      -- process in-range entity
    else
      ents_cache[ent] = nil
    end
  end
end

function MY_ADDON.Cleanup()
  hook.Remove("OnEntityCreated", "MyAddonCacheReg")
  hook.Remove("Think", "MyAddonThink")
  hook.Remove("EntityRemoved", "MyAddonCacheCleanup")
  ply = nil
  ents_cache = setmetatable({}, { __mode = "k" })
end
```

Reason: Weak-keyed table avoids full map scans every tick; incremental spawn/remove hooks keep the cache live at O(1) per mutation; `DistToSqr` skips the sqrt in the hot loop, and the weak reference table lets dead ents auto-evict without manual cleanup on the per-tick sweep.


```lua
-- Prop spawn rate limiter: 10 attempts per 1-second fixed window per player
-- Denies before entity creation, does not interfere with other hooks when allowed

local limits = {}

local function window()
    return math.floor(SysTime())
end

local function cleanup(ply)
    limits[ply] = nil
end

local function allow(ply)
    local w = window()
    local d = limits[ply]
    if not d then
        d = { win = w, count = 0 }
        limits[ply] = d
    end
    if d.win ~= w then
        d.win = w
        d.count = 0
    end
    if d.count >= 10 then return false end
    d.count = d.count + 1
    return true
end

hook.Add("PlayerSpawnObject", "PropRateLimit", function(ply, model)
    if not IsValid(ply) then return end
    if not allow(ply) then return false end
end)

hook.Add("PlayerDisconnected", "PropRateLimit", function(ply)
    cleanup(ply)
end)

hook.Add("InitPostEntity", "PropRateLimit", function()
    for _, v in ipairs(player.GetAll()) do
        cleanup(v)
    end
end)
```
Reason: Rate-limit before entity creation by hooking PlayerSpawnObject, the only pre-spawn hook in GMod Lua that fires for props; per-player fixed 1 s window using math.floor(SysTime()), with no allocations when under budget so other addons' hooks chain uninterrupted, and full state cleanup on disconnect / map start.


Does not combine bounded writes, typed binding, and one transaction with the built-in sql library.

```lua
local function insertScores(rows)
    local count = math.min(#rows, 500)
    sql.Query("BEGIN TRANSACTION")
    for i = 1, count do
        local r = rows[i]
        local id = tonumber(r.id)
        local score = tonumber(r.score)
        if id and score then
            sql.Query(("INSERT INTO scores(id, score) VALUES (%d, %d)"):format(id, score))
        end
    end
    sql.Query("COMMIT")
end
```
Reason: Wraps all writes in SQL transaction for atomic batch commit, gates on `tonumber` coercion then `%d` formatting so only integer values reach the query, and caps at 500 rows via `math.min` to bound memory and execution cost.


Safely escapes with sql.SQLStr but does not use the preferred sql.QueryTyped.

```lua
local ok = sql.Query("INSERT INTO notes(text) VALUES(" .. sql.SQLStr(untrusted_variable) .. ")")
if ok == false then
    ErrorNoHalt("SQL Error: " .. sql.LastError())
end
```
Reason: `sql.SQLStr` escapes untrusted input to prevent SQL injection, `sql.Query` returns `false` on error and `sql.LastError()` retrieves the error message.


Revalidates the captured entity inside the delayed callback.

```lua
timer.Simple(1,function()IsValid(ent)&&ent:Remove()end)
```
Reason: `timer.Simple` fires once after 1s; `IsValid` must guard the removal because a previously-removed entity becomes a non-nil NULL entity (Entity(0)) whose method calls would error.


Does not clean transfer state across disconnect and timeout paths.

```lua
local transfers = transfers or {}

function CancelTransfer(player)
    local data = transfers[player]
    if not data then return end

    local peer = data.peer
    transfers[player] = nil
    if peer and transfers[peer] and transfers[peer].peer == player then
        transfers[peer] = nil
    end

    if IsValid(peer) then
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "TransferCleanup_Disconnect", function(ply)
    CancelTransfer(ply)
end)

timer.Create("TransferCleanup_Timeout", 1, 0, function()
    local now = CurTime()
    for ply, data in pairs(transfers) do
        if now - data.lastActivity > 30 then
            CancelTransfer(ply)
        end
    end
end)
```
Reason: Single `CancelTransfer` function handles both hooks by reading `peer` before deletion, includes a consistency guard (`transfers[peer].peer == player`) to avoid removing a peer entry that no longer references this player, and iterates `pairs` directly in the one-second timer because Lua 5.1's `next` tolerates current-key deletion without table corruption.


Core 8/8: interaction, targeted-open, server-authoritative, item-validation, affordability, purchase-order, no-client-authority, no-broadcast-menu. Missing core: none. Hardening 0/3: none. Missing hardening: proximity, rate-limit, payload-bound.

```lua
AddCSLuaFile()

ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Shop NPC"
ENT.Category = "DarkRP"
ENT.Spawnable = true
ENT.Author = "iyda"

local shopItems = {
    { name = "Health Kit", price = 200, apply = function(ply) ply:SetHealth(math.min(ply:GetMaxHealth(), ply:Health() + 50)) end },
    { name = "Armor",      price = 300, apply = function(ply) ply:SetArmor(math.min(100, ply:Armor() + 50)) end },
    { name = "Lockpick",   price = 500, apply = function(ply) ply:Give("lockpick") end },
    { name = "Keypad Cracker", price = 800, apply = function(ply) ply:Give("keypad_cracker") end },
}

function ENT:Initialize()
    self:SetModel("models/player/alyx.mdl")
    self:SetHullType(HULL_HUMAN)
    self:SetHullSizeNormal()
    self:SetNPCState(NPC_STATE_SCRIPT)
    self:SetSolid(SOLID_BBOX)
    self:Capabilities(CAP_TURN_HEAD)
    self:SetMoveType(MOVETYPE_NONE)
    self:SetUseType(SIMPLE_USE)
    self:DropToFloor()
end

if SERVER then
    util.AddNetworkString("ShopNPC_OpenMenu")
    util.AddNetworkString("ShopNPC_Buy")

    function ENT:Use(_, caller)
        if IsValid(caller) and caller:IsPlayer() then
            net.Start("ShopNPC_OpenMenu")
            net.Send(caller)
        end
    end

    net.Receive("ShopNPC_Buy", function(_, ply)
        local id = net.ReadUInt(8)
        local item = shopItems[id]
        if not item then return end
        if ply:canAfford(item.price) then
            ply:addMoney(-item.price)
            item.apply(ply)
            ply:ChatPrint("You bought " .. item.name .. "!")
        else
            ply:ChatPrint("You cannot afford " .. item.name .. ".")
        end
    end)
else
    net.Receive("ShopNPC_OpenMenu", function()
        local frame = vgui.Create("DFrame")
        frame:SetTitle("Shop NPC")
        frame:SetSize(320, 40 + #shopItems * 45 + 20)
        frame:Center()
        frame:MakePopup()

        for i, item in ipairs(shopItems) do
            local btn = vgui.Create("DButton", frame)
            btn:SetText(item.name .. "  -  $" .. item.price)
            btn:SetPos(20, 30 + i * 45)
            btn:SetSize(280, 35)
            btn.DoClick = function()
                net.Start("ShopNPC_Buy")
                net.WriteUInt(i, 8)
                net.SendToServer()
            end
        end
    end)
end
```

Reason: Self-contained DarkRP shop NPC entity that opens a Derma menu on use for players to buy items via canAfford/addMoney, with server-authoritative purchase validation.


```lua
for ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```

Reason: `ents.Iterator()` yields each entity directly through the loop variable, so no cached table is materialized or mutated; we only read `ent` and call `use` when `wanted` holds.


```lua
for _, ent in ents.Iterator() do
    if IsValid(ent) and ent:GetClass() == "prop_physics" then
        -- visit ent
    end
end
```

Reason: `ents.Iterator()` yields entities one at a time without first allocating a table of the whole entity list, and we filter by class inside the loop.


File receiver satisfies 8/13 confinement checks.

```lua
util.AddNetworkString("MyAddon.ReadUpload")

net.Receive("MyAddon.ReadUpload", function(len, ply)
    if len > 8 + 64 * 8 then return end
    if not IsValid(ply) or not ply:IsSuperAdmin() then return end

    local name = net.ReadString()
    if type(name) ~= "string" then return end
    if #name < 1 or #name > 64 then return end
    if name:find("[^%w_%.%-]") then return end
    if name == "." or name == ".." then return end

    local path = "myaddon/uploads/" .. name
    local f = file.Open(path, "rb", "DATA")
    if not f then return end

    local data = f:Read(65536)
    f:Close()
    if not data then return end

    consume(data)
end)
```
Reason: Enforces superadmin auth, a bounded net message, a single strict `[%w_%.%-]`-only 1–64 char filename segment (blocking `.`/`..` and any path traversal), a capped 65536-byte read from the DATA path, and closes the handle before calling `consume`.


Uses an object hook identifier so invalid objects are removed automatically.

```lua
-- Register using the entity AS the hook identifier.
-- GMod's hook system treats a non-string identifier as an object:
-- it auto-removes the hook once IsValid(identifier) is false,
-- so a removed entity never lingers on the hook list.
function MyAddon.RegisterTick(ent, fn)
    hook.Add("MyAddon.Tick", ent, fn)
end

-- Drive it from the entity's own Think-style method:
function ENT:Think()
    hook.Run("MyAddon.Tick")
    self:NextThink(CurTime() + 0.1)
    return true
end

-- Equivalent explicit removal (called on Entity:Remove / OnRemove):
function ENT:OnRemove()
    hook.Remove("MyAddon.Tick", self)
end
```

Reason: Passing the entity as the hook identifier lets GMod's object-lifecycle support auto-remove the hook when the entity becomes invalid; `OnRemove` gives explicit removal for the same guarantee.


```lua
local MATERIAL_PATH = "vgui/white"

local paintMaterial = Material(MATERIAL_PATH)
local paintColor = Color(255, 80, 80, 220)

local HEALTH_BAR_X, HEALTH_BAR_Y = 16, ScrH() - 64
local HEALTH_BAR_W, HEALTH_BAR_H = 200, 20

hook.Add("HUDPaint", "HUDPaintStatusOverlay", function()
	local localPlayer = LocalPlayer()
	if not IsValid(localPlayer) or not localPlayer:Alive() then return end

	local health = localPlayer:Health()
	local healthFraction = math.Clamp(health / 100, 0, 1)

	surface.SetMaterial(paintMaterial)
	surface.SetDrawColor(paintColor)
	surface.DrawTexturedRect(HEALTH_BAR_X, HEALTH_BAR_Y, HEALTH_BAR_W * healthFraction, HEALTH_BAR_H)
end)
```

Reason: Material and color are created once at load, LocalPlayer is read a single time and guarded, and the bar geometry/color are reused per frame with only health derived fresh.


Chunk receiver satisfies 12/20 state and size checks.

```lua
util.AddNetworkString("MyAddon.Chunk")

function MyAddon.Chunk(len, ply)
    local transfer = MyAddon.transfers[ply]
    if not transfer then return end

    local id = net.ReadUInt(32)
    if id ~= transfer.id then return end

    local index = net.ReadUInt(16)
    if index < 1 or index > 64 then return end
    if transfer.chunks[index] ~= nil then return end

    local size = net.ReadUInt(16)
    if size > 24000 then return end
    if size > net.BytesLeft() then return end
    if transfer.totalBytes + size > 1048576 then return end

    local data = net.ReadData(size)

    transfer.chunks[index] = data
    transfer.received = transfer.received + 1
    transfer.totalBytes = transfer.totalBytes + size
    transfer.lastActivity = CurTime()
end

net.Receive("MyAddon.Chunk", MyAddon.Chunk)
```

Reason: Validates the transfer exists, rejects mismatched ids/indices/duplicates and oversized/overflowing chunks against BytesLeft and the 64/24000/1048576 limits before net.ReadData, then stores data and updates received, totalBytes, and lastActivity, with the net string pooled once via util.AddNetworkString.


Payload receiver satisfies 9/11 bounded-decompression checks.

```lua
local NET_STRING = "MyAddon.Upload"

util.AddNetworkString(NET_STRING)

local MAX_COMPRESSED   = 32 * 1024    -- 32 KiB
local MAX_DECOMPRESSED = 256 * 1024   -- 256 KiB

net.Receive(NET_STRING, function(len, ply)
    if not IsValid(ply) or not ply:IsAdmin() then return end

    local compLen = len / 8
    if compLen <= 0 or compLen > MAX_COMPRESSED then return end

    local comp = net.ReadData(compLen)
    if not comp or #comp ~= compLen then return end

    local ok, decoded = pcall(util.Decompress, comp)
    if not ok or not decoded or #decoded > MAX_DECOMPRESSED then return end

    consume(decoded)
end)
```

Reason: `util.AddNetworkString` pools the constant name at load; the `len` arg (bits) yields the LZMA byte count with no extra prefix, both size caps are enforced, and `pcall` around `util.Decompress` rejects invalid/bomb decompression before `consume` runs.


Does not use compact typed fields with targeted net.Send recipients.

```lua
if (SERVER) then
    util.AddNetworkString("gmod_state_update")

    local STATE_BITS = 3
    local AMOUNT_BITS = 10

    function SendStateUpdate(state, amount, recipients)
        if (not recipients or #recipients == 0) then return end
        net.Start("gmod_state_update")
        net.WriteUInt(state, STATE_BITS)
        net.WriteUInt(amount, AMOUNT_BITS)
        net.Send(recipients)
    end
end
```

Reason: Pooled string at load time plus fixed-width 3+10 bit WriteUInt avoids table serialization, and net.Send(recipients) fans out one packet to all affected players instead of per-player sends.


Receiver satisfies 8/15 per-player budget checks.

```lua
local NET_STRING = "MyAddon.Action"
util.AddNetworkString(NET_STRING)

local WINDOW_SECONDS = 1
local MAX_PER_WINDOW = 20

-- ply -> { start = number (CurTime at window open), count = number }
local budget = {}

net.Receive(NET_STRING, function(len, ply)
    -- Reject over 64 bits (8 bytes) before reading the entity.
    if len > 8 then return end

    local now = CurTime()
    local b = budget[ply]
    if not b or now - b.start >= WINDOW_SECONDS then
        b = { start = now, count = 0 }
        budget[ply] = b
    end

    -- Reject over budget before reading the entity.
    if b.count >= MAX_PER_WINDOW then return end

    local ent = net.ReadEntity()

    -- Consume one slot only for messages we actually accepted into the window.
    b.count = b.count + 1

    if IsValid(ent) then
        perform(ent)
    end
end)

hook.Add("PlayerDisconnected", "MyAddon.Action.Cleanup", function(ply)
    budget[ply] = nil
end)
```

Reason: Pools the net string once via `util.AddNetworkString`, rejects >64-bit messages using the byte length arg, enforces a per-player 1-second fixed window capped at 20, validates the entity before `perform`, and clears budget state on disconnect.


Receiver includes 7/11 required trust-boundary checks.

```lua
util.AddNetworkString("MyAddon.SetPower")

local RECEIVE_INTERVAL = 0.25 -- seconds; reject requests faster than this
local RATE_LIMIT = 30         -- max accepted requests per window
local RATE_WINDOW = 5         -- seconds
local MAX_POWER = 100

local lastRequest = {} -- ply -> last accepted timestamp

local function isOwner(ply, ent)
    if not IsValid(ent) then return false end
    local owner = ent.CPPIGetOwner and ent:CPPIGetOwner() or ent.Owner
    return owner == ply
end

net.Receive("MyAddon.SetPower", function(len, ply)
    if not IsValid(ply) or not ply:IsAdmin() then return end

    local now = CurTime()
    local last = lastRequest[ply] or 0
    if now - last < RECEIVE_INTERVAL then return end -- bound spam

    local ent = net.ReadEntity()
    if not IsValid(ent) or ent:GetClass() ~= "myaddon_device" then return end -- malformed
    if not isOwner(ply, ent) then return end

    local power = net.ReadUInt(7) -- 7 bits covers 0-127, bounds to unsigned
    if power == nil or power > MAX_POWER then return end -- malformed / out of range

    lastRequest[ply] = now
    ent:SetPower(power)
end)
```

Reason: Reads a 7-bit unsigned int to bound power to 0-100, validates entity class and CPPI ownership by an admin, and throttles each player to one request per 250ms to reject malformed and spammed messages before calling SetPower.


Defines Power with Entity:NetworkVar in SetupDataTables.

```lua
function ENT:SetupDataTables()
    self:NetworkVar("Int", 0, "Power")
end
```

Reason: `NetworkVar` is GMod's built-in entity-state primitive; it delta-compresses and only transmits when the integer value changes, making it ideal for a frequently read, occasionally updated predicted Power field.


Answer must contain 0 through 0 candidate loops.

```lua
local pos = ply:GetPos()
local radius = 512
local nearby = ents.FindInSphere(pos, radius)

for _, ent in ipairs(nearby) do
    if IsValid(ent) and ent ~= ply then
        -- do work with ent
    end
end
```
Reason: `ents.FindInSphere` is a fast C-side spatial query that returns only entities within the given radius, benchmarking cheaper than filtering all entities manually and giving a true distance-based result unlike FindInBox or FindInPVS.


```lua
local arr = { "a", "b", "c", "d" }   -- sequential, number-indexed
for i = 1, #arr do
    local v = arr[i]
    -- do work with v
end
```

Reason: Sequential integer-indexed arrays let Lua use a length-aware numeric loop (or ipairs) that walks the array without hashing keys, whereas string-keyed maps must use pairs/next which traverses the hash part and is slower.


```lua
local parts = {}
for i = 1, 10000 do
    parts[i] = "piece " .. i .. "\n"
end
local result = table.concat(parts)

-- vs. the slow way:
-- local result = ""
-- for i = 1, 10000 do
--     result = result .. "piece " .. i .. "\n"
-- end
```

Reason: Repeated `..` concatenation copies the whole growing string each iteration (O(n^2)); `table.concat` buffers pieces and joins them in one O(n) pass.


Guards the whole attack, preventing predicted state updates on replay.

```lua
function SWEP:PrimaryAttack()
	self:SetNextPrimaryFire(CurTime() + 0.1)

	if not IsFirstTimePredicted() then return end

	local effect = EffectData()
	effect:SetOrigin(self:GetOwner():GetShootPos())
	effect:SetNormal(self:GetOwner():GetAimVector())
	util.Effect("MuzzleFlash", effect)
end
```

Reason: SetNextPrimaryFire must run on every prediction pass so the fire rate stays consistent, while the side-effect (util.Effect) is gated behind IsFirstTimePredicted so it fires once, and only the effect block is guarded rather than the whole attack.


Does not show the required shared loading and server-authoritative action.

```lua
-- myaddon/shared.lua
-- Ensure clients download and run this file too
if SERVER then
    AddCSLuaFile("myaddon/shared.lua")
end

-- Code below executes on BOTH the server and the client
print("[myaddon] shared.lua loaded on " .. (SERVER and "server" or "client"))

-- ApplyDamage is server-authoritative: it may only run where the game state lives.
function ApplyDamage(ply, ent)
    -- Guard: only the server may mutate entity health
    if not SERVER then return end

    -- Validate the acting player before touching any entity
    if not IsValid(ply) or not ply:IsPlayer() then return end
    if not IsValid(ent) then return end

    ent:TakeDamage(10, ply)
end
```
Reason: AddCSLuaFile makes clients receive/run the file (shared), the SERVER guard keeps ApplyDamage server-authoritative, and the IsValid(ply):IsPlayer() check gates the damage on a real player.


Does not provide the complete maintained-set spatial design.

```lua
local CLASS = "my_addon_ent"
local RADIUS = 512
local RADIUS_SQ = RADIUS * RADIUS

-- Keyed set of addon-owned entities, keyed by entity index.
-- We seed this once and maintain it incrementally so the hot Think
-- loop never scans the whole map.
local entities = {}

-- Registration: incrementally add entities as they are created.
hook.Add("OnEntityCreated", "my_addon_track_ent", function(ent)
    if IsValid(ent) and ent:GetClass() == CLASS then
        entities[ent:EntIndex()] = ent
    end
end)

-- Cleanup: drop entities as they leave the world.
hook.Add("EntityRemoved", "my_addon_untrack_ent", function(ent)
    if IsValid(ent) and ent:GetClass() == CLASS then
        entities[ent:EntIndex()] = nil
    end
end)

-- Initialization: seed the set with entities that already exist.
-- Run once after the map has fully loaded so we don't scan every tick.
hook.Add("InitPostEntity", "my_addon_seed_ents", function()
    for _, ent in ipairs(ents.FindByClass(CLASS)) do
        if IsValid(ent) then
            entities[ent:EntIndex()] = ent
        end
    end
end)

-- Hot loop: find addon-owned entities within radius of the target.
hook.Add("Think", "my_addon_query_ents", function()
    local target = Entity(1) -- replace with the real target entity
    if not IsValid(target) then return end

    local tx, ty, tz = target:GetPos():Unpack()
    for _, ent in pairs(entities) do
        if IsValid(ent) then
            local ex, ey, ez = ent:GetPos():Unpack()
            local dx, dy, dz = ex - tx, ey - ty, ez - tz
            local distSq = dx * dx + dy * dy + dz * dz
            if distSq <= RADIUS_SQ then
                -- within radius: do per-tick work here
            end
        else
            entities[_] = nil -- defensive prune of stale keys
        end
    end
end)

-- Cleanup on unload/reload so hooks and the set don't leak.
hook.Add("ShutDown", "my_addon_cleanup", function()
    hook.Remove("OnEntityCreated", "my_addon_track_ent")
    hook.Remove("EntityRemoved", "my_addon_untrack_ent")
    hook.Remove("Think", "my_addon_query_ents")
    entities = {}
end)
```

Reason: Seeding once via InitPostEntity plus incremental OnEntityCreated/EntityRemoved maintenance keeps the Think hot loop to a distance-squared scan over a small keyed set, never the whole map.


Pre-spawn hook satisfies 6/8 throttling checks.

```lua
-- Per-player prop spawn rate limiter: max 10 attempts per fixed 1-second window.

local MAX_SPAWNS = 10
local WINDOW_SECONDS = 1

-- player -> { window = integer second index, count = number }
local playerSpawns = {}

hook.Add("PlayerSpawnProp", "RateLimitPlayerSpawnProp", function(ply, model)
    if not IsValid(ply) or not ply:IsPlayer() then return end

    local nowWindow = math.floor(CurTime() / WINDOW_SECONDS)
    local state = playerSpawns[ply]

    if not state or state.window ~= nowWindow then
        -- New fixed window: reset the counter.
        state = { window = nowWindow, count = 0 }
        playerSpawns[ply] = state
    end

    if state.count >= MAX_SPAWNS then
        -- Over budget: deny before any entity is created.
        -- Do not return a value otherwise, so other addons' hooks still run.
        ply:ChatPrint("Prop spawn limit reached (10 per second).")
        return false
    end

    state.count = state.count + 1
end)

hook.Add("PlayerDisconnected", "RateLimitCleanup", function(ply)
    playerSpawns[ply] = nil
end)
```

Reason: PlayerSpawnProp fires before the prop entity is created, returning false denies it without disrupting other addons' spawn hooks (which run via hook.Add), and PlayerDisconnected clears per-player state.


Does not combine bounded writes, typed binding, and one transaction with the built-in sql library.

```lua
local function InsertScores(rows)
    if not istable(rows) then return false end

    local MAX_ROWS = 500
    local n = math.min(#rows, MAX_ROWS)

    sql.Begin()

    for i = 1, n do
        local row = rows[i]
        if not istable(row) then
            sql.Rollback()
            return false
        end

        local id = tonumber(row.id)
        local score = tonumber(row.score)
        if id == nil or score == nil then
            sql.Rollback()
            return false
        end

        local query = string.format(
            "INSERT INTO scores (id, score) VALUES (%s, %d);",
            sql.SQLStr(tostring(id)),
            score
        )

        if sql.Query(query) == false then
            sql.Rollback()
            return false
        end
    end

    sql.Commit()
    return true
end
```

Reason: `sql.Begin()`/`sql.Commit()` batches all writes into a single transaction for speed, `tonumber` enforces numeric typing, and `sql.SQLStr` safely escapes the id, preventing injection across hundreds of inserts.


Safely escapes with sql.SQLStr but does not use the preferred sql.QueryTyped.

```lua
local untrusted = ... -- untrusted variable text
local escaped = sql.SQLStr(untrusted)
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. escaped .. ")")
if result == false then
    ErrorNoHalt("notes insert failed: " .. tostring(sql.LastError()))
end
```

Reason: GMod's built-in SQLite API (`sql.Query`) has no parameter binding, so the preferred safe pattern is to escape untrusted input with `sql.SQLStr` (which quotes and escapes for SQLite) and to handle errors by checking for the `false` sentinel returned on failure, then reading `sql.LastError()`.


Revalidates the captured entity inside the delayed callback.

```lua
timer.Simple(1, function() if IsValid(ent) then ent:Remove() end end)
```
Reason: `IsValid(ent)` safely no-ops if `ent` is gone or nil, so calling `Remove()` only when the entity still exists prevents errors and redundant removal.


Cleanup satisfies 7/11 disconnect and timeout requirements.

```lua
local transfers = transfers or {}

local function cancelTransfer(ply)
    local entry = transfers[ply]
    if not entry then return end

    local peer = entry.peer
    transfers[ply] = nil

    if IsValid(peer) and transfers[peer] then
        transfers[peer] = nil
        notifyCancelled(peer)
    end
end

hook.Add("PlayerDisconnected", "Transfers.Cleanup", function(ply)
    cancelTransfer(ply)
end)

timer.Create("Transfers.TimeoutCheck", 1, 0, function()
    local now = os.time()
    for ply, entry in pairs(transfers) do
        if now - entry.lastActivity > 30 then
            cancelTransfer(ply)
        end
    end
end)
```

Reason: A single `cancelTransfer` removes the player's entry and, if the peer is still valid, its mirrored entry plus a `notifyCancelled` call; both the disconnect hook and the 1s timeout timer reuse it, covering both sides and inactivity.


Core 4/8: interaction, item-validation, affordability, no-broadcast-menu. Missing core: targeted-open, server-authoritative, purchase-order, no-client-authority. Hardening 0/3: none. Missing hardening: proximity, rate-limit, payload-bound.

```lua
-- DarkRP Shop NPC
-- Place this file in: addons/darkrp_shop_npc/lua/entities/shop_npc/init.lua
AddCSLuaFile()

ENT.Type = "anim"
ENT.Base = "base_gmodentity"
ENT.PrintName = "Shop NPC"
ENT.Author = "You"
ENT.Category = "DarkRP"
ENT.Spawnable = true
ENT.AdminSpawnable = true

-- Define shop items here. Each item: name, price, and what to give the player.
SHOP_ITEMS = {
    { name = "Health Kit",   price = 250,  give = function(ply) ply:SetHealth(math.min(ply:GetMaxHealth(), ply:Health() + 50)) end },
    { name = "Armor",        price = 400,  give = function(ply) ply:SetArmor(math.min(100, ply:Armor() + 50)) end },
    { name = "Lockpick",     price = 500,  give = function(ply) ply:Give("lockpick") end },
    { name = "Gun License",  price = 2000, give = function(ply) ply:setDarkRPVar("hasGunLicense", true) end },
}

if SERVER then
    function ENT:Initialize()
        self:SetModel("models/player/group01/male_02.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:Capabilities(CAP_ANIMATEDFACE + CAP_TURN_HEAD)
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
    end

    function ENT:Use(activator, caller)
        if not IsValid(caller) or not caller:IsPlayer() then return end
        net.Start("ShopNPC_OpenMenu")
            net.WriteEntity(self)
        net.Send(caller)
    end

    util.AddNetworkString("ShopNPC_Buy")
    util.AddNetworkString("ShopNPC_OpenMenu")

    net.Receive("ShopNPC_Buy", function(len, ply)
        local index = net.ReadUInt(8)
        local item = SHOP_ITEMS[index]
        if not item then return end

        if ply:canAfford(item.price) then
            ply:addMoney(-item.price)
            item.give(ply)
            ply:ChatPrint("Purchased " .. item.name .. " for $" .. item.price)
            DarkRP.notify(ply, 0, 4, "You bought a " .. item.name .. "!")
        else
            DarkRP.notify(ply, 1, 4, "You cannot afford " .. item.name .. "!")
        end
    end)
else
    net.Receive("ShopNPC_OpenMenu", function()
        local npc = net.ReadEntity()
        local frame = vgui.Create("DFrame")
        frame:SetTitle("Shop NPC")
        frame:SetSize(300, 400)
        frame:Center()
        frame:MakePopup()

        local scroll = vgui.Create("DScrollPanel", frame)
        scroll:Dock(FILL)

        for i, item in ipairs(SHOP_ITEMS) do
            local btn = vgui.Create("DButton", scroll)
            btn:SetText(item.name .. "  -  $" .. item.price)
            btn:Dock(TOP)
            btn:SetTall(40)
            btn:DockMargin(4, 4, 4, 0)
            btn.DoClick = function()
                net.Start("ShopNPC_Buy")
                    net.WriteUInt(i, 8)
                net.SendToServer()
            end
        end
    end)
end
```

Reason: Created a self-contained DarkRP scripted NPC entity that opens a Derma shop menu on use and processes purchases against the player's DarkRP wallet using canAfford/addMoney.


Processes ents.Iterator results directly without mutating its cache.

```lua
for ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```

Reason: `ents.Iterator()` returns an iterator function that yields each entity in turn, so iterating with a `for ... in` loop processes entities directly and never touches or mutates the underlying entity list.


File receiver satisfies 5/13 confinement checks.

```lua
util.AddNetworkString("MyAddon.ReadUpload")

local MAX_NAME = 64
local MAX_BYTES = 65536
local DIR = "myaddon/uploads/"

net.Receive("MyAddon.ReadUpload", function(len, ply)
    if not IsValid(ply) or not ply:IsSuperAdmin() then return end
    if len > MAX_NAME * 8 + 16 then return end

    local name = net.ReadString()
    if #name > MAX_NAME then return end
    if not name:match("^[%w_.%-]+$") then return end

    local path = DIR .. name
    local f = file.Open(path, "rb", "DATA")
    if not f then return end

    local size = math.min(f:Size(), MAX_BYTES)
    local data = f:Read(size) or ""
    f:Close()

    consume(data)
end)
```

Reason: Validate sender is superadmin, bound net message length, restrict filename to one safe ASCII segment, clamp read to 65536 bytes, and always close the handle before consume.


Uses an object hook identifier so invalid objects are removed automatically.

```lua
-- Option A: object-lifecycle support. Passing the entity as the hook
-- identifier makes the hook system auto-remove the hook when the entity
-- is removed (becomes NULL), so no permanent hook retains the entity.
function MyAddon.RegisterTick(ent)
    hook.Add("Tick", ent, function(self)
        if not IsValid(self) then return end
        self:ThinkStep()
    end)
end

-- Option B: equivalent explicit removal. Give the hook a unique string id,
-- then drop it the moment the entity is removed.
function MyAddon.RegisterTickExplicit(ent)
    local id = "MyAddon_Tick_" .. ent:EntIndex()
    hook.Add("Tick", id, function()
        if not IsValid(ent) then return end
        ent:ThinkStep()
    end)
    ent:CallOnRemove(id, function()
        hook.Remove("Tick", id)
    end)
end
```

Reason: Using the entity as the hook identifier lets the hook system automatically remove the registration when the entity is removed, so a removed entity is never retained by a permanent hook; Option B shows the equivalent explicit `hook.Remove` via `CallOnRemove`.


Caches stable render resources and derives per-frame values once.

```lua
local MAT = Material("vgui/white")
local COLOR = Color(255, 60, 60, 220)
local HEALTH_X, HEALTH_Y, BAR_W, BAR_H = 16, 16, 200, 12

hook.Add("HUDPaint", "MyHealthHUD", function()
    local ply = LocalPlayer()
    if not IsValid(ply) or not ply:Alive() then return end

    local hp = math.Clamp(ply:Health(), 0, ply:GetMaxHealth())
    local frac = ply:GetMaxHealth() > 0 and hp / ply:GetMaxHealth() or 0

    surface.SetMaterial(MAT)
    surface.SetDrawColor(COLOR)
    surface.DrawTexturedRect(HEALTH_X, HEALTH_Y, BAR_W, BAR_H)

    surface.SetDrawColor(0, 0, 0, 200)
    surface.DrawTexturedRect(HEALTH_X, HEALTH_Y, BAR_W * (1 - frac), BAR_H)

    draw.SimpleText("HP: " .. hp, "DermaDefault", HEALTH_X, HEALTH_Y + BAR_H + 2, COLOR, TEXT_ALIGN_LEFT)
end)
```

Reason: Material, color, and layout constants are built once at load; LocalPlayer is read once and guarded; per-frame values (hp, frac) are computed once and reused, avoiding repeated table/resource creation on the hot path.


Chunk receiver satisfies 15/20 state and size checks.

```lua
util.AddNetworkString("MyAddon.Chunk")

local MAX_CHUNKS = 64
local MAX_CHUNK_BYTES = 24000
local MAX_TOTAL_BYTES = 1048576

net.Receive("MyAddon.Chunk", function(len, ply)
    local transfer = MyAddon.transfers[ply]
    if not transfer then return end

    local id = net.ReadUInt(32)
    if id ~= transfer.id then return end

    local index = net.ReadUInt(16)
    if index < 1 or index > MAX_CHUNKS then return end
    if transfer.chunks[index] ~= nil then return end

    local size = net.ReadUInt(16)
    if size < 1 or size > MAX_CHUNK_BYTES then return end
    if transfer.totalBytes + size > MAX_TOTAL_BYTES then return end
    if size > net.BytesLeft() then return end

    local data = net.ReadData(size)
    transfer.chunks[index] = data
    transfer.received = transfer.received + 1
    transfer.totalBytes = transfer.totalBytes + size
    transfer.lastActivity = CurTime()
end)
```

Reason: Reads fields in send order, validates id/index/duplicate/size/capacity/bytes-left before ReadData, stores data and updates counters, and pools the net string once.


Bounds compressed input before reading and caps decompressed output before use.

```lua
local NET_UPLOAD = "MyAddon.Upload"

if SERVER then
    util.AddNetworkString(NET_UPLOAD)

    net.Receive(NET_UPLOAD, function(len, ply)
        if not IsValid(ply) or not ply:IsAdmin() then return end

        local bytes = len / 8
        if bytes == 0 or bytes > 32768 then return end

        local compressed = net.ReadData(bytes)
        if not compressed then return end

        local decoded = util.Decompress(compressed, 262144)
        if not decoded or #decoded > 262144 then return end

        consume(decoded)
    end)
end
```

Reason: `util.AddNetworkString` pools the constant string once at load time; the callback enforces the 32 KiB compressed (`len/8 > 32768`) and 256 KiB decompressed (`util.Decompress(..., 262144)` returning nil or over-limit) bounds and drops invalid LZMA, then calls `consume(decoded)`.


```lua
local STATE_BITS = 3    -- 0..7 fits in 3 bits
local AMOUNT_BITS = 10  -- 0..1000 fits in 10 bits

net.PoolString("gmod_affected_state")

local function SendAffectedState(recipients, state, amount)
    for i = 1, #recipients do
        local ply = recipients[i]
        if IsValid(ply) and ply:IsPlayer() then
            net.Start("gmod_affected_state")
            net.WriteUInt(state, STATE_BITS)
            net.WriteUInt(amount, AMOUNT_BITS)
            net.Send(ply)
        end
    end
end
```

Reason: bit-packed WriteUInt avoids table serialization, net.PoolString amortizes the message name, and per-player net.Send scopes the fanout to exactly the affected recipients instead of broadcasting.


Receiver satisfies 8/15 per-player budget checks.

```lua
util.AddNetworkString("MyAddon.Action")

local MAX_BITS = 64
local MAX_PER_WINDOW = 20
local WINDOW_SECONDS = 1

local budget = {} -- [Player] = { window = number, count = number }

local function perform(ent)
    -- implement the action for the validated entity
end

net.Receive("MyAddon.Action", function(len, ply)
    if len > MAX_BITS then return end

    local window = math.floor(CurTime() / WINDOW_SECONDS)

    local b = budget[ply]
    if not b or b.window ~= window then
        b = { window = window, count = 0 }
        budget[ply] = b
    end

    if b.count >= MAX_PER_WINDOW then return end
    b.count = b.count + 1

    local ent = net.ReadEntity()
    if not IsValid(ent) then return end

    perform(ent)
end)

hook.Add("PlayerDisconnected", "MyAddon.CleanupActionBudget", function(ply)
    budget[ply] = nil
end)
```

Reason: Net string is pooled once via util.AddNetworkString; len>64 and over-budget checks reject before net.ReadEntity; a fixed 1-second floor window caps each player at 20 messages; and PlayerDisconnected clears the per-player budget so no state leaks across reconnects.