目录

  1. Lua堆栈
  2. Lua堆栈操作
  3. C++调用lua
  4. Lua调用C++

There is something beautiful, just to find it.

Lua堆栈

要理解Lua和C++的交互,首先要清楚Lua堆栈。简单来说Lua和C++交互是通过一个无处不在的虚拟堆栈来的。

在Lua中,lua堆栈是一个结构,堆栈的索引可以是整数或者负数,+1表示栈底,-1表示栈顶。

存入栈的数据类型包含数值,字符串,指针,table,闭包等。

1
2
3
4
5
6
7
lua_pushcclosure(L, func, 0) // 创建并压入一个闭包

lua_createtable(L, 0, 0) // 新建并压入一个表

lua_pushnumber(L, 343) // 压入一个数字

lua_pushstring(L, mystr) // 压入一个字符串

这里要说明的是, 你压入的类型有数值, 字符串, 表和闭包[在c中看来是不同类型的值], 但是最后都是统一用TValue这种数据结构来保存的:), 下面用图简单的说明一下这种数据结构:

Tvalue结构对应于lua中的所有数据类型,是一个键值对的结构,这就是lua动态类型的实现,它把值和类型绑在一起,用tt记录value的类型,value也是一个联合结构,由value定义,可以 看到这个联合有四个域,先说明简单的:

  • p:可以存一个指针,实际上是lua中的light userdata结构
  • n:所有数值存在这里,不管是int还是float
  • b:Boolean值
  • gc:其它诸如table,thread,closure,string需要内存管理垃圾回收的类型都存在这里。 gc是一个指针,它可以指向的类型由联合体GCObject来定义。

从上面我们可以得到结论:

  1. lua中,number,boolean,nil,light userdata可以直接存在栈上元素里的,和垃圾回收没有关系。
  2. lua中,string,table,closure,userdata,thread存在栈上的元素里的只是指针,它们在声明周期结束的时候被垃圾回收。

Lua堆栈操作

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

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
#include <iostream>  
#include <string.h>  
using namespace std;  

extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
void main()
{
//1.创建一个state
lua_State *L = luaL_newstate(); //返回一个指向堆栈的指针

<span class="c1">//2.入栈操作  </span>
<span class="n">lua_pushstring</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="s">&#34;I am so cool~&#34;</span><span class="p">);</span>   
<span class="n">lua_pushnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="mi">20</span><span class="p">);</span>  

<span class="c1">//3.取值操作  </span>
<span class="k">if</span><span class="p">(</span> <span class="n">lua_isstring</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="mi">1</span><span class="p">)){</span>             <span class="c1">//判断是否可以转为string  </span>
    <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="n">lua_tostring</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="mi">1</span><span class="p">)</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>  <span class="c1">//转为string并返回  </span>
<span class="p">}</span>  
<span class="k">if</span><span class="p">(</span> <span class="n">lua_isnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="mi">2</span><span class="p">)){</span>  
    <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="n">lua_tonumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="mi">2</span><span class="p">)</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>  
<span class="p">}</span>  

<span class="c1">//4.关闭state  </span>
<span class="n">lua_close</span><span class="p">(</span><span class="n">L</span><span class="p">);</span>  
<span class="k">return</span> <span class="p">;</span>  

}

int lua_gettop (lua_State L); //返回栈顶索引(即栈长度)
void lua_settop (lua_State
L, int idx); //ua_settop将栈顶设置为一个指定的位置,即修改栈中元素的数量。
//如果值比原栈顶高,则高的部分nil补足,如果值比原栈低,则原栈高出的部分舍弃。所以可以用lua_settop(0)来清空栈。
void lua_pushvalue (lua_State L, int idx);//将idx索引上的值的副本压入栈顶
void lua_remove (lua_State
L, int idx); //移除idx索引上的值
void lua_insert (lua_State L, int idx); //弹出栈顶元素,并插入索引idx位置
void lua_replace (lua_State
L, int idx); //弹出栈顶元素,并替换索引idx位置的值

c++调用lua

lua和c通信时有这样一个约定,所有的lua中的值由lua来管理,c++中产生的值lua不知道,如果你(c/c++)想要什么, 你告诉我(lua), 我来产生, 然后放到栈上, 你只能通过api来操作这个值, 我只管我的世界。

这里我们写一个hello.lua

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

写一个c++文件调用lua:

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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
#include <iostream>  
#include <string.h>  
using namespace std;  

extern "C"
{
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}
void main()
{
//1.创建Lua状态
lua_State *L = luaL_newstate();
if (L == NULL)
{
return ;
}

<span class="c1">//2.加载Lua文件  </span>
<span class="kt">int</span> <span class="n">bRet</span> <span class="o">=</span> <span class="n">luaL_loadfile</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="s">&#34;hello.lua&#34;</span><span class="p">);</span>  
<span class="k">if</span><span class="p">(</span><span class="n">bRet</span><span class="p">)</span>  
<span class="p">{</span>  
    <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;load file error&#34;</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>  
    <span class="k">return</span> <span class="p">;</span>  
<span class="p">}</span>  

<span class="c1">//3.运行Lua文件  参数2:传递参数数量,参数3:返回数量,参数4错误处理函数。</span>
<span class="n">bRet</span> <span class="o">=</span> <span class="n">lua_pcall</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">,</span><span class="mi">0</span><span class="p">);</span>  
<span class="k">if</span><span class="p">(</span><span class="n">bRet</span><span class="p">)</span>  
<span class="p">{</span>  
    <span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;pcall error&#34;</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>  
    <span class="k">return</span> <span class="p">;</span>  
<span class="p">}</span>  

<span class="c1">//4.读取变量  </span>
<span class="n">lua_getglobal</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="s">&#34;str&#34;</span><span class="p">);</span>  
<span class="n">string</span> <span class="n">str</span> <span class="o">=</span> <span class="n">lua_tostring</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">);</span>  
<span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;str = &#34;</span><span class="o">&lt;&lt;</span><span class="n">str</span><span class="p">.</span><span class="n">c_str</span><span class="p">()</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span>        <span class="c1">//str = I am so cool~  </span>

<span class="c1">//5.读取table  </span>
<span class="n">lua_getglobal</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="s">&#34;tbl&#34;</span><span class="p">);</span>   
<span class="n">lua_getfield</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">,</span><span class="s">&#34;name&#34;</span><span class="p">);</span>  
<span class="n">str</span> <span class="o">=</span> <span class="n">lua_tostring</span><span class="p">(</span><span class="n">L</span><span class="p">,</span><span class="o">-</span><span class="mi">1</span><span class="p">);</span>  
<span class="n">cout</span><span class="o">&lt;&lt;</span><span class="s">&#34;tbl:name = &#34;</span><span class="o">&lt;&lt;</span><span class="n">str</span><span class="p">.</span><span class="n">c_str</span><span class="p">()</span><span class="o">&lt;&lt;</span><span class="n">endl</span><span class="p">;</span> <span class="c1">//tbl:name = shun  </span>

<span class="c1">//6.读取函数  </span>
<span class="n">lua_getglobal</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="s">&#34;add&#34;</span><span class="p">);</span>        <span class="c1">// 获取函数,压入栈中  </span>
<span class="n">lua_pushnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="mi">10</span><span class="p">);</span>          <span class="c1">// 压入第一个参数  </span>
<span class="n">lua_pushnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="mi">20</span><span class="p">);</span>          <span class="c1">// 压入第二个参数  </span>
<span class="kt">int</span> <span class="n">iRet</span><span class="o">=</span> <span class="n">lua_pcall</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">1</span><span class="p">,</span> <span class="mi">0</span><span class="p">);</span><span class="c1">// 调用函数,调用完成以后,会将返回值压入栈中,2表示参数个数,1表示返回结果个数。  </span>
<span class="k">if</span> <span class="p">(</span><span class="n">iRet</span><span class="p">)</span>                       <span class="c1">// 调用出错  </span>
<span class="p">{</span>  
    <span class="k">const</span> <span class="kt">char</span> <span class="o">*</span><span class="n">pErrorMsg</span> <span class="o">=</span> <span class="n">lua_tostring</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">);</span>  
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="n">pErrorMsg</span> <span class="o">&lt;&lt;</span> <span class="n">endl</span><span class="p">;</span>  
    <span class="n">lua_close</span><span class="p">(</span><span class="n">L</span><span class="p">);</span>  
    <span class="k">return</span> <span class="p">;</span>  
<span class="p">}</span>  
<span class="k">if</span> <span class="p">(</span><span class="n">lua_isnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">))</span>        <span class="c1">//取值输出  </span>
<span class="p">{</span>  
    <span class="kt">double</span> <span class="n">fValue</span> <span class="o">=</span> <span class="n">lua_tonumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="o">-</span><span class="mi">1</span><span class="p">);</span>  
    <span class="n">cout</span> <span class="o">&lt;&lt;</span> <span class="s">&#34;Result is &#34;</span> <span class="o">&lt;&lt;</span> <span class="n">fValue</span> <span class="o">&lt;&lt;</span> <span class="n">endl</span><span class="p">;</span>  
<span class="p">}</span>  

<span class="c1">//至此,栈中的情况是:  </span>
<span class="c1">//=================== 栈顶 ===================   </span>
<span class="c1">//  索引  类型      值  </span>
<span class="c1">//   4   int:      30   </span>
<span class="c1">//   3   string:   shun   </span>
<span class="c1">//   2   table:     tbl  </span>
<span class="c1">//   1   string:    I am so cool~  </span>
<span class="c1">//=================== 栈底 ===================   </span>

<span class="c1">//7.关闭state  </span>
<span class="n">lua_close</span><span class="p">(</span><span class="n">L</span><span class="p">);</span>  
<span class="k">return</span> <span class="p">;</span>  

}
// 将需要设置的值设置到栈中 ,修改值
lua_pushstring(L, "我是一个大帅锅~");
// 将这个值设置到table中(此时tbl在栈的位置为2)
lua_setfield(L, 2, "name");
// 创建一个新的table,并压入栈
lua_newtable(L);
// 往table中设置值
lua_pushstring(L, "Give me a girl friend !"); //将值压入栈
lua_setfield(L, -2, "str"); //将值设置到table中,并将Give me a girl friend 出栈

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

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

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

1
2
3
4
5
6
lua_getglobal(L, "add");        // 获取函数,压入栈中  
lua_pushnumber(L, 10);          // 压入第一个参数  
lua_pushnumber(L, 20);          // 压入第二个参数  
int iRet= lua_pcall(L, 2, 1, 0);// 将2个参数出栈,函数出栈,压入函数返回结果  
lua_pushstring(L, "我是一个大帅锅~");  //   
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),类似的,会将获得的值替换name。

可以看出来, lua中提供的一些类型和c中是对应的, 也提供一些c中没有的类型. 其中有一些药特别的说明一下:

nil值, c中没有对应, 但是可以通过lua_pushnil向lua中压入一个nil值。

注意: lua_push*族函数都有”创建一个类型的值并压入”的语义, 因为lua中所有的变量都是lua中创建并保存的, 对于那些和c中有对应关系的lua类型, lua会通过api传来的附加参数, 创建出对应类型的lua变量放在栈顶, 对于c中没有对应类型的lua类型, lua直接创建出对应变量放在栈顶.

例如:

  • lua_pushstring(L, “string”) lua根据”string”创建一个 TString obj, 绑定到新分配的栈顶元素上

  • lua_pushcclosure(L,func, 0) lua根据func创建一个 Closure obj, 绑定到新分配的栈顶元素上

  • lua_pushnumber(L,5) lua直接修改新分配的栈顶元素, 将5赋值到对应的域

  • lua_createtable(L,0, 0)lua创建一个Tabke obj, 绑定到新分配的栈顶元素上

总之, 这是一个 c value –> lua value的流向, 不管是想把一个简单的5放入lua的世界, 还是创建一个table, 都会导致:

  1. 栈顶新分配元素
  2. 绑定或赋值

还是为了重复一句话, 一个c value入栈就是进入了lua的世界, lua会生成一个对应的结构并管理起来, 从此就不再依赖这个c value。

lua value –> c value时, 是通过 lua_to* 族api实现, 很简单, 取出对应的c中的域的值就行了, 只能转化那些c中有对应值的lua value, 比如table就不能to c value, 所以api中夜没有提供 lua_totable这样的接口。

Lua调用C++

有三种方法可以实现Lua调用c++中的代码。

第一种,直接写到lua源码中,然后重新编译lua文件。

在lua.c文件中加入自己的函数,别忘记在lua.h头文件中声明:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// This is my function  
static int getTwoVar(lua_State *L)  
{  
    // 向函数栈中压入2个值  
    lua_pushnumber(L, 10);  
    lua_pushstring(L,"hello");  
<span class="k">return</span> <span class="mi">2</span><span class="p">;</span>  

}

pmain函数中,luaL_openlibs函数后加入以下代码:
//注册函数
lua_pushcfunction(L, getTwoVar); //将函数放入栈中
lua_setglobal(L, "getTwoVar"); //设置lua全局变量getTwoVar
//lua_register(L,"getTwoVar",getTwoVar);

lua_setglobal会弹出栈顶元素,并为其设置值。

编译之后可以直接调用函数了,但是不推荐这么做。

第二种:使用静态依赖的方式:

创建avg.lua:

1
2
3
avg, sum = average(10, 20, 30, 40, 50)  
print("The average is ", avg)  
print("The sum is ", sum)

创建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
#include <stdio.h>  
extern "C" {  
#include "lua.h"  
#include "lualib.h"  
#include "lauxlib.h"  
}  

/* 指向Lua解释器的指针 /
lua_State
L;
static int average(lua_State L)
{
/
得到参数个数 */
int n = lua_gettop(L);
double sum = 0;
int i;

<span class="cm">/* 循环求参数之和 */</span>  
<span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>  
<span class="p">{</span>  
    <span class="cm">/* 求和 */</span>  
    <span class="n">sum</span> <span class="o">+=</span> <span class="n">lua_tonumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span>  
<span class="p">}</span>  
<span class="cm">/* 压入平均值 */</span>  
<span class="n">lua_pushnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">sum</span> <span class="o">/</span> <span class="n">n</span><span class="p">);</span>  
<span class="cm">/* 压入和 */</span>  
<span class="n">lua_pushnumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">sum</span><span class="p">);</span>  
<span class="cm">/* 返回返回值的个数 */</span>  
<span class="k">return</span> <span class="mi">2</span><span class="p">;</span>  

}

int main ( int argc, char argv[] )
{
/
初始化Lua */
L = lua_open();

<span class="cm">/* 载入Lua基本库 */</span>  
<span class="n">luaL_openlibs</span><span class="p">(</span><span class="n">L</span><span class="p">);</span>  
<span class="cm">/* 注册函数 */</span>  
<span class="n">lua_register</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="s">&#34;average&#34;</span><span class="p">,</span> <span class="n">average</span><span class="p">);</span>  
<span class="cm">/* 运行脚本 */</span>  
<span class="n">luaL_dofile</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="s">&#34;avg.lua&#34;</span><span class="p">);</span>  
<span class="cm">/* 清除Lua */</span>  
<span class="n">lua_close</span><span class="p">(</span><span class="n">L</span><span class="p">);</span>  

<span class="cm">/* 暂停 */</span>  
<span class="n">printf</span><span class="p">(</span> <span class="s">&#34;Press enter to exit…&#34;</span> <span class="p">);</span>  
<span class="n">getchar</span><span class="p">();</span>  
<span class="k">return</span> <span class="mi">0</span><span class="p">;</span>  

}

c++来带调用我们的lua文件,很别扭不是么?

第三种:使用动态库链接:

我们先新建一个dll工程,工程名为mLualib。(因此最后导出的dll也为mLualib.dll,然后编写我们的c++模块,以函数为例,我们先新建一个.h文件和.cpp文件。

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#pragma once  
extern "C" {  
#include "lua.h"  
#include "lualib.h"  
#include "lauxlib.h"  
}  

#ifdef LUA_EXPORTS
#define LUA_API __declspec(dllexport)
#else
#define LUA_API __declspec(dllimport)
#endif

extern "C" LUA_API int luaopen_mLualib(lua_State *L);//定义导出函数

.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
#include <stdio.h>  
#include "mLualib.h"  
static int averageFunc(lua_State *L)  
{  
    int n = lua_gettop(L);  
    double sum = 0;  
    int i;  
<span class="cm">/* 循环求参数之和 */</span>  
<span class="k">for</span> <span class="p">(</span><span class="n">i</span> <span class="o">=</span> <span class="mi">1</span><span class="p">;</span> <span class="n">i</span> <span class="o">&lt;=</span> <span class="n">n</span><span class="p">;</span> <span class="n">i</span><span class="o">++</span><span class="p">)</span>  
    <span class="n">sum</span> <span class="o">+=</span> <span class="n">lua_tonumber</span><span class="p">(</span><span class="n">L</span><span class="p">,</span> <span class="n">i</span><span class="p">);</span>  

<span class="n">lua_pushn
文章作者: 安全书
文章链接: https://lua.ren/zl/2016-01-01-821_Lua%E5%92%8CC++%E7%9A%84%E4%BA%A4%E4%BA%92%20/
版权声明: 本博客所有文章除特别声明外,均采用 null 许可协议。转载请注明来自 安全书