开发者

String concatenation in Lua

just reading up on Lua for a 开发者_运维问答project. I do not like the '..' operator used to concatenate strings (just looks unnatural to me). I do not know enough about Lua yet - but it seems its very flexible.

Is it possible to somehow 'modify' this behaviour (perhaps using metatables?) so that I can use '+' instead of '..' for string concatenation?


Try this code:

getmetatable("").__add = function(x,y) return x..y end
print("hello"+" "+"world")


Yes, it's possible. This article from IBM has one example that uses a special "String" class:

-- Overload the add operation
-- to do string concatenation
--
mt = {}

function String(string)
  return setmetatable({value = string or ''}, mt)
end

-- The first operand is a String table
-- The second operand is a string
-- .. is the Lua concatenate operator
--
function mt.__add(a, b)
  return String(a.value..b)
end

s = String('Hello')
print((s + ' There ' + ' World!').value )

This approach has the advantage that it doesn't step on the toes of the existing string table, and it's slightly more clear to existing Lua users that you're doing something "different" with the __add operator.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜