问题
In vanilla Lua 5.2, I have a module that contains:
Two local functions, A and B: B will always call A, A will sometimes call B and sometimes will call the functions stored in C;
C: a table (local). It contains tables which contains tables which can contain tables... which will at the end contain functions. These functions may call either A or B;
Then there's the return function, D, which will be returned when my module is loaded using
require
. It will call A.
At the end, it looks quite like this:
--don't pay attention to what the functions do:
--I am only writing them down to explain how they interact with each other
local A, B, C
C = {
...
{
function(a)
B(a)
end
}
...
}
A = function(a)
...
if (...) then
B(a)
end
...
if (...) then
C[...]...[...](a)
end
...
end
B = function(a)
A(a)
end
return function(s) -- we called this one D
A(s)
end
Now, my problem is this: the declaration of C uses its own local variables, metatables and all that stuff, to the point I enclosed its declaration in a do ... end
block.
It also is - with all those tables inside tables and newlines for each curly brace and indentation and so on - quite long. So I wanted to put it in its own module, but then it couldn't access B.
So, my question is: is there a way to pass B and maybe even A to the file where C is declared while loading it? I mean something like this, if it were possible:
--in the original module
local A, B, C
C = require("c", A, B)
...
And then, in c.lua:
local A, B = select(1, ...), select(2, ...)
C = {
...
{
function(a)
B(a)
end
}
...
}
I really have no idea on how to do it.
Is there a way to pass variables from the requiring file to the required file which doesn't involve the variables being inserted in the global namespace?
回答1:
main module:
local A, B, C
A = function(a)
...
if (...) then
B(a)
end
...
if (...) then
C[...]...[...](a)
end
...
end
B = function(a)
A(a)
end
C = require("c")(A, B)
return function(s) -- we called this one D
A(s)
end
c.lua:
local function C_constructor(A, B)
local C =
{
...
{
function(a)
B(a)
end
}
...
}
return C
end
return C_constructor
回答2:
Is there a way to pass variables from the requiring file to the required file which doesn't involve the variables being inserted in the global namespace?
Not with the default require
function, but that shouldn't stop you from writing your own require
function that does this. Obviously this will make the solution specific to your application, so those required files will not function correctly when a standard Lua interpreter (with its require
function) is used.
来源:https://stackoverflow.com/questions/38702063/modules-using-each-others-local-objects