C language calls Lua Function
I remember when I went to school, in junior high school English, surfing the internet was called surfing the internet, and surfing the internet was called Chinese. In that period, people often called the Internet a cyberspace. Now that I have worked, I have spent a lot of time on Weibo, zhihu, and QQ. These fragmented readings make it easy to read and obtain superficial information. However, they are time-consuming black holes, and time flies at 1 minute 1 second. At the end of the year, I will tell you how many questions I have answered, I read as much text as A Dream of Red Mansions. It's just that when you get down and think about it, these superficial readings don't bring you deep, systematic knowledge. In your time line, two adjacent messages are often inaccessible. In addition, you may also check if there are any updates from time to time, and look forward to a bright display of your information. The result is often lost. The information on the screen is always rolling. It is so lively that everyone is enjoying the carnival, but my heart is so empty and lonely.
In the lua API, the procedure for calling a function is simple: 1. Press the function you want to call and use lua_getglobal. 2. Press the call parameter. 3. Use lua_pcall4. The result is displayed from the stack.
For example, suppose you have a lua function: function f (x, y)
Return (x ^ 2 * math. sin (y)/(1-x)
End
Then, we can define a c function to encapsulate this call:/* call a function 'F' defined in Lua */
Double f (double x, double y ){
Double z; lua_getglobal (L, "f"); lua_pushnumber (L, x); lua_pushnumber (L, y);/* do the call (2 arguments, 1 result) */if (lua_pcall (L, 2, 1, 0 )! = 0) error (L, "error running function 'F': % s", lua_tostring (L,-1 ));
If (! Lua_isnumber (L,-1) error (L, "function 'F' must return a number"); z = lua_tonumber (L,-1); lua_pop (L, 1); return z;
}
Lua_pcall pops up the functions and parameters before the result is pushed. If multiple results are returned, the first one is pushed first. If lua_pcall fails, a non-zero value is returned. (End)