商讯信箱
用户名: @
密  码:   注册|忘记密码
登录
个人用户经销商
您的位置:首页 > 技术频道 > 正文

Lua中回调的技巧

作者:来自ITPUB论坛  2008-02-15

  【IT168 技术文档】回调的技巧

  回调函数能够提供参数化的数据结构处理方式.

  计算能够计算个数的表的Values和

  function sumover(t, fcn) --fcn(v)   local sum = 0;   table.foreachi(t, function(i,v)   sum = sum + (fcn(v) or 0);   end);   return sum;   end

  这个sumover函数, 你可以为他传递一个数字索引的表和fcn回掉函数做为参数, 并且他会返回这个表中所有value的个数总和.

  使用下面的代码

  local totalCount = sumover(auctions, function(a) return a.count; end);

  来替换

  local totalCount = 0;   table.foreachi(auctions, function(a) totalCount = totalCount + (a.count or 0); end);

  虽然没有太大的区别但第一种更简洁了些.

 

1
【内容导航】
第1页: Lua中回调的技巧
©版权所有。未经许可,不得转载。
[责任编辑:cynthia]
[an error occurred while processing this directive]
[an error occurred while processing this directive]
[an error occurred while processing this directive]