现在的位置: 首页 > 综合 > 正文

Lua脚本调用C函数小结

2013年10月11日 ⁄ 综合 ⁄ 共 1898字 ⁄ 字号 评论关闭

 Lua脚本调用C函数小结
 
Lua脚本调用C函数小结
仔细的学习了一下,发现功能的确非常强大。用脚本调用C的函数,都希望有如下特性:
1. 多输出
Lua 本身就支持函数返回多个值,语法如下:
x,y = testext.Test()

2. 可以使用类似C的结构的形式输入输出
Lua 的Table可以在形式上很好的模仿C的结构,
a = {}
a.i = 101
a.name = "jason"
a.subtable = {}
a.subtable.i = 99
相当于
struct A
{
  int i;
  string name;
  struct subtable
  { 
     int i;
  }
}
这个能力一般的脚本是不具备的。我们的应用中,很多参数都是用结构组织的,
以前使用TCL,就只能让用户平铺的输入。现在好多了. 

输出也可以,在C的函数中可以返回一个table给Lua脚本。TCL也可以返回一个Array.

不过给Lua写C函数太痛苦了,全部是基于堆栈的,而且非常的不直观,看来还需要
研究一下如何封装。网上有不少基于模版的封装,得好好看看。

测试代码如下:


Lua
local testlib 
= package.loadlib("testext.dll","luaopen_testext")
if
(testlib)then
    testlib()
else

    
-- Error
end

= {}
a.i 
= 101

a.name 
= "jason hah"
a.subtable 
= {}
a.subtable.i 
= 99

= testext.Complex(a)
print(r.mydata)

C
static int Complex(lua_State*
 L)
{
    
//1. get the table from Lua Script

    int i = lua_gettop(L);
    
if( i != 1
)
    {
         lua_pushstring(L, 
"Complex(table)"
 ) ;
         
return 1
;
    }

    if (lua_istable(L, 1))
    {
        lua_pushstring(L,
"i"
);
        lua_gettable(L,
-2
);
        
if(lua_isnumber(L,-1
))
        {
            
int j = lua_tonumber(L, -1
);
            printf(
"The table.j = %d "
,j);
        }
        lua_remove(L,
-1
);

        lua_pushstring(L,"name");
        lua_gettable(L,
-2
);
        
if(lua_isstring(L,-1
))
        {
            
char* name = lua_tostring(L, -1
);
            printf(
"The table.name = %s "
,name);
        }

        lua_remove(L,-1);
        lua_pushstring(L,
"subtable"
);
        lua_gettable(L,
-2
);
        
if(lua_istable(L,-1
))
        {
            lua_pushstring(L,
"i"
);
            lua_gettable(L,
-2
);
            
if(lua_isnumber(L,-1
))
            {
                
int j = lua_tonumber(L, -1
);
                printf(
"The table.j = %d "
,j);
            }
        }
    }
    
else

    {
        lua_pushstring(L, 
"Complex(table)" ) ;
        
return 1
;
    }    
    
//2. Return Another table to Lua Script

    lua_newtable(L);
    lua_pushstring(L, 
"mydata"
);
    lua_pushnumber(L,
66
);
    lua_settable(L,
-3
);    
    
return 1
;
}

抱歉!评论已关闭.