Created
May 18, 2011 07:50
-
-
Save walterlua/978161 to your computer and use it in GitHub Desktop.
Implementation of JavaScript array.concat() in Lua. Also, adds the function to Lua's table library
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
-- table.copy( array, ... ) returns a shallow copy of array. | |
-- A variable number of additional arrays can be passed in as | |
-- optional arguments. If an array has a hole (a nil entry), | |
-- copying in a given source array stops at the last consecutive | |
-- item prior to the hole. | |
-- | |
-- Note: In Lua, the function table.concat() is equivalent | |
-- to JavaScript's array.join(). Hence, the following function | |
-- is called copy(). | |
table.copy = function( t, ... ) | |
local copyShallow = function( src, dst, dstStart ) | |
local result = dst or {} | |
local resultStart = 0 | |
if dst and dstStart then | |
resultStart = dstStart | |
end | |
local resultLen = 0 | |
if "table" == type( src ) then | |
resultLen = #src | |
for i=1,resultLen do | |
local value = src[i] | |
if nil ~= value then | |
result[i + resultStart] = value | |
else | |
resultLen = i - 1 | |
break; | |
end | |
end | |
end | |
return result,resultLen | |
end | |
local result, resultStart = copyShallow( t ) | |
local srcs = { ... } | |
for i=1,#srcs do | |
local _,len = copyShallow( srcs[i], result, resultStart ) | |
resultStart = resultStart + len | |
end | |
return result | |
end | |
-- Example Usage: | |
local t1 = {1,3,5,7,9} | |
local t2 = {2,4,6,333} | |
t2[6] = 555 -- create hole | |
local t3 = {11,13,17,19} | |
local c = table.copy( t1, t2, t3 ) | |
print( table.concat( c, ", " ) ) -- output: 1, 3, 5, 7, 9, 2, 4, 6, 333, 11, 13, 17, 19 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment