20070709 LUA 调用 C 函数 返回值
http://www.yippeesoft.com

static int average(lua_State *L)
&leftsign;
/* get number of arguments */
int n = lua_gettop(L);
double sum = 0;
int i;

/* loop through each argument */
for (i = 1; i <= n; i++)
&leftsign;
 /* total the arguments */
 sum += lua_tonumber(L, i);
&rightsign;

/* push the average */
lua_pushnumber(L, sum / n);

/* push the sum */
lua_pushnumber(L, sum);

/* return the number of results */
return 2;
&rightsign;

void CTestLuaSpDlg::OnLuaG()
&leftsign;
// TODO: 在此添加命令处理程序代码
/* initialize Lua */
L = lua_open();

/* load Lua base libraries */
lua_baselibopen(L);

/* register our function */
lua_register(L, "average", average);

/* run the script */

/*const char *buf = "avg, sum = average(10, 20, 30, 40, 50);return sum";

int ii=luaL_dostring(L, buf);*/
 
 luaL_loadfile(L, "\\\\Storage\\\\Program Files\\\\TestLuaSp\\\\add.lua") ;
 //加载后要用lua_resume运行.
 lua_resume(L,0);

 //调用脚本中函数
 lua_getglobal(L, "lua_func1");

 //传给lua_func1参数1,参数2
 lua_pushnumber(L, 21);
 lua_pushnumber(L, 23);

 //调用lua中函数,传入个参数,有一个返回值 ,看lua_call 和lua_pcall区别
 lua_pcall(L, 2, 1, 0);

 //取值
 lua_Number retsum;

 //注意返回值是通过-1来获取
 retsum = lua_tonumber(L, -1);
/* cleanup Lua */
lua_close(L);

 
&rightsign;

function lua_func1(val1, val2)
–调用cbuilder中函数
val1 = average(val1, val2)
return val1
end

历史博文

标签:, , ,
三月 28, 2008 at 3:10 下午 by yippee 1,028 次
Category: Dev
Tags: , , ,