如何在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"))
点赞
用户12446146
用户12446146

repeat 是在 Lua 中的保留字。尝试一下:

function helloworld()
    print("hello world")
end
function frepeat(command)
    for i=1,10 do
        command()
    end
end
frepeat(helloworld)
2019-12-07 17:53:06
用户459640
用户459640

frepeat(helloworld("hello")) 不会像 frepeat(helloworld) 一样将 helloworld 函数传递进来,因为它的意思始终是调用 helloworld 一次,然后将结果传递给 frepeat

你需要定义一个函数来实现你想要传递的功能。但对于一个单次使用的函数来说,简单的方法是使用函数表达式:

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

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

2019-12-07 18:26:10
用户107090
用户107090

尝试以下代码:

function helloworld(arg)
    print(arg)
end

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

frepeat(helloworld,"hello")

如果你需要多个参数,请使用 ... 代替 arg

2019-12-07 20:43:04