Lua语言教程2

来源:互联网 发布:什么软件可以越狱的 编辑:程序博客网 时间:2024/04/28 21:43

Lua 语言的简单介绍

文章来源于http://www.lupaworld.com

1. Lua的特点

Lua 是一个小巧的脚本语言。作者是巴西人。该语言的设计目的是为了嵌入应用程序中,从而为应用程序提供灵活的扩展和定制功能。它的主页是 www.lua.org

Lua最著名的应用是在暴雪公司的网络游戏WOW中。

Lua脚本可以很容易的被C/C++代码调用,也可以反过来调用C/C++的函数,这使得Lua在应用程序中可以被广泛应用。不仅仅作为扩展脚本,也可以作为普通的配置文件,代替XML,Ini等文件格式,并且更容易理解和维护。

Lua由标准C编写而成,代码简洁优美,几乎在所有操作系统和平台上都可以编译,运行。一个完整的Lua解释器不过200k,在目前所有脚本引擎中,Lua的速度是最快的。这一切 都决定了Lua是作为嵌入式脚本的最佳选择。

Lua 有一个同时进行的JIT项目,提供在特定平台上的即时编译功能,这将给Lua带来更加优秀的性能。请访问 http://luajit.luaforge.net/ 来了解这个项目。

和Python等脚本不同,Lua并没有提供强大的库,这是由它的定位决定的。所以Lua不适合作为开发独立应用程序的语言。不过Lua还是具备了比如数学运算和字符串处理等基本的功能。

Lua 目前的最新版本是 5.1.

 

Lua只有一种数据类型,table. 实际上就是hash表。它用这个来模拟数组,链表等等。 在语法上,Lua支持如下形式:

data = {} --定义一个table   data.i = 1   data.name = "jason"   data.package = {1,2,2,3,56,7}   data.others = {}   data.others.a = 1   data.others.b = 1.1

这使得Lua具有了跟C的struct类似的形式,非常便于设计C函数的参数,用一个table就可以传入很复杂的参数。

2. 数据交换介绍

  1. Lua和C程序通过一个堆栈交换数据: struct lua_State

  2. 堆栈的序号可以从栈顶和栈底计数,从栈底计数,则栈底是1,向栈顶方向递增。从栈顶计数,则栈顶是-1,向栈底方向递减。一般都用从栈顶计数的方式。堆栈的默认大小是20,可以用lua_checkstack修改.用lua_gettop则可以获得栈里的元素数目。并不是说在栈顶有一个整形元素。而是计算了一下栈顶元素在栈里的正index,相当于元素数目。

  3. Lua 调用C函数用的堆栈是临时的,调用结束之后就被销毁了。

  4. 如何从堆栈中获取从Lua脚本中的参数

    1. 如果知道Lua脚本中某个全局变量的名字,可以用void lua_getglobal (lua_State *L, const char *name) 。这个函数会将name所指Lua变量的值放在栈顶.

    2. 如果是在C 函数中要获取Lua调用函数使用的参数:

      1. 首先用lua_gettop检查参数数量

      2. 用lua_is...类函数检测参数的类型,做好错误处理

      3. 用lua_to...类函数将参数转换为number或者string.(对Lua来说,只有这两种简单类型)

        lua_tonumber返回的是double

        lua_tostring返回的是char*

      4. 用lua_remove从栈中删除掉元素

      5. 继续获取下一个元素. 因为每次都调用lua_remove,所以每次调用lua_tonumber,使用的index都将固定是-1,即栈顶。

      6. 如果lua_istable成立,那么说明栈顶是一个table.注意table是不能取出来的,只能把table里的元素一个个取出来。

        首先把元素的名字压入栈顶: lua_pushstring(L,"i"); 然后就可以用lua_gettable调用,值会放在栈顶。同时刚才压入的元素名字被弹出。 用上面的办法,可以把这个值取出来。记得也应该lua_remove。 如果table的某一个元素也是table,重复即可。 当table的所有元素都取完了,记住这个table本身还在堆栈里,要用lua_remove把它删除。

      7. 如果要获取的是一个数组(所谓数组,其实就是key是从1开始的数字序列的table,并且值类型相同),用lua_next可以遍历这个数组:

        首先lua_pushnil,压入一个空值,然后

        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
  5. 如何从C返回数据给Lua脚本

    用lua_push...类函数压入数据到堆栈中,并用return n;来告诉Lua返回了几个返回值。 Lua是天生支持多个返回值的,如 x,y = Test()。 Lua会根据n从栈里取相应的数据。

    如果要返回一个table:

    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.其他都被弹掉了。

    如果要返回一个数组,用如下代码:(注意那个关于trick的注释,我在等官方的解释。经过验证,这个问题只在windows版本调用dll中方法的时候出现。WinCE正常)

    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 < arri.size();i++)        {            lua_pushnumber(L,arri[i]);            lua_rawseti(L,-2,i+1);        }     }     lua_settable(L,-3);

    这样产生的数组可以在Lua中如下遍历:

    for i,v in ipairs(data.arri) do        print(v)     end

    或者是

    for i=1,table.getn(data.arri) do        print(data.arri[i])     end

    只有数组才能这样,name,value构成的Record不行,table.getn也只对数组有效。

  6. 由于上述代码的高度相似性,所以很容易实现自动生成这些代码。比如,根据C的一个struct定义:

    typedef enum {    BR_9600,    BR_4800,} BaudRate;typedef struct flag{    int onoff;    int j;    long l;    double d;    char* name;    BaudRate rate;}flag;

    可以自动产生如下代码:

    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;}

    LuaToData也是类似的。

    如果使用面向对象的方式封装起flag来,把DataToLua变成flag类的一个方法,就更加方便了。

3. C和Lua脚本互相调用举例

首先是C的主程序初始化Lua脚本引擎,并注册一些函数供脚本中调用:

//function for Lua to call//return a integer array to the scriptstatic 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;}

脚本的代码如下:

array = getarr()if array ~= nil then    result = 1    for i=1,table.getn(array),1 do        print(array[i])    endelse    result = 0end

4. 参考资料

  1. http://www.lua.org

文章来源于http://www.lupaworld.com

原创粉丝点击