gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:49:01 25 4
gpt4 key购买 nike

我正在尝试将我编写的一段代码从 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

Lua 脚本(仍然无法正常工作并出错):

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

最佳答案

Lua 的异常处理方式与其他语言略有不同。不是将代码包装在 try/catch 语句中,而是使用 pcall 在“ protected 环境”中运行一个函数。

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

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

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

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

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

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

关于python - 如何将 Python 脚本转换为 Lua 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17840613/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com