繁体   English   中英

如何或可以将带有参数的函数作为参数传递给 lua 中的函数?

[英]How or Can I pass a function with argument as a parameter to a function in lua?

我不是直接运行 lua,而是运行 CC-Tweaks ComputerCraft 版本。 这是我正在努力完成的一个例子。 它不能按原样工作。

*已编辑。 我有一个要传递的函数,但没有一个带有自己参数的函数。

function helloworld(arg)

    print(arg)

end

function frepeat(command)

    for i=1,10 do

        command()

    end

end

frepeat(helloworld("hello"))

frepeat(helloworld("hello"))

不会像frepeat(helloworld)那样传递helloworld函数,因为它总是意味着它的样子:调用helloworld一次,然后将该结果传递给frepeat

您需要定义一个函数来执行您想要传递该函数的操作。 但是对于一次性函数来说,一个简单的方法是使用函数表达式:

frepeat( function () helloworld("hello") end )

这里的表达式function () helloworld("hello") end结果是一个没有名字的函数,它的主体说在每次调用该函数时将"hello"传递给helloworld

试试这个代码:

function helloworld(arg)
    print(arg)
end

function frepeat(command,arg)
    for i=1,10 do
        command(arg)
    end
end

frepeat(helloworld,"hello")

如果您需要多个参数,请使用...而不是arg

“重复”是 lua 中的保留字。 尝试这个:

function helloworld()
    print("hello world")
end
function frepeat(command)
    for i=1,10 do
        command()
    end
end
frepeat(helloworld)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM