Created
July 1, 2010 23:05
-
-
Save malkia/460695 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function DeleteArrayElements( array, index, count ) | |
-- Deletes one or more (count) array elements from the specified index. | |
-- Returns an undo function, which if called would revert the operation. | |
local deletedElements = {} | |
assert( index >= 1 and index <= #array, "index=" .. index .. " must be >= 1 and <= " .. #array .. " (#array)" ) | |
assert( count >= 1 and count <= #array - index + 1, "count=" .. count .. " must be >= 1 and <= " .. #array - index + 1 .. " (#array - index + 1) where #array=" .. #array .. " and index=" .. index) | |
for i = 0, count - 1 do | |
deletedElements[ #deletedElements + 1 ] = array[ index + i ] | |
end | |
for i = 0, #array - index - count do -- move the elements up | |
array[ index + i ] = array[ index + count + i ] | |
end | |
for i = 1, count do -- shrink the array | |
array[ #array ] = nil | |
end | |
return function() | |
InsertArrayElements( array, index, deletedElements ) | |
end | |
end | |
function InsertArrayElements( array, index, elements ) | |
-- Inserts, or appends (if index == #array + 1), one or more elements to the array from the specified index. | |
-- Returns an undo function, which if called would revert the operation. | |
local count = #elements | |
assert( index >= 1 and index <= #array + 1, "index=" .. index .. " must be >= 1 and <= " .. #array .. " (#array + 1)" ) | |
assert( count >= 1, "#elements=" .. count .. " must be >= 1" ) | |
if index <= #array then | |
for i = 1, count do -- extend the array | |
array[ #array + 1 ] = "" | |
end | |
for i = #array, index + count, -1 do -- move the elements down | |
array[ i ] = array[ i - count ] | |
end | |
end | |
for i = 1, count do -- copy the elements | |
array[ index + (i - 1) ] = elements[ i ] | |
end | |
return function() -- Undo Operation | |
DeleteArrayElements( array, index, count ) | |
end | |
end | |
function TestInsertDeleteArrayElements() | |
local a1 = { 1, 2, 3, 4, "Five", { 1, 2 }, 3 } | |
local undo = {} | |
for i=1,#a1 do print(a1[i]) end | |
undo = DeleteArrayElements(a1, 2, 5) | |
print("\nAfter Delete:") | |
for i=1,#a1 do print(a1[i]) end | |
undo(); print("\nUndo:") | |
for i=1,#a1 do print(a1[i]) end | |
undo = InsertArrayElements(a1, 2, { "Du Du", 3.14, "Samba Di Generio" }) | |
print("\nAfter Insert:") | |
for i=1,#a1 do print(a1[i]) end | |
undo(); print("\nUndo:") | |
for i=1,#a1 do print(a1[i]) end | |
end | |
TestInsertDeleteArrayElements() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment