Table.hx 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package lua;
  2. /**
  3. This library provides generic functions for table manipulation.
  4. **/
  5. // TODO: use an abstract here?
  6. @:native("_G.table")
  7. extern class Table<A,B> implements ArrayAccess<B> implements Dynamic<B> {
  8. @:analyzer(no_fusion)
  9. public inline static function create<A,B>(?arr:Array<B>, ?hsh:Dynamic) : Table<A,B> {
  10. return untyped __lua_table__(arr,hsh);
  11. }
  12. public inline static function fromArray<T>(arr:Array<T>) : Table<Int,T>{
  13. var ret = Table.create();
  14. for (idx in 0...arr.length){
  15. ret[idx+1] = arr[idx];
  16. }
  17. return ret;
  18. }
  19. public inline static function fromMap<A,B>(map:Map<A,B>) : Table<A,B>{
  20. var ret = Table.create();
  21. for (k in map.keys()){
  22. ret[untyped k] = map.get(k);
  23. }
  24. return ret;
  25. }
  26. public inline static function fromDynamic<A,B>(dyn:Dynamic) : Table<A,B>{
  27. var ret = Table.create();
  28. for (f in Reflect.fields(dyn)){
  29. ret[untyped f] = Reflect.field(dyn, f);
  30. }
  31. return ret;
  32. }
  33. @:overload(function<A,B>(table:Table<A,B>):Void{})
  34. public static function concat<A,B>(table:Table<A,B>, ?sep:String) : String;
  35. public static function foreach<A,B>(table:Table<A,B>, f:A->B->Void) : Void;
  36. public static function foreachi<A,B>(table:Table<A,B>, f:A->B->Int->Void) : Void;
  37. public static function sort<A,B>(table:Table<A,B>, ?order : A->A->Bool) : Void;
  38. @:overload(function<B>(table:Table<Int,B>, value:B):Void{})
  39. public static function insert<B>(table:Table<Int,B>, pos:Int, value:B) : Void;
  40. @:overload(function<B>(table:Table<Int,B>):Void{})
  41. public static function remove<B>(table:Table<Int,B>, ?pos:Int) : Void;
  42. #if (lua_ver >= 5.2)
  43. public static function pack<T>(args:haxe.extern.Rest<T>) : Table<Int,T>;
  44. public static function unpack<Int,V>(args:lua.Table<Int,V>, ?min : Int, ?max : Int) : Dynamic;
  45. #end
  46. }
  47. typedef AnyTable = Table<Dynamic, Dynamic>;