Status Codes to pcall
Lesson 30 of 48 in Coddy's Lua for C Developers course.
C APIs commonly report failure with a status code and place successful results in an output parameter. Lua can also return status values, but error raises a failure that interrupts normal execution. pcall(fn, ...) invokes a function in protected mode and returns a success boolean followed by its results or the raised error value. The examples reject a negative input and print a stable application message. The C caller inspects a boolean status; the Lua caller inspects the boolean returned by pcall. The failure message itself need not be printed.
C
#include <stdbool.h>
#include <stdio.h>
static bool double_nonnegative(int value, int *result) {
if (value < 0) {
return false;
}
*result = value * 2;
return true;
}
int main(void) {
int result = 0;
if (!double_nonnegative(-1, &result)) {
puts("caught");
} else {
printf("%d\n", result);
}
return 0;
}Lua
local function double_nonnegative(value)
if value < 0 then error("negative input") end
return value * 2
end
local ok, value = pcall(double_nonnegative, -1)
if not ok then
print("caught")
else
print(value)
endPorting trap
Pass a function to pcall. Writing pcall(risky()) evaluates risky before protection starts. Error text can contain source locations, so translate failures into deliberate output instead of depending on a runtime diagnostic format.
Challenge
EasyInput is a single integer text. Raise an error inside a helper for malformed text or a negative integer; use pcall to return invalid on failure. Otherwise return twice the number. Accept only an optional minus followed by digits.
Edit app.lua. The visible locked main.lua reads stdin into a sequence of lines, calls app.run(lines), and prints its returned value with one final newline. Do not print diagnostics or change the module names. Empty input gives an empty sequence. All numeric inputs are small enough to avoid overflow.
Try it yourself
local app = require("app")
local lines = {}
for line in io.lines() do lines[#lines + 1] = line end
print(app.run(lines))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Lua for C Developers
1First Lua Programs
Run Lua ModulesPrint and CommentNames and Local ScopeNumbers and ConversionStrings and Byte PositionsRecap: Format a Receipt4Functions and Closures
Functions and ArgumentsDefaults and Options TablesMultiple Results and VarargsCallbacks and Captured StateRecap: Pricing Functions2Values and Decisions
Absence and Table FieldsTruth and Default ValuesBranches and BoundsValues and Table IdentityRecap: Admission Rules3Iteration and Flow
Numeric for and Limitswhile and repeatArray Loops to ipairsFiltering and Early ExitRecap: Reading Stats6Ordering, Modules and Errors
Sorting and ComparatorsParsing with Lua PatternsModules and requireStatus Codes to pcallRecap: Validate a BatchPractice on your own: Online Lua compiler