Corresponding to the latest lua5.4 beta version: 2019-10-09 Published
This function is modified twice before grammar, syntax currently no accident will be the final decision, there is no information on the latest Chinese, so I came here to send it.
First introduced to this function:
Are labeled to-be-closed local variables, it will be beyond the scope, call its __closed element method, which provides a C ++ destructor similar role for us.
It is marked as a to-be-closed variable should meet two prerequisites:
1, which is a table
2, has been designated __close element method for it
The current version Syntax: add <close> after the variable name, the variable is marked as to-be-closed variable
local t<close> = ...
Example:
test2 function () local T = {X = . 1 }; setmetatable (T, {__close = function (...) Print ( ' Close ' )} End); local TC <Close> = T; - the function returns, automatically performing the method of tc __close element. End test2 (); - a file operation as an example: - in the absence of to-be- case closed variables: function foo () - Open a file local FD = io.open ( ' C: \\. 1. TXT ' , ' R & lt ' ); - to read the file local X = FD: read ( ' * A '); - Next, the file content is determined - if we need a variety of content on the logical IF X == ' . 1 ' the then FD: Close (); return ; the else IF X == ' 2 ' the then Print ( ' file contents: 2 ' ); FD: Close (); return ; End Print ( ' wrong file content: ' .. X-); FD: Close (); End - to-BE- case of closed: foo2 function () - Add <close> after the variable name local fd<Close> = io.open ( ' C: \\ 1.txt ' , ' R & lt ' ); - Then you have to write a return position and various super annoying fd: close () goodbye - Read take file local X = FD: Read ( ' * A ' ); IF X == ' . 1 ' the then return ; the else IF X == ' 2 ' the then Print ( ' file content: 2 ' ); return ; End Print ( ' wrong file content: '.. X-); End - c ++ to achieve the std :: lock_guard for example: - xshare. Lock xshare.unlock from my other article: HTTPS: // www.cnblogs.com/babypapa/p/ 11711389.html function lock_guard (XT) local T = {xstab = XT}; setmetatable (T, {__close = function (Tab) xshare.unlock (tab.xstab)} End) xshare. Lock (XT); return T; End foo3 function (XT) local LG <Close> = lock_guard (XT); ... End