简答的lua调用c++函数例子

来源:互联网 发布:涉密网络保密检查标准 编辑:程序博客网 时间:2024/06/03 06:40

[huangxw3@ubuntu]$cat main.lua

-- call a C++ function

avg, sum = average(10, 20, 30, 40, 50)

print("The average is ", avg)

print("The sum is ", sum)

=============================

[huangxw3@ubuntu]$cat test.cpp

#include <iostream>

#include <stdio.h>

 

extern "C" {

        #include "lua.h"

        #include "lualib.h"

        #include "lauxlib.h"

}

using namespace std ;

 

/* 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 */

                if (!lua_isnumber(L, i))

                {

                        lua_pushstring(L, "Incorrect argument to 'average'");

                        lua_error(L);

                }

                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[] )

{

        int error ;

        /* initialize Lua */

        L = lua_open();

        /* load Lua base libraries */

        luaopen_base(L); // 加载Lua基本库

        luaL_openlibs(L);

        /* register our function */

        lua_register(L, "average", average);

        /* run the script */

        error = luaL_dofile(L,"main.lua");

        /* cleanup Lua */

        lua_close(L);

        return 0;

}

[huangxw3@ubuntu]$ g++ test.cpp -Wall -g -fPIC -lm -ldl -llua -D USER_DEF -o test

[huangxw3@ubuntu]$./test

The average is  30

The sum is      150

原创粉丝点击