Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何或可以将参数为参数的函数传递给lua中的函数?_Lua_Computercraft - Fatal编程技术网

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

如何或可以将参数为参数的函数传递给lua中的函数?,lua,computercraft,Lua,Computercraft,我不是直接运行lua,但CC调整了ComputerCraft版本。这是我努力实现的一个例子。它不能按原样工作 *编辑。我要传递一个函数,但不是一个有自己参数的函数 function helloworld(arg) print(arg) end function frepeat(command) for i=1,10 do command() end end frepeat(helloworld("hello")) “repeat”是lu

我不是直接运行lua,但CC调整了ComputerCraft版本。这是我努力实现的一个例子。它不能按原样工作

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

function helloworld(arg)

    print(arg)

end

function frepeat(command)

    for i=1,10 do

        command()

    end

end

frepeat(helloworld("hello"))

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

function helloworld()
    print("hello world")
end
function frepeat(command)
    for i=1,10 do
        command()
    end
end
frepeat(helloworld)
不会像
frepeat(helloworld)
那样传递
helloworld
函数,因为它总是像这样传递:调用
helloworld
一次,然后将结果传递给
frepeat

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

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

请尝试以下代码:

function helloworld(arg)
    print(arg)
end

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

frepeat(helloworld,"hello")

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

谢谢您的快速回复,很遗憾,我问错了问题,不得不编辑我的问题。然而,在我的示例中,我确实更改了函数名。@marcm在回答后更改问题而不是goog想法。但在你们的情况下,解决办法很简单。只需将“frepeat(helloworld)”替换为“frepeat(function()helloworld(“hello”)end”,如aschepler的下一个答案所述。lhf和aschelper给出了不同但同样好的答案。也许他们应该合并成一个答案?
function helloworld(arg)
    print(arg)
end

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

frepeat(helloworld,"hello")