lua-users home
lua-l archive

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


List,

I'm writing some code that might potentially handle very large strings. To write this properly/efficient I have a question on string immutability.

What the wiki says [1];
> Immutability of strings
> 
> Lua strings are immutable and interned. This has some implications.
> To create a string that differs in only one-character from an 
> existing 100 MB string requires creating an entirely new 100 MB 
> string since the original string cannot be modified.

Does this mean that in the following snippet;

local first  = [[ some 100mb stuff here ]]
local second = first
local third  = first .. "x"

There actually only 1 100mb memory block is allocated for both variables 'first' and 'second' as they share the same value (and point to the same memory block because it is only a simple assignment)?
And for 'third' a new memory block is allocated to store a full copy of the 100mb data? Because it assigns an expression?

If 'first' and 'second' share the memory, it means I can freely assign my large string or pass it around as a function argument (as long as I don't modify it). But if they each get their own copy in memory, then I should be very careful and probably limit the string to a single shared upvalue.

Any help is appreciated.
Thijs

[1] http://lua-users.org/wiki/ImmutableObjects