Search code examples
luafunction-declaration

Lua - Can a function be called from a table value and its value returned


I'm asking for help regarding this matter as I cannot quite get the grasp of if it is possible let alone if I am just doing it wrong.

my = {
    Question = AskQuestion()
}

function AskQuestion()
    return "What do you want to know?"
end

My intention is to do, print(my.Question) and have it return "What do you want to know?", So far I have just ran into headaches and errors trying to get this to work.

Further on should this be solved I can presume rather than figuring it out myself I may as well ask in addition. What about passing on a value to the function.

my = {
    Answer = MyAnswer(vAnswer)
}

function MyAnswer(vAnswer)
    if vAnswer == "42" then return "Life.." end
end

So here I would want to do, print(my.Answer(42)) and it return "Life.."


Solution

  • Just invert your declaration:

    function AskQuestion()
        return "What do you want to know?"
    end
    
    my = {
         Question = AskQuestion()
    }
    

    Since Lua is interpreted you have to have everything defined before you can use.

    When setting a variable you don't need to pass the (vAnswer) because it is not a defition, it is just a existing-function usage, so change to:

    function MyAnswer(vAnswer)
        if vAnswer == "42" then return "Life.." end
    end
    
    my = {
        Answer = MyAnswer
    }
    

    I am assuming here that you are using a different my table, but you should get the picture.