kenlistian

勤学多思

  IT博客 :: 首页 :: 新随笔 ::  :: 聚合  :: 管理 ::
  412 随笔 :: 0 文章 :: 23 评论 :: 0 Trackbacks
理解Upvalues

把它理解为一个与C static变量等价的东西即可。


如下函数:
 
 static int counter(lua_State* L);

 int newCounter(Lua_State* L){
   lua_pushnumber(L, 0);
   lua_pushcclosure(L, &counter, 1);
   return 1;
  }

  其中调用lua_pushcclosure 函数,就是创建了一个闭包函数,
  即在该counter函数中,可以使用由
      lua_pushnumber  压入的初始值0。
  其中压入一个upvalues值,则在pushcclosure第三个参数个数则为1.

  在函数中
  static int counter (lua_State *L)
  {
     double val = lua_tonumber(L, lua_upvalueindex(1));
     lua_pushnumber(L, ++val); 
     lua_pushvalue(L, -1);        /* duplicate it */
     lua_replace(L, lua_upvalueindex(1));
     return 1;
  }

  lua_upvaluesindex(1) ,就是取出upvalues值,其索引为第一个参数。
  由于这个参数并不是堆栈中索引,而是仅仅表示参数序位的索引,即,取出
  upvalue的当前值。 
  







 

 


posted on 2008-10-27 16:56 kenlistian 阅读(923) 评论(0)  编辑 收藏 引用 所属分类: AI
只有注册用户登录后才能发表评论。