lua-users home
lua-l archive

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


On Aug 25, 2015 2:37 AM, "Ulrich Schmidt" <u.sch.zw@gmx.de> wrote:
>
> Hi all.
>
> I deal with some really large strings i have to sort in some way and finally create a concatinated result string. The string content doesnt change.
> I store the strings in a table using non integer keys. (eg.: file names)
> I dont want to make copies of the strings because they are large.
> Finally i create a sorted table with integer keys and do a table.concat to create the
> really large result string.
>
> Now the problem:
>
> i want to move a string without making a copy
> from a table '[string] = string"' to a table '[int] = string'.
>
> table.remove() doesnt work because it requests integer keys.
>
> So i do a simple asignment;
>     td[int] = ts["key"];
>     ts["key"] = nil;
>
> As far as i know this creates a copy of the value-sting.
>
> My question/ suggestion:
>
> Why not allow string keys in table.remove?
> Simply remove one entry from the table without shifting around other entries.
>
> Any pros and cons? I overlooked something?
>
>
> Thanks.
> Ulrich.
>
>
>
Lua strings are immutable (they can't be changed), so there should never be multiple copies of a string in one Lua state[1]. Lua will just pass around references (pointers) to them instead, and dispose of them once they're no longer needed (garbage collection). So there's no need to worry about excessive string copying, unless you're modifying one large string frequently (that does require copying as far as I know[2], since it can't modify the original).

[1] for very short strings it might keep multiple copies when this would be more efficient than keeping references, but this is an implementation detail that we don't need to know about. :-)

[2] now I'm curious whether it might actually modify the existing string instead of copying, in cases where there are no remaining references to the original?