Call the Lua function (zz) in C/C ++)

Source: Internet
Author: User

Http://hi.baidu.com/darkpaladin/blog/item/00468551e6b67e2542a75bb2.html

[Convert] The Lua function is called in C/C ++.

1. Configure the Work Environment

A. Download The Lua installation packageSf_200472410155.zip

B. decompress the package for Win32. Put it in the directory of a disk, for example, C:/lua50.

C Open VC ++ 6.0 and click setting under the project to set the include directory to C:/lua50. Add Lua + Lib. lib to the Lib library, and copy Lua + Lib. dll and Lua + Lib. Lib under C:/lua50ProgramCurrent Directory

【(Wind dance movie day Description: From www.luachina.net

Using Lua in VC is similar (6.0,). If you can understand the usage of the general library, it is very easy to use Lua.
If you use a pure Lua Library (not a third-party library, such as luabind and lubplus), you may obtain three types of Lua packages.
1. source code package downloaded from www.lua.org
2. Compiled Lua library packages provided by others
3. Compiled Lua dynamic link library packages provided by others
For the first package, you only need to compile the Lua library by yourself and then use it in the same way as 2nd (in fact, the usage of the third package is only one step more)
How to compile Lua source code? Decompress the package and open the install file in the Lua Directory, which lists three projects.
Library: lapi. c lcode. c ldebug. c ldump. c lfunc. c lgc. c llex. c
Lmem. c lobject. c lopcodes. c LP *** R. C lstate. c lstring. c
Ltable. c ltm. c lundump. c LVM. c lzio. c
Lauxlib. c lbaselib. c ldblib. c liolib. c lmathlib. c loslib. c
Ltablib. c lstrlib. c loadlib. c linit. c
Interpreter: Library, Lua. c
Compiler: Library, luac. c print. c
Library, interpreter, and compiler. In fact, you only need the first library, which enables you to embed Lua into your program library. interpreteris the interpreter and also refers to lua.exe, we can regard it as a sample program using the Lua library. The third compiler is to compile Lua text into the binary format of Lua, so generally speaking, the second and third are not very important to you or are not used at all.
To compile these three libraries, you can open your ide (VC), create three projects, and add the files corresponding to each project to the corresponding project you created, then compile the file to generate your library (* .libscripts, lua.exeand luac.exe
Install also mentioned that you can use luavs. BAT to generate the file. Check the content of the batch file cd src.
CL/O2/W3/C/dlua_build_as_dll L *. c
Del Lua. OBJ luac. OBJ
Link/dll/out: lua51.dll L *. OBJ
CL/O2/W3/C/dlua_build_as_dll Lua. c
Link/out: lua.exe Lua. OBJ lua51.lib
CD ..
Environment, it is because there is no binary file directory with vcss in your environment variables and it cannot be found to cl.exe (as long as you have installed VC, this file will certainly exist) (as a program, if you do not know the environment variable, I think it's a bit sad)
Now you have the header file, library file (or dynamic link library, except the dynamic link library. DLL also provides. lib file), then the rest is how to embed Lua into your program.
First, you must # include where you use the Lua function. In fact, Lua has three headers, Lua. h, lualib. h, lauxlib. h. You can open these header files to check the Lua API (lua5.x changes some function names of lua4.x, but lua5.0.2 uses some macros to be compatible with previous function names, 5.1.1 removes these macros. You can check these header files to see that the API function names have been changed. The more common one is lauxlib. h)
PS: if you are using C ++, don't forget to use the link library. Code The generation method is C ++ or C, because C ++ will eventually change its function name (for example, lua_open is changed to lua_open @ 4). Generally, the generation method of C code is selected, because different C ++ compilers may change the function name rules very differently, as to why should I change my name and think about function overloading? Let's go to Google. If you use the C code generation method when compiling the Linked Library, do not forget to add extern "c" to # include"
Of course, if you only include the header file, a link error will certainly occur, because the code of the corresponding function cannot be found during the link, and the code is included in the static library file *. lib (or dynamic link library *. DLL). There are two methods to add the link library file to VC: one is set in the project, the other is to use
# Pragma comment (Lib, "*****. lib ")
)]
Example 1:
Main. cpp
//--------------------------------------------------
# Include <stdio. h>

Extern "C "{
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}

/* Lua interface declaration */
Lua_state * l;

Int main (INT argc, char * argv [])
{
/* Initialize Lua */
L = lua_open ();

/* Load the Lua database */
Lua_baselibopen (L );

/* Run the Lua script */
Lua_dofile (L, "test. Lua ");

/* Clear Lua */
Lua_close (L );

Return 0;
}

Script test. Lua:
Write the following code in notepad and change the extension to Lua.
-- Simple test

Print "Hello, world! "
Example 2:
First, write a Lua file in notepad.

---- Fun. Lua --------
Function add (x, y)
Return x + y
End

In the previous tutorial, calling lua_dofile () will execute the script.
In this chapter, scripts are defined as a function.
Use lua_dofile () to make this function effective in our program.

The Lua function can receive multiple parameters and return multiple types of results.

Stack is used.

To call a Lua function, we must first press the function stack.
The result of this function is determined by the parameter. Therefore, we need to call the Function
Lua_call (). After calling this function, the returned results will exist in the stack.

Procedure:
1. Use lua_getglobal () to put the Add function into the stack.
2. Press the first parameter into the stack with lua_pushnumber ()
3. Press the second parameter into the stack with lua_pushnumber ()
4. Use lua_call () to call a function.
5. Now we use lua_tonumber to retrieve the result from the stack header.
6. Finally, use lua_pop to remove the result value from the stack.

Code: luaadd. cpp
If you prefer to replace C ++ with C, rename it luaadd. C and remove
Extern "C ".
# Include <stdio. h>

Extern "C "{
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}

/* The Lua interpreter */
Lua_state * l;

Int luaadd (int x, int y)
{
Int sum;

/* The function name */
Lua_getglobal (L, "add ");

/* The first argument */
Lua_pushnumber (L, X );

/* The second argument */
Lua_pushnumber (L, y );

/* Call the function with 2
Arguments, return 1 result */
Lua_call (l, 2, 1 );

/* Get the result */
Sum = (INT) lua_tonumber (L,-1 );
Lua_pop (L, 1 );

Return sum;
}

Int main (INT argc, char * argv [])
{
Int sum;
/* Initialize Lua */
L = lua_open ();

/* Load Lua base libraries */
Lua_baselibopen (L );

/* Load the script */
Lua_dofile (L, "add. Lua ");
/* Call the Add function */
Sum = luaadd (10, 15 );

/* Print the result */
Printf ("the sum is % d \ n", sum );

/* Cleanup Lua */
Lua_close (L );

Return 0;
}
Ii. Call the C function in Lua
We use C/C ++ to create a function and tell the Lua interpreter. Then we call this function in Lua and use the return value of the function.
Define a C/C ++ function:
To enable a function in C/C ++ to be called by Lua, the function must be defined as follows:
Code: typedef int (* lua_cfunction) (lua_state * l );
That is to say, the function must use the Lua interpreter as the parameter and the return value is of the int type. Since the Lua interpreter acts as a function parameter, the function can actually obtain any number of parameters from the stack. The returned integer represents the number of values in the stack. If you want to call a C/C ++ function in Lua, it is easy to encapsulate it to meet the above requirements.
In the following example of the C ++ average function, we can clearly see how the C/C ++ function is called in Lua.
1. lua_gettop () returns the subscript index at the top of the stack. Because the subscript of the stack in Lua starts from 1, the returned value is actually the number of function parameters.
2. For Loop Calculation of the total number of parameters.
3. Average parameters are imported into the stack by calling lua_pushnumber.
4. The sum of parameters is then added to the stack.
5. Finally, the return value of the function is 2, indicating that two return values exist and have been written into the stack.
After a function is defined, we must inform the Lua compiler of its existence. This is done in the main () function after the Lua interpreter is initialized and the class library is loaded.
Save the following code as luaavg. cpp. If you prefer to use C instead of C ++, you need to save the file as luatest. C and remove the extern.
# Include <stdio. h>
Extern "C "{
# Include "Lua. H"
# Include "lualib. H"
# Include "lauxlib. H"
}
/* The Lua interpreter */
Lua_state * l;
Static int average (lua_state * l)
{
/* Get number of arguments */
Int n = lua_gettop (L );
Double sum = 0;
Int I;
/* Loop through each argument */
For (I = 1; I <= N; I ++)
{
/* Total the arguments */
Sum + = lua_tonumber (L, I );
}
/* Push the average */
Lua_pushnumber (L, sum/N );
/* Push the sum */
Lua_pushnumber (L, sum );
/* Return the number of results */
Return 2;
}
Int main (INT argc, char * argv [])
{
/* Initialize Lua */
L = lua_open ();
/* Load Lua base libraries */
Lua_baselibopen (L );
/* Register our function */
Lua_register (L, "average", average );
/* Run the script */
Lua_dofile (L, "avg. Lua ");
/* Cleanup Lua */
Lua_close (L );
Return 0;
}
The following is a simple Lua script:
-- Simple test
Code print "Hello, world! "
Make sure it runs.
Compile:
Compile the C/C ++ file saved above with your favorite compiler. The following uses Linux as an example:
Type the following command line:
Code: G ++ luatest. cpp-llua-llualib-O luatest
If there are no errors, run the program:
Code:./luatest
The program should print: Hello, world!
If you are not a Linux operating system and use a VC ++ compiler, You need:
1. Create a new Win32 console application project.
2. Add the file luatest. cpp to your project.
3. Go to the project and click the link page in settings.
4. Add Lua + Lib. lib to the object/library modules list.
5. Compile the program by F7.
Before running the program, make sure that Lua + Lib. DLL files can be found in windows, copy this file from c: \ Program Files \ Lua-5.0 to the Visual C ++ project directory, if the compilation is not wrong, now you can press Ctrl + F5 to run the program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.