Lua Academy · Lesson

Managing State and Error Handling

Use lua_pcall for protected calls and handle errors in the C layer.

Lesson 4 of 413 steps

Managing State and Error Handling is a free Lua Academy lesson on CoddyKit. This is lesson 4 of 4. Any 3 lessons of this learning path are free to read in full — after that, CoddyKit PRO unlocks every lesson, plus hands-on practice with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, and your progress syncs across the web and the CoddyKit app. The Lua Academy course includes 4 lessons in total.

Multiple Lua States

You can run multiple lua_State instances in the same process. Each is fully independent: separate globals, separate stacks, no shared memory by default.

Thread States

lua_newthread(L) creates a child thread (coroutine) sharing the same global environment but with its own stack. This is how Lua coroutines are implemented in C.

Sharing Data Between States

Data cannot be passed between independent Lua states directly. Serialize to strings or use C-side shared memory structures accessible via userdata.

Protected Calls vs Raw Calls

lua_pcall catches errors (uses setjmp/longjmp under the hood). lua_call propagates errors and aborts the program. Always use lua_pcall in production.

// Safe:
if (lua_pcall(L, nargs, nresults, 0) != LUA_OK) {
  const char *err = lua_tostring(L, -1);
  lua_pop(L, 1);
  // handle error
}

Error Objects

Errors in Lua can be any value — not just strings. error({code=404, msg="not found"}) pushes a table as the error. C code reads it from the stack on pcall failure.

Panic Handler

If an error escapes a pcall (e.g., from a C function called without protection), Lua calls the panic handler set via lua_atpanic(L, fn) before aborting.

// C code
lua_atpanic(L, function(lua_State *L) {
  fprintf(stderr, "PANIC: %s\n", lua_tostring(L, -1));
  exit(1);
  return 0;
});

Stack Restoration on Error

After a lua_pcall error, the stack is restored to the state before the call (minus the function and args, plus the error object on top).

State Cleanup

Always close the state with lua_close(L) when done. This triggers all __gc finalizers and frees all allocated memory.

Thread Safety

A Lua state is not thread-safe. Never call two C API functions on the same state concurrently. Use one state per OS thread, or use a mutex to serialize access.

Memory Allocator

By default Lua uses realloc. Provide a custom allocator with lua_newstate(allocFn, ud) for memory tracking, limits, or custom pools.

Sandboxing with Multiple States

Run untrusted code in a fresh, isolated Lua state with no standard libraries opened. Any crash or resource exhaustion is contained to that state.

Error Handling Question

What is the difference between lua_call and lua_pcall?

Recap: Managing State and Errors

Use lua_pcall (never lua_call) in production. Set a panic handler for last-resort recovery. Keep one state per thread. Use multiple isolated states for sandboxing. Always call lua_close to clean up.

Free to start

Learn Lua with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
40
Lessons
159

Frequently Asked Questions

Is the “Managing State and Error Handling” lesson free?

Yes — any 3 lessons of the Lua Academy learning path, including “Managing State and Error Handling”, are free to read in full here on the web. After that, CoddyKit PRO unlocks every lesson, plus interactive practice with a built-in code editor and a 24/7 AI tutor. The Lua Academy course includes 4 lessons in total.

What will I learn in “Managing State and Error Handling”?

Use lua_pcall for protected calls and handle errors in the C layer. You practise Lua Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Lua Academy?

No prior experience is required. Lua Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “Managing State and Error Handling” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Lua Academy lesson?

Yes. Every Lua Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. The Lua C API Stack Model
  2. Calling Lua Functions from C
  3. Registering C Functions in Lua
  4. Managing State and Error Handling
← Back to Lua Academy