How to call a function within a function?

function a()
	function b()
		return 'b'
	end
end

-- How to call function `b` from here and get the returned value? 
function a()
    return function()
        print('b')
    end
end

a()()

you can return the function and then call that function

EDIT:
fixed the code
it was broken

If the nested function is global, you can already call it from outside its scope.

local function foo()
    function bar()
        print("hello world");
    end
end

foo(); -- you need to declare `bar` first.
bar();

On second thought, I don’t think it’s a good idea to try to call a built-in function from outside the scope of the main function, because the built-in function will inherit values declared in the main function and thus these values won’t be present if I try to call the built-in function directly.

For example:

function a()
	local v = 1
	function b()
		print(v)
	end
	b()
end
a() -- will print '1'

In the example above, the variable v would not be declared if it were possible to call function b from outside function a.
In this case, the ideal would be to have no nested functions.

2 Likes
local b,c
function a()
	b = function()
		return 'b'
	end
	c = function()
		return 'c'
	end
end
a()
print(b(),c())

another method

3 Likes