lua-users home
lua-l archive

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


On Tue, Jul 30, 2019 at 8:45 AM Abhijit Nandy <abhijit.nandy@gmail.com> wrote:
> What I am wondering is, apart from using the static analyzer to catch it, is there any code patch that can make variable declarations local by default?

How do you access globals then?
Have you to use `__ENV.name` everywhere ?
So, could to completely forbid the globals work for you?

If this is the case, I just wrote a patch some day ago. It is for the
last commit on github [1] but it is very simple, probably you can
adapt it to the official release. I attached the last version.

The patch lets you to mark a do/end block with one of the following:

- <autoglobal>: it works like the common do/end block
- <withupvalue>: a free name inside this block raises an error instead
of being translated to `__ENV.name`
- <localonly>: an error is raised when accessing an upvalue too (so
local variables only are allowed, it is similar to the noupvalues by
Sergey)

Note:

- A non-marked do/end block inherits the behaviour from the parent block.
- The main chunk starts in the <autoglobal> mode (as usual).

For your use case, I think you could do one of the following:

1) in the patch, you can change the default for the main chunk to
<withupvalue>, or
2) in your lua code, you can write a wrapper for the lua function
"load" that puts any lua code in a

do <withupvalue>
  -- paste here the original script
end

> Or is it too core to the language that changing this could cause issues elsewhere? I am willing to sacrifice performance as we are on PC and its worth doing this for us to prevent erroneous code if it can be done without requiring significant change to syntax.

The patch rises error at compile time, so the performance should not
be affected.

Please note that the patch is somehow "Compatible" with the regular
lua: if you write a script that works as expected with the patch, you
can remove any mark from the do/end blocks, and the result is valid
for the regular lua too [2].

pocomane

[1] https://github.com/lua/lua/commit/9e6807c3c9d5036e999f636f936df07b72284442
[2] Of course, if no do/end block is marked it is alright valid for a
regular lua. And this is true also if you changed the default mode, or
if you wrapped the "load" function.

Attachment: do_attrib_proof_of_concept.diff
Description: Binary data