문제

Note: this trick also applies to scripting languages other than Lua, or to any other document type that might be considered an application in some contexts and a document in others.

If an interpreter is already associated to handle .lua files in Windows (i.e. if double clicking on a .lua file runs it in the interpreter) it is easy to make them executable directly on the command line.

You need to:

  1. put the script in a directory that is listed in the PATH environment variable;
  2. add the .lua extension to the PATHEXT environment variable.

In this way you can run any Lua script by typing its name on the command line. The problem now is that you cannot put another Lua script in any directory on the PATH without risking it to be executed, even if you don't want it to be executed. (An example of such a .lua file would be a module private to your program that will be loaded by require. Modules are by convention also named .lua, but rarely support execution as a free-standing program.)

So it is an all-or-nothing situation. Either you allow any script in a directory on the path to be executed or none.

Is there a way to allow only some scripts in a directory on the path to be runnable typing their name?

도움이 되었습니까?

해결책

The trick is that the console PATHEXT mechanism understands "double extensions", i.e. adding a .exe.lua "extension" to PATHEXT will make executable only those Lua scripts which have their full-name ending in .exe.lua (of course you can choose another extension, say .run.lua). Note: I used the quotes to avoid possible confusion and for lack of better terminology (remember that, conventionally, the file extension is the part of the file name after the last dot).

Therefore by adding .exe.lua to PATHEXT only whatevername.exe.lua will be executable, whereas any other Lua script won't (provided it doesn't have the same "double extension").

This allows to distinguish "normal" scripts from "executable" ones without either separating them in different directories or define a new custom file extension, which involves modification to the registry.

Moreover since this behaviour is controlled by an environment variable, it is a per-process setting - you can enable it only for a specific console window. For example if you create a batch file with this content:

@set PATHEXT=%PATHEXT%;.exe.lua &cmd /K

and you run it, it will open a console that will be able to execute all .exe.lua scripts found on the path, but not any other .lua script.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top