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

来源:互联网 发布:艾媒咨询数据 编辑:程序博客网 时间:2024/06/01 10:00
链接: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!
原创粉丝点击