Warning Paradox: Global '<NAME>' is only used in the enclosing function ...; consider changing it to local

If I have only this:

	function a(arg)
		if arg == 1 then b(1) end
	end

	function b(arg)
		if arg == 2 then a(2) end
	end

… no warnings are shown.

But if I enclose these functions inside another function:

local function main()
	function a(arg)
		if arg == 1 then b(1) end
	end

	function b(arg)
		if arg == 2 then a(2) end
	end
end

… I get:

W003: (2,11) Global ‘a’ is only used in the enclosing function ‘main’; consider changing it to local
W003: (3,20) Global ‘b’ is only used in the enclosing function ‘main’; consider changing it to local

If I change only local function a I get:

W003: (3,20) Global ‘b’ is only used in the enclosing function ‘main’; consider changing it to local

If I change both to local I get:

W001: (3,20) Unknown global ‘b’

How to solve this puzzle?

1 Like

It looks like you need forward-declaration. This is where you name the variables before you assign anything to them. Give this a shot and let me know if it works.

local function main()
    local a
    local b
	function a(arg)
		if arg == 1 then b(1) end
	end

	function b(arg)
		if arg == 2 then a(2) end
	end
end

Also for what it’s worth, creating functions inside of functions might not be a good idea. It’s fine if you only plan on calling main once, but if you call it multiple times then you might be creating a lot of extra functions for nothing. Make of that what you will.

3 Likes

Define b before a, since you’re calling it within the function named a.