Managing State and Error Handling
Use lua_pcall for protected calls and handle errors in the C layer.
Managing State and Error Handling is a free Lua Academy lesson on CoddyKit — lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Lua Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
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.
Frequently asked questions
Is the “Managing State and Error Handling” lesson free?
Yes — the full text of “Managing State and Error Handling” is free to read here on the web, and the Lua Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Lua Academy course, upgrade to CoddyKit PRO.
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; this is — lesson 4 of 4, so you can start here or from the beginning and move at your own pace.
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
- The Lua C API Stack Model
- Calling Lua Functions from C
- Registering C Functions in Lua
- Managing State and Error Handling