Lua errors
Fix "attempt to index a nil value" in Lua
This error means the value before a dot or bracket is nil. Find the first lookup that returns nil, then trace where that value should have been set.
Inspect the failing expression
For player.stats.coins, inspect player first, then player.stats. One of those values is nil. Check them immediately before the failing line and use the stack trace to find the caller.
print("player", player)
print("stats", player and player.stats)
local coins = player.stats.coins
If player exists but stats prints nil, fix the code that creates or loads stats. Adding or {} at the failing line may stop the error while quietly giving you the wrong result.
Do not guess from the final field name. In player.stats.coins, the error can mean either player or player.stats is nil. The exact line and the values immediately before it tell you which lookup failed.
Common causes
- A table was never initialized.
- A lookup key is misspelled or absent.
requirereturned a different module shape than the caller expects.- An object is used before an asynchronous setup step finishes.
- A game or host API is unavailable in the current runtime.
Fix the missing value
Initialize required state before reading it. If a value is genuinely optional, check it and handle the missing case explicitly. A missing player record and a player with zero coins are different states; do not turn both into zero just to suppress the error.
local function readCoins(player)
if not player then
return nil, "player is not ready"
end
if not player.stats then
return nil, "stats have not loaded"
end
return player.stats.coins
end
Here the caller can decide whether to retry, show an error or use a documented default. If state comes from an event or asynchronous load, wait for that operation rather than assuming it has finished. In a game, also confirm that the code runs on the side where that object is available.
Trace an intermittent failure
If the error happens only sometimes, record the input or event that triggered it, the object identity, and whether initialization completed first. Add temporary logging at the writer and reader of the missing field. When the order is clear, remove the logging and fix the initialization or event sequence. A blanket pcall around the failing read can hide the bug without fixing the state.
If the error appears only after obfuscation
Run the original and protected script with the same inputs and in the same runtime. Note which lookup first becomes nil, the build identifier, and the exact error text. A missing Roblox or MoonLoader API is different from a value lost by a transformation. Reduce the case to the smallest script that still differs, then send a support ticket without private keys or credentials.
Lua Script Doctor can flag syntax and runtime-target mismatches. For a protection workflow, see how to build and test a Lua script.
Reviewed on . Browse all Lua guides.