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

问题描述 投票:4回答:3

我不是直接使用lua,而是CC-Tweaks ComputerCraft版本。这是我要完成的一个例子。它不能按原样工作。

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

function helloworld(arg)

    print(arg)

end

function frepeat(command)

    for i=1,10 do

        command()

    end

end

frepeat(helloworld("hello"))

lua computercraft
3个回答
2
投票

尝试此代码:

function helloworld(arg)
    print(arg)
end

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

frepeat(helloworld,"hello")

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


2
投票
frepeat(helloworld("hello"))

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

您需要定义一个函数来执行您想要传递的功能。但是,针对一次性函数执行此操作的一种简单方法是函数表达式:

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

这里的表达式function () helloworld("hello") end导致一个没有名称的函数,其主体表示每次调用该函数时都会将"hello"传递给helloworld


1
投票

“ repeat”是lua中的保留字。试试这个:

function helloworld()
    print("hello world")
end
function frepeat(command)
    for i=1,10 do
        command()
    end
end
frepeat(helloworld)
© www.soinside.com 2019 - 2024. All rights reserved.