如何或可以将参数为参数的函数传递给lua中的函数?
我不是直接运行lua,但CC调整了ComputerCraft版本。这是我努力实现的一个例子。它不能按原样工作 *编辑。我要传递一个函数,但不是一个有自己参数的函数如何或可以将参数为参数的函数传递给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
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")