Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 349
crazicrafter1 Avatar asked Dec 19 '22 00:12

crazicrafter1


2 Answers

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()
like image 82
Axnyff Avatar answered Jan 07 '23 12:01

Axnyff


@Axnyff explains what you might be trying to do. I'll explain what you did.

If you are familiar with other languages, please note that Lua does not have function declarations; It has function definitions, which are expressions that produce a function value when evaluated. Function definition statements, which you have used, are just shortcuts that implicitly include an assignment. See the manual.

When you run your code, a function definition is evaluated and the resulting function value is assigned to the variable test. Then the variable test is evaluated and its value is called as a function (and it is one).

When that function executes, three function definitions are evaluated and assigned to the variables awesome, notawesome, and notevenawesome, repsectively. It doesn't return anything.

So, when the result of calling test (nil) is indexed by the string "awesome", you get the error.

If you wanted to call the function value referred by the variable awesome, just do awesome().

like image 42
Tom Blodget Avatar answered Jan 07 '23 10:01

Tom Blodget