Lua和C++交互总结(很详细)

2023-11-20

出处:http://blog.csdn.net/shun_fzll/article/details/39120965

一.lua堆栈


要理解lua和c++交互,首先要理解lua堆栈。


简单来说,Lua和C/c++语言通信的主要方法是一个无处不在的虚拟栈。栈的特点是先进后出。

在lua中,lua堆栈就是一个struct,堆栈索引的方式可是是正数也可以是负数,区别是:正数索引1永远表示栈底,负数索引-1永远表示栈顶。如图:



二.堆栈的操作


因为lua与c/c++是通过栈来通信,lua提供了C API对栈进行操作。

我们先来看一个最简单的例子:


[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建一个state  
  14.     lua_State *L = luaL_newstate();  
  15.       
  16.     //2.入栈操作  
  17.     lua_pushstring(L, "I am so cool~");   
  18.     lua_pushnumber(L,20);  
  19.   
  20.     //3.取值操作  
  21.     if( lua_isstring(L,1)){             //判断是否可以转为string  
  22.         cout<<lua_tostring(L,1)<<endl;  //转为string并返回  
  23.     }  
  24.     if( lua_isnumber(L,2)){  
  25.         cout<<lua_tonumber(L,2)<<endl;  
  26.     }  
  27.   
  28.     //4.关闭state  
  29.     lua_close(L);  
  30.     return ;  
  31. }  
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建一个state  
  14.     lua_State *L = luaL_newstate();  
  15.       
  16.     //2.入栈操作  
  17.     lua_pushstring(L, "I am so cool~");   
  18.     lua_pushnumber(L,20);  
  19.   
  20.     //3.取值操作  
  21.     if( lua_isstring(L,1)){             //判断是否可以转为string  
  22.         cout<<lua_tostring(L,1)<<endl;  //转为string并返回  
  23.     }  
  24.     if( lua_isnumber(L,2)){  
  25.         cout<<lua_tonumber(L,2)<<endl;  
  26.     }  
  27.   
  28.     //4.关闭state  
  29.     lua_close(L);  
  30.     return ;  
  31. }  


可以简单理解为luaL_newstate返回一个指向堆栈的指针,其它看注释应该能懂了吧。

如果对extern "C"不熟悉的可以点击这里:http://blog.csdn.net/shun_fzll/article/details/39078971


其他一些栈操作:


[cpp]  view plain copy
  1. int   lua_gettop (lua_State *L);            //返回栈顶索引(即栈长度)  
  2. void  lua_settop (lua_State *L, int idx);   //                
  3. void  lua_pushvalue (lua_State *L, int idx);//将idx索引上的值的副本压入栈顶  
  4. void  lua_remove (lua_State *L, int idx);   //移除idx索引上的值  
  5. void  lua_insert (lua_State *L, int idx);   //弹出栈顶元素,并插入索引idx位置  
  6. void  lua_replace (lua_State *L, int idx);  //弹出栈顶元素,并替换索引idx位置的值  
[cpp]  view plain  copy
  1. int   lua_gettop (lua_State *L);            //返回栈顶索引(即栈长度)  
  2. void  lua_settop (lua_State *L, int idx);   //                
  3. void  lua_pushvalue (lua_State *L, int idx);//将idx索引上的值的副本压入栈顶  
  4. void  lua_remove (lua_State *L, int idx);   //移除idx索引上的值  
  5. void  lua_insert (lua_State *L, int idx);   //弹出栈顶元素,并插入索引idx位置  
  6. void  lua_replace (lua_State *L, int idx);  //弹出栈顶元素,并替换索引idx位置的值  


lua_settop将栈顶设置为一个指定的位置,即修改栈中元素的数量。如果值比原栈顶高,则高的部分nil补足,如果值比原栈低,则原栈高出的部分舍弃。

所以可以用lua_settop(0)来清空栈。


三.c++调用lua


我们经常可以使用lua文件来作配置文件。类似ini,xml等文件配置信息。
现在我们来使用c++来读取lua文件中的变量,table,函数。


现在有这样一个hello.lua 文件:


[cpp]  view plain copy
  1. str = "I am so cool"  
  2. tbl = {name = "shun", id = 20114442}  
  3. function add(a,b)  
  4.     return a + b  
  5. end  
[cpp]  view plain  copy
  1. str = "I am so cool"  
  2. tbl = {name = "shun", id = 20114442}  
  3. function add(a,b)  
  4.     return a + b  
  5. end  


我们写一个test.cpp来读取它:


[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建Lua状态  
  14.     lua_State *L = luaL_newstate();  
  15.     if (L == NULL)  
  16.     {  
  17.         return ;  
  18.     }  
  19.   
  20.     //2.加载lua文件  
  21.     int bRet = luaL_loadfile(L,"hello.lua");  
  22.     if(bRet)  
  23.     {  
  24.         cout<<"load file error"<<endl;  
  25.         return ;  
  26.     }  
  27.   
  28.     //3.运行lua文件  
  29.     bRet = lua_pcall(L,0,0,0);  
  30.     if(bRet)  
  31.     {  
  32.         cout<<"pcall error"<<endl;  
  33.         return ;  
  34.     }  
  35.   
  36.     //4.读取变量  
  37.     lua_getglobal(L,"str");  
  38.     string str = lua_tostring(L,-1);  
  39.     cout<<"str = "<<str.c_str()<<endl;        //str = I am so cool~  
  40.   
  41.     //5.读取table  
  42.     lua_getglobal(L,"tbl");   
  43.     lua_getfield(L,-1,"name");  
  44.     str = lua_tostring(L,-1);  
  45.     cout<<"tbl:name = "<<str.c_str()<<endl; //tbl:name = shun  
  46.   
  47.     //6.读取函数  
  48.     lua_getglobal(L, "add");        // 获取函数,压入栈中  
  49.     lua_pushnumber(L, 10);          // 压入第一个参数  
  50.     lua_pushnumber(L, 20);          // 压入第二个参数  
  51.     int iRet= lua_pcall(L, 2, 1, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。  
  52.     if (iRet)                       // 调用出错  
  53.     {  
  54.         const char *pErrorMsg = lua_tostring(L, -1);  
  55.         cout << pErrorMsg << endl;  
  56.         lua_close(L);  
  57.         return ;  
  58.     }  
  59.     if (lua_isnumber(L, -1))        //取值输出  
  60.     {  
  61.         double fValue = lua_tonumber(L, -1);  
  62.         cout << "Result is " << fValue << endl;  
  63.     }  
  64.   
  65.     //至此,栈中的情况是:  
  66.     //=================== 栈顶 ===================   
  67.     //  索引  类型      值  
  68.     //   4   int:      30   
  69.     //   3   string:   shun   
  70.     //   2   table:     tbl  
  71.     //   1   string:    I am so cool~  
  72.     //=================== 栈底 ===================   
  73.   
  74.     //7.关闭state  
  75.     lua_close(L);  
  76.     return ;  
  77. }  
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建Lua状态  
  14.     lua_State *L = luaL_newstate();  
  15.     if (L == NULL)  
  16.     {  
  17.         return ;  
  18.     }  
  19.   
  20.     //2.加载lua文件  
  21.     int bRet = luaL_loadfile(L,"hello.lua");  
  22.     if(bRet)  
  23.     {  
  24.         cout<<"load file error"<<endl;  
  25.         return ;  
  26.     }  
  27.   
  28.     //3.运行lua文件  
  29.     bRet = lua_pcall(L,0,0,0);  
  30.     if(bRet)  
  31.     {  
  32.         cout<<"pcall error"<<endl;  
  33.         return ;  
  34.     }  
  35.   
  36.     //4.读取变量  
  37.     lua_getglobal(L,"str");  
  38.     string str = lua_tostring(L,-1);  
  39.     cout<<"str = "<<str.c_str()<<endl;        //str = I am so cool~  
  40.   
  41.     //5.读取table  
  42.     lua_getglobal(L,"tbl");   
  43.     lua_getfield(L,-1,"name");  
  44.     str = lua_tostring(L,-1);  
  45.     cout<<"tbl:name = "<<str.c_str()<<endl; //tbl:name = shun  
  46.   
  47.     //6.读取函数  
  48.     lua_getglobal(L, "add");        // 获取函数,压入栈中  
  49.     lua_pushnumber(L, 10);          // 压入第一个参数  
  50.     lua_pushnumber(L, 20);          // 压入第二个参数  
  51.     int iRet= lua_pcall(L, 2, 1, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。  
  52.     if (iRet)                       // 调用出错  
  53.     {  
  54.         const char *pErrorMsg = lua_tostring(L, -1);  
  55.         cout << pErrorMsg << endl;  
  56.         lua_close(L);  
  57.         return ;  
  58.     }  
  59.     if (lua_isnumber(L, -1))        //取值输出  
  60.     {  
  61.         double fValue = lua_tonumber(L, -1);  
  62.         cout << "Result is " << fValue << endl;  
  63.     }  
  64.   
  65.     //至此,栈中的情况是:  
  66.     //=================== 栈顶 ===================   
  67.     //  索引  类型      值  
  68.     //   4   int:      30   
  69.     //   3   string:   shun   
  70.     //   2   table:     tbl  
  71.     //   1   string:    I am so cool~  
  72.     //=================== 栈底 ===================   
  73.   
  74.     //7.关闭state  
  75.     lua_close(L);  
  76.     return ;  
  77. }  


知道怎么读取后,我们来看下如何修改上面代码中table的值:


[cpp]  view plain copy
  1. // 将需要设置的值设置到栈中  
  2. lua_pushstring(L, "我是一个大帅锅~");  
  3. // 将这个值设置到table中(此时tbl在栈的位置为2)  
  4. lua_setfield(L, 2, "name");  
[cpp]  view plain  copy
  1. // 将需要设置的值设置到栈中  
  2. lua_pushstring(L, "我是一个大帅锅~");  
  3. // 将这个值设置到table中(此时tbl在栈的位置为2)  
  4. lua_setfield(L, 2, "name");  


我们还可以新建一个table:


[cpp]  view plain copy
  1. // 创建一个新的table,并压入栈  
  2. lua_newtable(L);  
  3. // 往table中设置值  
  4. lua_pushstring(L, "Give me a girl friend !"); //将值压入栈  
  5. lua_setfield(L, -2, "str"); //将值设置到table中,并将Give me a girl friend 出栈  
[cpp]  view plain  copy
  1. // 创建一个新的table,并压入栈  
  2. lua_newtable(L);  
  3. // 往table中设置值  
  4. lua_pushstring(L, "Give me a girl friend !"); //将值压入栈  
  5. lua_setfield(L, -2, "str"); //将值设置到table中,并将Give me a girl friend 出栈  


需要注意的是:堆栈操作是基于栈顶的,就是说它只会去操作栈顶的值。


举个比较简单的例子,函数调用流程是先将函数入栈,参数入栈,然后用lua_pcall调用函数,此时栈顶为参数,栈底为函数,所以栈过程大致会是:参数出栈->保存参数->参数出栈->保存参数->函数出栈->调用函数->返回结果入栈。

类似的还有lua_setfield,设置一个表的值,肯定要先将值出栈,保存,再去找表的位置。


再不理解可看如下例子:

[cpp]  view plain copy
  1. lua_getglobal(L, "add");        // 获取函数,压入栈中  
  2. lua_pushnumber(L, 10);          // 压入第一个参数  
  3. lua_pushnumber(L, 20);          // 压入第二个参数  
  4. int iRet= lua_pcall(L, 2, 1, 0);// 将2个参数出栈,函数出栈,压入函数返回结果  
  5.   
  6. lua_pushstring(L, "我是一个大帅锅~");  //   
  7. lua_setfield(L, 2, "name");             // 会将"我是一个大帅锅~"出栈  
[cpp]  view plain  copy
  1. lua_getglobal(L, "add");        // 获取函数,压入栈中  
  2. lua_pushnumber(L, 10);          // 压入第一个参数  
  3. lua_pushnumber(L, 20);          // 压入第二个参数  
  4. int iRet= lua_pcall(L, 2, 1, 0);// 将2个参数出栈,函数出栈,压入函数返回结果  
  5.   
  6. lua_pushstring(L, "我是一个大帅锅~");  //   
  7. lua_setfield(L, 2, "name");             // 会将"我是一个大帅锅~"出栈  

另外补充一下:

lua_getglobal(L,"var")会执行两步操作:1.将var放入栈中,2.由lua去寻找变量var的值,并将变量var的值返回栈顶(替换var)。
lua_getfield(L,-1,"name") 的作用等价于 lua_pushstring(L,"name") + lua_gettable(L,-2)


四.lua调用c++


我们分三个方法实现它。


方法一:直接将模块写入lua源码中


在lua中调用c/c++,我们可以将函数写lua.c中,然后重新编译lua文件。
也许你用的是lua for windows集成环境,没关系,不会编译lua可以参考这篇:http://blog.csdn.net/snlscript/article/details/15533373


编译好后是这样子的:(如图)




然后我们可以在lua.c中加入我们自己的函数。函数要遵循规范(可在lua.h中查看)如下:


[cpp]  view plain copy
  1. typedef int (*lua_CFunction) (lua_State *L);  
[cpp]  view plain  copy
  1. typedef int (*lua_CFunction) (lua_State *L);  


换句话说,所有的函数必须接收一个lua_State作为参数,同时返回一个整数值。因为这个函数使用Lua栈作为参数,所以它可以从栈里面读取任意数量和任意类型的参数。而这个函数的返回值则表示函数返回时有多少返回值被压入Lua栈。(因为Lua的函数是可以返回多个值的)


然后我们在lua.c中加入如下函数:


[cpp]  view plain copy
  1. // This is my function  
  2. static int getTwoVar(lua_State *L)  
  3. {  
  4.     // 向函数栈中压入2个值  
  5.     lua_pushnumber(L, 10);  
  6.     lua_pushstring(L,"hello");  
  7.   
  8.     return 2;  
  9. }  
[cpp]  view plain  copy
  1. // This is my function  
  2. static int getTwoVar(lua_State *L)  
  3. {  
  4.     // 向函数栈中压入2个值  
  5.     lua_pushnumber(L, 10);  
  6.     lua_pushstring(L,"hello");  
  7.   
  8.     return 2;  
  9. }  


在pmain函数中,luaL_openlibs函数后加入以下代码:


[cpp]  view plain copy
  1. //注册函数  
  2. lua_pushcfunction(L, getTwoVar); //将函数放入栈中  
  3. lua_setglobal(L, "getTwoVar");   //设置lua全局变量getTwoVar  
[cpp]  view plain  copy
  1. //注册函数  
  2. lua_pushcfunction(L, getTwoVar); //将函数放入栈中  
  3. lua_setglobal(L, "getTwoVar");   //设置lua全局变量getTwoVar  

通过查找lua.h


[cpp]  view plain copy
  1. /#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))  
[cpp]  view plain  copy
  1. /#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))  


我们发现之前的注册函数可以这样子写:


[cpp]  view plain copy
  1. lua_register(L,"getTwoVar",getTwoVar);  
[cpp]  view plain  copy
  1. lua_register(L,"getTwoVar",getTwoVar);  


运行,结果如图:




当然,一般我们不建议去修改别人的代码,更倾向于自己编写独立的c/c++模块,供lua调用,下面来讲讲如何实现。


方法二:使用静态依赖的方式


1.新建一个空的win32控制台工程,记得在vc++目录中,把lua中的头文件和lib文件的目录包含进来,然后->链接器->附加依赖项->将lua51.lib和lua5.1.lib也包含进来。


2.在目录下新建一个avg.lua如下:


[cpp]  view plain copy
  1. avg, sum = average(10, 20, 30, 40, 50)  
  2. print("The average is ", avg)  
  3. print("The sum is ", sum)  
[cpp]  view plain  copy
  1. avg, sum = average(10, 20, 30, 40, 50)  
  2. print("The average is ", avg)  
  3. print("The sum is ", sum)  


3.新建test.cpp如下:


[cpp]  view plain copy
  1. #include <stdio.h>  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. /* 指向Lua解释器的指针 */  
  10. lua_State* L;  
  11. static int average(lua_State *L)  
  12. {  
  13.     /* 得到参数个数 */  
  14.     int n = lua_gettop(L);  
  15.     double sum = 0;  
  16.     int i;  
  17.   
  18.     /* 循环求参数之和 */  
  19.     for (i = 1; i <= n; i++)  
  20.     {  
  21.         /* 求和 */  
  22.         sum += lua_tonumber(L, i);  
  23.     }  
  24.     /* 压入平均值 */  
  25.     lua_pushnumber(L, sum / n);  
  26.     /* 压入和 */  
  27.     lua_pushnumber(L, sum);  
  28.     /* 返回返回值的个数 */  
  29.     return 2;  
  30. }  
  31.   
  32. int main ( int argc, char *argv[] )  
  33. {  
  34.     /* 初始化Lua */  
  35.     L = lua_open();  
  36.   
  37.     /* 载入Lua基本库 */  
  38.     luaL_openlibs(L);  
  39.     /* 注册函数 */  
  40.     lua_register(L, "average", average);  
  41.     /* 运行脚本 */  
  42.     luaL_dofile(L, "avg.lua");  
  43.     /* 清除Lua */  
  44.     lua_close(L);  
  45.   
  46.     /* 暂停 */  
  47.     printf( "Press enter to exit…" );  
  48.     getchar();  
  49.     return 0;  
  50. }  
[cpp]  view plain  copy
  1. #include <stdio.h>  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. /* 指向Lua解释器的指针 */  
  10. lua_State* L;  
  11. static int average(lua_State *L)  
  12. {  
  13.     /* 得到参数个数 */  
  14.     int n = lua_gettop(L);  
  15.     double sum = 0;  
  16.     int i;  
  17.   
  18.     /* 循环求参数之和 */  
  19.     for (i = 1; i <= n; i++)  
  20.     {  
  21.         /* 求和 */  
  22.         sum += lua_tonumber(L, i);  
  23.     }  
  24.     /* 压入平均值 */  
  25.     lua_pushnumber(L, sum / n);  
  26.     /* 压入和 */  
  27.     lua_pushnumber(L, sum);  
  28.     /* 返回返回值的个数 */  
  29.     return 2;  
  30. }  
  31.   
  32. int main ( int argc, char *argv[] )  
  33. {  
  34.     /* 初始化Lua */  
  35.     L = lua_open();  
  36.   
  37.     /* 载入Lua基本库 */  
  38.     luaL_openlibs(L);  
  39.     /* 注册函数 */  
  40.     lua_register(L, "average", average);  
  41.     /* 运行脚本 */  
  42.     luaL_dofile(L, "avg.lua");  
  43.     /* 清除Lua */  
  44.     lua_close(L);  
  45.   
  46.     /* 暂停 */  
  47.     printf( "Press enter to exit…" );  
  48.     getchar();  
  49.     return 0;  
  50. }  


执行一下,我们可以得到结果:



大概顺序就是:我们在c++中写一个模块函数,将函数注册到lua解释器中,然后由c++去执行我们的lua文件,然后在lua中调用刚刚注册的函数。


看上去很别扭啊有木有。。。接下来介绍一下dll调用方式。


方法三:使用dll动态链接的方式


我们先新建一个dll工程,工程名为mLualib。(因此最后导出的dll也为mLualib.dll)


然后编写我们的c++模块,以函数为例,我们先新建一个.h文件和.cpp文件。


h文件如下:(如果你不是很能明白头文件的内容,点击这里:http://blog.csdn.net/shun_fzll/article/details/39078971。)


[cpp]  view plain copy
  1. #pragma once  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. #ifdef LUA_EXPORTS  
  10. #define LUA_API __declspec(dllexport)  
  11. #else  
  12. #define LUA_API __declspec(dllimport)  
  13. #endif  
  14.   
  15. extern "C" LUA_API int luaopen_mLualib(lua_State *L);//定义导出函数  
[cpp]  view plain  copy
  1. #pragma once  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. #ifdef LUA_EXPORTS  
  10. #define LUA_API __declspec(dllexport)  
  11. #else  
  12. #define LUA_API __declspec(dllimport)  
  13. #endif  
  14.   
  15. extern "C" LUA_API int luaopen_mLualib(lua_State *L);//定义导出函数  

.cpp文件如下:


[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include "mLualib.h"  
  3.   
  4. static int averageFunc(lua_State *L)  
  5. {  
  6.     int n = lua_gettop(L);  
  7.     double sum = 0;  
  8.     int i;  
  9.   
  10.     /* 循环求参数之和 */  
  11.     for (i = 1; i <= n; i++)  
  12.         sum += lua_tonumber(L, i);  
  13.   
  14.     lua_pushnumber(L, sum / n);     //压入平均值  
  15.     lua_pushnumber(L, sum);         //压入和  
  16.   
  17.     return 2;                       //返回两个结果  
  18. }  
  19.   
  20. static int sayHelloFunc(lua_State* L)  
  21. {  
  22.     printf("hello world!");  
  23.     return 0;  
  24. }  
  25.   
  26. static const struct luaL_Reg myLib[] =   
  27. {  
  28.     {"average", averageFunc},  
  29.     {"sayHello", sayHelloFunc},  
  30.     {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
  31. };  
  32.   
  33. int luaopen_mLualib(lua_State *L)  
  34. {  
  35.     luaL_register(L, "ss", myLib);  
  36.     return 1;       // 把myLib表压入了栈中,所以就需要返回1  
  37. }  
[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include "mLualib.h"  
  3.   
  4. static int averageFunc(lua_State *L)  
  5. {  
  6.     int n = lua_gettop(L);  
  7.     double sum = 0;  
  8.     int i;  
  9.   
  10.     /* 循环求参数之和 */  
  11.     for (i = 1; i <= n; i++)  
  12.         sum += lua_tonumber(L, i);  
  13.   
  14.     lua_pushnumber(L, sum / n);     //压入平均值  
  15.     lua_pushnumber(L, sum);         //压入和  
  16.   
  17.     return 2;                       //返回两个结果  
  18. }  
  19.   
  20. static int sayHelloFunc(lua_State* L)  
  21. {  
  22.     printf("hello world!");  
  23.     return 0;  
  24. }  
  25.   
  26. static const struct luaL_Reg myLib[] =   
  27. {  
  28.     {"average", averageFunc},  
  29.     {"sayHello", sayHelloFunc},  
  30.     {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
  31. };  
  32.   
  33. int luaopen_mLualib(lua_State *L)  
  34. {  
  35.     luaL_register(L, "ss", myLib);  
  36.     return 1;       // 把myLib表压入了栈中,所以就需要返回1  
  37. }  

不理解没关系,我们先编译它,然后新建一个lua文件,在lua中我们这样子来调用:(调用之前记得把dll文件复制到lua文件目录下)


[cpp]  view plain copy
  1. require "mLualib"  
  2. local ave,sum = ss.average(1,2,3,4,5)//参数对应堆栈中的数据  
  3. print(ave,sum)  -- 3 15  
  4. ss.sayHello()   -- hello world!  
[cpp]  view plain  copy
  1. require "mLualib"  
  2. local ave,sum = ss.average(1,2,3,4,5)//参数对应堆栈中的数据  
  3. print(ave,sum)  -- 3 15  
  4. ss.sayHello()   -- hello world!  

成功调用了有木有?我们看到了输出信息。(木有成功你留言,我教你!)

至此都发生了什么呢?梳理一下:

1.我们编写了averageFunc求平均值和sayHelloFunc函数,
2.然后把函数封装myLib数组里面,类型必须是luaL_Reg
3.由luaopen_mLualib函数导出并在lua中注册这两个函数。

那么为什么要这样子写呢?实际上当我们在lua中:


[cpp]  view plain copy
  1. require "mLualib"  
[cpp]  view plain  copy
  1. require "mLualib"  


这样子写的时候,lua会这么干:


[cpp]  view plain copy
  1. local path = "mLualib.dll"    
  2. local f = package.loadlib(path,"luaopen_mLualib")   -- 返回luaopen_mLualib函数  
  3. f()                                                 -- 执行  
[cpp]  view plain  copy
  1. local path = "mLualib.dll"    
  2. local f = package.loadlib(path,"luaopen_mLualib")   -- 返回luaopen_mLualib函数  
  3. f()                                                 -- 执行  

所以当我们在编写一个这样的模块的时候,编写luaopen_xxx导出函数的时候,xxx最好是和项目名一样(因为项目名和dll一样)

需要注意的是:函数参数里的lua_State是私有的,每一个函数都有自己的栈。当一个c/c++函数把返回值压入Lua栈以后,该栈会自动被清空。


五.总结 


这篇文章花了好几天才整理的,最后总结一下就是:

lua和c++是通过一个虚拟栈来交互的。

c++调用lua实际上是:由c++先把数据放入栈中,由lua去栈中取数据,然后返回数据对应的值到栈顶,再由栈顶返回c++。

lua调c++也一样:先编写自己的c模块,然后注册函数到lua解释器中,然后由lua去调用这个模块的函数。


转载请注明出处:http://blog.csdn.net/shun_fzll/article/details/39120965 出处:http://blog.csdn.net/shun_fzll/article/details/39120965

一.lua堆栈


要理解lua和c++交互,首先要理解lua堆栈。


简单来说,Lua和C/c++语言通信的主要方法是一个无处不在的虚拟栈。栈的特点是先进后出。

在lua中,lua堆栈就是一个struct,堆栈索引的方式可是是正数也可以是负数,区别是:正数索引1永远表示栈底,负数索引-1永远表示栈顶。如图:



二.堆栈的操作


因为lua与c/c++是通过栈来通信,lua提供了C API对栈进行操作。

我们先来看一个最简单的例子:


[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建一个state  
  14.     lua_State *L = luaL_newstate();  
  15.       
  16.     //2.入栈操作  
  17.     lua_pushstring(L, "I am so cool~");   
  18.     lua_pushnumber(L,20);  
  19.   
  20.     //3.取值操作  
  21.     if( lua_isstring(L,1)){             //判断是否可以转为string  
  22.         cout<<lua_tostring(L,1)<<endl;  //转为string并返回  
  23.     }  
  24.     if( lua_isnumber(L,2)){  
  25.         cout<<lua_tonumber(L,2)<<endl;  
  26.     }  
  27.   
  28.     //4.关闭state  
  29.     lua_close(L);  
  30.     return ;  
  31. }  
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建一个state  
  14.     lua_State *L = luaL_newstate();  
  15.       
  16.     //2.入栈操作  
  17.     lua_pushstring(L, "I am so cool~");   
  18.     lua_pushnumber(L,20);  
  19.   
  20.     //3.取值操作  
  21.     if( lua_isstring(L,1)){             //判断是否可以转为string  
  22.         cout<<lua_tostring(L,1)<<endl;  //转为string并返回  
  23.     }  
  24.     if( lua_isnumber(L,2)){  
  25.         cout<<lua_tonumber(L,2)<<endl;  
  26.     }  
  27.   
  28.     //4.关闭state  
  29.     lua_close(L);  
  30.     return ;  
  31. }  


可以简单理解为luaL_newstate返回一个指向堆栈的指针,其它看注释应该能懂了吧。

如果对extern "C"不熟悉的可以点击这里:http://blog.csdn.net/shun_fzll/article/details/39078971


其他一些栈操作:


[cpp]  view plain copy
  1. int   lua_gettop (lua_State *L);            //返回栈顶索引(即栈长度)  
  2. void  lua_settop (lua_State *L, int idx);   //                
  3. void  lua_pushvalue (lua_State *L, int idx);//将idx索引上的值的副本压入栈顶  
  4. void  lua_remove (lua_State *L, int idx);   //移除idx索引上的值  
  5. void  lua_insert (lua_State *L, int idx);   //弹出栈顶元素,并插入索引idx位置  
  6. void  lua_replace (lua_State *L, int idx);  //弹出栈顶元素,并替换索引idx位置的值  
[cpp]  view plain  copy
  1. int   lua_gettop (lua_State *L);            //返回栈顶索引(即栈长度)  
  2. void  lua_settop (lua_State *L, int idx);   //                
  3. void  lua_pushvalue (lua_State *L, int idx);//将idx索引上的值的副本压入栈顶  
  4. void  lua_remove (lua_State *L, int idx);   //移除idx索引上的值  
  5. void  lua_insert (lua_State *L, int idx);   //弹出栈顶元素,并插入索引idx位置  
  6. void  lua_replace (lua_State *L, int idx);  //弹出栈顶元素,并替换索引idx位置的值  


lua_settop将栈顶设置为一个指定的位置,即修改栈中元素的数量。如果值比原栈顶高,则高的部分nil补足,如果值比原栈低,则原栈高出的部分舍弃。

所以可以用lua_settop(0)来清空栈。


三.c++调用lua


我们经常可以使用lua文件来作配置文件。类似ini,xml等文件配置信息。
现在我们来使用c++来读取lua文件中的变量,table,函数。


现在有这样一个hello.lua 文件:


[cpp]  view plain copy
  1. str = "I am so cool"  
  2. tbl = {name = "shun", id = 20114442}  
  3. function add(a,b)  
  4.     return a + b  
  5. end  
[cpp]  view plain  copy
  1. str = "I am so cool"  
  2. tbl = {name = "shun", id = 20114442}  
  3. function add(a,b)  
  4.     return a + b  
  5. end  


我们写一个test.cpp来读取它:


[cpp]  view plain copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建Lua状态  
  14.     lua_State *L = luaL_newstate();  
  15.     if (L == NULL)  
  16.     {  
  17.         return ;  
  18.     }  
  19.   
  20.     //2.加载lua文件  
  21.     int bRet = luaL_loadfile(L,"hello.lua");  
  22.     if(bRet)  
  23.     {  
  24.         cout<<"load file error"<<endl;  
  25.         return ;  
  26.     }  
  27.   
  28.     //3.运行lua文件  
  29.     bRet = lua_pcall(L,0,0,0);  
  30.     if(bRet)  
  31.     {  
  32.         cout<<"pcall error"<<endl;  
  33.         return ;  
  34.     }  
  35.   
  36.     //4.读取变量  
  37.     lua_getglobal(L,"str");  
  38.     string str = lua_tostring(L,-1);  
  39.     cout<<"str = "<<str.c_str()<<endl;        //str = I am so cool~  
  40.   
  41.     //5.读取table  
  42.     lua_getglobal(L,"tbl");   
  43.     lua_getfield(L,-1,"name");  
  44.     str = lua_tostring(L,-1);  
  45.     cout<<"tbl:name = "<<str.c_str()<<endl; //tbl:name = shun  
  46.   
  47.     //6.读取函数  
  48.     lua_getglobal(L, "add");        // 获取函数,压入栈中  
  49.     lua_pushnumber(L, 10);          // 压入第一个参数  
  50.     lua_pushnumber(L, 20);          // 压入第二个参数  
  51.     int iRet= lua_pcall(L, 2, 1, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。  
  52.     if (iRet)                       // 调用出错  
  53.     {  
  54.         const char *pErrorMsg = lua_tostring(L, -1);  
  55.         cout << pErrorMsg << endl;  
  56.         lua_close(L);  
  57.         return ;  
  58.     }  
  59.     if (lua_isnumber(L, -1))        //取值输出  
  60.     {  
  61.         double fValue = lua_tonumber(L, -1);  
  62.         cout << "Result is " << fValue << endl;  
  63.     }  
  64.   
  65.     //至此,栈中的情况是:  
  66.     //=================== 栈顶 ===================   
  67.     //  索引  类型      值  
  68.     //   4   int:      30   
  69.     //   3   string:   shun   
  70.     //   2   table:     tbl  
  71.     //   1   string:    I am so cool~  
  72.     //=================== 栈底 ===================   
  73.   
  74.     //7.关闭state  
  75.     lua_close(L);  
  76.     return ;  
  77. }  
[cpp]  view plain  copy
  1. #include <iostream>  
  2. #include <string.h>  
  3. using namespace std;  
  4.   
  5. extern "C"  
  6. {  
  7.     #include "lua.h"  
  8.     #include "lauxlib.h"  
  9.     #include "lualib.h"  
  10. }  
  11. void main()  
  12. {  
  13.     //1.创建Lua状态  
  14.     lua_State *L = luaL_newstate();  
  15.     if (L == NULL)  
  16.     {  
  17.         return ;  
  18.     }  
  19.   
  20.     //2.加载lua文件  
  21.     int bRet = luaL_loadfile(L,"hello.lua");  
  22.     if(bRet)  
  23.     {  
  24.         cout<<"load file error"<<endl;  
  25.         return ;  
  26.     }  
  27.   
  28.     //3.运行lua文件  
  29.     bRet = lua_pcall(L,0,0,0);  
  30.     if(bRet)  
  31.     {  
  32.         cout<<"pcall error"<<endl;  
  33.         return ;  
  34.     }  
  35.   
  36.     //4.读取变量  
  37.     lua_getglobal(L,"str");  
  38.     string str = lua_tostring(L,-1);  
  39.     cout<<"str = "<<str.c_str()<<endl;        //str = I am so cool~  
  40.   
  41.     //5.读取table  
  42.     lua_getglobal(L,"tbl");   
  43.     lua_getfield(L,-1,"name");  
  44.     str = lua_tostring(L,-1);  
  45.     cout<<"tbl:name = "<<str.c_str()<<endl; //tbl:name = shun  
  46.   
  47.     //6.读取函数  
  48.     lua_getglobal(L, "add");        // 获取函数,压入栈中  
  49.     lua_pushnumber(L, 10);          // 压入第一个参数  
  50.     lua_pushnumber(L, 20);          // 压入第二个参数  
  51.     int iRet= lua_pcall(L, 2, 1, 0);// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。  
  52.     if (iRet)                       // 调用出错  
  53.     {  
  54.         const char *pErrorMsg = lua_tostring(L, -1);  
  55.         cout << pErrorMsg << endl;  
  56.         lua_close(L);  
  57.         return ;  
  58.     }  
  59.     if (lua_isnumber(L, -1))        //取值输出  
  60.     {  
  61.         double fValue = lua_tonumber(L, -1);  
  62.         cout << "Result is " << fValue << endl;  
  63.     }  
  64.   
  65.     //至此,栈中的情况是:  
  66.     //=================== 栈顶 ===================   
  67.     //  索引  类型      值  
  68.     //   4   int:      30   
  69.     //   3   string:   shun   
  70.     //   2   table:     tbl  
  71.     //   1   string:    I am so cool~  
  72.     //=================== 栈底 ===================   
  73.   
  74.     //7.关闭state  
  75.     lua_close(L);  
  76.     return ;  
  77. }  


知道怎么读取后,我们来看下如何修改上面代码中table的值:


[cpp]  view plain copy
  1. // 将需要设置的值设置到栈中  
  2. lua_pushstring(L, "我是一个大帅锅~");  
  3. // 将这个值设置到table中(此时tbl在栈的位置为2)  
  4. lua_setfield(L, 2, "name");  
[cpp]  view plain  copy
  1. // 将需要设置的值设置到栈中  
  2. lua_pushstring(L, "我是一个大帅锅~");  
  3. // 将这个值设置到table中(此时tbl在栈的位置为2)  
  4. lua_setfield(L, 2, "name");  


我们还可以新建一个table:


[cpp]  view plain copy
  1. // 创建一个新的table,并压入栈  
  2. lua_newtable(L);  
  3. // 往table中设置值  
  4. lua_pushstring(L, "Give me a girl friend !"); //将值压入栈  
  5. lua_setfield(L, -2, "str"); //将值设置到table中,并将Give me a girl friend 出栈  
[cpp]  view plain  copy
  1. // 创建一个新的table,并压入栈  
  2. lua_newtable(L);  
  3. // 往table中设置值  
  4. lua_pushstring(L, "Give me a girl friend !"); //将值压入栈  
  5. lua_setfield(L, -2, "str"); //将值设置到table中,并将Give me a girl friend 出栈  


需要注意的是:堆栈操作是基于栈顶的,就是说它只会去操作栈顶的值。


举个比较简单的例子,函数调用流程是先将函数入栈,参数入栈,然后用lua_pcall调用函数,此时栈顶为参数,栈底为函数,所以栈过程大致会是:参数出栈->保存参数->参数出栈->保存参数->函数出栈->调用函数->返回结果入栈。

类似的还有lua_setfield,设置一个表的值,肯定要先将值出栈,保存,再去找表的位置。


再不理解可看如下例子:

[cpp]  view plain copy
  1. lua_getglobal(L, "add");        // 获取函数,压入栈中  
  2. lua_pushnumber(L, 10);          // 压入第一个参数  
  3. lua_pushnumber(L, 20);          // 压入第二个参数  
  4. int iRet= lua_pcall(L, 2, 1, 0);// 将2个参数出栈,函数出栈,压入函数返回结果  
  5.   
  6. lua_pushstring(L, "我是一个大帅锅~");  //   
  7. lua_setfield(L, 2, "name");             // 会将"我是一个大帅锅~"出栈  
[cpp]  view plain  copy
  1. lua_getglobal(L, "add");        // 获取函数,压入栈中  
  2. lua_pushnumber(L, 10);          // 压入第一个参数  
  3. lua_pushnumber(L, 20);          // 压入第二个参数  
  4. int iRet= lua_pcall(L, 2, 1, 0);// 将2个参数出栈,函数出栈,压入函数返回结果  
  5.   
  6. lua_pushstring(L, "我是一个大帅锅~");  //   
  7. lua_setfield(L, 2, "name");             // 会将"我是一个大帅锅~"出栈  

另外补充一下:

lua_getglobal(L,"var")会执行两步操作:1.将var放入栈中,2.由lua去寻找变量var的值,并将变量var的值返回栈顶(替换var)。
lua_getfield(L,-1,"name") 的作用等价于 lua_pushstring(L,"name") + lua_gettable(L,-2)


四.lua调用c++


我们分三个方法实现它。


方法一:直接将模块写入lua源码中


在lua中调用c/c++,我们可以将函数写lua.c中,然后重新编译lua文件。
也许你用的是lua for windows集成环境,没关系,不会编译lua可以参考这篇:http://blog.csdn.net/snlscript/article/details/15533373


编译好后是这样子的:(如图)




然后我们可以在lua.c中加入我们自己的函数。函数要遵循规范(可在lua.h中查看)如下:


[cpp]  view plain copy
  1. typedef int (*lua_CFunction) (lua_State *L);  
[cpp]  view plain  copy
  1. typedef int (*lua_CFunction) (lua_State *L);  


换句话说,所有的函数必须接收一个lua_State作为参数,同时返回一个整数值。因为这个函数使用Lua栈作为参数,所以它可以从栈里面读取任意数量和任意类型的参数。而这个函数的返回值则表示函数返回时有多少返回值被压入Lua栈。(因为Lua的函数是可以返回多个值的)


然后我们在lua.c中加入如下函数:


[cpp]  view plain copy
  1. // This is my function  
  2. static int getTwoVar(lua_State *L)  
  3. {  
  4.     // 向函数栈中压入2个值  
  5.     lua_pushnumber(L, 10);  
  6.     lua_pushstring(L,"hello");  
  7.   
  8.     return 2;  
  9. }  
[cpp]  view plain  copy
  1. // This is my function  
  2. static int getTwoVar(lua_State *L)  
  3. {  
  4.     // 向函数栈中压入2个值  
  5.     lua_pushnumber(L, 10);  
  6.     lua_pushstring(L,"hello");  
  7.   
  8.     return 2;  
  9. }  


在pmain函数中,luaL_openlibs函数后加入以下代码:


[cpp]  view plain copy
  1. //注册函数  
  2. lua_pushcfunction(L, getTwoVar); //将函数放入栈中  
  3. lua_setglobal(L, "getTwoVar");   //设置lua全局变量getTwoVar  
[cpp]  view plain  copy
  1. //注册函数  
  2. lua_pushcfunction(L, getTwoVar); //将函数放入栈中  
  3. lua_setglobal(L, "getTwoVar");   //设置lua全局变量getTwoVar  

通过查找lua.h


[cpp]  view plain copy
  1. /#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))  
[cpp]  view plain  copy
  1. /#define lua_register(L,n,f) (lua_pushcfunction(L, (f)), lua_setglobal(L, (n)))  


我们发现之前的注册函数可以这样子写:


[cpp]  view plain copy
  1. lua_register(L,"getTwoVar",getTwoVar);  
[cpp]  view plain  copy
  1. lua_register(L,"getTwoVar",getTwoVar);  


运行,结果如图:




当然,一般我们不建议去修改别人的代码,更倾向于自己编写独立的c/c++模块,供lua调用,下面来讲讲如何实现。


方法二:使用静态依赖的方式


1.新建一个空的win32控制台工程,记得在vc++目录中,把lua中的头文件和lib文件的目录包含进来,然后->链接器->附加依赖项->将lua51.lib和lua5.1.lib也包含进来。


2.在目录下新建一个avg.lua如下:


[cpp]  view plain copy
  1. avg, sum = average(10, 20, 30, 40, 50)  
  2. print("The average is ", avg)  
  3. print("The sum is ", sum)  
[cpp]  view plain  copy
  1. avg, sum = average(10, 20, 30, 40, 50)  
  2. print("The average is ", avg)  
  3. print("The sum is ", sum)  


3.新建test.cpp如下:


[cpp]  view plain copy
  1. #include <stdio.h>  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. /* 指向Lua解释器的指针 */  
  10. lua_State* L;  
  11. static int average(lua_State *L)  
  12. {  
  13.     /* 得到参数个数 */  
  14.     int n = lua_gettop(L);  
  15.     double sum = 0;  
  16.     int i;  
  17.   
  18.     /* 循环求参数之和 */  
  19.     for (i = 1; i <= n; i++)  
  20.     {  
  21.         /* 求和 */  
  22.         sum += lua_tonumber(L, i);  
  23.     }  
  24.     /* 压入平均值 */  
  25.     lua_pushnumber(L, sum / n);  
  26.     /* 压入和 */  
  27.     lua_pushnumber(L, sum);  
  28.     /* 返回返回值的个数 */  
  29.     return 2;  
  30. }  
  31.   
  32. int main ( int argc, char *argv[] )  
  33. {  
  34.     /* 初始化Lua */  
  35.     L = lua_open();  
  36.   
  37.     /* 载入Lua基本库 */  
  38.     luaL_openlibs(L);  
  39.     /* 注册函数 */  
  40.     lua_register(L, "average", average);  
  41.     /* 运行脚本 */  
  42.     luaL_dofile(L, "avg.lua");  
  43.     /* 清除Lua */  
  44.     lua_close(L);  
  45.   
  46.     /* 暂停 */  
  47.     printf( "Press enter to exit…" );  
  48.     getchar();  
  49.     return 0;  
  50. }  
[cpp]  view plain  copy
  1. #include <stdio.h>  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. /* 指向Lua解释器的指针 */  
  10. lua_State* L;  
  11. static int average(lua_State *L)  
  12. {  
  13.     /* 得到参数个数 */  
  14.     int n = lua_gettop(L);  
  15.     double sum = 0;  
  16.     int i;  
  17.   
  18.     /* 循环求参数之和 */  
  19.     for (i = 1; i <= n; i++)  
  20.     {  
  21.         /* 求和 */  
  22.         sum += lua_tonumber(L, i);  
  23.     }  
  24.     /* 压入平均值 */  
  25.     lua_pushnumber(L, sum / n);  
  26.     /* 压入和 */  
  27.     lua_pushnumber(L, sum);  
  28.     /* 返回返回值的个数 */  
  29.     return 2;  
  30. }  
  31.   
  32. int main ( int argc, char *argv[] )  
  33. {  
  34.     /* 初始化Lua */  
  35.     L = lua_open();  
  36.   
  37.     /* 载入Lua基本库 */  
  38.     luaL_openlibs(L);  
  39.     /* 注册函数 */  
  40.     lua_register(L, "average", average);  
  41.     /* 运行脚本 */  
  42.     luaL_dofile(L, "avg.lua");  
  43.     /* 清除Lua */  
  44.     lua_close(L);  
  45.   
  46.     /* 暂停 */  
  47.     printf( "Press enter to exit…" );  
  48.     getchar();  
  49.     return 0;  
  50. }  


执行一下,我们可以得到结果:



大概顺序就是:我们在c++中写一个模块函数,将函数注册到lua解释器中,然后由c++去执行我们的lua文件,然后在lua中调用刚刚注册的函数。


看上去很别扭啊有木有。。。接下来介绍一下dll调用方式。


方法三:使用dll动态链接的方式


我们先新建一个dll工程,工程名为mLualib。(因此最后导出的dll也为mLualib.dll)


然后编写我们的c++模块,以函数为例,我们先新建一个.h文件和.cpp文件。


h文件如下:(如果你不是很能明白头文件的内容,点击这里:http://blog.csdn.net/shun_fzll/article/details/39078971。)


[cpp]  view plain copy
  1. #pragma once  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. #ifdef LUA_EXPORTS  
  10. #define LUA_API __declspec(dllexport)  
  11. #else  
  12. #define LUA_API __declspec(dllimport)  
  13. #endif  
  14.   
  15. extern "C" LUA_API int luaopen_mLualib(lua_State *L);//定义导出函数  
[cpp]  view plain  copy
  1. #pragma once  
  2.   
  3. extern "C" {  
  4. #include "lua.h"  
  5. #include "lualib.h"  
  6. #include "lauxlib.h"  
  7. }  
  8.   
  9. #ifdef LUA_EXPORTS  
  10. #define LUA_API __declspec(dllexport)  
  11. #else  
  12. #define LUA_API __declspec(dllimport)  
  13. #endif  
  14.   
  15. extern "C" LUA_API int luaopen_mLualib(lua_State *L);//定义导出函数  

.cpp文件如下:


[cpp]  view plain copy
  1. #include <stdio.h>  
  2. #include "mLualib.h"  
  3.   
  4. static int averageFunc(lua_State *L)  
  5. {  
  6.     int n = lua_gettop(L);  
  7.     double sum = 0;  
  8.     int i;  
  9.   
  10.     /* 循环求参数之和 */  
  11.     for (i = 1; i <= n; i++)  
  12.         sum += lua_tonumber(L, i);  
  13.   
  14.     lua_pushnumber(L, sum / n);     //压入平均值  
  15.     lua_pushnumber(L, sum);         //压入和  
  16.   
  17.     return 2;                       //返回两个结果  
  18. }  
  19.   
  20. static int sayHelloFunc(lua_State* L)  
  21. {  
  22.     printf("hello world!");  
  23.     return 0;  
  24. }  
  25.   
  26. static const struct luaL_Reg myLib[] =   
  27. {  
  28.     {"average", averageFunc},  
  29.     {"sayHello", sayHelloFunc},  
  30.     {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
  31. };  
  32.   
  33. int luaopen_mLualib(lua_State *L)  
  34. {  
  35.     luaL_register(L, "ss", myLib);  
  36.     return 1;       // 把myLib表压入了栈中,所以就需要返回1  
  37. }  
[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include "mLualib.h"  
  3.   
  4. static int averageFunc(lua_State *L)  
  5. {  
  6.     int n = lua_gettop(L);  
  7.     double sum = 0;  
  8.     int i;  
  9.   
  10.     /* 循环求参数之和 */  
  11.     for (i = 1; i <= n; i++)  
  12.         sum += lua_tonumber(L, i);  
  13.   
  14.     lua_pushnumber(L, sum / n);     //压入平均值  
  15.     lua_pushnumber(L, sum);         //压入和  
  16.   
  17.     return 2;                       //返回两个结果  
  18. }  
  19.   
  20. static int sayHelloFunc(lua_State* L)  
  21. {  
  22.     printf("hello world!");  
  23.     return 0;  
  24. }  
  25.   
  26. static const struct luaL_Reg myLib[] =   
  27. {  
  28.     {"average", averageFunc},  
  29.     {"sayHello", sayHelloFunc},  
  30.     {NULL, NULL}       //数组中最后一对必须是{NULL, NULL},用来表示结束      
  31. };  
  32.   
  33. int luaopen_mLualib(lua_State *L)  
  34. {  
  35.     luaL_register(L, "ss", myLib);  
  36.     return 1;       // 把myLib表压入了栈中,所以就需要返回1  
  37. }  

不理解没关系,我们先编译它,然后新建一个lua文件,在lua中我们这样子来调用:(调用之前记得把dll文件复制到lua文件目录下)


[cpp]  view plain copy
  1. require "mLualib"  
  2. local ave,sum = ss.average(1,2,3,4,5)//参数对应堆栈中的数据  
  3. print(ave,sum)  -- 3 15  
  4. ss.sayHello()   -- hello world!  
[cpp]  view plain  copy
  1. require "mLualib"  
  2. local ave,sum = ss.average(1,2,3,4,5)//参数对应堆栈中的数据  
  3. print(ave,sum)  -- 3 15  
  4. ss.sayHello()   -- hello world!  

成功调用了有木有?我们看到了输出信息。(木有成功你留言,我教你!)

至此都发生了什么呢?梳理一下:

1.我们编写了averageFunc求平均值和sayHelloFunc函数,
2.然后把函数封装myLib数组里面,类型必须是luaL_Reg
3.由luaopen_mLualib函数导出并在lua中注册这两个函数。

那么为什么要这样子写呢?实际上当我们在lua中:


[cpp]  view plain copy
  1. require "mLualib"  
[cpp]  view plain  copy
  1. require "mLualib"  


这样子写的时候,lua会这么干:


[cpp]  view plain copy
  1. local path = "mLualib.dll"    
  2. local f = package.loadlib(path,"luaopen_mLualib")   -- 返回luaopen_mLualib函数  
  3. f()                                                 -- 执行  
[cpp]  view plain  copy
  1. local path = "mLualib.dll"    
  2. local f = package.loadlib(path,"luaopen_mLualib")   -- 返回luaopen_mLualib函数  
  3. f()                                                 -- 执行  

所以当我们在编写一个这样的模块的时候,编写luaopen_xxx导出函数的时候,xxx最好是和项目名一样(因为项目名和dll一样)

需要注意的是:函数参数里的lua_State是私有的,每一个函数都有自己的栈。当一个c/c++函数把返回值压入Lua栈以后,该栈会自动被清空。


五.总结 


这篇文章花了好几天才整理的,最后总结一下就是:

lua和c++是通过一个虚拟栈来交互的。

c++调用lua实际上是:由c++先把数据放入栈中,由lua去栈中取数据,然后返回数据对应的值到栈顶,再由栈顶返回c++。

lua调c++也一样:先编写自己的c模块,然后注册函数到lua解释器中,然后由lua去调用这个模块的函数。


转载请注明出处:http://blog.csdn.net/shun_fzll/article/details/39120965
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Lua和C++交互总结(很详细) 的相关文章

随机推荐

  • 毕业设计 STM32人体红外测温枪温度采集系统 - 单片机

    文章目录 1 前言 2 主要器件 3 实现效果 4 设计原理 MLX90614 红外温度传感器 5 部分实现代码 6 最后 1 前言 这两年开始毕业设计和毕业答辩的要求和难度不断提升 传统的毕设题目缺少创新和亮点 往往达不到毕业答辩的要求
  • go语言的安装已经调试

    go语言作为google的一个主推语言 最近很多人都在研究 也花了一点时间对他的安装进行了测试 本人使用Sublime Text 2 GoSublime gocode 顾名思义首先是安装Go 这里有很详细的安装说明 http code go
  • 单相逆变器的建模与仿真

    1 电路拓扑 本次设计采用单相全桥逆变电路 使用LC滤波器 负载使用单相桥式整流 电路如图所示 2 控制思路 控制部分采用PI控制 包含电压外环和电流内环 而电流内环又分为电感电流反馈和电容电流反馈两种 其中电感电流内环电压外环的控制框图和
  • pip install 国内镜像源

    经验证 阿里的云最快 记得是https不是http 对于Python开发用户来讲 PIP安装软件包是家常便饭 而国外的源下载速度太慢 浪费时间 而且常出现下载后安装出错问题 故把pip安装源替换成国内镜像 可大幅提高下载速度 还可以提高安装
  • 计算机网络学习笔记第四章(网络层)超详细整理

    目录 4 1 网络层概述 1 简介 2 总结 4 2 网络层提供的两种服务 1 面向连接的虚电路服务 2 无连接的数据报服务 3 虚电路服务与数据报服务的对比 4 3 IPv4 1 概述 2 分类编制的IPv4地址 2 1 简介 2 2 总
  • 第六篇:进阶篇 车内的吸声性能及测试方法

    本专栏分享传统NVH知识点 从声学理论 材料声学 汽车噪声振动分析 车辆及其零部件甚至原材料的声学测试方法等多维度介绍汽车NVH 一些专用术语同时给出了中英文对照 欢迎新人 同行 爱好者一起交流 由于内容写的较为仓促 有误的地方欢迎大家批评
  • 【安装】win下的openvino安装及onnx模型转换.xml和.bin

    安装文档参考 openvino安装指导 包含相应依赖的安装 三步到位 我装的是python3 8 vs2019 cmake3 24 0 一般最新版本 这几个安装及注意的细节在文档中都有描述 一定一定要按上述文档安装 并且细节要注意 尤其是o
  • 一道面试题:JVM老年代空间担保机制

    面试问题 昨天面试的时候 面试官问的问题 什么是老年代空间担保机制 担保的过程是什么 老年代空间担保机制是谁给谁担保 为什么要有老年代空间担保机制 或者说空间担保机制的目的是什么 如果没有老年代空间担保机制会有什么不好 下面我们就带着这些问
  • Nuttx操作系统(三):构建模式

    1 1 Nuttx构建配置以及模式 Nuttx有三种不同的构建配置 FLAT构建 这种构建是所代码驻留在公共地址空间中 1 应用 内核以及board logic在一个flat地址环境中 2 所有的地址空间具有相同的属性 PROTECTED构
  • expected primary-expression before 'unsigned' 解决方案

    问题描述 语句result unsigned int 1 lt lt i 在本地可以编译运行 但是上传至LeetCode后出现编译错误 expected primary expression before unsigned 分析 语句太复杂
  • 【MedusaSTears】复杂定时任务SpringBoot+Quartz实例,解决jobclass如何注入一个service类,以及实现简单业务逻辑

    目录 吃水不忘挖井人系列 1 认识了解各种定时任务实现方式 2 本文主要参考 3 其他参考 一 业务需求 这里提一下我对 Scheduled和Quartz的一点小看法 如有误解还请指正 二 软件环境 java版本 SpringBoot版本
  • Ubuntu环境下使用APT安装Jenkins(详细教程)

    目录 1 安装JDK 1 1 使用APT查找已安装的JDK 1 2 若没有JDK11 则需要安装 2 使用war包或者APT两种安装方式 2 1 war包安装 推荐 方法简单 配置使用JDK 2 2 APT安装 3 配置Jenkins 3
  • 人工智能数学基础:利用导数判断函数单调性、凹凸性、极值、最值和描绘函数图形

    一 单调性判断定理 定理 设函数y f x 在 a b 上连续 在 a b 内可导 1 如果在 a b 内f x 0 且等号仅在有限多个点处成立 那么函数y f x 在 a b 上单调增加 2 如果在 a b 内f x 0 且等号仅在有限多
  • java 常见的异常大集合

    算术异常类 ArithmeticExecption 空指针异常类 NullPointerException 类型强制转换异常 ClassCastException 数组负下标异常 NegativeArrayException 数组下标越界异
  • Java多线程 - 线程池常用容量设置

    线程执行方式 线程的执行是由CPU进行调度的 一个CPU在 同一时刻只会执行一个线程 操作系统利用了时间片轮转的方式 CPU给每个任务都服务一定的时间 然后把当前任务的状态保存下来 再加载下一个任务的状态后 继续服务下一个任务 任务的保存及
  • Android Studio卸载以及安装教程

    手把手教学安卓安装 一 卸载教程 如果是第一次安装 直接看往下翻 1 先把Android Studio卸载2 将安装残余一起卸载 一定要卸载干净 否则在二次安装时会出现一大堆问题 a b c 好啦 到这里 所有的残余都已经删除干净 下面进入
  • opengl光线跟踪算法_计算机图形中的光线追踪(ray tracing)概念

    这是对MIT Foundation of 3D Computer Graphics第20章的翻译 本章讲解了光线追踪 ray tracing 技术的基础知识 本书内容仍在不断的学习中 因此本文内容会不断的改进 若有任何建议 请不吝赐教nin
  • centos7 网络不通?

    仅仅作为自己的笔记自己后续查看 1 首先我这里的vmvare 需要改成nat 模式 然后解决这个问题需要修改3个文件 1 etc sysconfig network 主机名 默认网关 DNS 2 etc sysconfig network
  • python 报错DataFrame object has no attribute dtype

    错误信息 DataFrame object has no attribute dtype 原因 在dataframe astype str 的列的数据类型有object类型 解决方法 将对象的列的数据先转成字符串
  • Lua和C++交互总结(很详细)

    出处 http blog csdn net shun fzll article details 39120965 一 lua堆栈 要理解lua和c 交互 首先要理解lua堆栈 简单来说 Lua和C c 语言通信的主要方法是一个无处不在的虚拟