How can I iterate Dynamic object in Haxe - json

I have Object parsed from JSON (haxe.Json.parse()) and I need to iterate over it.
I already tried to cast this object to Array<Dynamic>:
var data:String='{"data":{"0":0,"1":1},"method":"test"}';
var res:{method:String,data:Array<Dynamic>} = haxe.Json.parse(data);
for (n in res.data)
trace('aa')
There is no Can't iterate dynamic exception, just not working (iterating).
I completley don't understand why in Haxe iterating procedure is so difficult.

For the sake of posting a complete answer, and in case other people are wondering
In your first example, you've told the compiler that "res" contains two properties - one called "method" (which is a String) and one called "data" (which is Array). Now the JSON you're using doesn't actually have an Array<Dynamic>, it just has a dynamic object. An Array would look like: "data":[0,1].
So, assuming you meant for the JSON to have data as a Dynamic object, here is how you loop over it, using Reflect (as you mentioned in the comments):
var data:String='{"data":{"0":0,"1":1},"method":"test"}';
var res = haxe.Json.parse(data);
for (n in Reflect.fields(res.data))
trace(Reflect.field(res.data, n));
Note here we don't have to specify the type of "res", since we're using Reflection just leaving it as Dynamic will be fine.
Now, if your JSON actually contains an Array, the code might look like this:
var data:String='{"data":[0,1],"method":"test"}';
var res:{method:String,data:Array<Int>} = haxe.Json.parse(data);
for (n in res.data)
trace(n);
Here you use explicit typing to tell the compiler that res.data is an Array (and this time it actually is), and it can loop over it normally.
The reason you didn't get an error at compile-time is because the compiler thought there was genuinely going to be an array there, as you told it there was. At runtime, whether or not it throws an exception probably depends on the target... but you probably want to stay out of that anyway :)
Demo of both styles of code: http://try.haxe.org/#772A2

Related

Construct object on function ccall in Julia

I am trying to simplify some binding to C but I am not sure if this is even possible, what I am trying to do is pass an array and expect to receive in a function so an object can be constructed by the type specified in the parameter or by ccall calling the correct convert function and initialize a struct object.
Previous code, the bindings are full of Vector3(v...) and Color(c...), is there a way to avoid this be automatic handling?
drawline(startPos, endPos, color) = ccall((:DrawLine3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), Vector3(startPos...), Vector3(endPos...), Color(color...))
drawpoint([10,10,10],[100,100,100],[155,155,155,255]) # call example
Is it possible to reduce the code with something like this?:
struct Vector3
x::Cfloat
y::Cfloat
z::Cfloat
Vector3((x,y,z))=new(x,y,z)
end
#first attempt
#trying to call the Vector3 constructor without calling explicitly
drawpoint(startpos::Vector3,endpos::Vector3,color::Color) = ccall((:DrawPoint3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), startpos,endpos,color)
#second attempt (should be the simplest way to go)
#trying to receive arrays so ccall can convert from list or tuple to Struct object
drawpoint(startpos,endpos,color) = ccall((:DrawPoint3D, "my_lib"), Cvoid, (Vector3,Vector3,Color), startpos,endpos,color)
Is something like this even possible in Julia?
You just need to define the appropriate conversion. ccall will call this for you. I think this should do it:
Base.convert(::Type{Vector3}, x::AbstractVector) = Vector3(x)
You'll probably want to add some length checks and such, and I'd probably recommend using tuples or StaticArrays instead of Vectors for efficiency's sake.

How do I extract metadata from a var when a function returns its symbol?

I'm using re-frame with spec to validate app-db, much like in the todomvc example.
When a user makes an invalid entry, I'm using s/explain-data (in a re-frame interceptor) to return a problems map naming the :predicate which caused validation failure. This predicate is a symbol like project.db/validation-function.
My validation function has metadata which is accessible from the repl using:
(meta #'project.db/validation-function)
The function definition (in the project.db namespace) looks like this:
(defn validation-function
"docstring..."
{:error-message "error message"}
[param]
(function-body...)
The problem is I can't work out how to retrieve the metadata dynamically (working in project.events namespace), for example:
(let [explain-data (s/explain-data spec db)
pred (->> (:cljs.spec.alpha/problems explain-data) first :pred)
msg (what-goes-here? pred)]
msg)
I've tried the following things in place of what-goes-here?:
symbol? gives true
str gives "project.db/validation-function"
meta gives nil
var gives a compile-time error "Unable to resolve var: p1__46744# in this context"
I think the problem is that I'm getting a symbol, but I need the var it refers to, which is where the metadata lives.
I've tried using a macro, but don't really know what I'm doing. This is the closest discussion I could find, but I couldn't work it out.
Help!
In general, you can't do this because vars are not reified in ClojureScript.
From https://clojurescript.org/about/differences#_special_forms :
var notes
Vars are not reified at runtime. When the compiler encounters the var special form it emits a Var instance reflecting compile time metadata. (This satisfies many common static use cases.)
At the REPL, when you evaluate
(meta #'project.db/validation-function)
this is the same as
(meta (var project.db/validation-function))
and when (var project.db/validation-function) is compiled, JavaScript code is emitted to create a cljs.core/Var instance that contains, among other things, the data that you can obtain using meta. If you are curious, the relevant analyzer and compiler code is instructive.
So, if (var project.db/validation-function) (or the reader equivalent #'project.db/validation-function) doesn't exist anywhere in your source code (or indirectly via the use of something like ns-publics) this data won't be available at runtime.
The omission of var reification is a good thing when optimizing for code size. If you enable the :repl-verbose REPL option, you will see that the expression (var project.db/validation-function) emits a significant amount of JavaScript code.
When working with defs at the REPL, the compiler carries sufficient analysis metadata, and things are done—like having evaluations of def forms return the var rather than the value—in the name of constructing an illusion that you are working with reified Clojure vars. But this illusion intentionally evaporates when producing code for production delivery, preserving only essential runtime behavior.
edit: sorry I didn't see that var didn't work for you. Still working on it...
You need to surround the symbol project.db/validation-function with var. This will resolve the symbol to a var.
So what-goes-here? should be
(defn what-goes-here? [pred]
(var pred))

Actionscript: Why does this Event Listener cause massive memory consumption

I have an array of buttons and I attached event listeners like this.
arr[c].addEventListener(MouseEvent.MOUSE_UP, Proxy.go(this, click, Model.categoriesListXml.category_0[i].category_1[j].#category_id, Model.categoriesListXml.category_0[i].category_1[j].#name));
150 of these used 32MB of memory.
When I used the following memory dropped to 2MB.
var categoryId:String = Model.categoriesListXml.category_0[i].category_1[j].#category_id;
var name:String = Model.categoriesListXml.category_0[i].category_1[j].#name;
arr[c].addEventListener(MouseEvent.MOUSE_UP, Proxy.go(this, click, categoryId, name));
All I did was put the xml elements their own vars before using in the event listener.
Does anyone know why this is happening?
My guess is that the entire XML object gets included rather than just the elements I need.
I think it works as the following.
Try. Flash is very lazy when it comes to disposing anything XML-related. So lazy, in fact, that it even has System.disposeXML(...) method because otherwise an XML object might not be garbage collected even if you consciously remove every single reference to it.
Catch. It is important to understand, that most XML operations result in XML or XMLList object, say
// XML source.
var X:XML = <root a="1" />;
// You might think it returns String, but no, it is just autocast to String.
var a:String = X.#a;
// If you don't specify data type, this returns XMLList object of length 1,
// with an XML member of type "attribute", name "a" (or maybe "#a"), and so on.
var A:* = X.#a;
So, without explicitly casting your attribute to String you pass 2 XMLList objects as the function arguments instead (or so it seems).
Finally. Just looking at Proxy.go(...) tells us that it creates a delegate (which is a type of closure), an unnamed unbound function with the stored arguments list. It should look similar to this:
public function go(target:Object, method:Function, ...rest:Array):Function
{
return function():void
{
method.apply(target, rest);
}
}
This works due to ECMA standard (probably works with JavaScript as well) that allows closures to access all their parent method data: local variables and method arguments.
So, you have it. Some unnamed function keeps (pretty much forever) somewhere in the player's memory a list of untyped arguments, which contains your XMLList objects (which are persistent and not easily disposed of). Then you create 150 such monstrosities this way. It's only natural that memory leaks in fountains and niagaras.

AS3: how to pass by "object"

I was actually looking for a way to pass by reference in AS3 but then it seemed that adobe and lots of people's understanding of pass by reference is different from what I have been taught at the university. I was taught java was pass by value and C++ allowed pass by reference.
I'm not trying to argue what pass by value and reference are. I just want to explain why I'm using pass by object in the question...
Back to the question, I would like to do something like:
public function swapCard(cardA:Cards, cardB:Cards) {
var temp:Cards = cardA;
cardA = cardB;
cardB = temp;
}
...
swapCard(c1, c2);
EDIT: adding two examples on how I'm using the swapCard function
1) in the process of swaping a card between player1 and player2's hand
swapCard(player1.hand[s], player2.hand[t]);
2) in the process of swaping a card between player1's hand and deck
swapCard(player1.hand[s], player1.deck[rand]);
In C++, we only need to add a symbol before the parameters to make it work (and we call THIS pass by reference). But in AS3, cardA and cardB are just pointers to the formal parameters. Here in the function, changing the pointers does not do anything to the formal parameters :(
I have been searching for hours but I couldn't find a way to without knowing all the properties of the Cards.
If I have to change the properties of the cards one by one then maybe I should change swapCard to a static function in class Cards? (because I don't want to expose everything to another class) I'm not sure if this is a good practice either. This is like adding a swap_cars function into class Cars. If I let this happen, what will be next? Wash car, lend car, rent car... I really want to keep the Cards class clean and holds only the details of the card. Is there a possible way to do this properly in AS3?
The kind of swap function that you're trying to implement is not possible in AS3. The input parameters are references to the input objects but the references themselves are passed by value. This means that inside the function you can change the cardA and cardB but those changes will not be visible outside the function.
Edit: I added this portion after you edited your question with sample usage.
It seems like you're trying to swap two objects in 2 different arrays at given array positions in each - you can create a function for this in AS3 but not the way you attempted.
One possible implementation is to pass the arrays themselves and the positions that you're trying to exchange; something like this:
// Assumes arrays and indices are correct.
public function SwapCards(playerHand:Array, playerCardIndex:int,
playerDeck:Array, playerDeckIndex:int):void
{
var tempCard:Card = playerHand[playerHandIndex];
playerHand[playerHandIndex] = playerDeck[playerDeckIndex];
playerDeck[playerDeckIndex] = tempCard;
}
Note that you still exchange references and the arrays themselves are still passed by reference (and the array references are passed by value - you could, if you wanted, change the arrays to new arrays inside this function but you wouldn't see new arrays outside). However, because the array parameters refer to the same arrays inside and outside the function, you can make changes to the contents of the array (or other array properties) and those changes will be visible outside.
This solution is faster than cloning the card because that involves allocating memory for a new Card instance (which is expensive) and that temporary instance will also have to be freed by the garbage collector (which is also expensive).
You mentioned in a comment that you pass cards down to lower levels of code - if you don't have a back reference to the arrays (and the positions of the cards), you will not be able to easily swap cards - in AS3, all input parameters are copies (either the copy of the value for primitive types or the copy of the reference for complex objects - changes to the input parameters in a function will not be visible outside).
EDIT: renaming the function from clone to copyFrom as pointed out by aaron. Seems like clone is supposed to be used as objA = objB.clone()
At this point, I'm adding a copyFrom() function in the Cards class such that
var temp:Cards = new Cards(...);
var a:Cards = new Cards(...);
...
temp.copyFrom(a);
...
temp will be copying everything from a.
public function swapCard(cardA:Cards, cardB:Cards) {
var temp:Cards = new Cards();
temp.copyFrom(cardA);
cardA.copyFrom(cardB);
cardB.copyFrom(temp);
}
I will wait for a week or so to see if there are any other options
You have some good answers already, but based on the comments back-and-forth with me, here's my suggestion (I use "left" and "right" naming because it helps me visualize, but it doesn't matter):
function swapCard(leftCards:Array, leftCard:Card, rightCards:Array, rightCard:Card):void {
var leftIndex:int = leftCards.indexOf(leftCard);
var rightIndex:int = rightCards.indexOf(rightCard);
leftCards[leftIndex] = rightCard;
rightCards[rightIndex] = leftCard;
}
Now you can swap the cards in the two examples you posted like this:
swapCard(player1.hand, player1.hand[s], player2.hand, player2.hand[t]);
swapCard(player1.hand, player1.hand[s], player1.deck, player1.deck[rand]);
However, note that while this swaps the cards in the arrays, it does not swap direct references to the cards in those arrays. In other words:
var a:Card = player1.hand[0];
var b:Card = player2.hand[0];
swapCard(player1.hand, a, player2.hand, b);
// does not change the references a and b, they still refer to the same card
a == player2.hand[0];
a != player1.hand[0];
b == player1.hand[0];
b != player2.hand[0];
Typically, this sort of thing is handled by dispatching a "changed" event so that any code that cares about the state of a player's hand array will know to re-evaluate the state of the hand.
There's a deep misunderstanding going on here. The question is about object reference but the PO is not trying to swap any Object reference at all.
The problem comes from the fact that the PO does not understand the difference between variable and objects. He's trying to swap variable/object reference which is not dynamically possible of course. He wants with a function to make the variable holding a reference to Object A, swap its object reference with another variable. Since Objects can be passed around but not variables (since they are just holders (not pointers)) the task is not possible without a direct use of the given variable.
To resume:
variables are not Objects!
variables hold a reference to an object.
variables cannot be passed in function or referenced in functions because THEY ARE NOT OBJECTS.

AS3: calling a property by name or by reference

I am kinda new to AS and stumbled upon a "funny looking" feature in the documentation:
You can use the Object class to create associative arrays. At its core, an associative array is an instance of the Object class, and each key-value pair is represented by a property and its value. Another reason to declare an associative array using the Object data type is that you can then use an object literal to populate your associative array (but only at the time you declare it). The following example creates an associative array using an object literal, accesses items using both the dot operator and the array access operator, and then adds a new key-value pair by creating a new property:
Copy var myAssocArray:Object = {fname:"John", lname:"Public"};
trace(myAssocArray.fname); // John
trace(myAssocArray["lname"]); // Public
myAssocArray.initial = "Q";
trace(myAssocArray.initial); // Q
from here.
I understand that there are cases where this can be helpful, like this one but with a backround in mostly typesafe languages like Java and C# I am a little bit confused about which access-operator is common practice and why.
Normally I would go with the dot oporator, as it allows me and the compiler to keep track of all given properties and you are save regarding typos.
The code I am looking at right now uses both, with no recognizable pattern, which is even more confusing.
Any input on this? Is one better than the other? Why? When to use which one?
Normally I would go with the dot oporator, as it allows me and the
compiler to keep track of all given properties and you are save
regarding typos.
You are not safe against typos. When you create an Object, any property that you haven't defined/assigned to will just return undefined.
var awd:Object = {}
awd.aaa++ //NaN
awd ['aaa']++ //NaN
The compiler will not catch any attempt to reference a property that hasn't been defined.
I use the [] method almost exclusively because it does everything I would need the . method to do plus more. The biggest advantage for me is that I can access properties via variables.
var awd:Object = {}
var key:String = 'some_key';
awd [key] = 1;
awd.key = 5; //This will literally assign to the 'key' property, not what I want