lua-users home
lua-l archive

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


2015-11-13 10:19 GMT+00:00 Viacheslav Usov <via.usov@gmail.com>:
> This problem is not specific to Lua and probably exists in every
> GC-collected environment, so there are some established ways of dealing with
> it. In C#, for example, this is done via the keyword 'using', which
> establishes a scope, upon exiting which (including exiting via an
> exception), the object is finalized. Example from
> https://msdn.microsoft.com/en-us/library/yh598w02.aspx
>
> using (Font font1 = new Font("Arial", 10.0f))
> {
>     byte charset = font1.GdiCharSet;
> }
>
>
> Syntactically, this could be transferred to Lua using a new keyword, such as
> block, instead of local, to define a local variable that must be finalized
> when exiting the block (including error exits). The finalization will use
> the __gc methamethod, if present, and subsequent garbage collection proceeds
> in the usual manner. For example:
>
> block file = io.open('file')
>
> Comments?

What about yields? You cannot close the file on yield, because the
yield might be caused by nested sub-calls out of your control. And you
cannot "not close" the file, because the thread might never be
resumed.

This shows there is no universal solution to the problem. The code
inside the block must cooperate with the code outside.