Status Codes to pcall
Lesson 30 of 48 in Coddy's Lua for Go Developers course.
Go usually returns errors as ordinary values and uses panic/recover for exceptional unwinding. Lua error raises an error, while pcall returns a success flag plus results or an error value. These are different mechanisms: protect the risky call itself and inspect the flag before interpreting results. Normal validation failures can instead use explicit return values.
Go
package main
import ("fmt")
func protected(){defer func(){if recover()!=nil {fmt.Println("caught")}}(); panic("bad")}
func main(){
protected()
}
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 so risky execution occurs inside protection.
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 Go 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