6

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)

1 Answer 1

12

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 ...
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.