Lua中的函数创建

当我用赋值创建函数时,“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)

起作用:

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)
点赞
用户734069
用户734069

这是因为当你执行 local countDown = ... 时,countDown 变量直到 ... 部分执行完成之后才 _存在_。因此,你的函数将访问一个 全局 变量,而不是尚不存在的本地变量。

请注意,Lua 将 local function countDown ... 转换为以下形式:

local countDown
countDown = function ...
2013-06-08 12:04:46