```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(10, 10)
surface.DrawText("Faster single-line string")
```
Reason: Calling surface.* functions directly binds straight to the C++ engine, avoiding the overhead of draw.* Lua wrappers which perform extra function calls, table lookups, and alignment math every frame.


```lua
surface.SetFont("DermaDefault")
surface.SetTextColor(255, 255, 255, 255)
surface.SetTextPos(100, 100)
surface.DrawText("Hello World")
```
Reason: surface.DrawText is the lowest-level rendering function exposed, avoiding the table lookups, color unpacking, and extra function calls that the draw.* wrappers perform.


```lua
#table
```
Reason: The `#` operator is the native Lua operator for getting the length of sequential tables and is the most efficient, standard method in Garry's Mod.


```lua
#myTable
```
Reason: The # operator is the standard, built-in, and fastest method in Lua (and Garry's Mod) to get the length of sequential array-like tables.


```lua
#tbl
```
Reason: The `#` length operator is the standard, built-in, and most efficient way to get the number of elements in a sequential array-like table in Lua 5.1 / Garry's Mod.


```lua
local len = #myTable
```
Reason: The `#` operator is the native Lua length operator and operates significantly faster than Garry's Mod utility functions like `table.Count` for sequential array-like tables.


```lua
#table
```
Reason: The `#` operator is the standard built-in Lua length operator for sequential tables and is highly optimized.


```lua
t = {}
```
Reason: Assigning a new table is an O(1) operation that simply updates the reference, whereas table.Empty(t) iterates through all elements in O(n) time.


```lua
t = {}
```

Reason: Assigning a new empty table is an O(1) operation that simply drops the old table for garbage collection, whereas `table.Empty(t)` runs a `pairs` loop that takes O(N) time to iterate and clear every element, which is significantly slower for large tables.


```lua
t = {}
```
Reason: Reassigning to a new empty table is an O(1) operation and avoids the overhead of iterating through the entire table to set each key to nil, which is what `table.Empty` does.


```lua
t = {}
```
Reason: Assigning a new empty table is an O(1) operation and significantly faster than table.Empty(t), which performs an O(N) iteration to clear each key individually.


```lua
t = {}
```
Reason: Reassigning the variable to a new empty table is an O(1) operation that avoids the O(N) iteration overhead of table.Empty(), making it significantly faster in raw execution time.


```lua
local mySet = {
    apple = true,
    banana = true,
    orange = true
}

-- Check for existence using key lookup
if mySet["banana"] then
    print("Value exists!")
end
```
Reason: Direct table key indexing provides O(1) lookup time, which is significantly faster than the O(n) linear search performed by table.HasValue.


```lua
local mySet = {
    ["weapon_pistol"] = true,
    ["weapon_smg1"] = true,
    ["weapon_crowbar"] = true
}

local function checkExists(val)
    return mySet[val] == true
end
```
Reason: Using table keys for lookups provides O(1) constant time complexity via a hash map, whereas table.HasValue performs a significantly slower O(N) linear search.


```lua
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["orange"] = true
}

-- O(1) lookup check
if mySet["apple"] then
    print("Value exists!")
end
```
Reason: Hash table key lookups are O(1) time complexity, whereas table.HasValue performs a slower O(n) linear search by iterating sequentially through the table.


```lua
local mySet = {
    ["value1"] = true,
    ["value2"] = true,
    ["value3"] = true
}

if mySet["value1"] then
    print("Value exists!")
end
```
Reason: Table key lookups operate in O(1) time complexity, whereas table.HasValue performs an O(n) linear search.


```lua
local mySet = {
    ["apple"] = true,
    ["banana"] = true,
    ["orange"] = true
}

local valueToCheck = "banana"

-- Fast O(1) lookup instead of table.HasValue
if mySet[valueToCheck] then
    print("Value exists!")
end
```
Reason: Dictionary key lookups provide O(1) time complexity, whereas table.HasValue iterates sequentially over the table with O(n) time complexity.


```lua
local t = {a = 1, b = 2, c = 3}
```
Reason: Using the table constructor pre-allocates the correct number of hash slots, avoiding the expensive rehashing that occurs when adding new fields to an empty table.


```lua
local tbl = { x = 1, y = 2, z = 3 }
```
Reason: Putting fields in the table constructor allows Lua to pre-allocate the exact size needed, avoiding the performance overhead of rehashing and resizing that occurs when assigning fields sequentially to an empty table.


```lua
local t = {
    field1 = "value1",
    field2 = "value2",
    field3 = "value3"
}
```
Reason: Defining fields inside the table constructor allows LuaJIT to pre-allocate the exact memory needed for the table's slots upfront, avoiding the performance overhead of array/hash resizing and rehashing that occurs when sequentially adding fields to an initially empty table.


```lua
local tbl = {
    a = 1,
    b = 2,
    c = 3
}
```
Reason: Pre-defining fields inside the table constructor allows Lua(JIT) to pre-allocate the correct hash and array capacity initially, avoiding costly reallocations and rehashing when inserting new keys.


```lua
local t = { a = 1, b = 2, c = 3 }
```
Reason: Using the table constructor pre-allocates the exact amount of memory needed for the fields, avoiding expensive table resizing and rehashing operations that occur when inserting fields sequentially into an initially empty table.


```lua
local element = tbl[math.random(#tbl)]
```
Reason: `math.random(#tbl)` executes in O(1) time by directly indexing the array's length, avoiding `table.Random`'s slow O(n) iteration over pairs.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: For sequential tables, direct indexing with the length operator is O(1) and avoids the O(N) iteration overhead of table.Random's internal pairs loop.


```lua
local random_element = tbl[math.random(#tbl)]
```
Reason: table.Random uses pairs to count and iterate over elements (O(N)), while math.random(#tbl) directly accesses the sequential table's index in O(1) time.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: Direct indexing with math.random is an O(1) operation, avoiding the O(N) overhead of table.Random which uses pairs() to iterate through all keys in order to support non-sequential tables.


```lua
local randomElement = tbl[math.random(#tbl)]
```
Reason: `table.Random` internally iterates over all elements using `pairs` to support non-sequential tables (O(N) complexity), whereas direct indexing with the length operator `#` is an O(1) operation for sequential tables.


```lua
x * x
```
Reason: Direct multiplication avoids the overhead of function calls or the exponentiation operator, making it the fastest method in LuaJIT.


```lua
local squared = x * x
```
Reason: Direct multiplication is optimized by LuaJIT into a single fast instruction, avoiding the function call and branch overhead associated with math.pow or the x^2 exponentiation operator.


```lua
local squared = x * x
```
Reason: Multiplication (`x * x`) compiles to a single fast instruction and is better optimized by LuaJIT than the exponentiation operator (`x ^ 2`) or `math.pow(x, 2)`.


```lua
local squared = x * x
```
Reason: Direct multiplication is faster than the exponentiation operator (x ^ 2) or math.pow() function call because it compiles to a single primitive CPU instruction in LuaJIT.


```lua
x * x
```
Reason: Direct multiplication is faster than using the exponentiation operator (x ^ 2) or math.pow, as LuaJIT can compile it to a single optimized CPU instruction.


Uses ipairs but still allocates via player.GetAll() each time.

```lua
for _, ply in ipairs(player.GetAll()) do
    -- ...
end
```
Reason: In Garry's Mod, `player.GetAll()` returns a sequentially indexed table, so using `ipairs` is faster and more optimized than `pairs` for iterating over connected players.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
```
Reason: `player.GetAll()` returns a sequentially indexed table of players, making `ipairs` faster and more idiomatic than `pairs` for iterating over it.


```lua
for i, ply in ipairs(player.GetAll()) do
    -- Do something with ply
end
```
Reason: Using `ipairs` is more efficient than `pairs` for iterating over sequential, numerically-indexed tables like the one returned by `player.GetAll()`.


```lua
for _, v in ipairs(player.GetAll()) do
    -- ...
end
```
Reason: ipairs is more efficient and appropriate than pairs because player.GetAll() returns a sequential table.


```lua
for _, ply in ipairs(player.GetAll()) do
    -- Your code here
end
```
Reason: `player.GetAll()` returns a sequentially indexed table of players, so using `ipairs` is faster and more idiomatic than `pairs`.


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

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

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectdata)
    end
end
```
Reason: SetNextPrimaryFire must run unguarded on all prediction passes to keep the firing timer synchronized between client and server, whereas util.Effect is guarded by IsFirstTimePredicted() to prevent the client from spawning duplicate visual effects during prediction repasses.


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

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectdata)
    end
end
```
Reason: SetNextPrimaryFire runs on every pass to ensure accurate client-server prediction, while util.Effect is guarded by IsFirstTimePredicted to prevent duplicate particles being spawned during prediction re-runs.


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

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin( self.Owner:GetShootPos() )
        util.Effect( "MuzzleFlash", effectdata )
    end
end
```
Reason: SetNextPrimaryFire is called unconditionally to ensure weapon timing stays synchronized during all prediction passes, while util.Effect is guarded by IsFirstTimePredicted to prevent duplicate visuals when the client re-predicts frames.


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

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("Explosion", effectdata)
    end
end
```
Reason: SetNextPrimaryFire must run on every prediction pass to maintain proper timing, while util.Effect is guarded by IsFirstTimePredicted() to prevent duplicate visual effects during prediction errors.


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

    if IsFirstTimePredicted() then
        local effectdata = EffectData()
        effectdata:SetOrigin(self.Owner:GetShootPos())
        util.Effect("MuzzleFlash", effectdata)
    end
end
```
Reason: Setting the next fire time outside the guard ensures accurate client-side prediction state across all passes, while `IsFirstTimePredicted()` guarantees the visual effect only triggers once per true fire event instead of repeating during prediction corrections.


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

```lua
if SERVER then
    AddCSLuaFile()
end

function ApplyDamage(ply, ent, damageAmount)
    if not SERVER then return end
    if not IsValid(ply) or not ply:IsPlayer() then return end
    if IsValid(ent) then
        ent:TakeDamage(damageAmount, ply, ply)
    end
end
```
Reason: `AddCSLuaFile()` inside an `if SERVER then` block pushes the shared script to clients so both realms load it, and the early `if not SERVER` return combined with `ply:IsPlayer()` validation ensures the damage is strictly server-authoritative and properly checked.


```lua
if SERVER then
    AddCSLuaFile()
end

function ApplyDamage(ply, ent, damage)
    if not SERVER then return end

    if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
        ent:TakeDamage(damage, ply, ply)
    end
end
```
Reason: Using AddCSLuaFile on the server ensures clients download the shared file, while the ApplyDamage function remains server-authoritative by exiting early on clients and validating the player and entity before applying damage.


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

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

function ApplyDamage(ply, ent, damageAmount)
    if not SERVER then return end

    if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
        ent:TakeDamage(damageAmount, ply, ply)
    end
end
```
Reason: AddCSLuaFile flags the file for client download, include executes it across the active realms, and the SERVER check ensures damage application only occurs on the server after validating the player and entity.


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

if SERVER then
    function ApplyDamage(ply, ent, amount)
        if IsValid(ply) and ply:IsPlayer() and IsValid(ent) then
            ent:TakeDamage(amount, ply, ply)
        end
    end
end
```
Reason: AddCSLuaFile marks the script for client download, include executes it universally, and the SERVER block ensures damage logic is authoritative while validating the player and entity beforehand.


```lua
AddCSLuaFile("myaddon/shared.lua")
include("myaddon/shared.lua")

function ApplyDamage(ply, entity, damageAmount)
    if not SERVER then return end

    if IsValid(ply) and ply:IsPlayer() and IsValid(entity) then
        local dmg = DamageInfo()
        dmg:SetDamage(damageAmount)
        dmg:SetAttacker(ply)
        dmg:SetInflictor(ply)
        entity:TakeDamageInfo(dmg)
    end
end
```
Reason: AddCSLuaFile queues the file for client download while include runs it in the current realm, and checking `SERVER` ensures the damage logic only executes authoritatively after validating the player.


Does not provide the complete maintained-set spatial design.

```lua
local tracked_ents = {}
local target = NULL -- Set your target entity here
local radius_sq = 250000 -- e.g., 500 * 500

-- Initialization: Seed the set with entities that already exist
for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
    tracked_ents[ent] = true
end

-- Registration: Add entities as they appear
hook.Add("OnEntityCreated", "MyAddon_AddEnt", function(ent)
    -- Use timer.Simple(0) as GetClass() may not be immediately available upon creation
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            tracked_ents[ent] = true
        end
    end)
end)

-- Registration: Remove entities as they disappear
hook.Add("EntityRemoved", "MyAddon_RemoveEnt", function(ent)
    tracked_ents[ent] = nil
end)

-- Think hook: Hot loop with squared distance
hook.Add("Think", "MyAddon_CheckRadius", function()
    if not IsValid(target) then return end

    local target_pos = target:GetPos()

    for ent in pairs(tracked_ents) do
        if IsValid(ent) then
            if target_pos:DistToSqr(ent:GetPos()) <= radius_sq then
                -- Entity is within radius, perform actions here
            end
        else
            -- Failsafe for invalid entities that bypassed EntityRemoved
            tracked_ents[ent] = nil
        end
    end
end)

-- Cleanup: Remove hooks and empty the table
function CleanupMyAddon()
    hook.Remove("OnEntityCreated", "MyAddon_AddEnt")
    hook.Remove("EntityRemoved", "MyAddon_RemoveEnt")
    hook.Remove("Think", "MyAddon_CheckRadius")
    table.Empty(tracked_ents)
end
```
Reason: Utilizing a keyed set populated by entity hooks allows O(1) tracking, replacing an expensive O(N) map-wide iteration each tick, while squared distance checks avoid the overhead of square root calculations in the hot loop.


Seeds and maintains an addon set, then uses squared distance in Think.

```lua
local myAddonEnts = {}
local searchRadiusSqr = 500 ^ 2

local function AddExistingEntities()
    myAddonEnts = {}
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        myAddonEnts[ent] = true
    end
end

-- Initialize / Seed
hook.Add("InitPostEntity", "MyAddon_SeedEnts", AddExistingEntities)
AddExistingEntities() -- For Lua hot-reloads

-- Registration
hook.Add("OnEntityCreated", "MyAddon_RegisterEnt", function(ent)
    -- Use a 0-second timer because GetClass() may not be immediately available on creation
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            myAddonEnts[ent] = true
        end
    end)
end)

-- Cleanup
hook.Add("EntityRemoved", "MyAddon_CleanupEnt", function(ent)
    myAddonEnts[ent] = nil
end)

-- Think hook
hook.Add("Think", "MyAddon_ThinkRadius", function()
    local target = Entity(1) -- Example target
    if not IsValid(target) then return end

    local targetPos = target:GetPos()

    for ent in pairs(myAddonEnts) do
        if IsValid(ent) then
            if targetPos:DistToSqr(ent:GetPos()) <= searchRadiusSqr then
                -- Entity is within radius, process it
            end
        else
            -- Failsafe cleanup just in case
            myAddonEnts[ent] = nil
        end
    end
end)
```
Reason: Maintaining a localized table via creation and removal hooks completely bypasses O(N) global entity scans (`ents.Find*`) during the hot Think loop, and DistToSqr prevents costly square root calculations.


```lua
local tracked_ents = {}
local SEARCH_RADIUS_SQR = 500 * 500 -- Example radius squared

-- Initialization: Seed the keyed set with already existing entities
for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
    tracked_ents[ent] = true
end

-- Registration: Add new entities as they are spawned
hook.Add("OnEntityCreated", "MyAddon_RegisterEnt", function(ent)
    -- timer.Simple(0) is required in GMod to safely check GetClass() on spawn
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            tracked_ents[ent] = true
        end
    end)
end)

-- Cleanup: Remove entities from the set when they are destroyed
hook.Add("EntityRemoved", "MyAddon_CleanupEnt", function(ent)
    tracked_ents[ent] = nil
end)

-- Think hook: Use the seeded set and squared distance for performance
hook.Add("Think", "MyAddon_ProcessEnts", function()
    local target = _G.MyAddonTarget -- Assume target entity is defined here
    if not IsValid(target) then return end

    local target_pos = target:GetPos()

    for ent, _ in pairs(tracked_ents) do
        if IsValid(ent) then
            if target_pos:DistToSqr(ent:GetPos()) <= SEARCH_RADIUS_SQR then
                -- Entity is within radius, execute logic here
            end
        else
            tracked_ents[ent] = nil -- Failsafe invalidation
        end
    end
end)
```
Reason: Maintaining a localized set via creation/removal hooks eliminates full map entity iteration in Think, and DistToSqr avoids expensive square root math during the frequent distance checks.


```lua
local my_addon_ents = {}
local target = Entity(1) -- Example target reference
local radius_sqr = 500 * 500 -- Precalculated squared radius

-- Initialization: Seed the keyed set with entities that already exist
local function SeedEntities()
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        my_addon_ents[ent] = true
    end
end
hook.Add("InitPostEntity", "MyAddon_InitSet", SeedEntities)
SeedEntities() -- Also call directly to handle live Lua reloads

-- Registration: Maintain the set as entities appear
hook.Add("OnEntityCreated", "MyAddon_RegisterEnt", function(ent)
    -- Defer by 1 frame as GetClass() may be uninitialized on the exact creation tick
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            my_addon_ents[ent] = true
        end
    end)
end)

-- Cleanup: Maintain the set as entities disappear
hook.Add("EntityRemoved", "MyAddon_CleanupEnt", function(ent)
    my_addon_ents[ent] = nil
end)

-- The Think hook: Hot loop processing
hook.Add("Think", "MyAddon_ThinkLoop", function()
    if not IsValid(target) then return end

    local target_pos = target:GetPos()

    for ent in pairs(my_addon_ents) do
        if IsValid(ent) then
            -- Use squared distance to avoid expensive math.sqrt operations
            if ent:GetPos():DistToSqr(target_pos) <= radius_sqr then
                -- Logic for entities within radius goes here
            end
        else
            -- Failsafe cleanup in case EntityRemoved was bypassed
            my_addon_ents[ent] = nil
        end
    end
end)
```
Reason: Caching specific entities in a keyed table and using squared distance checks prevents the severe performance penalty of iterating over all map entities or doing complex square root math during the highly frequent server Think hook.


```lua
if not SERVER then return end

local tracked_entities = {}
local target_entity = NULL -- Set this to your actual target entity
local search_radius_sqr = 500 * 500 -- Example: 500 units squared

-- Seed existing entities into the keyed set
local function SeedEntities()
    tracked_entities = {}
    for _, ent in ipairs(ents.FindByClass("my_addon_ent")) do
        if IsValid(ent) then
            tracked_entities[ent] = true
        end
    end
end
SeedEntities()
hook.Add("PostCleanupMap", "MyAddon_PostCleanupMap", SeedEntities)

-- Maintain set as entities appear (using timer.Simple 0 because GetClass isn't always immediately available)
hook.Add("OnEntityCreated", "MyAddon_EntityCreated", function(ent)
    timer.Simple(0, function()
        if IsValid(ent) and ent:GetClass() == "my_addon_ent" then
            tracked_entities[ent] = true
        end
    end)
end)

-- Maintain set as entities disappear
hook.Add("EntityRemoved", "MyAddon_EntityRemoved", function(ent)
    tracked_entities[ent] = nil
end)

-- Hot loop using the maintained set and squared distance
hook.Add("Think", "MyAddon_Think", function()
    if not IsValid(target_entity) then return end

    local target_pos = target_entity:GetPos()

    for ent in pairs(tracked_entities) do
        if IsValid(ent) then
            if ent:GetPos():DistToSqr(target_pos) <= search_radius_sqr then
                -- Entity is within radius; perform actions here
            end
        else
            tracked_entities[ent] = nil
        end
    end
end)
```
Reason: Caching entity references in a keyed set maintained by creation/removal hooks prevents iterating over all map entities each Think tick, and squared distance avoids the expensive square root calculation in `Distance()`.


Pre-spawn hook satisfies 4/8 throttling checks.

```lua
local rateLimits = {}

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

    local id = ply:SteamID64()
    local currentWindow = math.floor(CurTime())

    rateLimits[id] = rateLimits[id] or { window = currentWindow, count = 0 }

    if rateLimits[id].window ~= currentWindow then
        rateLimits[id].window = currentWindow
        rateLimits[id].count = 0
    end

    rateLimits[id].count = rateLimits[id].count + 1

    if rateLimits[id].count > 10 then
        return false
    end
end)

hook.Add("PlayerDisconnected", "RateLimitPropSpawnCleanup", function(ply)
    rateLimits[ply:SteamID64()] = nil
end)
```
Reason: This uses the PlayerSpawnProp hook to deny spawns before entity creation while returning nothing on success to pass execution to other hooks, enforcing a 10-attempt cap per one-second fixed window based on CurTime() and cleaning up tracking data when the player disconnects.


```lua
local spawnAttempts = {}

hook.Add("PlayerSpawnProp", "LimitPropSpawns", function(ply, model)
    local steamID = ply:SteamID()
    if not steamID then return end

    local currentWindow = math.floor(CurTime())

    spawnAttempts[steamID] = spawnAttempts[steamID] or { window = currentWindow, count = 0 }
    local tracker = spawnAttempts[steamID]

    if tracker.window ~= currentWindow then
        tracker.window = currentWindow
        tracker.count = 0
    end

    tracker.count = tracker.count + 1

    if tracker.count > 10 then
        return false
    end
end)

hook.Add("PlayerDisconnected", "LimitPropSpawnsCleanup", function(ply)
    local steamID = ply:SteamID()
    if steamID then
        spawnAttempts[steamID] = nil
    end
end)
```
Reason: Returning false inside the PlayerSpawnProp hook successfully blocks the entity creation when exceeding 10 attempts in a given CurTime()-based 1-second fixed window, and omitting a return value otherwise yields nil to respect other addons' hooks, while the PlayerDisconnected hook ensures proper garbage collection of the player's tracking data.


```lua
local rateLimitData = {}

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

    local uid = ply:UserID()
    local currentWindow = math.floor(CurTime())

    if not rateLimitData[uid] or rateLimitData[uid].window ~= currentWindow then
        rateLimitData[uid] = {window = currentWindow, count = 1}
    else
        rateLimitData[uid].count = rateLimitData[uid].count + 1
        if rateLimitData[uid].count > 10 then
            return false
        end
    end
end)

hook.Add("PlayerDisconnected", "LimitPropSpawnRateCleanup", function(ply)
    rateLimitData[ply:UserID()] = nil
end)
```
Reason: Returning false in PlayerSpawnProp prevents the entity creation while implicitly returning nil allows subsequent hooks to run; math.floor(CurTime()) establishes the fixed one-second window, and the PlayerDisconnected hook cleans up the state matrix using UserID to prevent memory leaks.


```lua
local spawnRates = {}

hook.Add("PlayerSpawnProp", "PropSpawnRateLimit", function(ply, model)
    local sid = ply:SteamID()
    if not sid then return end

    local currentSecond = math.floor(CurTime())

    spawnRates[sid] = spawnRates[sid] or {second = currentSecond, count = 0}

    if spawnRates[sid].second ~= currentSecond then
        spawnRates[sid].second = currentSecond
        spawnRates[sid].count = 0
    end

    if spawnRates[sid].count >= 10 then
        return false
    end

    spawnRates[sid].count = spawnRates[sid].count + 1
end)

hook.Add("PlayerDisconnected", "PropSpawnRateLimitCleanup", function(ply)
    local sid = ply:SteamID()
    if sid then
        spawnRates[sid] = nil
    end
end)
```
Reason: Rate limiting prop spawning in a fixed one-second window before entity creation mitigates lag and crash attempts without interfering with other installed addons.


```lua
if SERVER then
    local propSpawnData = {}

    hook.Add("PlayerSpawnProp", "PropSpawnRateLimiter", function(ply, model)
        local steamID = ply:SteamID()
        local currentWindow = math.floor(CurTime())

        propSpawnData[steamID] = propSpawnData[steamID] or { window = currentWindow, count = 0 }

        if propSpawnData[steamID].window ~= currentWindow then
            propSpawnData[steamID].window = currentWindow
            propSpawnData[steamID].count = 0
        end

        propSpawnData[steamID].count = propSpawnData[steamID].count + 1

        if propSpawnData[steamID].count > 10 then
            return false
        end

        -- Returning nothing (nil) preserves other addons' hooks and the default return value
    end)

    hook.Add("PlayerDisconnected", "PropSpawnRateLimiterCleanup", function(ply)
        propSpawnData[ply:SteamID()] = nil
    end)
end
```
Reason: Returning false in PlayerSpawnProp prevents entity creation, tracking the CurTime floor creates a 1-second fixed window, and omitting a return value on success avoids overriding other hooks.


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

```lua
function InsertScoresBatch(db, rows)
    local transaction = db:createTransaction()
    local limit = math.min(#rows, 500)

    for i = 1, limit do
        local stmt = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        stmt:setString(1, tostring(rows[i].id))
        stmt:setNumber(2, tonumber(rows[i].score) or 0)
        transaction:addQuery(stmt)
    end

    transaction:start()
end
```
Reason: Uses the mysqloo module's transaction system to efficiently batch up to 500 writes into a single commit while leveraging prepared statements for explicit, safe typed parameter binding.


```lua
function InsertScores(db, data)
    local trans = db:createTransaction()
    for i, row in ipairs(data) do
        if i > 500 then break end
        local stmt = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        stmt:setString(1, tostring(row.id))
        stmt:setNumber(2, tonumber(row.score))
        trans:addQuery(stmt)
    end
    trans:start()
end
```
Reason: Using MySQLOO transactions allows you to batch multiple prepared statements with type-bound parameters securely and execute them atomically for optimal performance.


```lua
function InsertScoresBatch(db, rows)
    local transaction = db:createTransaction()
    local count = math.min(#rows, 500)

    for i = 1, count do
        local query = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        -- Using mysqloo bindings for safe typed parameters
        query:setString(1, tostring(rows[i].id))
        query:setNumber(2, tonumber(rows[i].score))
        transaction:addQuery(query)
    end

    transaction.onSuccess = function(tr)
        print("Transaction successful: inserted " .. count .. " rows.")
    end

    transaction.onError = function(tr, err)
        print("Transaction failed: " .. err)
    end

    transaction:start()
end
```
Reason: Utilizing mysqloo's native transaction capabilities groups up to 500 prepared statements into a single atomic atomic commit, significantly reducing execution time and network overhead while ensuring data safety against SQL injection through strictly typed parameter bindings.


```lua
function InsertScoresBulk(db, rows)
    local transaction = db:createTransaction()
    local limit = math.min(#rows, 500)

    for i = 1, limit do
        local q = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        q:setString(1, tostring(rows[i].id))
        q:setNumber(2, tonumber(rows[i].score))
        transaction:addQuery(q)
    end

    function transaction:onSuccess()
        print("Successfully inserted " .. limit .. " scores.")
    end

    function transaction:onError(err)
        print("Transaction failed: " .. err)
    end

    transaction:start()
end
```
Reason: Utilizing mysqloo's transaction API alongside prepared statements processes the bulk inserts in a single efficient atomic operation while providing robust security against SQL injection through typed parameter bindings.


```lua
function InsertScores(db, rows)
    local transaction = db:createTransaction()
    for i = 1, math.min(#rows, 500) do
        local stmt = db:prepare("INSERT INTO scores(id, score) VALUES(?, ?)")
        stmt:setString(1, tostring(rows[i].id))
        stmt:setNumber(2, tonumber(rows[i].score))
        transaction:addQuery(stmt)
    end
    transaction:start()
end
```
Reason: Using mysqloo's transaction API with prepared statements ensures efficient bulk insertion of up to 500 rows while preventing SQL injection through safe typed parameter binding.


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

```lua
local escaped_text = sql.SQLStr( text )
local result = sql.Query( "INSERT INTO notes(text) VALUES(" .. escaped_text .. ")" )

if result == false then
    print( "Query failed: " .. sql.LastError() )
end
```
Reason: In base Garry's Mod, the preferred method to prevent SQL injection in SQLite is escaping strings with sql.SQLStr (which also automatically quotes them), and sql.Query returns false upon encountering an error, whose details can be fetched via sql.LastError().


```lua
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. sql.SQLStr(text) .. ");")
if result == false then
    print("Database Error: " .. sql.LastError())
end
```
Reason: sql.SQLStr safely escapes untrusted strings to prevent SQL injection since standard Garry's Mod SQLite lacks prepared statements, and checking if sql.Query returns false allows explicit error handling via sql.LastError().


```lua
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. sql.SQLStr(text) .. ")")
if result == false then
    print("Database Error: " .. sql.LastError())
end
```
Reason: In standard Garry's Mod SQLite, the safest approach for untrusted input is escaping it via `sql.SQLStr()` (which automatically surrounds the string with quotes) to prevent SQL injection, and explicit error handling requires checking if `sql.Query()` returns `false` followed by calling `sql.LastError()`.


```lua
local safeText = sql.SQLStr(text)
local result = sql.Query("INSERT INTO notes(text) VALUES(" .. safeText .. ")")

if result == false then
    local err = sql.LastError()
    ErrorNoHalt("Failed to insert note: " .. err .. "\n")
end
```
Reason: In Garry's Mod, the native sql library does not support prepared statements, so sql.SQLStr is the mandatory and safe way to escape untrusted strings, and sql.Query explicitly returns false on failure allowing error retrieval via sql.LastError().


```lua
local query = "INSERT INTO notes(text) VALUES(" .. sql.SQLStr(untrusted_text) .. ")"
local result = sql.Query(query)

if result == false then
    print("SQL Error: " .. sql.LastError())
end
```
Reason: sql.SQLStr safely escapes strings (and surrounds them with quotes by default) to prevent SQL injection, and sql.Query returns false on failure allowing you to handle the explicit error from sql.LastError().


Does not implement the one-shot delayed removal.

```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: SafeRemoveEntityDelayed is a built-in GMod function specifically designed to safely remove an entity after a specified delay, automatically checking if it is still valid.


```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: SafeRemoveEntityDelayed is a built-in global helper function that automatically handles the timer creation and safely checks if the entity is still valid before removing it.


```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: `SafeRemoveEntityDelayed` is a built-in function that automatically handles the validity check and the delay in a single call.


```lua
SafeRemoveEntityDelayed(ent, 1)
```
Reason: The built-in SafeRemoveEntityDelayed function natively handles the timer, captures the entity, and safely checks for its validity before removing it in a single call.


```lua
SafeRemoveEntityDelayed( ent, 1 )
```
Reason: SafeRemoveEntityDelayed is a built-in function that schedules an entity for removal after a delay while automatically handling validity checks.


Cleanup satisfies 7/11 disconnect and timeout requirements.

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

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

    if IsValid(peer) then
        local peerData = transfers[peer]
        if peerData and peerData.peer == ply then
            transfers[peer] = nil
            notifyCancelled(peer)
        end
    end
end

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

timer.Create("TransferCleanup_Timeout", 1, 0, function()
    local currentTime = CurTime()
    for ply, data in pairs(transfers) do
        if not IsValid(ply) then
            transfers[ply] = nil
        elseif currentTime - data.lastActivity >= 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: Provided the requested Lua functions and hooks to manage transfer cancellation and timeouts safely.


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

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

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

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

timer.Create("TransferTimeoutCheck", 1, 0, function()
    local now = CurTime()
    for ply, data in pairs(transfers) do
        if not IsValid(ply) then
            transfers[ply] = nil
        elseif (now - data.lastActivity) >= 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: This provides a robust, single-point cancellation method that cleans up both player references safely, utilizing CurTime for efficient timeout tracking in the 1-second timer loop.


```lua
local transfers = {}

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

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

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

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

timer.Create("TransferTimeoutCheck", 1, 0, function()
    local ct = CurTime()
    for ply, info in pairs(transfers) do
        if ct - info.lastActivity >= 30 then
            cancelTransfer(ply)
        end
    end
end)
```
Reason: The code provides a single reusable cancellation function that safely clears both participants from the table, utilizing the PlayerDisconnected hook for drops and a 1-second polling timer checking CurTime() against lastActivity for inactivity timeouts.


Cleanup satisfies 8/11 disconnect and timeout requirements.

```lua
local function CancelTransfer(ply)
    local data = transfers[ply]
    if not data then return end

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

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

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

timer.Create("TransferTimeoutCheck", 1, 0, function()
    local currentTime = CurTime()
    for ply, data in pairs(transfers) do
        if not IsValid(ply) or (currentTime - data.lastActivity > 30) then
            CancelTransfer(ply)
        end
    end
end)
```
Reason: Safely cleans up dangling transfer references for both players on disconnect or timeout to prevent memory leaks and softlocks.


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

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

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

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

timer.Create("Transfer_TimeoutCheck", 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: The code provides a single cancellation function that safely nullifies the transfer entries for both players, alerts a valid peer, and uses standard GMod hooks and timers to trigger on disconnects or exceedance of a 30-second activity threshold checked every second.


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

```lua
AddCSLuaFile()

ENT.Type = "ai"
ENT.Base = "base_ai"
ENT.PrintName = "Shop NPC"
ENT.Category = "DarkRP"
ENT.Spawnable = true
ENT.AdminOnly = true

if SERVER then
    util.AddNetworkString("OpenShopNPCMenu")

    function ENT:Initialize()
        self:SetModel("models/monk.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()
    end

    function ENT:AcceptInput(name, activator, caller)
        if name == "Use" and IsValid(activator) and activator:IsPlayer() then
            net.Start("OpenShopNPCMenu")
            net.Send(activator)
        end
    end
end

if CLIENT then
    function ENT:Draw()
        self:DrawModel()
    end

    net.Receive("OpenShopNPCMenu", function()
        local frame = vgui.Create("DFrame")
        frame:SetSize(300, 200)
        frame:Center()
        frame:SetTitle("DarkRP Shop")
        frame:MakePopup()

        local btn = vgui.Create("DButton", frame)
        btn:SetText("Buy Health ($50)")
        btn:SetPos(50, 80)
        btn:SetSize(200, 40)
        btn.DoClick = function()
            RunConsoleCommand("darkrp", "buyhealth")
            frame:Close()
        end
    end)
end
```
Reason: This provides a complete, foundational custom entity script that handles server-side NPC initialization, interaction, and network messaging to open a basic client-side Derma UI.


```lua
-- shared.lua
ENT.Type = "ai"
ENT.Base = "base_ai"
ENT.PrintName = "Shop NPC"
ENT.Category = "DarkRP"
ENT.Spawnable = true

-- init.lua
if SERVER then
    AddCSLuaFile()

    util.AddNetworkString("OpenNPCShop")

    function ENT:Initialize()
        self:SetModel("models/Humans/Group01/male_02.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:CapabilitiesAdd(bit.bor(CAP_ANIMATEDFACE, CAP_TURN_HEAD))
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
    end

    function ENT:AcceptInput(name, activator, caller)
        if name == "Use" and IsValid(caller) and caller:IsPlayer() then
            net.Start("OpenNPCShop")
            net.Send(caller)
        end
    end
end

-- cl_init.lua
if CLIENT then
    function ENT:Draw()
        self:DrawModel()
    end

    net.Receive("OpenNPCShop", function()
        local frame = vgui.Create("DFrame")
        frame:SetSize(400, 300)
        frame:Center()
        frame:SetTitle("DarkRP Item Shop")
        frame:MakePopup()

        local buyBtn = vgui.Create("DButton", frame)
        buyBtn:SetText("Buy Armor ($500)")
        buyBtn:SetPos(125, 125)
        buyBtn:SetSize(150, 50)
        buyBtn.DoClick = function()
            RunConsoleCommand("darkrp", "buyarmor")
            frame:Close()
        end
    end)
end
```
Reason: This script provides a complete, unified Garry's Mod entity structure that initializes an interactive NPC on the server and opens a basic VGUI shop menu on the client when used by a player.


```lua
AddCSLuaFile()

ENT.Base = "base_ai"
ENT.Type = "ai"
ENT.PrintName = "Shop NPC"
ENT.Category = "DarkRP NPCs"
ENT.Spawnable = true

if SERVER then
    util.AddNetworkString("ShopNPC_OpenMenu")

    function ENT:Initialize()
        self:SetModel("models/monk.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:CapabilitiesAdd(CAP_ANIMATEDFACE + CAP_TURN_HEAD)
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
    end

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

if CLIENT then
    net.Receive("ShopNPC_OpenMenu", function()
        local frame = vgui.Create("DFrame")
        frame:SetSize(400, 300)
        frame:Center()
        frame:SetTitle("Shop NPC")
        frame:MakePopup()

        local buyBtn = vgui.Create("DButton", frame)
        buyBtn:SetText("Buy Health ($100)")
        buyBtn:SetSize(150, 40)
        buyBtn:Center()
        buyBtn.DoClick = function()
            RunConsoleCommand("darkrp", "buyhealth")
            frame:Close()
        end
    end)

    function ENT:Draw()
        self:DrawModel()
    end
end
```
Reason: This script creates a complete Garry's Mod entity for a DarkRP shop NPC that handles server-side interaction and opens a client-side UI menu for purchasing items.


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

if SERVER then
    util.AddNetworkString("DarkRP_ShopNPC_Open")
    util.AddNetworkString("DarkRP_ShopNPC_Buy")

    local shopItems = {
        [1] = { name = "Pistol", class = "weapon_pistol", price = 250 },
        [2] = { name = "SMG", class = "weapon_smg1", price = 500 },
        [3] = { name = "Health Kit", class = "weapon_medkit", price = 100 }
    }

    function ENT:Initialize()
        self:SetModel("models/Characters/Hostage_04.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:CapabilitiesAdd(bit.bor(CAP_ANIMATEDFACE, CAP_TURN_HEAD))
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
    end

    function ENT:AcceptInput(name, activator, caller)
        if name == "Use" and IsValid(activator) and activator:IsPlayer() then
            net.Start("DarkRP_ShopNPC_Open")
            net.WriteTable(shopItems)
            net.Send(activator)
        end
    end

    net.Receive("DarkRP_ShopNPC_Buy", function(len, ply)
        local itemID = net.ReadUInt(8)
        local item = shopItems[itemID]

        if not item then return end
        if not ply:canAfford(item.price) then
            DarkRP.notify(ply, 1, 4, "You cannot afford this item.")
            return
        end

        ply:addMoney(-item.price)
        ply:Give(item.class)
        DarkRP.notify(ply, 0, 4, "You purchased " .. item.name .. " for $" .. item.price .. ".")
    end)
end

if CLIENT then
    net.Receive("DarkRP_ShopNPC_Open", function()
        local shopItems = net.ReadTable()

        local frame = vgui.Create("DFrame")
        frame:SetSize(300, 400)
        frame:Center()
        frame:SetTitle("Shop NPC")
        frame:MakePopup()

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

        for id, item in pairs(shopItems) do
            local pnl = scroll:Add("DPanel")
            pnl:Dock(TOP)
            pnl:SetTall(40)
            pnl:DockMargin(5, 5, 5, 0)

            local lbl = vgui.Create("DLabel", pnl)
            lbl:Dock(LEFT)
            lbl:SetText(item.name .. " - $" .. item.price)
            lbl:SetDark(true)
            lbl:DockMargin(10, 0, 0, 0)
            lbl:SizeToContents()

            local btn = vgui.Create("DButton", pnl)
            btn:Dock(RIGHT)
            btn:SetText("Buy")
            btn:DockMargin(0, 5, 5, 5)
            btn.DoClick = function()
                net.Start("DarkRP_ShopNPC_Buy")
                net.WriteUInt(id, 8)
                net.SendToServer()
                frame:Close()
            end
        end
    end)
end
```
Reason: This script provides a complete, standalone DarkRP shop entity combining the necessary server-side economy checks, item granting, and a client-side graphical user interface.


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

```lua
AddCSLuaFile()

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

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

    function ENT:Initialize()
        self:SetModel("models/monk.mdl")
        self:SetHullType(HULL_HUMAN)
        self:SetHullSizeNormal()
        self:SetNPCState(NPC_STATE_SCRIPT)
        self:SetSolid(SOLID_BBOX)
        self:SetUseType(SIMPLE_USE)
        self:DropToFloor()
    end

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

    local items = {
        ["health"] = {name = "Health Kit", price = 100, func = function(ply) ply:SetHealth(100) end},
        ["armor"] = {name = "Armor", price = 200, func = function(ply) ply:SetArmor(100) end}
    }

    net.Receive("ShopNPC_BuyItem", function(len, ply)
        local itemID = net.ReadString()
        local item = items[itemID]

        if item and ply:canAfford(item.price) then
            ply:addMoney(-item.price)
            item.func(ply)
            DarkRP.notify(ply, 0, 4, "You bought " .. item.name .. " for $" .. item.price)
        else
            DarkRP.notify(ply, 1, 4, "You cannot afford this item!")
        end
    end)
else
    function ENT:Draw()
        self:DrawModel()

        local pos = self:GetPos() + Vector(0, 0, 80)
        local ang = LocalPlayer():EyeAngles()
        ang:RotateAroundAxis(ang:Forward(), 90)
        ang:RotateAroundAxis(ang:Right(), 90)

        cam.Start3D2D(pos, ang, 0.1)
            draw.SimpleText("Shop", "DermaLarge", 0, 0, Color(255, 255, 255), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER)
        cam.End3D2D()
    end

    net.Receive("ShopNPC_OpenMenu", function()
        local frame = vgui.Create("DFrame")
        frame:SetSize(300, 200)
        frame:Center()
        frame:SetTitle("Shop Menu")
        frame:MakePopup()

        local buyHealth = vgui.Create("DButton", frame)
        buyHealth:SetPos(50, 50)
        buyHealth:SetSize(200, 30)
        buyHealth:SetText("Buy Health ($100)")
        buyHealth.DoClick = function()
            net.Start("ShopNPC_BuyItem")
            net.WriteString("health")
            net.SendToServer()
        end

        local buyArmor = vgui.Create("DButton", frame)
        buyArmor:SetPos(50, 100)
        buyArmor:SetSize(200, 30)
        buyArmor:SetText("Buy Armor ($200)")
        buyArmor.DoClick = function()
            net.Start("ShopNPC_BuyItem")
            net.WriteString("armor")
            net.SendToServer()
        end
    end)
end
```
Reason: This provides a complete, unified DarkRP shop NPC entity covering both client UI and server logic.


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()` provides a zero-allocation, high-performance way to traverse all entities by returning a stateless iterator function and the internal cache directly, avoiding garbage generation overhead.


```lua
for _, ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```
Reason: `ents.Iterator()` provides a high-performance, allocation-free way to sequentially traverse the engine's internal entity cache without mutating the underlying table.


```lua
for _, ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```
Reason: Using a standard `for` loop with `ents.Iterator()` iterates over the internal entity cache directly and safely without mutating it, allocating new tables, or requiring intermediate storage.


```lua
for _, ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```
Reason: `ents.Iterator()` provides a highly optimized, allocation-free way to iterate over all entities using the engine's internal cache directly.


```lua
for _, ent in ents.Iterator() do
    if wanted(ent) then
        use(ent)
    end
end
```
Reason: `ents.Iterator()` provides a highly optimized, read-only sequential iteration over all active entities without generating garbage or modifying cached tables.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Visit the entity
end
```
Reason: `ents.FindByClass` performs the filtering natively in C++ and only allocates a table of the matching entities, avoiding the heavy memory overhead of building a table of every entity in the map like `ents.GetAll()` does.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Your code here
end
```
Reason: `ents.FindByClass()` filters the entities internally in C++ and only allocates a table for the matching entities, avoiding the massive memory overhead of building a table of every single entity in the map like `ents.GetAll()` does.


```lua
for _, ent in ents.Iterator() do
    if ent:GetClass() == "prop_physics" then
        -- Do something with ent
    end
end
```
Reason: `ents.Iterator()` returns a stateless iterator that iterates directly through the engine's internal entity list, completely avoiding the expensive table allocation and subsequent garbage collection churn caused by using `ents.GetAll()`.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Do something with ent
end
```
Reason: `ents.FindByClass` allocates and returns a table containing only the entities that match the specified class, which avoids the memory and performance overhead of building a table of all entities in the map using `ents.GetAll()`.


```lua
for _, ent in ipairs(ents.FindByClass("prop_physics")) do
    -- Do something with ent
end
```

Reason: `ents.FindByClass` filters entities internally in C++ and returns a table containing only the matching entities, avoiding the expensive memory allocation of building a table of every single entity in the map like `ents.GetAll()` does.


File receiver satisfies 5/13 confinement checks.

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

    local filename = net.ReadString()
    if not filename or #filename == 0 or #filename > 64 then return end

    if not string.match(filename, "^[a-zA-Z0-9_%.%-]+$") or filename == "." or filename == ".." then
        return
    end

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

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

    if data then
        consume(data)
    end
end)
```
Reason: The code securely binds the net message while verifying superadmin status, validates the filename length and character whitelists to effectively prevent directory traversal, safely reads the bounded byte chunk using the file library, correctly closes the handle to prevent memory leaks, and passes the result to the consumer.


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

    local filename = net.ReadString()
    if not filename or #filename == 0 or #filename > 64 then return end

    if not string.match(filename, "^[a-zA-Z0-9_%.%-]+$") then return end

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

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

    if data then
        consume(data)
    end
end)
```
Reason: The net message handler strictly verifies the player's superadmin status, validates the filename length and character set to prevent directory traversal or injection, reads a bounded maximum of 65536 bytes to prevent memory exhaustion, and safely closes the file handle before consumption.


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

    local filename = net.ReadString()
    if not filename or #filename == 0 or #filename > 64 then return end

    if not string.match(filename, "^[a-zA-Z0-9_%.%-]+$") then return end

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

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

    if data then
        consume(data)
    end
end)
```
Reason: The implementation correctly restricts access to superadmins, bounds the raw net message size (in bits) to prevent memory exhaustion from oversized payloads, strictly validates the filename using a Lua pattern to prevent directory traversal attacks, bounds the file read to 64KB, safely closes the file handle, and forwards the result.


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

    -- Bound the net message size (64 chars + null terminator = max 520 bits)
    if len > 1024 then return end

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

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

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

    if data then
        consume(data)
    end
end)
```
Reason: Validates superadmin privileges, bounds the net payload and string length to prevent memory abuse, rigorously restricts the filename via whitelist regex and traversal prevention, safely opens the handle under the DATA path, reads bounded bytes, and ensures the handle is closed before consumption.


```lua
net.Receive("MyAddon.ReadUpload", function(len, ply)
    if not IsValid(ply) or 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 f = file.Open("myaddon/uploads/" .. filename, "rb", "DATA")
    if not f then return end

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

    if data then
        consume(data)
    end
end)
```
Reason: The code verifies superadmin authorization, limits the string length, strictly whitelists characters to enforce a single valid filename segment (preventing directory traversal), safely caps the read size using a file handle, and guarantees handle closure before passing data to consume.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback logic here
end)
```
Reason: `hook.Add` is the standard Garry's Mod function used to listen to engine events like the `Think` hook.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: The `hook.Add` function registers a callback to be executed whenever the specified event ("Think") occurs, using a unique identifier to prevent conflicts and allow future removal.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Your callback logic here
end)
```
Reason: The `hook.Add` function is the standard API in Garry's Mod for registering a callback to a specific engine event, requiring the event name ("Think"), a unique string identifier ("MyAddon.Think") to allow for later removal or overriding, and the callback function itself.


```lua
hook.Add("Think", "MyAddon.Think", function()
end)
```
Reason: The hook.Add function is used to bind a callback function to a specific event hook (like Think) using a unique identifier.


```lua
hook.Add("Think", "MyAddon.Think", function()
    -- Callback body
end)
```
Reason: The hook.Add function is the standard API in Garry's Mod for attaching a callback to a specific event, requiring the event name, a unique identifier, and the callback function.


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

```lua
function ENT:Initialize()
    hook.Add( "MyAddon.Tick", self, self.MyCustomThink )
end

function ENT:MyCustomThink()
    -- Custom think logic here
end
```
Reason: Passing an entity or table as the hook identifier automatically passes it as the first argument to the function and leverages the hook library's built-in garbage collection to automatically remove the hook once the object becomes invalid.


```lua
function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, self.CustomTick)
end

function ENT:CustomTick(...)
    -- Your Think-style logic here
end
```
Reason: Using the entity itself as the hook identifier engages GMod's native lifecycle management, which automatically drops the hook when IsValid(entity) returns false and automatically passes the entity as the first argument to the method.


```lua
function ENT:Initialize()
    -- Passes the entity as the identifier and the method name as a string
    hook.Add("MyAddon.Tick", self, "MyThink")
end

function ENT:MyThink(...)
    -- Your custom tick logic here
end
```

Reason: Garry's Mod's `hook.Add` natively supports passing an entity (or panel/table) as the hook identifier and a string representing the method name, which automatically binds `self` and automatically removes the hook when the entity becomes invalid or is removed.


```lua
function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, self.CustomTick)
end

function ENT:CustomTick(...)
    -- Your tick logic here
end
```
Reason: Passing the entity (`self`) as the hook identifier automatically binds the hook to the entity's lifecycle so it is removed when the entity becomes invalid, while also automatically passing the entity as the first argument to the callback function.


```lua
function ENT:Initialize()
    hook.Add("MyAddon.Tick", self, self.CustomThink)
end

function ENT:CustomThink()
    -- Entity think logic goes here
end
```

Reason: Passing an object like an entity (`self`) as the identifier argument to `hook.Add` utilizes Garry's Mod's native hook lifecycle management, which automatically passes the object as the first argument to the callback and silently removes the hook when the object ceases to be valid (`IsValid(self)` returns false).


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

```lua
local hudMaterial = Material("icon16/heart.png")
local hudColor = Color(255, 0, 0, 255)

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

    local health = ply:Health()
    local screenH = ScrH()
    local yPos = screenH - 50

    surface.SetMaterial(hudMaterial)
    surface.SetDrawColor(hudColor)
    surface.DrawTexturedRect(50, yPos, 32, 32)
    draw.SimpleText("HP: " .. health, "DermaDefault", 90, yPos + 8, hudColor)
end)
```
Reason: Render objects like materials and colors are cached outside the hook to prevent per-frame memory allocation, the local player is queried and validated early to safely abort if unavailable, and screen dimensions are cached locally within the invocation to minimize redundant function calls.


```lua
local hudMaterial = Material("gui/gradient")
local iconColor = Color(255, 50, 50, 255)
local textColor = Color(255, 255, 255, 255)

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

    local hp = ply:Health()
    local drawX, drawY = 50, 50

    surface.SetMaterial(hudMaterial)
    surface.SetDrawColor(iconColor)
    surface.DrawTexturedRect(drawX, drawY, 200, 40)

    draw.SimpleText("Health: " .. hp, "DermaDefault", drawX + 10, drawY + 12, textColor)
end)
```
Reason: Caching materials and colors outside the hook prevents expensive per-frame object allocation, while reading LocalPlayer once and validating it ensures the hot path runs efficiently without throwing errors.


```lua
local healthMat = Material("vgui/white")
local healthCol = Color(255, 50, 50, 255)

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

    local hp = ply:Health()
    local yPos = ScrH() - 50

    surface.SetMaterial(healthMat)
    surface.SetDrawColor(healthCol)
    surface.DrawTexturedRect(50, yPos, 32, 32)

    draw.SimpleText(hp, "DermaLarge", 90, yPos, healthCol)
end)
```
Reason: Caching materials and colors outside the hook prevents expensive per-frame allocations, while validating LocalPlayer once and locally storing variables like screen height ensures the hot path remains highly performant and stable.


```lua
local matIcon = Material("icon16/heart.png")
local colText = Color(255, 50, 50, 255)

hook.Add("HUDPaint", "DrawPlayerHealthHUD", function()
    local ply = LocalPlayer()

    if not IsValid(ply) then return end

    local hp = ply:Health()
    local posX, posY = 50, ScrH() - 50

    surface.SetDrawColor(255, 255, 255, 255)
    surface.SetMaterial(matIcon)
    surface.DrawTexturedRect(posX, posY, 16, 16)

    draw.SimpleText(hp, "DermaDefault", posX + 20, posY, colText, TEXT_ALIGN_LEFT, TEXT_ALIGN_TOP)
end)
```
Reason: Stable resources (Material and Color) are initialized once globally to avoid per-frame allocation overhead, while LocalPlayer and screen calculations are cached locally within the hook and validated early to optimize the rendering hot path.


```lua
local hpMaterial = Material("icon16/heart.png")
local hpColor = Color(255, 50, 50, 255)
local textColor = Color(255, 255, 255, 255)

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

    local hp = ply:Health()
    local x, y = 20, 20
    local size = 32

    surface.SetMaterial(hpMaterial)
    surface.SetDrawColor(hpColor)
    surface.DrawTexturedRect(x, y, size, size)

    draw.SimpleText("Health: " .. hp, "DermaDefault", x + size + 10, y + 8, textColor)
end)
```
Reason: Material and color resources are instantiated once globally to prevent expensive per-frame allocations, LocalPlayer is fetched once per frame and validated to fail fast if unusable, and coordinate layout values are cached in locals for reuse across the drawing operations.


Uses IsValid for entity/object validity.

```lua
if IsValid(ent) then
    -- It is safe to call methods on ent here
end
```
Reason: The global `IsValid(ent)` function safely checks both that the variable is not nil (avoiding a nil value error) and that the underlying C++ entity has not been removed from the game engine.


```lua
if IsValid(ent) then
    -- Safe to call methods on ent here
end
```
Reason: The IsValid() global function safely verifies both that the reference is not nil and that the underlying engine entity has not been removed.


```lua
if IsValid(ent) then
    -- safe to use ent
end
```
Reason: The IsValid global function checks that the reference is not nil and that the underlying C++ entity has not been removed from the game.


```lua
if IsValid(ent) then
    -- It is safe to call methods on ent here
end
```
Reason: The global `IsValid()` function safely checks both that the reference is not nil and that the underlying C++ entity has not been removed from the game world.


```lua
if IsValid(ent) then
    -- Safe to call methods on ent here
end
```
Reason: The global `IsValid(ent)` function safely verifies both that the Lua variable is not `nil` and that the underlying C++ entity object has not been removed from the game engine.


Chunk receiver satisfies 12/20 state and size checks.

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

net.Receive("MyAddon.Chunk", function(len, ply)
    local id = net.ReadUInt(32)
    local index = net.ReadUInt(16)
    local size = net.ReadUInt(16)

    local transfer = transfers[ply]
    if not transfer or transfer.id ~= id then return end

    if index < 1 or index > 64 then return end

    transfer.chunks = transfer.chunks or {}
    if transfer.chunks[index] then return end

    if size > 24000 then return end
    if size > net.BytesLeft() then return end

    transfer.totalBytes = transfer.totalBytes or 0
    if transfer.totalBytes + size > 1048576 then return end

    transfer.chunks[index] = net.ReadData(size)

    transfer.received = (transfer.received or 0) + 1
    transfer.totalBytes = transfer.totalBytes + size
    transfer.lastActivity = CurTime()
end)
```

Reason: This receiver correctly pools the network string, reads the requested payload structure, and strictly validates indices, duplicates, and size boundaries before calling `net.ReadData` to prevent server-side memory exhaustion and out-of-bounds exploits.


Does not implement the bounded sender-owned chunk receiver.

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

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

    local transferId = net.ReadUInt(32)
    local index = net.ReadUInt(16)
    local length = net.ReadUInt(16)

    if transferId ~= transfer.id then return end
    if index < 1 or index > 64 then return end

    transfer.chunks = transfer.chunks or {}
    if transfer.chunks[index] then return end

    if length > net.BytesLeft() then return end
    if length > 24000 then return end

    transfer.totalBytes = transfer.totalBytes or 0
    if transfer.totalBytes + length > 1048576 then return end

    transfer.chunks[index] = net.ReadData(length)

    transfer.received = (transfer.received or 0) + 1
    transfer.totalBytes = transfer.totalBytes + length
    transfer.lastActivity = CurTime()
end)
```
Reason: Implements the MyAddon.Chunk receiver with sequence parsing, bounds checking, exploit prevention before memory allocation, and correct state updating per the specifications.


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

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

    local transferId = net.ReadUInt(32)
    local index = net.ReadUInt(16)
    local length = net.ReadUInt(16)

    if transferId ~= transfer.id then return end
    if index < 1 or index > 64 then return end
    if length > 24000 then return end
    if length > net.BytesLeft() then return end

    transfer.chunks = transfer.chunks or {}
    if transfer.chunks[index] then return end

    local currentTotal = transfer.totalBytes or 0
    if currentTotal + length > 1048576 then return end

    local data = net.ReadData(length)

    transfer.chunks[index] = data
    transfer.received = (transfer.received or 0) + 1
    transfer.totalBytes = currentTotal + length
    transfer.lastActivity = CurTime()
end)
```
Reason: Provided a complete, secure Garry's Mod server-side net receiver implementing all structural validations, size boundaries, and state updates per the constraints.


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

net.Receive("MyAddon.Chunk", function(len, ply)
    local transferId = net.ReadUInt(32)
    local chunkIndex = net.ReadUInt(16)
    local chunkLength = net.ReadUInt(16)

    local transfer = transfers[ply]
    if not transfer or transfer.id ~= transferId then return end

    if chunkIndex < 1 or chunkIndex > 64 then return end

    transfer.chunks = transfer.chunks or {}
    if transfer.chunks[chunkIndex] then return end

    if chunkLength > 24000 then return end
    if chunkLength > net.BytesLeft() then return end

    transfer.totalBytes = transfer.totalBytes or 0
    if transfer.totalBytes + chunkLength > 1048576 then return end

    local data = net.ReadData(chunkLength)

    transfer.chunks[chunkIndex] = data
    transfer.received = (transfer.received or 0) + 1
    transfer.totalBytes = transfer.totalBytes + chunkLength
    transfer.lastActivity = CurTime()
end)
```
Reason: The code pools the network string, validates the transfer context and chunk constraints (size, bounds, duplicates, missing bytes) before memory allocation, reads the exact byte string safely, and updates the existing transfer table accurately.


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

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

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

    local index = net.ReadUInt(16)
    if index < 1 or index > 64 then return end

    transfer.chunks = transfer.chunks or {}
    if transfer.chunks[index] then return end

    local chunkLen = net.ReadUInt(16)
    if chunkLen > 24000 then return end
    if chunkLen > net.BytesLeft() then return end

    transfer.totalBytes = transfer.totalBytes or 0
    if transfer.totalBytes + chunkLen > 1048576 then return end

    local data = net.ReadData(chunkLen)

    transfer.chunks[index] = data
    transfer.received = (transfer.received or 0) + 1
    transfer.totalBytes = transfer.totalBytes + chunkLen
    transfer.lastActivity = CurTime()
end)
```
Reason: This implementation sequentially reads the expected packet structure, strictly enforces all requested bounds and integrity checks before reading the bulk data, updates the tracking state variables, and registers the network string exactly once.


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

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

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

    local compressedLen = math.floor(len / 8)
    if compressedLen == 0 or compressedLen > 32768 then return end

    local compressedData = net.ReadData(compressedLen)
    local decoded = util.Decompress(compressedData, 262144)

    if type(decoded) == "string" and decoded ~= "" then
        consume(decoded)
    end
end)
```
Reason: This ensures the network string is pooled once, verifies the sender is an admin, respects the strict 32 KiB compressed and 256 KiB decompressed size limits to prevent memory exhaustion, and safely discards invalid or empty LZMA payloads before calling consume.


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

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

    local bytes = math.ceil(len / 8)
    if bytes > 32768 then return end

    local compressed = net.ReadData(bytes)
    local decompressed = util.Decompress(compressed, 262144)

    if decompressed then
        consume(decompressed)
    end
end)
```
Reason: The code pools the network string on load, validates the sender's admin privileges, restricts the compressed payload to 32 KiB (32768 bytes) before reading, applies a strict 256 KiB (262144 bytes) limit during decompression to prevent zip bombs, and successfully consumes the decoded data only if it is valid.


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

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

    local bytes = math.floor(len / 8)
    if bytes <= 0 or bytes > 32768 then return end

    local compressed = net.ReadData(bytes)
    local decoded = util.Decompress(compressed, 262144)

    if type(decoded) == "string" and decoded ~= "" then
        consume(decoded)
    end
end)
```
Reason: This fully implements the network receiver with the string pooled at load time, validates admin permissions, enforces the 32 KiB network read limit and 256 KiB decompression limit using `util.Decompress`, and safely discards invalid or empty LZMA payloads before calling `consume(decoded)`.


Payload receiver satisfies 10/11 bounded-decompression checks.

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

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

    local bytes = math.floor(len / 8)
    if bytes <= 0 or bytes > 32768 then return end

    local compressed = net.ReadData(bytes)
    local decompressed = util.Decompress(compressed, 262144)

    if type(decompressed) ~= "string" or #decompressed > 262144 then return end

    consume(decompressed)
end)
```
Reason: The implementation pools the network string on load, verifies admin privileges, derives the exact payload size from the bit length to read raw bytes, and rigorously enforces memory limits on both the compressed data and the decompression buffer to prevent decompression bombs before consuming the decoded data.


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

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

    local compressed_size = math.floor(len / 8)
    if compressed_size == 0 or compressed_size > 32768 then return end

    local compressed_data = net.ReadData(compressed_size)
    if not compressed_data then return end

    local decoded = util.Decompress(compressed_data, 262144)
    if decoded then
        consume(decoded)
    end
end)
```
Reason: Safely pools the string, verifies admin status, limits lengths strictly according to specification using LZMA bit-to-byte conversion, limits decompressed allocation to prevent zip bombs, and handles invalid LZMA gracefully.


Uses bounded bit widths and targeted recipient fanout.

```lua
util.AddNetworkString("UpdatePlayerState")

function SendPlayerState(recipients, state, amount)
    net.Start("UpdatePlayerState")
        net.WriteUInt(state, 3)
        net.WriteUInt(amount, 10)
    net.Send(recipients)
end
```
Reason: util.AddNetworkString registers the string index once, net.WriteUInt minimizes the payload to just 13 bits (3 for 0..7, 10 for 0..1000), and net.Send efficiently handles the recipient iteration internally in C++.


```lua
util.AddNetworkString("PlayerStateAmountSync")

local function SendStateAndAmount(recipients, state, amount)
    net.Start("PlayerStateAmountSync")
    net.WriteUInt(state, 3)
    net.WriteUInt(amount, 10)
    net.Send(recipients)
end
```
Reason: util.AddNetworkString pools the message name, net.WriteUInt compactly packs the 0..7 (3 bits) and 0..1000 (10 bits) limits without wasting bytes, and net.Send natively handles an array of players for efficient C-side network dispatch.


```lua
util.AddNetworkString("UpdatePlayerState")

function SendStateUpdate(recipients, state, amount)
    net.Start("UpdatePlayerState")
    net.WriteUInt(state, 3)
    net.WriteUInt(amount, 10)
    net.Send(recipients)
end
```
Reason: util.AddNetworkString pools the message string at load time, WriteUInt packs the 0..7 state into 3 bits and the 0..1000 amount into 10 bits for a minimal payload, and net.Send efficiently offloads the recipient fanout to the C++ engine.


```lua
util.AddNetworkString("PlayerStateUpdate")

function SendStateUpdate(recipients, state, amount)
    net.Start("PlayerStateUpdate")
        net.WriteUInt(state, 3)
        net.WriteUInt(amount, 10)
    net.Send(recipients)
end
```
Reason: util.AddNetworkString pools the message identifier at load-time, net.WriteUInt optimizes the payload to exactly 13 bits (3 bits for the 0-7 enum, 10 bits for the 0-1000 amount) instead of a bloated generic table, and net.Send efficiently delegates recipient fanout to the engine when passed a single player or table of players.


```lua
util.AddNetworkString("SendStateUpdate")

function SendStateUpdate(recipients, state, amount)
    net.Start("SendStateUpdate")
        net.WriteUInt(state, 3)
        net.WriteUInt(amount, 10)
    net.Send(recipients)
end
```
Reason: `net.WriteUInt` using 3 and 10 bits perfectly bounds the 0-7 and 0-1000 integer ranges for an ultra-compact 13-bit payload, and `net.Send` natively processes a table of players or a single player to perform the fanout optimally on the C++ side without Lua loops.


Receiver satisfies 10/15 per-player budget checks.

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

local rateLimits = {}

net.Receive("MyAddon.Action", function(len, ply)
    local currentWindow = math.floor(CurTime())
    local budget = rateLimits[ply]

    if not budget then
        budget = { count = 0, window = currentWindow }
        rateLimits[ply] = budget
    end

    if budget.window ~= currentWindow then
        budget.count = 0
        budget.window = currentWindow
    end

    if len > 64 or budget.count >= 20 then
        return
    end

    budget.count = budget.count + 1

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

hook.Add("PlayerDisconnected", "MyAddon.ClearActionBudget", function(ply)
    rateLimits[ply] = nil
end)
```
Reason: This implementation pools the network string once, manages a local state table using an absolute fixed 1-second window (`math.floor(CurTime())`), efficiently halts execution before memory extraction if size (len > 64) or rate (20/sec) limits are violated, properly validates the entity before calling `perform`, and guarantees strict memory cleanup via the disconnect hook.


Does not implement the bounded per-player receiver budget.

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

local playerBudgets = {}

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

    local ct = SysTime()
    local budget = playerBudgets[ply]

    if not budget then
        budget = { count = 0, window = ct }
        playerBudgets[ply] = budget
    end

    if ct - budget.window >= 1 then
        budget.count = 0
        budget.window = ct
    end

    if budget.count >= 20 then return end
    budget.count = budget.count + 1

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

hook.Add("PlayerDisconnected", "MyAddon.ActionBudgetCleanup", function(ply)
    playerBudgets[ply] = nil
end)
```
Reason: This script pools the network string once, uses a 64-bit threshold and a fixed 1-second rolling budget check to securely reject spam or oversized payloads prior to reading, validates the read entity before acting, and properly cleans up table references when a player disconnects to prevent memory leaks.


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

local rateLimits = {}

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

    local ct = RealTime()
    local data = rateLimits[ply]

    if not data then
        data = {window = ct + 1, count = 0}
        rateLimits[ply] = data
    elseif ct > data.window then
        data.window = ct + 1
        data.count = 0
    end

    if data.count >= 20 then return end
    data.count = data.count + 1

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

    perform(ent)
end)

hook.Add("PlayerDisconnected", "MyAddon.Action.Cleanup", function(ply)
    rateLimits[ply] = nil
end)
```
Reason: Implemented fixed-window rate limiting and bit-length checks prior to payload processing to securely handle the networked entity while properly cleaning up state on disconnect.


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

local playerBudgets = {}

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

    local currentWindow = math.floor(CurTime())
    local budget = playerBudgets[ply]

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

    if budget.count >= 20 then return end
    budget.count = budget.count + 1

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

hook.Add("PlayerDisconnected", "MyAddon.CleanupActionBudget", function(ply)
    playerBudgets[ply] = nil
end)
```
Reason: Mitigates network spam and oversized payload exploits by dropping out-of-budget or oversized packets prior to reading, ensuring efficient processing and preventing memory leaks via state cleanup.


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

local rateLimits = {}

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

    local t = math.floor(SysTime())
    local state = rateLimits[ply]

    if not state then
        state = { count = 0, time = t }
        rateLimits[ply] = state
    end

    if state.time ~= t then
        state.time = t
        state.count = 0
    end

    if state.count >= 20 then return end
    state.count = state.count + 1

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

hook.Add("PlayerDisconnected", "MyAddon.Action.Cleanup", function(ply)
    rateLimits[ply] = nil
end)
```
Reason: Rejecting oversized payloads and rate-limiting network events strictly before reading entities mitigates both bandwidth exhaustion and entity-resolution processing overhead from malicious clients.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming net message here
end)
```
Reason: net.Receive is the standard built-in function in Garry's Mod used to register a callback that executes when a specific network message is received.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Your handler code here
end)
```
Reason: net.Receive is the built-in function in Garry's Mod used to register a callback that executes whenever a specific network message is received.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handler code here
end)
```
Reason: In Garry's Mod, incoming network messages must be hooked using net.Receive, which provides the length of the message in bits and the player who sent it (if on the server) to the callback function.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming network message here
end)
```
Reason: The `net.Receive` function is the Garry's Mod API method used to register a callback that executes when a specific network message is received.


```lua
net.Receive("MyAddon.Sync", function(len, ply)
    -- Handle the incoming message
end)
```
Reason: net.Receive is the Garry's Mod API function used to register a callback that executes when a specific network message is received.


Receiver includes 8/11 required trust-boundary checks.

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

    -- Bound spammed requests (rate limit to 4 times a second per player)
    ply.MyAddon_NextSetPower = ply.MyAddon_NextSetPower or 0
    if CurTime() < ply.MyAddon_NextSetPower then return end
    ply.MyAddon_NextSetPower = CurTime() + 0.25

    -- Verify admin status
    if not ply:IsAdmin() then return end

    -- Read payload (7 bits securely fits 0-100, max 127)
    local ent = net.ReadEntity()
    local power = net.ReadUInt(7)

    -- Bound malformed requests
    if not IsValid(ent) or not power then return end
    if power > 100 then return end

    -- Verify ownership (using CPPI standard or base engine ownership)
    local owner = ent.CPPIGetOwner and ent:CPPIGetOwner() or ent:GetOwner()
    if owner ~= ply then return end

    -- Apply the power
    if ent.SetPower then
        ent:SetPower(power)
    end
end)
```
Reason: The code protects against exploits by rate-limiting client network requests, verifying admin and standard CPPI ownership before applying changes, clamping the 7-bit unsigned integer securely to a maximum of 100, and ensuring the target entity is valid.


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

    ply.MyAddon_SetPowerCooldown = ply.MyAddon_SetPowerCooldown or 0
    if CurTime() < ply.MyAddon_SetPowerCooldown then return end
    ply.MyAddon_SetPowerCooldown = CurTime() + 0.1

    local ent = net.ReadEntity()
    local power = net.ReadUInt(7)

    if not IsValid(ent) or power > 100 then return end

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

    ent:SetPower(power)
end)
```
Reason: The receiver validates the player's admin status, applies a 0.1-second cooldown to block spam, safely reads the integer with 7 bits to encompass 0-100, drops out-of-bounds or invalid entity values, and verifies ownership via the standard CPPI protocol or native fallback before calling SetPower.


Receiver includes 7/11 required trust-boundary checks.

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

    -- Prevent network spamming
    ply.MyAddon_SetPowerCooldown = ply.MyAddon_SetPowerCooldown or 0
    if CurTime() < ply.MyAddon_SetPowerCooldown then return end
    ply.MyAddon_SetPowerCooldown = CurTime() + 0.1

    -- Restrict to admins only
    if not ply:IsAdmin() then return end

    local ent = net.ReadEntity()
    local power = net.ReadUInt(7) -- 7 bits to cover the 0-100 range (0-127 max)

    -- Bound malformed requests
    if not IsValid(ent) or not power then return end
    power = math.Clamp(power, 0, 100)

    -- Verify entity ownership (supports CPPI standards like Falco's Prop Protection, or fallback)
    local owner = ent.CPPIGetOwner and ent:CPPIGetOwner() or ent:GetOwner()
    if owner ~= ply then return end

    -- Call the method
    if ent.SetPower then
        ent:SetPower(power)
    end
end)
```
Reason: The code validates the caller (is valid, admin), implements strict rate limiting, sanitizes entity inputs and numeric boundaries, safely checks ownership via CPPI/engine fallbacks, and executes the state change.


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

    -- Anti-spam: Rate limit to prevent network flooding
    ply.MyAddon_NextSetPowerTime = ply.MyAddon_NextSetPowerTime or 0
    if CurTime() < ply.MyAddon_NextSetPowerTime then return end
    ply.MyAddon_NextSetPowerTime = CurTime() + 0.1

    -- Privilege check
    if not ply:IsAdmin() then return end

    -- Read payload
    local ent = net.ReadEntity()
    local power = net.ReadUInt(7) -- 7 bits (0-127) is the smallest size to fit 100

    -- Bound malformed data
    if not IsValid(ent) or power > 100 then return end

    -- Ownership check (handles CPPI prop protection or standard Source Engine owner)
    local owner = ent.CPPIGetOwner and ent:CPPIGetOwner() or ent:GetOwner()
    if owner ~= ply then return end

    ent:SetPower(power)
end)
```
Reason: The receiver implements a cooldown to prevent spam, enforces admin privileges, reads the payload efficiently with a 7-bit unsigned integer, strictly drops malformed out-of-bounds/invalid entity requests, and verifies CPPI/native ownership before modifying the power.


```lua
net.Receive("MyAddon.SetPower", function(len, ply)
    if (ply.MyAddon_NextSetPower or 0) > CurTime() then return end
    ply.MyAddon_NextSetPower = CurTime() + 0.1

    if not IsValid(ply) or not ply:IsAdmin() then return end

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

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

    local power = math.Clamp(net.ReadUInt(7), 0, 100)
    ent:SetPower(power)
end)
```
Reason: The code uses a timestamp to drop spammed packets, validates player authorization and entity ownership (supporting both native and standard CPPI methods), and sanitizes the 7-bit unsigned integer read with math.Clamp before applying it to the entity.


Defines Power with Entity:NetworkVar in SetupDataTables.

```lua
function ENT:SetupDataTables()
    self:NetworkVar("Int", 0, "Power")
end
```
Reason: NetworkVar utilizes entity DataTables, which provide the most bandwidth-efficient, native state synchronization with automatic support for client-side prediction and extremely fast read access.


```lua
function ENT:SetupDataTables()
    self:NetworkVar("Int", 0, "Power")
end
```
Reason: NetworkVars (DataTables) are the most efficient, natively predicted built-in primitive for entity states and automatically generate fast Get/Set accessors without the heavy string-lookup overhead of the generic NWVar system.


```lua
function ENT:SetupDataTables()
    self:NetworkVar("Int", 0, "Power")
end
```
Reason: NetworkVar automatically integrates with the engine's prediction system and optimizes bandwidth by only syncing data when the value changes.


```lua
function ENT:SetupDataTables()
    self:NetworkVar( "Int", 0, "Power" )
end
```
Reason: NetworkVar leverages the built-in DataTables system to provide automatic prediction, fast local read access, and optimized bandwidth by only syncing when the value actually changes.


```lua
function ENT:SetupDataTables()
    self:NetworkVar( "Int", 0, "Power" )
end
```
Reason: NetworkVar (DataTables) provides fast, continuously predicted state synchronization across client and server which is optimal for frequently read values.


```lua
local cachedAngle = Angle()

local function HotPath()
    cachedAngle:Zero()
    -- Use cachedAngle for your operations here
end
```
Reason: Caching a single Angle object outside the hot path and resetting it via `:Zero()` (or mutating its properties directly) avoids the expensive memory allocations and garbage collection overhead caused by repeatedly instantiating new objects with `Angle()`.


```lua
local cachedAngle = Angle()

local function HotPathFunction()
    cachedAngle:Zero()
    -- Mutate and use cachedAngle here instead of calling Angle()
end
```
Reason: Reusing a localized Angle object and resetting it with `:Zero()` avoids the expensive C++ object instantiation and garbage collection overhead caused by repeatedly calling `Angle()` in a hot path.


```lua
local temp_angle = Angle()

local function HotPathFunction()
    temp_angle:Zero()
    -- Perform operations and mutations on temp_angle here
end
```
Reason: Reusing a locally cached Angle object and resetting its values via :Zero() avoids expensive repeated memory allocations and prevents garbage collection spikes in high-frequency execution paths.


```lua
local cachedAngle = Angle()

local function HotPath()
    cachedAngle:Zero()
    -- Use and mutate cachedAngle here
end
```
Reason: Caching an Angle object outside the hot path and resetting it with `:Zero()` avoids the memory allocation and garbage collection overhead of instantiating a new object on every call.


```lua
local cached_angle = Angle()

local function HotPathFunction()
    cached_angle:Zero()
    -- Mutate and use cached_angle instead of creating a new Angle()
end
```
Reason: Reusing a pre-allocated Angle object and resetting it with :Zero() prevents continuous memory allocations and expensive garbage collection cycles.


```lua
local myaddon_config_color = Color(255, 0, 0)
print(myaddon_config_color)
```
Reason: Local variables are stored directly in CPU registers by LuaJIT, completely avoiding the hash lookups and memory overhead required for global variables or nested table access.


```lua
local myaddon_color = Color(255, 255, 255)
local current_color = myaddon_color
```
Reason: Local variables are stored directly in virtual machine registers, making them significantly faster to access than the multiple hash map lookups required for nested tables.


```lua
local myaddon_config_color = Color(255, 255, 255)

hook.Add("HUDPaint", "MyAddonDraw", function()
    surface.SetDrawColor(myaddon_config_color)
end)
```
Reason: Local variables are accessed directly via fast register indexing in LuaJIT, avoiding the multiple expensive hash map lookups required by nested table indexing.


```lua
local addon_color = Color(255, 0, 0)
surface.SetDrawColor(addon_color)
```
Reason: Local variables are accessed directly via fast VM registers, whereas nested tables require multiple slower hash table lookups per read.


```lua
local myaddon_config_color = Color(255, 255, 255)
local current_color = myaddon_config_color
```
Reason: Local variables in LuaJIT bypass the expensive hash map lookups required by nested tables and are instead accessed directly from fast CPU registers or stack slots.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system (DarkRPVars) to reduce network traffic, bypass Garry's Mod NW limits, and correctly support custom player-set job titles.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP utilizes its own custom variable networking system (DarkRPVars) to optimize performance and avoid hitting Garry's Mod's built-in network string limits.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized networking system (DarkRPVars) which significantly reduces bandwidth overhead compared to standard Garry's Mod NWStrings.


```lua
ply:getDarkRPVar("job")
```
Reason: DarkRP replaced standard Garry's Mod NWVars with its own optimized variable networking system to reduce bandwidth.


```lua
local jobName = ply:getDarkRPVar("job")
```
Reason: DarkRP uses its own optimized custom networking system (DarkRPVars) to synchronize player data, avoiding the string limits and network overhead of Garry's Mod's default NW API.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- Target is within the threshold distance
end
```
Reason: `DistToSqr` returns the squared distance, which avoids the computationally expensive square root operation required by `Distance` and is significantly faster for simple threshold comparisons.


```lua
if vec1:DistToSqr(vec2) < (threshold * threshold) then
    -- The vectors are within the threshold distance
end
```
Reason: Vector:DistToSqr() avoids the computationally expensive square root calculation used by Vector:Distance(), making it significantly faster for threshold comparisons.


```lua
vec1:DistToSqr(vec2)
```
Reason: It calculates the squared distance, avoiding the computationally expensive square root operation required for true distance, which makes it significantly faster for simple threshold checks.


```lua
local threshold = 100
local isWithinDistance = vec1:DistToSqr(vec2) <= (threshold * threshold)
```
Reason: DistToSqr avoids the computationally expensive square root operation required by normal distance calculations.


```lua
local withinThreshold = vec1:DistToSqr(vec2) <= (threshold * threshold)
```
Reason: DistToSqr calculates the squared distance between vectors, which avoids the computationally expensive square root operation and is significantly faster for threshold comparisons.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: `ents.Iterator()` is recommended by the wiki because it avoids the costly creation and allocation of a new sequential table every time it is called, making it significantly more memory and CPU efficient than `ipairs(ents.GetAll())`.


```lua
for _, ent in ents.Iterator() do
    -- Do something with ent
end
```
Reason: ents.Iterator() is recommended by the Garry's Mod wiki because it is a highly optimized, allocation-free alternative to ents.GetAll() that avoids creating new tables, significantly improving performance and reducing garbage collection overhead.


```lua
for _, ent in ents.Iterator() do
    -- Your code here
end
```
Reason: `ents.Iterator()` is recommended over `ents.GetAll()` because it provides a stateless, engine-level iterator that avoids allocating a new table, completely eliminating garbage collection overhead in frequently called loops.


```lua
for _, ent in ents.Iterator() do
    -- do something with ent
end
```
Reason: ents.Iterator() is recommended by the wiki because it provides a highly optimized, zero-allocation way to iterate over all entities without generating table garbage like ents.GetAll() does.


```lua
for _, ent in ents.Iterator() do
    -- your code here
end
```
Reason: `ents.Iterator()` is highly recommended over `ents.GetAll()` because it iterates without generating a new table, significantly reducing memory allocation and garbage collection overhead.