> ## Documentation Index
> Fetch the complete documentation index at: https://starcryptdocs.starsolenterprise.com/lua-docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Junk Code and Dead Code Insertion in Lua/Luau

> Pad Lua and Luau scripts with unreachable dead code, meaningless computations, decoy functions, and redundant assignments to raise reverse-engineering costs.

Junk code increases apparent complexity and script size, forcing an analyst to distinguish real logic from noise. When scattered strategically, junk code makes every line suspect: a function call might be critical, or it might do absolutely nothing. This page covers every major junk insertion technique for Lua and Luau, with code you can copy and adapt.

## Dead Code Blocks

The simplest junk insertion is wrapping code in conditions that are always false.

### Basic `if false` Blocks

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local function processOrder(order)
    if false then
        -- dead code that looks real
        validateInventory(order.items)
        checkShippingRestrictions(order.address)
        applyCouponCode(order, "SAVE20")
    end

    -- real logic
    return calculateTotal(order)
end
```

### Opaque-False Predicates

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local function processOrder(order)
    if (1 == 2) then
        -- dead code with decoy API calls
        local tracking = createTrackingNumber(order.id)
        notifyWarehouse(order, tracking)
        updateOrderStatus(order, "shipped")
    end

    return calculateTotal(order)
end
```

### Realistic-Looking Dead Code

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local function authenticateUser(credentials)
    if (math.huge < 0) then
        -- decoy: looks like OAuth flow
        local token = requestAccessToken(credentials.clientId)
        local refresh = generateRefreshToken(token)
        storeToken(credentials.userId, token, refresh)
        scheduleTokenRefresh(refresh, 3600)
        return token
    end

    -- real logic
    return validatePassword(credentials.username, credentials.password)
end
```

## Bogus Computations

Insert arithmetic and string operations whose results are discarded.

### Discarded Arithmetic

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local _ = math.sin(os.clock()) * 0 + 1
local _ = math.sqrt(123456789) % 1
local _ = (42 ^ 0) * (1 / 1) - 0
```

### Discarded String Operations

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local _ = string.rep("x", 100):sub(1, 1)
local _ = ("abc" .. "def"):gsub("[aeiou]", "")
local _ = string.format("%08x", 0):rep(5)
```

### Discarded Table Operations

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local _t = {}
for i = 1, 10 do
    _t[i] = i
end
local _ = table.concat(_t, ",")
local _ = table.remove(_t, 1)
```

### Scattering Bogus Computations

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local function computeScore(player)
    local _ = math.sin(os.clock()) * 0 + 1
    local base = player.level * 100
    local _ = string.rep("x", 50):sub(1, 1)
    local bonus = player.achievements * 10
    local _t = {}; for i = 1, 5 do _t[i] = i end
    return base + bonus
end
```

## Decoy Functions

Define functions with important-sounding names that are never called.

### Full Decoy Function Example

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local function validateLicense(licenseKey)
    local checksum = 0
    for i = 1, #licenseKey do
        checksum = checksum + string.byte(licenseKey, i)
    end
    local expected = checksum % 256
    local serverHash = requestHashFromServer(licenseKey)
    if serverHash and serverHash == expected then
        return true
    end
    logInvalidLicense(licenseKey, os.time())
    return false
end

local function checkExpiry(timestamp)
    local now = os.time()
    local diff = now - timestamp
    local days = math.floor(diff / 86400)
    if days > 30 then
        return false
    end
    return true
end

local function initSecureChannel(endpoint)
    local nonce = generateNonce(16)
    local handshake = encryptHandshake(nonce, endpoint)
    local response = sendSecure(handshake)
    return verifyResponse(response)
end

-- None of these functions are ever called
-- They exist only to waste analyst time

local function realInit()
    -- actual initialization
end
```

## Redundant Assignments

Assign a variable multiple times before its first real use.

### Multiple Reassignments

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local x = 0
x = x + 1
x = x * 2
x = x - 1
x = realValue  -- the actual assignment
```

### Assignment Through Intermediate Variables

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local tmp1 = val
local tmp2 = tmp1
local tmp3 = tmp2
local x = tmp3
```

### Combined with Junk Operations

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local x = 0
x = x + math.random(1, 10)
x = x * 2
x = x - (x % 2)
x = x / 2
x = realValue
```

## Inline Constant Expansion

Replace simple literals with equivalent expressions.

### Numeric Literal Expansion

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
-- Before
local maxHealth = 100
local damage = 42
local cooldown = 0

-- After
local maxHealth = (10 ^ 2)
local damage = (6 * 7)
local cooldown = (math.floor(0.9))
```

### Boolean Literal Expansion

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
-- Before
local enabled = true
local visible = false

-- After
local enabled = (1 == 1)
local visible = (1 ~= 1)
```

### String Concatenation

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
-- Before
local greeting = "hello"

-- After
local greeting = ("hel" .. "lo")
```

### Before/After Function Example

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
-- Before
local function setupPlayer(level)
    local health = 100 + level * 10
    local mana = 50 + level * 5
    local speed = 10
    return health, mana, speed
end

-- After
local function setupPlayer(level)
    local health = ((10 ^ 2) + level * ((5 * 2)))
    local mana = ((5 * (5 + 5)) + level * ((2 + 3)))
    local speed = ((math.floor(9.9)))
    return health, mana, speed
end
```

## Fake Error Handlers

Wrap code in `pcall` or `xpcall` with junk error handlers.

### Basic Fake Error Handler

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local ok, result = pcall(function()
    -- real logic
    return computeValue(data)
end)

if not ok then
    -- fake error handling
    logCriticalError(result)
    notifyAdmin(result)
    restartService()
end

-- actually just return the result
return result
```

### Error Handler with Decoy Logic

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local ok, result = pcall(function()
    return processPayment(order)
end)

if not ok then
    -- decoy: looks like rollback logic
    local rollbackId = generateRollbackId()
    revertTransaction(rollbackId)
    notifyAccounting(rollbackId, result)
    updateAuditLog("rollback", rollbackId)
    return nil
end

return result
```

## Automating Junk Insertion

You can automate junk insertion with a simple Lua script that reads source code and randomly inserts junk statements.

```lua theme={"theme":{"light":"ayu-dark","dark":"night-owl"}}
local junkStatements = {
    'local _ = math.sin(os.clock()) * 0 + 1',
    'local _ = string.rep("x", 100):sub(1, 1)',
    'local _t = {}; for i = 1, 10 do _t[i] = i end',
    'local _ = (1 == 1) and true or false',
    'local _ = math.sqrt(123456789) % 1',
}

local function insertJunk(source, probability)
    math.randomseed(os.time())
    local lines = {}
    for line in source:gmatch("[^\r\n]+") do
        table.insert(lines, line)
        if math.random() < probability then
            local junk = junkStatements[math.random(#junkStatements)]
            table.insert(lines, "    " .. junk)
        end
    end
    return table.concat(lines, "\n")
end

-- Usage
local source = io.open("input.lua", "r"):read("*a")
local obfuscated = insertJunk(source, 0.3)  -- 30% chance per line
io.open("output.lua", "w"):write(obfuscated)
```

> [!TIP]
>
> Randomize junk placement and content using `os.time()` as a seed so each obfuscation run produces different junk. This prevents analysts from diffing two versions to isolate real changes.

> [!NOTE]
>
> Excessive junk inflates file size and load time. Keep junk below 30% of total line count for scripts that are downloaded at runtime. For server-side or embedded scripts where size is not a concern, you can be more aggressive.

> **Will junk code fool deobfuscators?**
>
> Basic deobfuscators prune obvious dead code: `if false then` blocks are trivial to eliminate. Junk works best when combined with opaque predicates so the dead code path is not obviously dead. A static analyzer that cannot prove `(math.huge < 0)` is always false must conservatively keep the branch. Layer junk with control flow obfuscation for maximum resilience.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.