lua-users home
lua-l archive

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


Keep in mind, this is more of an observation to how files directly called by the command-line interpreter behave. In Python, it's important to use main to ensure that your module doesn't run like a script when you import it like a module. 

Lua never needs to worry about the difference between global and local declarations because it has a unique syntax for both. I speculate the reason for the boilerplate VARARGPREP and RETURN is just to make variable command-line arguments more seamless. Loading other modules with loadfile() doesn't necessarily render those locals as upvalues in the module -- they can't be read with debug like normal upvalues -- so I suspect those are not implicitly within a function.

On Fri, May 27, 2022, 10:05 AM Hugo Musso Gualandi <hgualandi@inf.puc-rio.br> wrote:
Python needs a main function because in that language toplevel variables are global. If you don't create a main function you will pollute the global namespace. This is not a problem in Lua. When you load a module, it implicitly puts everything inside an invisible main function. Local variables declared at the toplevel are local to the module.

What I do on my projects: if the file is a standalone script I usually don't bother with creating a main function. I the module is intended to be used via require, I put the code inside an exported function. I don't want to have side effects when I call require("mymodule").