lua-users home
lua-l archive

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


Rob Kendrick wrote:

Yes.  Declare the local variable before assigning to it;

function F()
	local G
	G = function(value)
		if value == 10 then
			return "stop"
		end
		return G(value + 1)
	end

	print( G(1))
end


Hi Rob. That works in Lua 5.x, but not in Lua 4.

error: cannot access a variable in outer scope;
  last token read: `G' at line 7 in file `D:\test4.lua'

In order to access G, I have to write %G

function F()
	local G
	G = function(value)
		if value == 10 then
			return "stop"
		end
		return %G(value + 1)
	end

	print( G(1))
end

print( F(1) )
assert(not G, "G escaped to the global scope")

but then I get
error: attempt to call a nil value
stack traceback:
   1:  function `G' at line 7 [file `D:\test4.lua']
   2:  function `F' at line 10 [file `D:\test4.lua']
   3:  main of file `D:\test4.lua' at line 13

because when the function gets "closed", G is nil.

I found no other way round than calling G and passing itself as an argument. Is there any other way around this?

Regards,
Ignacio