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?
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()
@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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With