lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Klaus Ripke wrote:
On Mon, Jan 16, 2006 at 12:47:53PM +0800, CHU Run-min wrote:

Thanks, I understand it.
But lua-5.1 manual seems confusing me. It says

"Finalizers allow you to coordinate Lua's garbage collection with
external resource management (such as closing files, network or
database connections, or freeing your own memory). "

For the most part this should be viewed as a desperate measure
of last resort only.

I'm not sure how desperate it is. The point of having __gc is to release resources. For tables and strings, those resources are owned by Lua and it therefore releases them without any intervention from you. Since neither tables nor strings have any user controlled data, they have no need for an externally accessible __gc method. If you want to put some user controlled resources into a table, you should wrap them in a userdata, which does have an __gc method. Then you get a chance to release them. Because this method might not run for a long time, a resource might be kept for longer than you expect, so you may want an explicit destroy to control this. But the system is consistent. If you implement __gc properly the resource will exist for as long as your object exists, then it will cease to exist.

--
chris marrin              ,""$, "As a general rule,don't solve puzzles
chris@marrin.com        b`    $  that open portals to Hell" ,,.
        ,.`           ,b`    ,`                            , 1$'
     ,|`             mP    ,`                              :$$'     ,mm
   ,b"              b"   ,`            ,mm      m$$    ,m         ,`P$$
  m$`             ,b`  .` ,mm        ,'|$P   ,|"1$`  ,b$P       ,`  :$1
 b$`             ,$: :,`` |$$      ,`   $$` ,|` ,$$,,`"$$     .`    :$|
b$|            _m$`,:`    :$1   ,`     ,$Pm|`    `    :$$,..;"'     |$:
P$b,      _;b$$b$1"       |$$ ,`      ,$$"             ``'          $$
 ```"```'"    `"`         `""`        ""`                          ,P`