lua-users home
lua-l archive

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


On Jul 14, 2012 9:48 PM, "Paco Willers" <paco.willers@gmail.com> wrote:
>
> 2012/7/6 Dirk Laurie <dirk.laurie@gmail.com>
>>
>> 2012/7/6 Paco Willers <paco.willers@gmail.com>:
>> > That's interesting. Is was wondering too. When to use a module (require) and
>> > when to use dofile...
>>
>> I use require if and only if the code is general enough to share over
>> several projects.  In that case, I get my sysadmin to put the module
>> in a system directory.  (That's not hard — it's me.)
>>
>
> So I learned something, I like that. :-)
>
> Learning and creating Lua code means (besides reading books, which I do, but they aren't very clear about this issue): reading and fully understanding someone else's code: how do they do things? So I examined this code: http://www.gammon.com.au/files/muds/luamud/, which is very clear to me. However I want to improve it first in order to create my own telnet game later, but it tricks me somewhere...
>
> Let me explain. The main file uses dofile to include a script file which contains a function called Init(). The Init() function is called by the global main code and calls other script files using dofile which contain functions that are called from anywhere in the program. I personally wouldn't do it that way, because global functions should in my humble opinion be outside this Init() function. (Am I right?)
>
> But anyway, the original downloaded scripts do run as expected. And in my humble opinion, when editing, every dofile(f) statement could be replaced by the contents of the file (f) itself without breaking the script. The result is one big .lua file that can be run on its own without the sub scripts. From thereon I could create my own program, and divide it into as many subscripts I like, and use dofile again. But it doesn't run that way as one big script file, the telnet client receives no data. And there are no error messages.
>
> That brings me to the question: what does dofile really do? Does it just copy/paste an external script file into the current one when running? Or are there scope issues with an approach like that?
>
> Have a nice day!
> --
> Paco

dofile() compiles and executes a file as a function, so it's like writing:
(function(...) FILE_CONTENTS_HERE end)()

But, the compiled function from dofile() won't share the same environment as if you'd written it inline - you have to use setfenv (5.1) or _ENV (5.2) if you want that.