lune icon indicating copy to clipboard operation
lune copied to clipboard

Feature request: find out if the script is the main script

Open lammermann opened this issue 1 year ago • 4 comments

In python you can do something like this

...
if __main__:
    main()

It would be pretty handy for my use case to have something similar in lune, too. I often like my scripts to be usable as scripts, but to be able to require them as a module in other situations (e.g. unit testing). Maybe the process library would be a good place for this. Than I could have at the end of my scripts something like this:

local process = require("@lune/process")
local M = {}
...
if process.is_main then
  M.main()
else
  return M
end

Would you consider adding this feature?

Btw. Thanks for lune. It's a great tool

lammermann avatar Dec 02 '24 08:12 lammermann

Seems a bit inappropriate to put it in the process built-in, since it does not have much to do with describing the lune process IMO, but more of describing the environment of the script being executed... maybe we include it as a global of some kind?

CompeyDev avatar Dec 22 '24 16:12 CompeyDev

A global sounds good to me. Maybe even in the same way as python does it. It seems unlikely anybody using __main__ in an existing script till now.

lammermann avatar Dec 23 '24 09:12 lammermann

This could be done through the script global if partial support for it were added. I use red-blox/Util's Future implementation and partial support where script.Parent goes up the file directory could make Roblox-made libraries more plug & play in the Luau ecosystem that Lune is providing.

This could be extended to have script.__main__ or script.is_main as well. It seems like a decent design structure to me and will be familiar with those coming from Roblox.

CleverSource avatar Dec 23 '24 15:12 CleverSource

Hey! I just realized you can already get this behavior using debug.getinfo(2, "f") == nil as a check.

This works because for a script which isn't required, it will be at the topmost stack frame and have nothing below it. Credit to @bjcscat for this solution over on the Discord server.

CompeyDev avatar Jan 23 '25 16:01 CompeyDev