lua-users home
lua-l archive

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




On Tue, Jun 11, 2019 at 1:10 PM David Heiko Kolf <david@dkolf.de> wrote:
Coda Highland wrote:
> However, non-assignable variables are pretty useful. There are some
> compiler optimizations that can happen when you know a variable is
> read-only, and of course asserting that something is read-only can help
> avoid programming mistakes.

This point currently raises some questions for me. I appreciate const
statements in an API, as they clearly document that a variable or a
parameter will not be changed.

However, in Lua locals are (as the name says) already limited to a
single file so they are not part of an API and any compiler looking at
the file could already see that it is only assigned once even without a
const statement.

So I get the impression that the proposed const statement adds very little.

I would actually prefer if the const statement is not added to Lua, as
the use cases of const and toclose would at least for me be completely
different:

E.g. I like to copy multiple dependency functions to constants at the
beginning of my libraries:

  local strsub, strrep, gmatch, strformat =
    string.sub, string.rep, string.gmatch, string.format
  local _ENV = nil

But I need a non-scoped error message:

  local <toclose> f, err = io.open("demo.txt")

Or do I miss some significant use case of a local const statement in Lua?

Best regards,

David


toclose must be const, because if you want to ensure __close is called as demanded by the contract then that means you can't change out the contents of that variable.

But beyond that, the use cases of const and toclose ARE completely different.

You use a const local to make sure you don't accidentally overwrite something. It's a matter of code hygiene. Modern JS programmers use it all the time because it helps you avoid (or if you've failed to avoid it, track down) accidentally changing out a value or reference that you need.

Can you write correct software without const locals? Of course you can. Is this a game-changing feature that's going to impact how everyone writes Lua code? No, it's not. You can still use Lua 5.4 without ever touching <const>. But since it's a feature that needed to be introduced to support <toclose>, there's no reason NOT to expose it to other uses as well, for the people who do want to make use of it.

As an aside, it also enables the possibility of some optimizations. I don't know if Lua is going to incorporate those right away, but when you can be certain that something isn't going to change, the compiler can make better decisions about how to generate code around it.

/s/ Adam