2010-11-23 29 views
2

只是在Lua上阅读了一个项目。我不喜欢用来连接字符串的'..'运算符(对我来说看起来很不自然)。我对Lua还不够了解 - 但它看起来非常灵活。Lua中的字符串连接

是否有可能以某种方式'修改'此行为(也许使用metatables?),以便我可以使用'+'而不是'..'来进行字符串连接?

+0

你为什么不使用join()方法? – Mudassir 2010-11-23 10:31:10

+0

@mudassir:我试图让脚本编写者(最终是我自己)的生活更轻松。目标受众不是编码员。所以我希望他们能够写出简单的语句,例如greeting ='hello'+'world' – skyeagle 2010-11-23 11:35:34

+2

字符串与“+”的连接是邪恶的,任何实现它的人都应该死于缓慢而痛苦的死亡。 – 2010-11-23 14:06:48

回答

3

是的,这是可能的。 This article from IBM具有使用一个特殊的“字符串”类中的一个例子:

-- 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) 

这种方法的优点是它不会对现有的字符串表的脚趾一步,这是稍微清楚现有的Lua用户认为您正在与__add运营商进行某种“不同”的活动。

6

试试这个代码:

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