Lua Faq翻译之为什么lua中没有类似于+=的操作符以及用Lua实现C++中的<<操作符

链接:http://lua-users.org/wiki/LuaFaq和http://lua-users.org/wiki/CustomOperators


在实现lua时,目标之一就是简洁。大多数语言包括许多特性,这就意味着他们有许多复杂的特效,比如C++,pythoh,Lisp。很少语言像Forth和lua这样,语法简洁。lua目标是提供那些真正需要的原子特性,但如果需要,你可以利用这些原子特性,实现许多其他复杂的特性。比如可以实现其他语言中的模块(modules),面向对象(OO),在lua 5以后的版本中,还可以利用协程(coroutines)实现异常(exceptions)和线程(threads)。因此lua中没有类似于+=操作符。


如果你真正想实现类似的功能,可以参考链接:http://lua-users.org/wiki/CustomOperators,比如下面的代码,就实现了类似于C++中的<<操作符:


-----------------------------------
--用lua实现类似于c++中的输出操作符<<
--来自:http://lua-users.org/wiki/CustomOperators
-----------------------------------
local CustomOp = {}
function CustomOp:__div(b)
return getmetatable(self.a)["__" .. self.op](self.a,b)
end
setmetatable(CustomOp, {__call =
function(class,a,op)
return setmetatable({a = a,op = op},CustomOp) --注意函数setmetatable返回的是要设置的元表的table
end
})


function enable_cution_ops(mt)
function mt:__div(op)
return CustomOp(self,op)
end
end


osstream = {}
osstream.__index = osstream
enable_cution_ops(osstream)
function osstream:write(s)
io.write(s)
end


osstream['__<<'] = function(self,s)
self:write(s)
return self
end


setmetatable(osstream,{__call =
function(class,file)
file = file or io.output()
return setmetatable({file = file},osstream)
end
})


cout = osstream()
endl = "\n"


--例子
local _=cout / '<<' / 'hello' / '<<' / ',world!' / '<<' / endl  --输出:hello,world!
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值