Programming and Scripting :: lua - dofile or require ?
A question for lua users,
Is it better to use 'dofile' or 'require' ? I'm writing server software with lighttpd and sqlite and not compiling any modules, just plain script. Any advantages using 'require' in terms of speed or efficiency, cpu time, memory?
All pages requests pass through a main script, so globals play a large part e.g the session ID.
I've Googled a bit, but it's not too clear the differences. tks in advance.My understanding of the two has to do with namespaces.
dofile is chunk loading mechanism, that it is generates functions from a "chunk" of load code. This does not take into account any separation of variables into a separate namespace.
require is used for Lua modules. Modules are also "chunks" of Lua code but with a more formal namespace. All new global variables are stored in a namespace table. This table name is the same as the module name. This provides a much cleaner way to create functions without worry of variable name collisions. You would reference your modules functions via module_name.function_name This mechanism allows for much wider use and sharing of function libraries. Lua Rocks are examples of modules that one would use require.Is it then that a compiled script (luac) becomes a module ? I notice that I can 'require' a plain script, does that also become a 'module' once loaded?
I think 'require' might also handle repeated 'requires' much like #ifndef in C, though I think it might do no harm to do 'dofile' s more than once.
Quote
I think it might do no harm to do 'dofile's more than once.
As long as the subsequent scripts do not clobber the previous ones, as Robert said. When you dofile the file is added to the current script and has the ability to break things. As long as all files have unique names you should be ok.
original here.