Translation from http://gamedevgeek.com/tutorials/calling-c-functions-from-lua/
Call the C ++ function in Lua
The second part of my tutorial explains how to call the Lua function in C ++. In this section, we will discuss the opposite-calling the C ++ function in Lua. Since I didn't come up with a simple example to illustrate this situation, I used the average function in the Lua official document to explain it.
This tutorial covers lua5.1. Each Lua version has some very different features. The following Sample Code cannot be run in the old version of Lua. If you are still using the old version and do not want to upgrade it, don't worry. I have provided the source code download connection for the 4.0 and 5.0 tutorials at the bottom of the article. Okay, let's get started!
In this article, we will use C ++ to create a function, tell the Lua interpreter about it, and finally call it from Lua and use its results. I will also talk about the error check in the Lua program later.
Define functions
The first step is to define a function. All the C/C ++ functions called in Lua will be called using the following class of pointers:
typedef int (*lua_CFunction) (lua_State *L);
In other words, the function must use the Lua interpreter as a unique parameter and return a unique integer. Because a Lua interpreter is used as a parameter, the function can actually obtain any number of parameters from the stack. As we will see later, the returned integer is actually the number of values pushed into the stack. With this easy encapsulation, you can meet your need to call C ++ functions in Lua.
The C ++ function average () below demonstrates how to accept multiple parameters and return more than one value. Remember, this function is a function that matches the preceding typedef.
- The lua_gettop function returns the index value at the top of the stack. Because the stack in Lua is numbered from 1, the value obtained by this function is the number of parameters.
- Calculate the sum of all parameters in the for loop.
- Call lua_pushnumber () to press the parameter average value to the stack.
- Push the sum of parameters into the stack.
- Finally, the function returns 2, indicating that two return values are in the stack.
Now that the C ++ function has been defined, we must tell the Lua interpreter. This will be completed after the Lua interpreter is initialized and loaded into the database in the main function:
/* Register a function */
Lua_register (L, "average", average );
Save the file as luaavg. cpp. If you directly use C instead of C ++, change the file name to luaavg. C and delete extern "C.
# Include <stdio. h>
Extern "C "{
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}
/* Pointer to the Lua interpreter */
Lua_state * l;
Static int average (lua_state * l)
{/* Obtain the number of parameters */
Int n = lua_gettop (L );
Double sum = 0;
Int I;
/* Calculate the sum of parameters cyclically */
For (I = 1; I <= N; I ++)
{
/* Sum */
Sum + = lua_tonumber (L, I );
}
/* Press the average value */
Lua_pushnumber (L, sum/N );
/* Press and */
Lua_pushnumber (L, sum );
/* Number of returned values */
Return 2;
}
Int main (INT argc, char * argv [])
{
/* Initialize Lua */
L = lua_open ();
/* Load the basic Lua database */
Lual_openlibs (L );
/* Register a function */
Lua_register (L, "average", average );
/* Run the script */
Lual_dofile (L, "avg. Lua ");
/* Clear Lua */
Lua_close (L );
/* Pause */
Printf ("press enter to exit... ");
Getchar ();
Return 0;
}
The following is a Lua script that calls the average function with five parameters and displays two returned values. We save it as AVG. Lua:
-- call a C++ function
avg, sum = average(10, 20, 30, 40, 50)
print("The average is ", avg)
print("The sum is ", sum)
Compile
In Linux, type:
g++ luaavg.cpp -llua -llualib -o luaavg
Then, run the following command:
./luaavg
If there is no problem, the program will display the average value, and.
In Visual C ++, perform the following steps:
- Create a new blank Win32 console application project.
- Add "luatest. cpp" to your project.
- Select properties from the project menu.
- Enter "lua5.1.lib" in "add dependencies" in "input" of "connector ".
- OK.
In this case, follow F7 to build the program.
If you are using a dll library, make sure that it is stored in the application directory or where it can be found in windows. If you are using a static Connection Library, you do not need.
Error Handling
If you have read the Lua API documentation, you will see that the average function above is not correctly checked. This is done to make it easier to explain, but you should do some error detection in the real program. In the above example, we should at least check whether each parameter is a number. Add the following code to the For Loop:
if (!lua_isnumber(L, i)) {
lua_pushstring(L, "Incorrect argument to 'average'");
lua_error(L);
}
It is easy to add such a check and make debugging easier. This is important when processing programs written in two different languages.
(This article is translated by groov0v. For more information, see the source !)