首先来一段PIL中的说明:
Life is not always that easy. Sometimes, an object needs other resources besides raw memory, such as file descriptors, window handles, and the like. (Often these resources are just memory too, but managed by some other part of the system). In such cases, when the object becomes garbage and is collected, somehow those other resources must be released too. Several OO languages provide a specific mechanism (called finalizer or destructor) for that need. Lua provides finalizers in the form of the __gc
metamethod. This metamethod only works for userdata values. When a userdatum is about to be collected and its metatable has a __gc
field, Lua calls the value of this field (which should be a function), passing as an argument the userdatum itself. This function can then release any resource associated with that userdatum.
假设现在我们需要写一个遍历目录的库,遍历文件基本流程是:
findFile -> 打开一个编译句柄
nextFile -> 遍历目录中的文件
closeFind -> 遍历完成
在lua使用遍历目录库:
for name in dir(path) do .... end