20070709 LUA 调用 C 函数 多个返回值  2
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; //平均值 函数

#undef luaL_dostring
#define luaL_dostring(L,s) \\
 (luaL_loadstring(L, s) &line;&line; lua_pcall(L, 0, LUA_MULTRET, 0))
void CTestLuaSpDlg::OnLuaF()
&leftsign;
 // TODO: 在此添加命令处理程序代码
 lua_State *L = lua_open();
 

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

 lua_register(L, "average", average);
 const char *buf = "r1,r2=average(500, 10)  return r1,r2";

 luaL_dostring(L, buf);

 //lua_pushstring(L,"r1");
 //lua_pushstring(L,"r2");
 //lua_gettable(L,LUA_GLOBALSINDEX);
 //lua_getglobal(L,"r1");
 int result = lua_tonumber(L,-1);
 lua_pop(L,1);
 //lua_getglobal(L,"r2");
  result = lua_tonumber(L, -1);

 lua_close(L);
&rightsign;

~~~~~~~~
资料:

int main (void)
&leftsign;
   lua_State *L = lua_open();
  //lua base libs; comment the next 4 lines if you are using Lua version 5.11
   lua_baselibopen(L);
   lua_iolibopen(L);
   lua_strlibopen(L);
   lua_mathlibopen(L); 
   char myArg[] = "result = 2 * 2";
   luaL_dostring(L,myArg);
   lua_pushstring(L,"result")
   lua_gettable(L,LUA_GLOBALSINDEX);
   int result = lua_tonumber(L,-1);
   printf("Value of result is %d\\n",result);
   lua_close(L);
   return 0;
&rightsign;

~~~~~~~~~~~~

Loading and executing a simple script

We\’ll start off with a simple appliance of a lua script, setting the size of a applications resolution at startup.

 screenWidth = 800
 screenHeight = 600

and save that as settings.lua and place into your executable directory

int main (void)
&leftsign;
  lua_State *L = lua_open();
  //lua base libs; comment the next 4 lines if you are using Lua version 5.11
  lua_baselibopen(L);
  lua_iolibopen(L);
  lua_strlibopen(L);
  lua_mathlibopen(L);
  int width,height;
  if(luaL_loadfile(L,"settings.lua") &line;&line; lua_pcall(L,0,0,0))
     printf("Error failed to load %s",lua_tostring(L,-1));
  else
  &leftsign;
       lua_getglobal(L,"screenWidth");
       if(lua_isnumber(L,-1))
          width = lua_tonumber(L,-1);
       else
       &leftsign; 
            printf("Error screenWidth is NAN\\n");
            width = 600;
       &rightsign;
       lua_getglobal(L,"screenHeight");
       if(lua_isnumber(L,-1))
          height = lua_tonumber(L,-1);
       else
       &leftsign; 
            printf("Error screenHeight is NAN\\n");
            height = 480;
       &rightsign;
  &rightsign;
  lua_close(L);
  // initialise screen yadda
  return 0;
&rightsign;

历史博文

标签:, , , ,
四月 2, 2008 at 3:59 下午 by yippee 1,036 次
Category: Dev
Tags: , , , ,