Protect one operation in Lua
LANGUAGE GUIDE · LUA
The Lua function pcall runs a function and gives you two answers. The first says whether it completed. The second holds its result or an explanation of the error.
local Script = {}function Script.run(context)
local ok, value = pcall(function()
local n = tonumber(context.raw)
assert(n and n >= 0, "Expected a nonnegative fare")
return n
end)
if not ok then
Log("gate | " .. tostring(value))
return 0
end
return value
endreturn ScriptWith raw set to "3", tonumber produces 3 and the record returns 3. With "bad", the assertion fails. The console identifies lua_guard and its failing line, and the routine returns the chosen fallback, 0.
This fallback works for a display that should show zero. For a purchase, returning zero could accidentally grant a free ticket. Return an explicit failure status and refuse the transaction if a real zero would be meaningful.
This example protects synchronous Lua code. A helper that completes normally and returns false still leaves pcall’s first answer true. Check the helper’s returned value as well.
