Advertisement
Guest User

Untitled

a guest
Mar 18th, 2018
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.23 KB | None | 0 0
  1. -- closures are anonymous function in a function
  2.  
  3. local function currentNumber() -- scopes can be used in functions aka local or global
  4.   i = 0 -- create a variable called 'i' and assigned it to a number '0'
  5.   print("lol")
  6.   return function() -- create an anonymous function and return it (also called a closure)
  7.     i = i + 1 -- add 1 to the variable i
  8.     print("lol")
  9.     return i -- return the variable i so the print() function will print the value inside the 'i' variable
  10.   end
  11. end
  12.  
  13. print("==================================")
  14.  
  15. -- you can assigned a function to a variable
  16. local first = currentNumber() --if a function was assigned to a variable then the function will execute
  17.  
  18. print("==================================")
  19.  
  20. print(first()) -- prints out the return values in the function
  21. print(first) -- PROBLEM HERE: why does it print out the function id or something, it didn't print out the current value of the variable
  22. -- 'i'...
  23.  
  24. print("==================================")
  25.  
  26. print(currentNumber()) -- prints out what needs to be printed in function and prints out the function id
  27.  
  28. print("==================================")
  29.  
  30. currentNumber() -- execute the function block
  31.  
  32. print("======================================")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement