Is there any fmod function in actionscript 3.0? - actionscript-3

I searched the official actionscript reference for the Math class (http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Math.html) but it doesn't say anything about an fmod function
Is there a way to use fmod in actionscript?

How about use this BigDecimal class for AS3.
var x : BigDecimal = new BigDecimal(11.1);
var bdval : BigDecimal = x.remainder(new BigDecimal(3));
trace(bdval.numberValue()); // 2.1 = fmod(11.1, 3);
and create your own fmod function.
function fmod(a:Number, b:Number): Number
{
var x : BigDecimal = new BigDecimal(a);
var bdval : BigDecimal = x.remainder(new BigDecimal(b));
return bdval.numberValue();
}
trace(fmod(4.3, 2.1)); // 0.1

Related

How is this function return value being ignored in Actionscript?

I'm trying to port the Box2DFlashAS3 physics engine to another language (Xojo). I am not particularly fluent in Actionscript (but am more so than I am with C++ which Box2D was originally written in).
As I understand it, parameters passed to functions in Actionscript as done so by reference. Consider these two classes (greatly cut down for simplicity, it's the two GetInverse() functions I'm interested in):
public class b2Mat22 {
public function GetInverse(out:b2Mat22) : b2Mat22 {
var a:Number = col1.x;
var b:Number = col2.x;
var c:Number = col1.y;
var d:Number = col2.y;
var det:Number = a * d - b * c;
if (det != 0.0)
{
det = 1.0 / det;
}
out.col1.x = det * d; out.col2.x = -det * b;
out.col1.y = -det * c; out.col2.y = det * a;
return out;
}
public var col1:b2Vec2 = new b2Vec2();
public var col2:b2Vec2 = new b2Vec2();
}
and
public class b2Transform {
public function GetInverse(out:b2Transform = null) : b2Transform {
if (!out)
out = new b2Transform();
R.GetInverse(out.R);
out.position.SetV(b2Math.MulMV(out.R, position));
out.position.NegativeSelf();
return out;
}
public var position:b2Vec2 = new b2Vec2();
public var R:b2Mat22 = new b2Mat22();
}
I don't understand R.GetInverse(out.R); in the b2Transform class. Doesn't the GetInverse() function of the b2Mat22 class return a value? If so, why is it not being used?
That a function returns a value does not mean that this value needs to be used.
Here is an example:
Array - reverse()
Returns: Array — The new array.
Reverses the array in place.
var letters:Array = new Array("a", "b", "c");
trace(letters); // a,b,c
letters.reverse();
trace(letters); // c,b,a
You can see it modifies the array but it STILL returns the new array. This can be used for some techniques like method chaining:
myArray.reverse().concat(...) //you couldn't do this if it didn't return the new array, in that case you would have to do this:
// --->
myArray.reverse();
myArray.concat(...);
Also note that in AS (just like in JS, Java, etc.) the parameter is passed by reference if it is an object but the primitive values are not passed by reference.
Now to say the complete truth I have no idea what those methods from Box2D do, but I believe this might be the case.

Actionscript 3 - Call to a possibly undefined method Round through a reference with static type Class

Okay, It seems like I fixed the problem below by turning everything into a public static. But how about the Math functions? It is gicing me a Error:Call to a possibly undefined method Round through a reference with static type Class
I am new to AS3. This is just my 2nd day of coding.. but there seems
to be something that I can't understand why it's happening.
private var baseExp:int = 10;
private var offset:int = 32;
private var expCurve:Number = 1.036486;
//------------------------
private var nextExp:Number = Math.Round(Math.Pow((base_stats[0] * (baseExp / expCurve)), expCurve * (1 + (base_stats[0] / (offset * 5)))));
private var _nextExp:Number = nextExp;
private var currentExp:int = 0;
/*
* Check Exp if player can LEVEL UP
*/
public static function CheckExp():void {
if (currentExp >= nextExp) {
base_stats[0] += 1;
//Add Stat Increments here
currentExp -= nextExp;
for (var i:int = 1; i < base_stats.length; i++) {
trace(base_stats[i]);
}
}
if (nextExp != _nextExp) {
RefreshRequiredExp();
_nextExp = nextExp;
}
}
I declared nextExp, _nextExp and currentExp as private... but when I call them in the static function CheckExp, it throws the `Access of
Undefined Property nextExp` etc. etc.
And also an `Error: Call to a possibly undefined method Pow through a reference with static type Class.` in the Math functions.
Is there something wrong I'm doing?
I fixed the Math problems by changing Math.Round to Math.round. same with the others. also the private vars was set to private static var to match the functions. Okayyyy it's fixed.
Wow, I didn't know I can fix this myself.
This is really ridiculous, I feel like I'm just talking to myself.

Existing class to get property chain in ActionScript3?

Is there an existing class in Flash or Flex that gets the value from an object from it's property chain?
For example, something like this:
private function labelFunction(item:Object, column:GridColumn):String {
// where dataField equals "fields.status.name"
var value:String = PropertyChain.getValue(field, column.dataField);
return value;
}
~~~ Update ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
I found this private method in the Binding class as well that could probably be used in a custom class:
/**
* #private
*/
private static function getFirstWord(destStr:String):String
{
// indexPeriod and indexBracket will be equal only if they
// both are -1.
var indexPeriod:int = destStr.indexOf(".");
var indexBracket:int = destStr.indexOf("[");
if (indexPeriod == indexBracket)
return destStr;
// Get the characters leading up to the first period or
// bracket.
var minIndex:int = Math.min(indexPeriod, indexBracket);
if (minIndex == -1)
minIndex = Math.max(indexPeriod, indexBracket);
return destStr.substr(0, minIndex);
}
I don't think there's an existing function. But it's very easy to build one, and it need not be restricted to generic Object sources, as any member of any object can be retrieved by name using square bracket notation. This simple version doesn't do any validation:
public static function getByName(root:*, member:String):* {
var memlist:Array = member.split('.');
var temp:* = root;
for(var i:uint = 0; i < memlist.length; i++)
temp = temp[memlist[i]];
return temp;
}
// And you can use this even on strongly-typed values, such as a MovieClip:
trace("stageWidth =", SomeUtil.getByName(mc, "stage.stageWidth"));

as3 operator= /(object assign )

I know that AS3 does not have pointer or reference. Every object is pass by reference already. (I supposed?)
What should I do if I want to do with pointer?
e.g. all object point to one target, I only need to change target's value, then all other object will access different value.
You can effectively get the same behavior by using a helper object to simulate a pointer -- in other words using it to carry the target reference. For instance:
public class PseudoPointer
{
private var obj:Object;
private var prop:String;
public function PseudoPointer(obj:Object, prop:String)
{
// Point to property with name 'prop' on object 'obj'.
this.obj = obj;
this.prop = prop;
}
public function get value():* {
return obj[prop];
}
public function set value(value:*):void {
obj[prop] = value;
}
}
Then you could do this -- assume there's a magicNumber property on an object named target:
var numberPtr = new PseudoPointer(target, "magicNumber");
myDynamicObjectA.numberPtr = numberPtr;
myDynamicObjectB.numberPtr = numberPtr;
myDynamicObjectC.numberPtr = numberPtr;
Now any object that has a reference to the pseudo-pointer can read and write the target property:
numberPtr.value = 42;
You could create a function and in which you give it the value and then subsequently assign it to all of those other variables.
Something like below:
var objectA:Number;
var objectB:Number;
...
function myFunction(newValue:Number):void
{
objectA = newValue;
objectB = newValue;
...
}
You could try setting a variable reference to a function. Then if you update that reference, it would return a different function.
var myFunc:Function;
function funcOne():int {
return 1;
}
function funcTwo():int {
return 2;
}
function getFunc():Function {
return myFunc;
}
myFunc = funcOne;
var myObjOne:Object = new Object();
myObjOne.objFunc = getFunc;
var myObjTwo:Object = new Object();
myObjTwo.objFunc = getFunc;
trace(myObjOne.objFunc.call().call()); // 1
trace(myObjTwo.objFunc.call().call()); // 1
myFunc = funcTwo;
trace(myObjOne.objFunc.call().call()); // 2
trace(myObjTwo.objFunc.call().call()); // 2
This allows any object to point at a single function and have what that returns be updateable for all of them simultaneously. It's not the prettiest code and it's not as type-safe as if ActionScript had delegates to enforce the signatures of what's set for myFunc, but it is still a pretty flexible model if you get creative with it.
Have those pointers point to something that contains the object or has the object as a property on it.
So
var myArr:Array = [new YourObject()];
var client1:ArrayClient = new ArrayClient();
client1.array = myArr;
var client2:ArrayClient = new ArrayClient();
client2.array = myArr;
myArr[0] = new YourObject();
//client1.array[0]==client2.array[0]==the new object
However, this seems to be a great way to get yourself into a lot of trouble really quickly. What's the use case?

Ruby-like Question: Make this function shorter (ActionScript 3)

I just wrote this incredibly verbose code to turn numbers like 2 into 02. Can you make this function shorter, please (maintaning the functionality)?
public static function format(n:int, minimumLength:int):String {
var retVal:String = n.toString();
var stillNeed:int = minimumLength - retVal.length;
for (var i:int = 0; i < stillNeed; i++) {
retVal = "0" + retVal;
}
return retVal;
}
Please use types for variables. Extra points (good-vibe points, not SO points) if there's already a built-in function that I don't know about.
If anybody wants to post some extremely short equivalent in some other language, that would be fun too.
This wouldn't be the fastest implementation (it does some unnecessary copying and has a loop), but it is nice and readable:
public static function pad(num:int, minLength:uint):String {
var str:String = num.toString();
while (str.length < minLength) str = "0" + str;
return str;
}
I don't think there is a built-in way, but this might be cleaner (if not necessarily better performing):
//20 zeroes, could be more if needed
public static var Zeroes:String = "00000000000000000000"
public static function format(n:Number, minimumLength:int):String {
var retVal:String = (n.toFixed(0)); // cut off the decimals
var stillNeed:int = minimumLength - retVal.length;
retVal = Zeroes.substring(0, stillNeed) + retVal;
return retVal;
}
The "zeroes" var eliminates the need for looping, just prepend however many zeroes you need from a prebuilt string.
Christophe Herreman almost got it right, but his method adds more zeroes and not the differential amount. I fixed it a bit:
public static function format(n:int, minimumLength:int):String {
var v:String = n.toString();
var stillNeed:int = minimumLength - v.length;
return (stillNeed > 0) ? v : String(Math.pow(10, stillNeed) + v).substr(1);
}
My earlier try:
public static function format(n:int, minimumLength:int):String {
var stillNeed:int = minimumLength - n.toString().length;
return (n.split("").reverse().join("") as int) // 32 -> 23
*Math.pow(10, stillNeed > 0 ? stillNeed : 0).toString() // 23000
.split("").reverse().join(""); // 00032
}
public static function formatAny(n:Number, minimumLength:int):String {
return format((int)n) + n.toString().split('.')[ 1 ];
}
// use this if you want to handle -ve numbers as well
public static function formatAny(n:Number, minimumLength:int):String {
return (n < 0 ? '-' : '') + formatAny(n, minimumLength);
}
How about this:
public static function format(n:int, len:int):String {
var v:String = n.toString();
return (v.length >= len) ? v : String(Math.pow(10, len) + n).substr(1);
}
There is not built-in function to do this btw. If you need decent padding functions, take a look at the StringUtils in Apache Commons Lang.
Props to dirkgently and all others who have responded here, but apparently people are voting up without actually trying the code.
dirkgently's final function is mostly correct, but his '>' needs to be a '<'.
This function performs as desired (tested fairly thoroughly):
public static function format(n:int, minimumLength:int):String {
var v:String = n.toString();
var stillNeed:int = minimumLength - v.length;
return (stillNeed < 0) ? v : String(Math.pow(10, stillNeed) + v).substr(1);
}
"If anybody wants to post some
extremely short equivalent in some
other language, that would be fun too."
In javascript it is easy - paste this into your browser's address bar
javascript: function zit(n, w) {var z="000000000000000000"; return (z+n).substr(-w);} alert(zit(567, 9)); void(0);
I've always done this by taking a string that is the maximum padded width of zeros containing all zeros, then appeneding the string to padded to the end of the zeros string and then using substring to get the right hand Length digits.
Something like:
function pad(num:int, length:unit):String{
var big_padded:String "0000000000000000000000000000" + num.toString();
return big_padded.substring(big_padded.length - length);
}
The as3corelib package put out by adobe has a nice little NumberFormatter class that uses a series of STATIC classes. In this case you could use the addLeadingZero function.
//The following method is from the NumberFormatter class of the as3corelib package by Adobe.
public static function addLeadingZero(n:Number):String
{
var out:String = String(n);
if(n < 10 && n > -1)
{
out = "0" + out;
}
return out;
}
I included the function just to show it's simplicity, but I would use the package instead of yoinking the function because it provides many other useful features like StringUtils, encryption methods like MD5, blowfish, etc.
You can download the package here
For newer users you must provide a classpath to where this package lives. It is also smart to import the classes instead of using their fully qualified class names.
private function leadingZeros(value:int, numDigits:int):String
{
return String(new Array(numDigits + 1).join("0") + String(value)).substr(-numDigits, numDigits);
}