Alas, the mood is a bit bad today, I have less to say some long-winded words.
(Narrator: Great ... )
Previous Chapter Portal: http://www.jb51.net/article/55096.htm
After the introduction of the previous chapters, I believe that the LUA stack has been more familiar with, if not very familiar with the friends, the proposal to read a few more times before the tutorial, or more than a few times code.
So, if you're already familiar with the LUA stack, the next thing is easy.
Today, let's look at how C + + invokes the LUA function, and first look at what the Lua file looks like now:
Copy Code code as follows:
--Hellolua.lua file
myname = "Beauty Girl"
hellotable = {name = "Mutou", IQ = 125}
function Helloadd (NUM1, num2)
Return (NUM1 + num2)
End
We see a helloadd function, so now we're going to call this function in C + +.
(Narrator: The Getglobal must be used again, every time it ~! = =)
Directly on the code:
Copy Code code as follows:
/* C + + Call Lua's function * *
void Hellolua::d Emo3 () {
lua_state* PL = Lua_open ();
Luaopen_base (PL);
/* Execute script/*
Lual_dofile (PL, "Hellolua.lua");
* * Put the Helloadd function object on the stack.
Lua_getglobal (PL, "Helloadd");
/* Put the parameters required by the function into the stack * *
Lua_pushnumber (PL, 10);
Lua_pushnumber (PL, 5);
/*
Executes the function, the first parameter represents the number of arguments for the function, and the second parameter represents the number of return values of the function.
Lua first goes to the stack to fetch the parameters, then takes out the function object, and starts the function
*/
Lua_call (PL, 2, 1);
int iresult = Lua_tonumber (PL,-1);
Cclog ("Iresult =%d", iresult);
}
Briefly explain the steps:
1 Execute script (narrator: I knew you would say nonsense ...) )
2 Put the Helloadd function on the stack: Lua_getglobal (PL, "Helloadd"). (Narrator: See, I knew ~!. )
3 Helloadd has 2 parameters, we have to pass the parameters to Lua, so 2 parameters are put in the stack.
4 Steps 2nd and 3rd have put the data needed for the function into the stack, and then just tell LUA to fetch the data from the stack and execute the function ~! Call Lua_call, the comment is very detailed, here is not repeated.
(Narrator: Too simple point, anyway, no matter what to do, throw things into the stack, and then take things from the stack, OK ~ You can roll, after the tutorial I write, you are responsible for the Spit slot ~)
Come, we ignore the narration, the tutorial or something I write better, mainly, spit groove this work, not in line with my identity ~
(Narrator: ...) I have a feeling of being hit.
This is the end of this chapter, is it simple? ~
In the next chapter we introduce functions that call C + + in Lua ~!
(Narrator: This I like ~! )