Skip to reading
Error Handling & Debugging

Protect one operation in Lua

Edition 0.86.4.4 Hotfix 2

Updated through 0.86.4.4 Hotfix 2, with cinematic property, recorded-pose or voice-timing lessons as described in this guide. Earlier examples, screenshots and complete registry figures retain their stated edition context.

Download PDFView PDF page

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.

Code example
local Script = {}
Code example
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
end
Code example
return Script

With 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.

Page 17 of 37Permalink
Go to page