如何将Python脚本转换为Lua脚本?

iGw*_*wok 3 python error-handling lua try-catch blackmagic-fusion

我试图将我用Python编写的一段代码翻译成Lua.我在合成包Blackmagic Fusion中使用此代码.

任何帮助将不胜感激!

Python脚本(工作):

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
Run Code Online (Sandbox Code Playgroud)

Lua脚本(仍然没有工作和错误):

if pcall (comp:ActiveTool()) then
    print "Node Selected"
else
   comp:AddTool("PolylineMask", -32768, -32768)
end
Run Code Online (Sandbox Code Playgroud)

Col*_*Two 7

Lua的异常处理与其他语言的处理方式略有不同.而不是在try/catch语句中包装代码,而是在"受保护的环境"中运行函数pcall.

pcall的一般语法是:

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

myfunc您要调用的函数在哪里arg1等等是参数.请注意,您实际上并没有调用该函数,而只是传递它以便pcall可以为您调用它.

请记住,tbl:method(arg1, arg2)在Lua中是语法糖tbl.method(tbl, arg1, arg2).但是,由于您没有自己调用该函数,因此无法使用该语法.您需要将表传递给pcall第一个参数,如下所示:

pcall(tbl.method, tbl, arg1, arg2, ...)
Run Code Online (Sandbox Code Playgroud)

因此,在您的情况下,它将是:

local ok, err = pcall(comp.ActiveTool, comp)
Run Code Online (Sandbox Code Playgroud)