pythonerror-handlingluatry-catchblackmagic-fusion

How to translate a Python script to Lua script?


I am trying to translate a piece of code I wrote from Python to Lua. I am using this code inside of compositing package Blackmagic Fusion.

Any help would be greatly appreciated!

Python script (working):

try:
    comp.ActiveTool()                            # checks if a tool is selected
except:
    print("nothing selected")
    comp.AddTool("PolylineMask", -32768, -32768) # adds a tool if nothing's selected

Lua script (still not working and erroring):

if pcall (comp:ActiveTool()) then
    print "Node Selected"
else
   comp:AddTool("PolylineMask", -32768, -32768)
end

Solution

  • Lua's exception handling works a bit differently than in other languages. Instead of wrapping code in try/catch statements, you instead run a function in a 'protected environment' with pcall.

    The general syntax for pcall is:

    local ok, err = pcall(myfunc, arg1, arg2, ...)
    if not ok then
        print("The error message was "..err)
    else
        print("The call went OK!")
    end
    

    Where myfunc is the function you want to call and arg1 and so on are the arguments. Note that you aren't actually calling the function, you are just passing it so that pcall can call it for you.

    BUT keep in mind that tbl:method(arg1, arg2) in Lua is syntax sugar for tbl.method(tbl, arg1, arg2). However, since you aren't calling the function yourself, you can't use that syntax. You need to pass in the table to pcall as the first argument, like so:

    pcall(tbl.method, tbl, arg1, arg2, ...)
    

    Thus, in your case it would be:

    local ok, err = pcall(comp.ActiveTool, comp)