table.extend() to add two or more array tables without requiring extra temporary memory.
needsĀ info
SuzannaLinn Resident
A way to add two or more array tables without requiring extra temporary memory.
table.extend(t1, t2)
Appends all elements of array t2 to the end of array t1 The array t2 is cleared and its memory released. Elements are moved directly to avoid intermediate duplication.
Working like this, but without using extra memory during the process:
extend(t1, t2)
table.move(t2, 1, #t2, #t1 + 1, t1)
table.clear(t2) -- but without preserving the allocated space
return t1
end
or better:
table.extend(t1, ...)
Appends the elements of each additional array to the end of array t1, in the order provided. The source arrays are cleared and their memory released. Elements are moved directly to avoid intermediate duplication.
Log In
H
Harold Linden
marked this post as
needsĀ info
H
Harold Linden
Clearing the source table would be pretty unconventional for an
extend()
function.What's the motivating usecase here? Is it all the weird list-based APIs that LSL exposes? IMO it be preferable to had something like
table.append(t1, ...)
that could just take a variable number of args so you don't need to create an intermediary table to add params to the list in a not-ugly way?I can see a usecase for
table.extend()
as well, but mutating the input list feels weird to me.SuzannaLinn Resident
Harold Linden
The idea is to be able to do something like this without running out of memory:
-- simulating a big script that uses a lot of memory
local script = {}
for i = 1,2000 do
script["i "..i ] = i
end
print(ll.GetFreeMemory()) -- > 20907
--
-- two big arrays
local array1 = {}
local array2 = {}
for i = 1,500 do
table.insert(array1, i)
table.insert(array2, i)
end
print(ll.GetFreeMemory()) -- > 4459
--
-- table.extend(array1, array2)
table.move(array2, 1, #array2, #array1 + 1, array1) -- > Error: not enough memory
array2 = {}
The name and format of the function
extend()
, append()
, etc. is not important.Frio Belmonte
Harold Linden My motivating usecase would indeed be the table building for LL function calls, where the second table is an "anonymous literal" since I can't think of a better term for it.
The suggested version of table.append(t, ...) would probably help with that - of course you can do table.insert repeatedly right now, but that gets extremely wordy and it sounds like a multi-variable way of appending large sets to an existing table would help quite a bit, especially if a single table.append uses less memory, bytecode and time than repeated table.inserts.
Best case scenario: automatically performs table.shrink after the appending operation, to ensure you get the most compact parameter chunk possible to pass around.
Of course that approach wouldn't cover needing to fuse actual tables.
WolfGang Senizen
Yeh... i really don't like that table.move is called move.... it make promises it doesn't keep. xD