[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: scope of loadfile,dofile,require
- From: Luiz Henrique de Figueiredo <lhf@...>
- Date: Mon, 18 Mar 2002 22:12:20 -0300
>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*?
>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
>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