Skip to content
Tutorials Center
My learning

Topics

Lesson 24 of 32 ยท Standard Library and Tools

Debugging, Performance and Common Mistakes

Find bugs faster in Lua: print debugging, debug.traceback, accidental globals, 1-based off-by-one errors, the # operator and holes, table.concat and local caching.

Everyone writes bugs, and Lua's flexibility gives you a particular set of them: a misspelled variable silently becomes nil, a loop that starts at 0 skips or misses an element, a length that is "wrong" because of a hole in a table. The good news is that the language is small, so the same handful of mistakes explains most problems you will see.

In this lesson you will learn how to debug with print and debug.traceback, how to spot accidental globals and off-by-one errors, why # and holes do not mix, and two simple performance habits that matter: building strings with table.concat and caching globals in locals. Remember that you should measure before you optimize.

Lua is not installed on this site, so the Lua listings are read-only and show real output. The runnable examples are JavaScript stand-ins that model the behavior being explained.

A debugging routine

Read the message File, line and the variable name.
Print values Check what you assumed.
Trace the stack See how you got there.
Shrink it Cut until the bug is small.
1 / 2

Read the error message first

Most Lua errors tell you exactly where to look. A message has the shape file:line: description, and when Lua knows the variable it names it:

TEXT
main.lua:12: attempt to index a nil value (field 'user')
main.lua:20: attempt to perform arithmetic on a nil value (global 'totl')
main.lua:7: attempt to call a nil value (method 'push')

The first means user was nil when the code tried to read a field from it, so ask where user should have been set. The second names a global called totl, which is very likely a typo of total. The third calls a method that does not exist. Read the line number, look at the variable name, and form a guess before you change anything. For more on catching errors on purpose see Error Handling.

The fastest debugger is print. Show the values you believe in, and label them, because an empty string and nil both look like nothing:

LUA
local function area(w, h)
  print("area called with", w, h, type(w))
  return w * h
end
print(area("3", 4))
TEXT
area called with	3	4	string
12

This also reminds you that Lua converts a numeric string to a number in arithmetic. Two more helpers are worth knowing. string.format("%s", value) converts any value, including nil and tables, to text; and debug.getinfo(1, "l").currentline gives the current line number.

To see how the program reached a point, call debug.traceback:

LUA
local function inner()
  print(debug.traceback("here"))
end
local function outer()
  inner()
end
outer()

The output starts with here, then a line stack traceback:, then one line per active function, newest first, each with a file name and line number. The exact lines depend on how you run the script. Use xpcall(f, debug.traceback) to get such a report when an error happens, as shown in Error Handling.

When a bug refuses to show itself, shrink the program. Delete code and inputs until the smallest piece that still misbehaves remains; the cause is usually obvious by then. Full debuggers exist, for example in ZeroBrane Studio and as editor extensions, but print statements and tracebacks will take you a long way.

JS A hand-made traceback

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Accidental globals

In Lua, assigning to a name that has no local declaration creates a global. This makes typos dangerous:

LUA
local function sum(list)
  local total = 0
  for _, n in ipairs(list) do
    totl = total + n     -- typo: creates a global named totl
  end
  return total
end
print(sum({1, 2, 3}))
TEXT
0

There is no error. The loop wrote to totl, and total stayed 0. The cure is a strict mode that raises an error for undeclared globals, as shown in Modules and require, and the habit of writing local for every variable. A static checker such as luacheck also reports these mistakes automatically. You can even inspect compiled code with luac -l, where global accesses show up as GETTABUP and SETTABUP instructions on _ENV.

1-based indexing and off-by-one errors

Lua arrays start at 1, and #t is the index of the last element. These loops are correct:

LUA
local t = {"a", "b", "c"}
for i = 1, #t do print(i, t[i]) end
for i = #t, 1, -1 do print(i, t[i]) end

Starting at 0 does not raise an error, which is why this bug is hard to see:

LUA
for i = 0, #t do print(i, t[i]) end   -- first line prints: 0   nil
for i = 1, #t + 1 do ... end          -- runs one step too far

Other places to watch: string.sub(s, 1, 1) is the first character, s:sub(-1) is the last, indices in string.find start at 1, and table.insert(t, pos, value) expects pos between 1 and #t + 1. If you often use t[0], you are fighting the language: shift the indices instead.

The length operator and holes

#t is only reliable for sequences: tables whose positive integer keys are exactly 1..n with no nil in the middle. If an array has a hole, any index n where t[n] is not nil and t[n + 1] is nil is a valid answer, and Lua may return any of them.

LUA
local t = {1, 2, nil, 4}
print(#t)      -- could be 4 or 2; both are valid borders
t[#t + 1] = 5  -- appends after whichever border Lua picked

Do not depend on either answer. Prefer one of these approaches:

  • Keep arrays free of nil. Remove items with table.remove, not by assigning nil.
  • Store a separate count, such as list.n, when nil values are legitimate. table.pack(...) does exactly that and returns a table with an n field.
  • Use a sentinel value such as false or a special table for "empty".
JS Why # is ambiguous with holes

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Dot versus colon

Methods defined with a colon receive self as a hidden first parameter. Calling them with a dot skips that argument:

LUA
local Counter = {}
Counter.__index = Counter
function Counter.new() return setmetatable({n = 0}, Counter) end
function Counter:inc() self.n = self.n + 1 end

local c = Counter.new()
c.inc()      -- error: attempt to index a nil value (local 'self')
c:inc()      -- correct

If you see an error about self, check for a dot where a colon belongs. The reverse mistake also exists: Counter:new() passes the class as an unwanted first argument. See Objects and Classes for the full picture.

Performance: measure first

Fast Lua code is usually simple Lua code. Before changing anything, measure with os.clock():

LUA
local start = os.clock()
-- run the code you suspect
print(("%.3f seconds"):format(os.clock() - start))

Run the test several times, with realistic data sizes, because a single run is noisy. Then apply the habits below to the code that actually matters.

Build strings with table.concat

Strings are immutable, so s = s .. piece creates a new string and copies everything built so far. Doing this in a loop copies more and more text, and the cost grows with the square of the number of pieces. Collect the pieces in a table and join them once:

LUA
-- slow for large n
local s = ""
for i = 1, n do s = s .. i .. "," end

-- fast
local parts = {}
for i = 1, n do parts[#parts + 1] = i end
local s = table.concat(parts, ",")

For a handful of pieces, .. is perfectly fine; the table approach matters in loops with thousands of steps.

JS Counting the copies behind s = s .. x

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Cache globals and fields in locals

A global such as math.sin costs two table lookups every time you use it (_ENV.math, then .sin), while a local variable is a fast register access. In a hot loop, copy the function to a local first:

LUA
local sin = math.sin
local sum = 0
for i = 1, 1000000 do
  sum = sum + sin(i)
end

The same idea applies to fields you read repeatedly, such as local items = self.items. Locals also protect you from code that later reassigns a global. Do not overdo it: caching outside hot loops makes code harder to read for no measurable gain.

A few more habits

  • Avoid creating closures or tables inside the innermost loop when you can create them once outside.
  • Use t[#t + 1] = value or table.insert(t, value) to append; both are fine, so choose the one that is clearer.
  • Reuse tables where practical, because creating garbage costs time in the garbage collector.
  • Pick the right data structure: a set (seen[key] = true) beats searching a list on every step.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Your loop assigns totl = total + n by mistake. What happens in standard Lua?

    Assigning to an undeclared name creates a global. Strict-mode code, luacheck or the habit of using local catches this.
  2. 2. What is #t for t = {1, 2, nil, 4}?

    With holes, any border is a valid length, so the result is not something to rely on. Keep arrays free of nil or store the count yourself.
  3. 3. Why is s = s .. piece in a long loop slow?

    Every concatenation creates a new string. Collect pieces in a table and call table.concat once.
  4. 4. You see attempt to index a nil value (local 'self'). What is the likely cause?

    obj.method() does not pass the object, so self is nil inside the method. Use obj:method().
  5. 5. What should you do before optimizing a slow program?

    Measure first so you spend effort where it matters, then apply simple habits such as table.concat and local caching.

Summary

  • Read error messages first: file, line and variable name usually point at the bug.
  • Debug with labelled print calls, debug.traceback and xpcall(f, debug.traceback), and shrink the failing program.
  • Always declare variables local; a typo otherwise becomes a silent global.
  • Arrays start at 1 and #t is only reliable for sequences without holes.
  • Use obj:method() for colon-defined methods.
  • Build long strings with table.concat, cache hot globals in locals, and measure with os.clock before optimizing.

Next, see how Lua is embedded in larger programs in Lua in Games and Embedded Hosts.