lua-users home
lua-l archive

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


hi there,

here is a little code snippet:

   A='global'

   do
      local A='local'
	
	  require('dofile2.lua')
      dofile('dofile2.lua')
      local mychunk=loadfile('dofile2.lua')
	  mychunk()
   end

the dofile2.lua consists of
   print(A)

The output is:
global
global
global

now my bunch of questions/statements:
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?
So dofile and require only "see" the globals variable, and not a single local variable, and the latter only differs in including the same file only once no matter how often you try, and trying LUA_PATH
But then i thought loadfile would do the job i thought after, because it returns a function and functions get the scope of the context where they are defined, so i thought of dofile as

	return function () contentoffile end

but it also doesn't see the local context. Also intentional?

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
dofile('file.lua')()

Am i just blind, or is this the only difference between loadfile and dofile?

Is there any way to include other files so that they are defined in the context of the including statement?

Thanks,
  Dominik Wagner