Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function creating in Lua

When I create the function by assigning ,"if" condition doesn't work but when I do create the function like in second example below, it works. Can you tell me why?

Not working:

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)

Working:

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)
like image 336
Figen Güngör Avatar asked Jun 08 '13 11:06

Figen Güngör


1 Answers

That's because when you do local countDown = ..., the countDown variable doesn't exist until after the ... part has been executed. So your function will access a global variable, not the local one that doesn't exist yet.

Note that Lua converts local function countDown ... into the following:

local countDown
countDown = function ...
like image 157
Nicol Bolas Avatar answered Sep 20 '22 12:09

Nicol Bolas