leafo / moonscript

:crescent_moon: A language that compiles to Lua

Home Page:https://moonscript.org

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Support for Lua 5.4 attributes

gonzalezjo opened this issue · comments

A flag to enable support for Lua 5.4 attributes would be wonderful.

Lua 5.4 introduces the concept of attributes for local variables. With this new feature, two attributes were added: const and close.

const is exactly what it sounds like: compile time enforcement of immutability. There are a few ways this can be implemented, but I believe that it's important that MoonScript include the attributes wherever possible in its output. The reason why is simple: Lua 5.4 generates better bytecode when you use const wherever applicable.

The downside is that if support for const function parameters are desired, we'd have to special-case support for them. Lua 5.4 does not have support for them.

Examples of const:

local example <const> = {"hello"}
example.foo = "bar" -- Would compile

local example_2 <const> = {"hello"}
-- example_2 = 5 -- Would NOT compile 

-- local function fn(bar <const>) end -- Would NOT compile

close, on the other hand, is a bit more difficult to explain. It essentially does two things: makes a variable const, and gives it some RAII-like behavior. The former is hopefully clear by now, but the latter might not be.

To explain what I mean by RAII-like behavior, I mean that a variable marked close is defined as one that is essentially "opened" when it's initalized, and as soon as it is out of scope, automatically gets closed. Basically, it's a new form of finalizer that's considerably better than __gc. The metamethod responsible for close is __close, and it can be pretty handy for stuff that allocates unmanaged resources. For example, a file wrapper can use __close to automatically close file handles as soon as the wrapper goes out of the scope it was made in.