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

108 views Asked by At

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.."

2

There are 2 answers

3
prmottajr On BEST ANSWER

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.

0
Oliver On

A function is a first class entity in Lua so you can set a variable or table field to be a function:

function f() end -- do nothing
a = f

Then a refers to f, you can do to/with a as you can with f, such as calling it:

a() -- calls f()

Then you can set a to be another function, and call it:

function g(x) end
a = g -- a is now function g
a(1) -- calls g(1)

Everything in the above examples can be done with table fields too:

tt = { 
    f = function() print('hi') end, 
    g = function(x) print(x) end
}
tt.f() -- calls tt.f function
a = tt.f
a() -- calls tt.f
tt.h = a
tt.h() -- calls tt.f
tt.f = print -- now tt.f is print function
tt.f('bye') -- prints 'bye'