Frage

Haxe

public var bonus:Map<Int,Int>;

if (bonus.exists(id))
    score += bonus.get(id);

Compiles to the following php

if($bonus->exists($id))
    $score += $bonus->get($id);

Ideally I'd like haxe to generate

if(isset($bonus[$id]))
    $score += $bonus[$id];

I suspect it would be possible using dynamic however I'd like to avoid using dynamic as it is not recommended. Exists is unnecessary in php but will not compile for our as3 target. Current profiling shows exists (50% of execution time) and get (30%) are quite expensive. I'd hope that it would be possible to either use the built in array type or at least inline the exists and get calls. Can anyone tell me how or recommend a better way of doing this?

Thanks

War es hilfreich?

Lösung

For PHP's isset(), you may simply compare the variable with null, ie. "myVar != null".

if(bonus[id] != null)
    score += bonus[id];

or with ternary operator

score += (bonus[id] != null) ?: bonus[id];

Sidenote:

I believe, you could also try a PHP in_array() solution by using Lambda.has(arrayOrMap, "key");. But i don't know exactly if Lambda.has works on Maps.

But still, the != would be faster than a call to in_array().

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top