使用timer.performWithDelay()函数

当在侦听器中包含括号时,

timer.performWithDelay( delay, listener [, iterations] )

无法延迟函数调用。

如果我试图在

timer.performWithDelay()

中声明一个函数,它会给出语法错误。

那么如何使用在 timer.performWithDelay() 中包含的函数传递参数/对象?

我的代码:

local normal_remove_asteroid

normal_remove_asteroid = function (asteroid)
    asteroid:removeSelf()
    asteroid = nil
end

timer.performWithDelay(time, normal_remove_asteroid (asteroid) )
点赞
用户869951
用户869951

在 Lua 中,() 是函数调用运算符(除了在 function 关键字旁边):如果对象是函数或者有一个 __call 方法,它将立即被调用。因此,将 normal_remove_asteroid(asteroid)performWithDelay,实际上是将其赋值为 normal_remove_asteroid 函数调用的返回值。如果你想向函数传递参数,你必须创建一个临时的匿名函数,它不带任何参数:

local asteroid = ....
...
timer.performWithDelay(time, function() normal_remove_asteroid (asteroid) end )

匿名函数中的 asteroid 是一个上值;它必须在该行之上某处被定义(这在你的代码中必须已经是这种情况,因为你在 normal_remove_asteroid(asteroid) 中使用了它)。

注意,你不一定要使用匿名函数:你也可以显式地定义一个包装函数,但是为什么要费心命名它呢,它只是用来包装:

function wrap_normal_remove_asteroid()
    normal_remove_asteroid (asteroid)
end

timer.performWithDelay(time, wrap_normal_remove_asteroid)
2014-10-05 01:46:49