Question about the useage of the local function in module

Posted by Yeedoo on Tue 21 Feb 2012 05:14 AM — 5 posts, 22,478 views.

China #0
In a module or package. What's the different with the function and the local function?
Just the local function cant be seen from outside the module?
I tried to setup a module with a local function
wang_test={}
function wang_test.foo1(str)
local _f=foo2 ()
_f()
end --function wang_test.foo1()
---------------------------------
local function foo2 ()
return function ()
print('This is my test')
end --
end --local function f_2 

but When i use the module, i got that
attempt to call global 'foo2' (a nil value)
What's the problem? Thank you!
Amended on Tue 21 Feb 2012 05:15 AM by Yeedoo
USA #1
Yeedoo said:
Just the local function cant be seen from outside the module?

That's all it does, yes. The function is assigned to a new local variable instead of the globals list.
China #2
Twisol said:

The function is assigned to a new local variable instead of the globals list.


But the local function foo2 was called only in my module.
In the mushclient world,i just write thus
require'wang_test'
      wang_test.foo1()

USA #3
Oh, I see. I thought those were in separate files for some reason.

You can't use a local function (or a local anything, really) before it's been defined. A local can only be accessed from the point it's created up until its scope closes. A global can be used from anywhere, so long as it's been created first.

All you need to do is re-order your function definitions, or else pre-create the locals.

wang_test={}

local function foo2 ()
  return function ()
    print('This is my test')
  end --
end --local function f_2

function wang_test.foo1(str)
  local _f=foo2 ()
  _f()
end --function wang_test.foo1()
Amended on Tue 21 Feb 2012 06:19 AM by Twisol
China #4
Twisol said:

Oh, I see. I thought those were in separate files for some reason.

You can't use a local function (or a local anything, really) before it's been defined. A local can only be accessed from the point it's created up until its scope closes. A global can be used from anywhere, so long as it's been created first.

All you need to do is re-order your function definitions, or else pre-create the locals.


I got that! Thank you for so quick reply