lua - dofile or require ?


Forum: Programming and Scripting
Topic: lua - dofile or require ?
started by: humpty

Posted by humpty on May 01 2008,13:22
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.

Posted by roberts on May 01 2008,14:06
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.

Posted by humpty on May 01 2008,23:41
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.

Posted by mikshaw on May 02 2008,01:06
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.

Powered by Ikonboard 3.1.2a
Ikonboard © 2001 Jarvis Entertainment Group, Inc.