Creating a function in Lua

When I create a function by assignment, the if condition does not work, but when I create a function, as in the second example below, it works. Can you tell me why?

Does not work:

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) 

IN:

 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) 
+6
source share
1 answer

This is because when you do local countDown = ... , the variable countDown does not exist until part ... is executed. That way, your function will access a global variable, not a local variable that does not yet exist.

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

 local countDown countDown = function ... 
+12
source

Source: https://habr.com/ru/post/946847/


All Articles