I have a strange problem with using modules, which I hope an expert
can help me with. :)
I am writing a module which exports one function (f in my example)
and uses another function (g in my example) as a local "helper"
function. For brevity I will show the module declaration inside a
function, although in practice it is in a separate file, this is
just for testing.
First, this works perfectly:
-----------
function m_installer ()
module ("m", package.seeall)
local function g ()
print "inside g"
end -- g
function f ()
print "inside f"
g () -- call g
end -- f
end -- module m_installer
m_installer () -- install module
m.f () -- call f inside module
-----------
However, for documentation reasons I wanted to put f (the exported
function) near the top of the file, and have g (the internal
function) further down. This is what happens:
-----------
function m_installer ()
module ("m", package.seeall)
function f ()
print "inside f"
g () -- call g
end -- f
local function g ()
print "inside g"
end -- g
end -- module m_installer
m_installer ()
m.f () -- error: attempt to call global 'g' (a nil value)
-----------
OK, I looked through the manual, and found I need to put a forward
declaration of g inside the function, so that when f is compiled it
knows it is a local function and not a global one. But, it doesn't
work:
-----------
function m_installer ()
module ("m", package.seeall)
local g -- forward declare g
function f ()
print "inside f"
g () -- call g
end -- f
local function g ()
print "inside g"
end -- g
end -- module m_installer
m_installer ()
m.f () -- error: attempt to call upvalue 'g' (a nil value)
-----------
I don't quite get how g is an upvalue. It is just another variable
inside the module. I can make the problem go away by removing the
"local" from the function declaration for g, but I wanted it there
because it really is a local function, I don't even want it
exported as part of the module.
Has anyone any suggestions for how to make this work in the way I
wanted? Thanks.
- Nick Gammon