# Linked List package, initiated 02.02.2013

package.checkclib('llist');  # has C dynamic link library been found ?

llist.initstring := 'llist v0.3.0 for Agena as of October 19, 2014\n';

# Converts a linked list to a table
llist.listtotable := proc(l :: llist) is
   local f := llist.iterate(l);
   create local table r(l);
   for i to size l do
      r[i] := f()
   od;
   return r
end;

# add further metamethods

llist.mt := [
   '__tostring' ~ proc(l :: llist) is
      local c, r, sll, f, s;
      c, r, sll := 1, '', size l;
      create seq s(10);
      if sll = 0 then return 'llist()' fi;
      f := llist.iterate(l);
      while c <= sll do
         insert tostring(f()) into s;
         if c % 10 = 0 or c = sll then
            r := r & join(s, ', ') & ', ';
            s := null;
            create seq s(10)
         fi;
         inc c
      od;
      return 'llist(' & r[1 to -3] & ')'
   end
];

# now assign them

scope  # okay, this works in Lua 5.1, too. Do not call debug.getregistry
   if getmetatable :: procedure then  # protect against sandboxing
      local _mt := getmetatable(llist.list());  # get the internal registry metatable for lists
      if assigned(_mt) then
         for i, j in llist.mt do
            _mt[i] := j
         od
      fi
   fi
epocs;