在Lua中创建函数

Fig*_*gör 6 lua function coronasdk

当我通过分配创建函数时,"if"条件不起作用,但是当我创建函数时,如下面的第二个示例,它可以工作.你能告诉我为什么吗?

不工作:

local start=os.time()

local countDown = function(event)
   if((os.time()-start)==3) then
      Runtime: removeEventListener("enterFrame", countDown)
   end
   print(os.time()-start)
end

Runtime:addEventListener("enterFrame", countDown)
Run Code Online (Sandbox Code Playgroud)

工作:

local start=os.time()

local function countDown(event)
   if((os.time()-start)==3) then
      Runtime: removeEventListener("enterFrame", countDown)
   end
   print(os.time()-start)
end

Runtime:addEventListener("enterFrame", countDown)
Run Code Online (Sandbox Code Playgroud)

Nic*_*las 12

这是因为当你这样做local countDown = ...时,countDown变量不存在,直到之后的...部分已经被执行.因此,您的函数将访问全局变量,而不是尚不存在的本地变量.

请注意,Lua转换local function countDown ...为以下内容:

local countDown
countDown = function ...
Run Code Online (Sandbox Code Playgroud)