当前位置:网站首页>Read a blog, re understand closures and tidy up

Read a blog, re understand closures and tidy up

2022-04-23 16:54:00 The interview was rejected 10000 times

  Closures are rarely used when writing business , I didn't understand it carefully , When you see that a blog writes closure well, you can understand , Sort it out so that you can understand :

quote :https://blog.csdn.net/albertsh/article/details/82906284

print("\nexample 1:");
function counter()
    local count = 0;
    return function()
        count = count + 1;
        return count;
    end
end

func = counter();
--   The essence here is func = function() count = count + 1 return count end
--   Every call later func() They call this function
-- This is a standard counter , It is also a standard closure , in other words Lua Support such Syntax , Closure can always refer to external variables after definition , And this variable can be referenced throughout the life cycle of the return function , Add an external variable and modify this variable , The value referenced in the closure will also change

print(func());
print(func());
print(func());

 

版权声明
本文为[The interview was rejected 10000 times]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204231359046607.html