lua-users home
lua-l archive

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

Op Ma. 8 Jul. 2019 om 19:33 het Gé Weijers <> geskryf:

> Yes, you can do without "local <toclose>", but I would not call your example readable code. The point of adding features like this to a language is to make programs simpler and easier to understand by increasing the expressive power of the language.
> This is a whole lot more readable:
> local <toclose> f = assert("test.txt", "r"))
> -- do something with f
> return value
> I think the "<toclose>" facility is a fair tradeoff between added language complexity and expressive power. It's also likely to be much faster because there's no need to create closures, no need to pack or unpack parameter lists, and no need to use 'pcall' or forward the error.

The VM instructions in lopcodes.c are

opmode(0, 0, 0, 0, iABC)              /* OP_TBC */
opmode(0, 0, 0, 0, iABC)              /* OP_CLOSE */

So 'local <toclose> x = initializer' generates the same code as 'local
x = initlalizer', plus ' TBC lx' where lx is the number of the local
variable x, plus 'CLOSE lx' at the end of the scope.

Given that there is to be a name for the attribute that x should have,
only two bytes '<>' of syntax is used up, and those bytes provide the
feature of associating other attributes with a local variable.

Personally (as I have argued in another post) I think the name
'close', with metamethod '__toclose', too specific, since it is merely
a method called when a local name with which that variable is
associated goes out of scope. There is no need at all for the value
itself to end its existence: it could have other names. 'close' is
appropriate for a file, but the value really could be anything, e.g. a
custom message handler.

-- Dirk