[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: scope of loadfile,dofile,require
- From: "nikdo79" <dominik-wagner@...>
- Date: Tue, 19 Mar 2002 11:59:53 -0000
--- In lua-l@y..., Luiz Henrique de Figueiredo <lhf@t...> wrote:
> >i thought dofile does the file in an do/end block and gets the scope of the place where it's called. but it doesn't. is that the wanted behavior? and when it is - why?
>
> This is the intended behavior. dofile (and loadfile) is a function like any
> other function. Lua's parser does not treat them specially.
>
> Do you expect a function to be able to see local variables outside the scope
> of its definition? More precisely, do you expect a function to be able to see
> local variables in the scope it is *called*?
Thanks, i didn't get this. of course this is normal behaviour when dofile, loadfile and require are normal functions.
> >So the i use the loadfile function only when i have to call some code more than once. but hey, i could simply put my code between a return function() 'file' end and would get the same effect. so what's the benefit of this function? and if i would like to i could nonetheless dofile my file and execute it only once by
>
> One use of loadfile is to be able to check whether a chunk is syntactically
> correct before executing it. Another use is to be able to run a chunk repeatedly
> without recompiling it. All this could be done with dofile alone, by wrapping
> the contents of the file inside "return function () XXX end" as you mention,
> but loadfile is a cleaner solution. But yes, dofile is essentially the same
> as
> function dofile(x)
> local f,e=loadfile()
> if f==nil then
> return f,e
> else
> return f()
> end
> end
so loadfile was first, and dofile is the addon? ;-)
> >Is there any way to include other files so that they are defined in the context of the including statement?
>
> No. Or rather, you have to do it yourself: redefine dofile or loadfile to read
> the whole file in memory and then gsub every instance of say "$include file.lua"
> with the contents of file.lua. Then run dostring or loadstring on the modified
> file contents.
> --lhf
so i have to do a kind of preprocessor for this. which is not the thing i'd like to do, because i would have to go over the whole file, and then lua goes over the whole file parsing again. i don't think preprocessing is a neat function for a interpreted language.
Thanks,
Dominik