Search code examples
functionluanested-function

How to call a function within a function in Lua?


I have this code:

function test()
    function awesome()
        print("im awesome!")
    end

    function notawesome()
        print("im not awesome.")
    end

    function notevenawesome()
        print("im not even awesome...")
    end
end

test().notawesome()

When I run this, the console prints

15: attempt to index a nil value

What I'm trying to do is call the function notawesome() within the function test(), how would I do that?


Solution

  • Your function is not returning anything (thus returning nil). Something like this should work:

    function test()
        function awesome()
            print("im awesome!")
        end
    
        function notawesome()
            print("im not awesome.")
        end
    
        function notevenawesome()
            print("im not even awesome...")
        end
        result = {}
        result["notawesome"] = notawesome
        result["awesome"] = awesome
        result["notevenawesome"] = notevenawesome
        return result
    end
    test().notawesome()