lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Monday 19, Javier Guerra Giraldez wrote:
> On Sun, Dec 18, 2011 at 8:05 PM, Gé Weijers <ge@weijers.org> wrote:
> > Even in C++ adding a single character to a string using += can result in
> > copying the whole string to a new buffer, an O(n) operation. There are
> > tricks to keep the amortized complexity of your string operations from
> > getting out of hand, such as doubling the string buffer size when you
> > need to reallocate, but a single operations can still be slow.
> 
> the point isn't about (in)efficiency, but about semantics.  in C++,
> the += operator modifies the value, so any variable that points to the
> same value will see the modification, regardless of if a new string
> has been allocated or not.
> 
> In Lua, if a += operator gets accepted, it would have to be _very_
> clear if it's a mutating operator (and would have to add the
> respective metatable operators) or if it's just sugar for a=a+b
> (making the syntax somewhat misleading)

There is a patch [1] to add += -= *= /= %= ^= operators and metamethods  
__add_eq, __sub_eq, etc...  to Lua 5.1.4  The operators are mutable.

It even handles this:
obj.field += 42

Where 'obj' can be a table or any other type like a userdata value as long as 
it has __index/__newindex metamethods to handle the accessing & updating of 
the 'field'.

1. http://lua-
users.org/files/wiki_insecure/power_patches/5.1/compound_operators_5.1.4.patch

-- 
Robert G. Jakabosky