function newtable(t) n = setmetatable(t,{__mode="v"}) for k,v in pairs(t) do n[k] = v end return n; end -- normalized printing function eles(t,f) f = f or pairs all = {} for k,v in f(t) do table.insert( all, "["..tostring(k).."]="..tostring(v) ) end table.sort( all ) return tostring(t).."{"..table.concat(all,',').."}" end -- basic weak-reference table test local src = "return { 'one', 'two', 'three', 'four', a='aaa', b='bbb', c='ccc', d='ddd'}" local weak = newtable( loadstring(src)() ) local strong = { weak[1], weak[3], a=weak.a, c=weak.c } print( 'before, weak:', eles(weak) ) print( 'before, strong:', eles(strong) ) print( 'gc', pcall( collectgarbage, "collect" ) ) print( 'after, weak:', eles(weak) ) print( 'after, strong:', eles(strong) ) print( 'gc', pcall( collectgarbage, "collect" ) ) print( 'after, weak:', eles(weak) ) print( 'after, strong:', eles(strong) ) print( '-- concat tests' ) function tryconcat(t) print( table.concat(t) ) print( table.concat(t,'--') ) print( table.concat(t,',',2) ) print( table.concat(t,',',2,2) ) print( table.concat(t,',',5,2) ) end tryconcat( newtable{ "one", "two", "three", a='aaa', b='bbb', c='ccc' } ) tryconcat( newtable{ "one", "two", "three", "four", "five" } ) function tryconcat(t) print( table.concat(t) ) print( table.concat(t,'--') ) print( table.concat(t,',',2) ) end tryconcat( newtable{ a='aaa', b='bbb', c='ccc', d='ddd', e='eee' } ) tryconcat( newtable{ [501]="one", [502]="two", [503]="three", [504]="four", [505]="five" } ) tryconcat( newtable{} ) -- insert, maxn print( '-- insert, maxn tests' ) local t = newtable{ "one", "two", "three", a='aaa', b='bbb', c='ccc' } print( eles(t) ) table.insert(t,'six'); print( eles(t) ) table.insert(t,1,'seven'); print( eles(t) ) table.insert(t,4,'eight'); print( eles(t) ) table.insert(t,7,'nine'); print( eles(t) ) table.insert(t,10,'ten'); print( eles(t) ) -- remove print( '-- remove tests' ) t = newtable{ "one", "two", "three", "four", "five", "six", "seven", [10]="ten", a='aaa', b='bbb', c='ccc' } print( eles(t) ) print( 'table.remove(t)', table.remove(t) ); print( eles(t) ) print( 'table.remove(t,1)', table.remove(t,1) ); print( eles(t) ) print( 'table.remove(t,3)', table.remove(t,3) ); print( eles(t) ) print( 'table.remove(t,5)', table.remove(t,5) ); print( eles(t) ) print( 'table.remove(t,10)', table.remove(t,10) ); print( eles(t) ) print( 'table.remove(t,-1)', table.remove(t,-1) ); print( eles(t) ) print( 'table.remove(t,-1)', table.remove(t,-1) ) ; print( eles(t) ) -- sort print( '-- sort tests' ) function sorttest(t,f) t = (t) print( table.concat(t,'-') ) if f then table.sort(t,f) else table.sort(t) end print( table.concat(t,'-') ) end --[[ sorttest( newtable{ "one", "two", "three" } ) sorttest( newtable{ "www", "vvv", "uuu", "ttt", "sss", "zzz", "yyy", "xxx" } ) sorttest( newtable{ "www", "vvv", "uuu", "ttt", "sss", "zzz", "yyy", "xxx" }, function(a,b) return b