How Lua calls C + + functions

Source: Internet
Author: User

The first step is to define the function. All C + + functions that are called in Lua are invoked using the following class of pointers:

typedef int (*lua_cfunction) (Lua_state *l);

In other words, the function must take 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 get any number of arguments from the stack.

In the following we will see that the returned integer is actually the number of values pressed into the stack. With such an easy package, you can meet the requirements for calling C + + functions in Lua.

The C + + function average () given below demonstrates how to accept multiple parameters and return more than one value. Remember, the function is a function that matches the above typedef:

#include"stdafx.h"#include <stdio.h>extern"C" {    #include"lua.h"#include"Lualib.h"#include"Lauxlib.h"}static int average (lua_state*m) {     /* Get the number of parameters */int n=lua_gettop (L); Double Sum=0;    int i; /* loop to find the sum of parameters */ for(i =1; I <= N; i++)    {        /* Sum */sum+=Lua_tonumber (L, i); }    /* Press Average */lua_pushnumber (L, Sum/N); /* Press in and */lua_pushnumber (L, sum); /* Returns the number of returned values */return 2;}/* Pointer to LUA interpreter */int lua_call_cpp (int argc, char*argv[]) {    /* Initialize LUA *///l =Lua_open (); Lua_state* L =lual_newstate (); /* load into LUA basic library */lual_openlibs (L); /* Register 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;}

Save the file as Lua_avg.cpp. If you are using C instead of C + +, change the file name to LUAAVG.C, and then delete the extern "C".

Code Explanation:

    1. The Lua_gettop function returns the index value at the top of the stack. Because the stack is numbered in Lua starting at 1, the value that the function obtains is the number of arguments.
    2. Calculates the sum of all parameters in the for loop.
    3. Call Lua_pushnumber () to stack the average of the parameters.
    4. The sum of the parameters is pressed into the stack.
    5. Finally, the function returns 2, indicating that there are two return values in the stack.
compiling

Under Linux, at the command line, type:

g++ Luaavg.cpp-llua-llualib-o Luaavg

Then, type the following command to run:

./luaavg

If there is no problem, the program will show the average, and.

In Visual C + + you will need to perform the following steps:

    1. Create a new empty WIN32 console Application project.
    2. Add "Lua_call_cpp.cpp" to your project.
    3. Select the Properties menu in the Project menu.
    4. Enter "Lua5.2.3.lib" in "Additional dependencies" in the input column of the connector.

At this point, press F7 to build the program.

If you're using a DLL library, make sure you put it in the application's directory or where the Windows system can find it. If you are using a static connection library, you do not need it.

Error handling

If you have read the LUA API documentation, you will see that the average function above actually has no error checking.

However, in the real program you should do some error detection. In the above example, we should at least check that each parameter is not a number.

By adding the following code to the FOR loop:

if (!lua_isnumber (L, i)) {        "incorrect argument to ' average '");           Lua_error (L);}
It's easy to add such checks, and it makes debugging easier. This is very important when dealing with programs written in two different languages;

Original: http://blog.csdn.net/Lodger007/article/details/837349

How Lua calls C + + functions

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.