Menu
CoddyTech

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)
end

Porting 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 icon

Challenge

Easy

Input 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))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Lua for C Developers

Practice on your own: Online Lua compiler