Lua调用c++例子

[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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值