一招搞定C++调用Lua代码配置文件函数(附代码)


本文摘自PHP中文网,作者php是最好的语言,侵删。

Lua文件里面是有两个函数的,然后用cpp文件调用代码,最后,还有很关键的一步,编译时,我们需要加上附加选项: g++ main.cpp -o main -llua -ldl。过程看起来简单,还是需要动手操作的。

首先你要安装lua的dev,安装很简单:

yum install lua-devel

即可,很多Linux系统自带Lua但是没有dev,有点小坑。

下面是Lua文件,里面就两个函数:

1

2

3

4

5

6

7

function add(a, b)

    return a + b

end

 

function hello()

    print("Hello Lua!!!")

end

之后是cpp文件的调用代码:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

#include<iostream>

#include<string>

 

using std::cout;

using std::endl;

using std::string;

 

//extern的意义,将下面文件当成C风格文件使用

extern "C"

{

    #include<lua.h>

    #include<lauxlib.h>

    #include<lualib.h>

}

 

int main()

{

    //创建环境

    lua_State *L = luaL_newstate();

    if(L == NULL)

    {  

        cout << "State error" << endl;

        return -1;

    }  

 

    //加载库

    luaL_openlibs(L);

    const string file = "func.lua";

    // 加载文件

    int ret = luaL_dofile(L, file.c_str());

    if(ret)

    {  

        cout << "dofile error" << endl;

        return -1;

    }  

 

    //hello函数没有参数,直接调用

    lua_getglobal(L, "hello");

    lua_pcall(L, 0, 0, 0); //三个0含义,0实参,0返回值,0自定义错误处理

 

    lua_getglobal(L, "add"); 

    //向add函数传入两个参数,这里直接传了12,传变量也ok

    lua_pushnumber(L, 1); 

    lua_pushnumber(L, 2);

    lua_pcall(L,2,1,0);       

 

    //返回值被放在-1的位置上

    cout << lua_tonumber(L, -1) << endl;

 

    lua_close(L);

 

    return 0;

}

最后,还有很关键的一步,编译时,我们需要加上附加选项:

g++ main.cpp -o main -llua -ldl

看看结果:

20180720173720341_meitu_1.jpg

大功告成

相关推荐:

记第一次lua和C互相调用的例子

lua与c语言互相调用

c++如何调用PHP的函数

以上就是一招搞定C++调用Lua代码配置文件函数(附代码)的详细内容!

相关阅读 >>

一招搞定c++调用lua代码配置文件函数(附代码)

更多相关阅读请进入《C++调用Lua函数(附代码)》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...