lua-users home
lua-l archive

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



On 07/05/2014 10:40, Thiago L. wrote:
So I have a challenge for you all: A table copy script in less than 270 chars

Rules:
1. It has to have table.copy.deep and table.copy.shallow
2. It has to be smaller than 270 chars
3. It has to handle the following tables:
============================================
local t1,t2,t3,t4,t5 = {},{},{},{},{}

t1[t2]=t3
t1[t3]=t1
t1[t1]=t1
t1[t4]=t3
t1["test"]="it works"
t1[0]=true
t1[true]=false
t1[false]=true
t1[math.huge]="yes"
t1[-math.huge]="no"
t2[t1]=t3
t3[t1]=t4
t4[t4]=t5
t5[t1],t5[t2],t5[t3],t5[t4],t5[t5]=t1,t2,t3,t4,t5
============================================
4. Deep copies must deepcopy table keys (you may use an argument to enable/disable this one) 5. You are not required to copy metatables, but doing so will earn you extra points

Finally, here is the 270 chars long script made: [1]
local k,o,n,s,d=pairs,type,"table"s,d=function(a,b)b={}for x,y in k(a)do b[x]=y end return b end,function(a,r,t)t={}r=r or{}r[a]=t for x,y in k(a)do if n==o(x)then x=r[x]or d(x,r)end if n==o(y)then y=r[y]or d(y,r)end t[x]=y end return t end table.copy={shallow=s,deep=d}


[1] - This one might be a bit easier to read/understand: https://gist.github.com/SoniEx2/fc5d3614614e4e3fe131
Oh and I forgot to add:
Rule 6. No external libs.