Question

If I require three included files in my Lua script, can any function in any one of those files then see (and most importantly, call) any of the other functions ?

I'm running into the problem of functions calling functions which call other functions. I tried to put the various functions in other files, and then include them instead of writing them into the main file.

I think it's working, my tests are convincing if not conclusive.

My mainline code does this...

 require "SOME_REQUIRED_FILE_01"
 require "SOME_REQUIRED_FILE_02"
 require "SOME_REQUIRED_FILE_03"

 XYZ = 0

 File_02_Function_A()

I looked on The Lua Site and found THIS PAGE but I'm not totally clear on it.

Can EVERY function in all three required files see EVERY OTHER function in all three files ?

Was it helpful?

Solution

require is basically the same as dofile, except for mechanisms that avoid loading the same file multiple times (and some other useful things like loaders). That means, that they can set global variables (though they should not) as well. So, if you set a global variable in one of the required files, the global can be seen in the entire scope of the require function. That means in other required files as well.

Having said that, it is not best practise to set global variables in required files. It is better to return a table that has functions and variables exported by the module inside. Then you would call those functions like this:

local some_required_file_01 = require "SOME_REQUIRED_FILE_01"
local some_result_01 = some_required_file_01.some_function_01()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top