﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>C++博客-一路向北-文章分类-LUA</title><link>http://www.cppblog.com/deane/category/6754.html</link><description>        前进......</description><language>zh-cn</language><lastBuildDate>Tue, 20 May 2008 03:10:15 GMT</lastBuildDate><pubDate>Tue, 20 May 2008 03:10:15 GMT</pubDate><ttl>60</ttl><item><title>LuaBind --最强大的Lua C++ Bind</title><link>http://www.cppblog.com/deane/articles/49208.html</link><dc:creator>李阳</dc:creator><author>李阳</author><pubDate>Thu, 08 May 2008 05:52:00 GMT</pubDate><guid>http://www.cppblog.com/deane/articles/49208.html</guid><wfw:comment>http://www.cppblog.com/deane/comments/49208.html</wfw:comment><comments>http://www.cppblog.com/deane/articles/49208.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/deane/comments/commentRss/49208.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/deane/services/trackbacks/49208.html</trackback:ping><description><![CDATA[&nbsp;&nbsp;&nbsp;&nbsp; 摘要: 转LuaBind --最强大的Lua C++ Bind 1 介绍LuaBind 是一个帮助你绑定C++和Lua的库.她有能力暴露 C++ 函数和类到 Lua . 她也有能力支持函数式的定义一个Lua类,而且使之继承自C++或者Lua. Lua类可以覆写从 C++ 基类继承来的虚函数. 她的目标平台是Lua 5.0 ,不能支持Lua 4.0 .她利用模板原编程技术实现.这意味着,你不需要额外的预...&nbsp;&nbsp;<a href='http://www.cppblog.com/deane/articles/49208.html'>阅读全文</a><img src ="http://www.cppblog.com/deane/aggbug/49208.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/deane/" target="_blank">李阳</a> 2008-05-08 13:52 <a href="http://www.cppblog.com/deane/articles/49208.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Lua 的简单介绍</title><link>http://www.cppblog.com/deane/articles/47058.html</link><dc:creator>李阳</dc:creator><author>李阳</author><pubDate>Mon, 14 Apr 2008 09:27:00 GMT</pubDate><guid>http://www.cppblog.com/deane/articles/47058.html</guid><wfw:comment>http://www.cppblog.com/deane/comments/47058.html</wfw:comment><comments>http://www.cppblog.com/deane/articles/47058.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.cppblog.com/deane/comments/commentRss/47058.html</wfw:commentRss><trackback:ping>http://www.cppblog.com/deane/services/trackbacks/47058.html</trackback:ping><description><![CDATA[<p><br>&nbsp;</p>
<p>&nbsp;</p>
<div class=toc>
<dl>
<dt><span class=section><a href="http://blog.vckbase.com/jzhang/archive/2006/08/18/21972.html#d0e4"><u><font color=#800080>1. Lua的特点</font></u></a></span>
<dt><span class=section><a href="http://blog.vckbase.com/jzhang/archive/2006/08/18/21972.html#d0e34"><u><font color=#800080>2. 数据交换介绍</font></u></a></span>
<dt><span class=section><a href="http://blog.vckbase.com/jzhang/archive/2006/08/18/21972.html#d0e125"><u><font color=#800080>3. C和Lua脚本互相调用举例</font></u></a></span>
<dt><span class=section><a href="http://blog.vckbase.com/jzhang/archive/2006/08/18/21972.html#d0e136"><u><font color=#800080>4. 参考资料</font></u></a></span></dt></dl></div>
<div class=section lang=en>
<div class=titlepage>
<div>
<div>
<h2 class=title style="CLEAR: both"><a name=d0e4></a>1.&nbsp;Lua的特点</h2>
</div>
</div>
</div>
<p>Lua 是一个小巧的脚本语言。作者是巴西人。该语言的设计目的是为了嵌入应用程序中，从而为应用程序提供灵活的扩展和定制功能。它的主页是 <a href="http://www.lua.org/" target=_top><u><font color=#0000ff>www.lua.org</font></u></a>。</p>
<p>Lua最著名的应用是在暴雪公司的网络游戏WOW中。</p>
<p>Lua脚本可以很容易的被C/C++代码调用，也可以反过来调用C/C++的函数，这使得Lua在应用程序中可以被广泛应用。不仅仅作为扩展脚本，也可以作为普通的配置文件，代替XML,Ini等文件格式，并且更容易理解和维护。</p>
<p>Lua由标准C编写而成，代码简洁优美，几乎在所有操作系统和平台上都可以编译，运行。一个完整的Lua解释器不过200k，在目前所有脚本引擎中，Lua的速度是最快的。这一切 都决定了Lua是作为嵌入式脚本的最佳选择。</p>
<p>Lua 有一个同时进行的JIT项目，提供在特定平台上的即时编译功能，这将给Lua带来更加优秀的性能。请访问 <a href="http://luajit.luaforge.net/" target=_top><u><font color=#0000ff>http://luajit.luaforge.net/</font></u></a> 来了解这个项目。</p>
<p>和Python等脚本不同，Lua并没有提供强大的库，这是由它的定位决定的。所以Lua不适合作为开发独立应用程序的语言。不过Lua还是具备了比如数学运算和字符串处理等基本的功能。</p>
<p>Lua 目前的最新版本是 5.1.</p>
<p>&nbsp;</p>
<p>Lua只有一种数据类型，table. 实际上就是hash表。它用这个来模拟数组，链表等等。 在语法上，Lua支持如下形式：</p>
<pre class=programlisting>   data = {} --定义一个table
data.i = 1
data.name = "<a title=我的主页 href="http://jason.rocklv.net/" target=_blank><a title=我的主页 href="http://jason.rocklv.net/" target=_blank><u><font color=#0000ff>jason</font></u></a></a>"
data.package = {1,2,2,3,56,7}
data.others = {}
data.others.a = 1
data.others.b = 1.1</pre>
<p>这使得Lua具有了跟C的struct类似的形式，非常便于设计C函数的参数，用一个table就可以传入很复杂的参数。</p>
</div>
<div class=section lang=en>
<div class=titlepage>
<div>
<div>
<h2 class=title style="CLEAR: both"><a name=d0e34></a>2.&nbsp;数据交换介绍</h2>
</div>
</div>
</div>
<div class=orderedlist>
<ol type=1>
    <li>
    <p>Lua和C程序通过一个堆栈交换数据: struct lua_State</p>
    <li>
    <p>堆栈的序号可以从栈顶和栈底计数，从栈底计数，则栈底是1,向栈顶方向递增。从栈顶计数，则栈顶是-1,向栈底方向递减。一般都用从栈顶计数的方式。堆栈的默认大小是20，可以用lua_checkstack修改.用lua_gettop则可以获得栈里的元素数目。并不是说在栈顶有一个整形元素。而是计算了一下栈顶元素在栈里的正index,相当于元素数目。</p>
    <li>
    <p>Lua 调用C函数用的堆栈是临时的，调用结束之后就被销毁了。</p>
    <li>
    <p>如何从堆栈中获取从Lua脚本中的参数</p>
    <div class=orderedlist>
    <ol type=a>
        <li>
        <p>如果知道Lua脚本中某个全局变量的名字，可以用void lua_getglobal (lua_State *L, const char *name) 。这个函数会将name所指Lua变量的值放在栈顶.</p>
        <li>
        <p>如果是在C 函数中要获取Lua调用函数使用的参数：</p>
        <div class=orderedlist>
        <ol type=i>
            <li>
            <p>首先用lua_gettop检查参数数量</p>
            <li>
            <p>用lua_is...类函数检测参数的类型，做好错误处理</p>
            <li>
            <p>用lua_to...类函数将参数转换为number或者string.(对Lua来说，只有这两种简单类型)</p>
            <p>lua_tonumber返回的是double</p>
            <p>lua_tostring返回的是char*</p>
            <li>
            <p>用lua_remove从栈中删除掉元素</p>
            <li>
            <p>继续获取下一个元素. 因为每次都调用lua_remove,所以每次调用lua_tonumber,使用的index都将固定是-1，即栈顶。</p>
            <li>
            <p>如果lua_istable成立，那么说明栈顶是一个table.注意table是不能取出来的，只能把table里的元素一个个取出来。</p>
            <p>首先把元素的名字压入栈顶： lua_pushstring(L,"i"); 然后就可以用lua_gettable调用，值会放在栈顶。同时刚才压入的元素名字被弹出。 用上面的办法，可以把这个值取出来。记得也应该lua_remove。 如果table的某一个元素也是table，重复即可。 当table的所有元素都取完了，记住这个table本身还在堆栈里，要用lua_remove把它删除。</p>
            <li>
            <p>如果要获取的是一个数组(所谓数组，其实就是key是从1开始的数字序列的table,并且值类型相同),用lua_next可以遍历这个数组：</p>
            <p>首先lua_pushnil，压入一个空值，然后</p>
            <pre class=programlisting> while (lua_next(L, -2) != 0)
            {
            if(lua_isnumber(L,-1)) //判断元素类型，也可能是string
            {
            arrf.add((float)lua_tonumber(L, -1));//获取元素的值
            lua_remove(L,-1);
            }
            }
            lua_remove(L,-1);//删除NIL</pre>
            </li>
        </ol>
        </div>
        </li>
    </ol>
    </div>
    <li>
    <p>如何从C返回数据给Lua脚本</p>
    <p>用lua_push...类函数压入数据到堆栈中，并用return n;来告诉Lua返回了几个返回值。 Lua是天生支持多个返回值的，如 x,y = Test()。 Lua会根据n从栈里取相应的数据。</p>
    <p>如果要返回一个table:</p>
    <pre class=programlisting>     lua_newtable(L);//创建一个表格，放在栈顶
    lua_pushstring(L, "mydata");//压入key
    lua_pushnumber(L,66);//压入value
    lua_settable(L,-3);//弹出key,value，并设置到table里面去
    lua_pushstring(L, "subdata");//压入key
    lua_newtable(L);//压入value,也是一个table
    lua_pushstring(L, "mydata");//压入subtable的key
    lua_pushnumber(L,53);//value
    lua_settable(L,-3);//弹出key,value,并设置到subtable
    lua_settable(L,-3);//这时候父table的位置还是-3,弹出key,value(subtable),并设置到table里去
    lua_pushstring(L, "mydata2");//同上
    lua_pushnumber(L,77);
    lua_settable(L,-3);
    return 1;//堆栈里现在就一个table.其他都被弹掉了。</pre>
    <p>如果要返回一个数组，用如下代码：(注意那个关于trick的注释，我在等官方的解释。经过验证，这个问题只在windows版本调用dll中方法的时候出现。WinCE正常)</p>
    <pre class=programlisting>     lua_pushstring(L,"arri");
    lua_newtable(L);
    {
    //a trick:otherwise the lua engine will crash. This element is invisible in Lua script
    lua_pushnumber(L,-1);
    lua_rawseti(L,-2,0);
    for(int i = 0; i &lt; arri.size();i++)
    {
    lua_pushnumber(L,arri[i]);
    lua_rawseti(L,-2,i+1);
    }
    }
    lua_settable(L,-3);</pre>
    <p>这样产生的数组可以在Lua中如下遍历：</p>
    <pre class=programlisting>     for i,v in ipairs(data.arri) do
    print(v)
    end</pre>
    <p>或者是</p>
    <pre class=programlisting>     for i=1,table.getn(data.arri) do
    print(data.arri[i])
    end</pre>
    <p>只有数组才能这样，name,value构成的Record不行，table.getn也只对数组有效。</p>
    <li>
    <p>由于上述代码的高度相似性，所以很容易实现自动生成这些代码。比如，根据C的一个struct定义：</p>
    <pre class=programlisting>typedef enum
    {
    BR_9600,
    BR_4800,
    } BaudRate;
    typedef struct flag
    {
    int onoff;
    int j;
    long l;
    double d;
    char* name;
    BaudRate rate;
    }flag;
    </pre>
    <p>可以自动产生如下代码：</p>
    <pre class=programlisting>bool DataToLua(flag data,lua_State *L)
    {
    lua_newtable(L);
    lua_pushstring(L,"onoff");
    lua_pushnumber(L,(double)data.onoff);
    lua_settable(L,-3);
    lua_pushstring(L,"j");
    lua_pushnumber(L,(double)data.j);
    lua_settable(L,-3);
    lua_pushstring(L,"l");
    lua_pushnumber(L,(double)data.l);
    lua_settable(L,-3);
    lua_pushstring(L,"d");
    lua_pushnumber(L,(double)data.d);
    lua_settable(L,-3);
    lua_pushstring(L,"name");
    lua_pushstring(L,data.name.c_str());
    lua_settable(L,-3);
    lua_pushstring(L,"rate");
    lua_pushnumber(L,(double)(int)data.rate);
    lua_settable(L,-3);
    return true;
    }</pre>
    <p>LuaToData也是类似的。</p>
    <p>如果使用面向对象的方式封装起flag来，把DataToLua变成flag类的一个方法，就更加方便了。</p>
    </li>
</ol>
</div>
</div>
<div class=section lang=en>
<div class=titlepage>
<div>
<div>
<h2 class=title style="CLEAR: both"><a name=d0e125></a>3.&nbsp;C和Lua脚本互相调用举例</h2>
</div>
</div>
</div>
<p>首先是C的主程序初始化Lua脚本引擎，并注册一些函数供脚本中调用：</p>
<pre class=programlisting>//function for Lua to call
//return a integer array to the script
static int l_getarr (lua_State *L)
{
lua_newtable(L);//create table
lua_pushnumber(L,1);//push the value
lua_rawseti(L,-2,1);//set t[1]=v
lua_pushnumber(L,2);
lua_rawseti(L,-2,2);
lua_pushnumber(L,3);
lua_rawseti(L,-2,3);
lua_pushnumber(L,4);
lua_rawseti(L,-2,4);
return 1;
}
int main()
{
lua_State *L = lua_open();   /* opens Lua */
luaopen_base(L);             /* opens the basic library */
luaopen_table(L);            /* opens the table library */
luaopen_string(L);           /* opens the string lib. */
luaopen_math(L);             /* opens the math lib. */
lua_pushcfunction(L, l_getarr); // Register a function
lua_setglobal(L, "getarr");
if (lua_dofile(L, "testlua.lua"))//Load the script file and Run it
{
printf("run script failed\n");
}
else
{
lua_getglobal(L, "result"); //Get the global variant in Lua script
if(lua_isnumber(L,-1))
{
printf("The result of the Lua script is %d\n",lua_tonumber(L,-1));
}
}
lua_close(L);
return 0;
}</pre>
<p>脚本的代码如下：</p>
<pre class=programlisting>array = getarr()
if array ~= nil then
result = 1
for i=1,table.getn(array),1 do
print(array[i])
end
else
result = 0
end
</pre>
</div>
<div class=section lang=en>
<div class=titlepage>
<div>
<div>
<h2 class=title style="CLEAR: both"><a name=d0e136></a>4.&nbsp;参考资料</h2>
</div>
</div>
</div>
<div class=orderedlist>
<ol type=1>
    <li>
    <p><a href="http://www.lua.org/" target=_top><u><font color=#0000ff>http://www.lua.org</font></u></a></p>
    </li>
</ol>
</div>
</div>
<img src ="http://www.cppblog.com/deane/aggbug/47058.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.cppblog.com/deane/" target="_blank">李阳</a> 2008-04-14 17:27 <a href="http://www.cppblog.com/deane/articles/47058.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>