[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

Logo

北京人形旗下天工造物具身智能开源社区,聚焦具身天工与慧思开物两大平台

更多推荐