Reputation: 323
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?
Upvotes: 5
Views: 6274
Reputation: 7036
If you want to achieve that instead to use the main function you can use an object:
test = {
awesome = (function()
return 'im awesome!'
end),
notawesome = (function()
return 'im not awesome.'
end),
notevenawesome = (function()
return 'im not even awesome...'
end)
}
To call your functions use this:
print(test.notawesome()) --> im not awesome.
Upvotes: 0
Reputation: 9944
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()
Upvotes: 7
Reputation: 20772
@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()
.
Upvotes: 5