Reputation: 3338
A simple question: How do I set the prototype for a function that has not been implemented yet?
I just want to do this, cause I'm referring to a function that does not exist(yet). In C, we would do something like this:
int foo(int bar);
int myint = foo(1);
int foo(int bar)
{
return bar;
}
How do I do this in Lua (with corona)?
Upvotes: 5
Views: 4543
Reputation: 29000
You can't. Amber's comment is correct.
Lua doesn't have a concept of type signatures or function prototypes.
The type of foo
is that of the object it contains, which is dynamic, changing at runtime. It could be function
in one instant, and string
or integer
or something else in the next.
Conceptually Lua doesn't have a compilation step like C. When you say "run this code" it starts starts executing instructions at the top and works it's way down. In practice, Lua first compiles your code into bytecode before executing it, but the compiler won't balk at something like this:
greet()
function greet()
print('Hello.')
end
Because the value contained in greet
is determined at runtime. It's only when you actually try to call (i.e. invoke like a function) the value in greet
, at runtime, that Lua will discover that it doesn't contain a callable value (a function or a table/userdata with a metatable containing a __call
member) and you'll get a runtime error: "attempt to call global 'greet' (a nil value)". Where "nil value" is whatever value greet
contained at the time the call was attempted. In our case, it was nil
.
So you will have to make sure that that the code that creates a function and assigns it to foo
is called before you attempt to call foo
.
It might help if you recognize that this:
local myint = foo(1)
function foo(bar)
return bar
end
Is syntax sugar for this:
local myint = foo(1)
foo = function(bar)
return bar
end
foo
is being assigned a function value. That has to happen before you attempt to call that function.
main
function to begin the "execution time".
For example:
function main()
greet()
end
function greet()
print('Hello.')
end
main()
As greet
has been declared in _G
, main
can access it.
Upvotes: 8