AS3: Error #1065: Variable is not defined - arrays

Using getDefinitionByName I am consistently getting the error saying it is not defined (as the title says). The particular code I am using is
var tileID:String = String(getDefinitionByName("evt.target.data."+mapData[i][j]))
mapData is already populated by a character in each position. The plan is that I can use the value of whatever mapData is as the variable name for the conversion of the single character to the full linkage name of a tile. These properties come from another external .txt file that is setup for variables (this is the external file the code line links to).
The variables in the external file look something like &N=exampleTile.
So when it comes to setting tileID it should end up being exampleTile. (Assuming mapData[i][j] = "N").
But it doesn't. I have read around at other solutions saying that the file may not have loaded or anything, but I can't make sense of or apply any of those fixes.

As Florian points out, getDefinitionByName is specifically for getting a Class reference. Something like "flash.net.URLLoader" would give you a reference to the URLLoader class for example. It's not used for getting regular variables by their names (so "evt.target.data.N" wouldn't return anything even if "N" was a property of data).
It sounds like your evt.target.data is a long string along the lines of "A=tileA&B=tileB&C=tileC". If so, you need to parse that string out to separate variables first. You should be able to use URLVariables with that data format (flash.net.URLVariables), then you can read the parsed variables using the [ ] array access operator: urlVariablesObject["variableName"]. So you might do something like this:
import flash.events.Event;
import flash.net.URLVariables;
import flash.net.URLLoader;
import flash.net.URLRequest;
var loader:URLLoader = new URLLoader();
var parsedData:URLVariables;
var mapData:Array = [["A", "B", "C"], ["D", "E", "F"]];
loader.addEventListener(Event.COMPLETE, externalFileLoaded);
loader.load(new URLRequest("externalFile.txt"));
// externalFile.txt contains "A=tileA&B=tileB&C=tileC&D=tileD&E=tileE&F=tileF".
function externalFileLoaded(evt:Event):void {
parsedData = new URLVariables(evt.target.data);
var tileID:String = readMap(0, 1);
trace(tileID); // "tileB".
}
function readMap(i:uint, j:uint):String {
var mapValue:String = mapData[i] [j];
var tileID:String = parsedData[mapValue];
return tileID;
}

That doesn't make any sense. getDefinitionByName is used to retrieve a Class instance of a certain type - the Class named like the string passed. And the definition will always start with "evt.target.data.".
Did you ever debugged your way through it?
function any_handler(i:int, j:int):void {
const suffix:String = mapData[i][j],
qualifiedName:String = "evt.target.data." + suffix;
// this is wrong
const titleID:String = String(getDefinitionByName(qualifiedName));
}
You really should take a look in the debugger in order to know the value of the string you are creating.

Related

Access returned computed array within method and manipulate

I have a computed array which is full of tags and updates depending on what selection i make in the select box. I would like to take this array and pass it to a method and then run a method to update what “results” have an active class. Although I get an array saying I can’t run forEach on this element.
Been through a few topics and understand computed properties dont work like that but surely there is a way around this.
https://jsfiddle.net/39jb3fzw/6/
Short Snippet
methods: {
updateOutput() {
var tags = this.tagArray;
tags.forEach(function(tag) {
console.log(tag);
})
}
},
computed: {
concatenated: function () {
var ret = this.selected.concat(this.selected2, this.selected3);
this.tagArray = ret;
//this.updateOutput();
return ret;
}
}
Full Output
https://jsfiddle.net/39jb3fzw/6/
Thanks again :slight_smile:
It looks like the issue is the line:
var ret = this.selected.concat(this.selected2, this.selected3);
That line of code is returning an empty string rather than an array. This is because this.selectedX is a string rather than an Array. This explains why tag.forEach is undefined. forEach doesn't exist on the String prototype.
You can create this an array instead be doing
var ret = [ this.selected, this.selected2, this.selected3 ]
From there you can set this.tagArray to ret
Hope this helps

Make many dynamic variable (inctance name) with one loop

I have many class in my library almost 300, and I want to generate instance name by loop. In other words I wanna instead of this approach(witch has many code line):
X:This is my problem:
var cm1: Cm1 = new Cm1();
var cm2: Cm2 = new Cm2();
var cm3: Cm3 = new Cm3();
...
use like this approach (less than 10 code lines):
Y:I think this is solution:
for (var i: uint = 1; i < 4; i++)
{
var getChildByName("cm" + i): getChildByName("Cm" + i) = new getChildByName("Cm" + i);
}
but I know above code does not work, is there any way to make them !
-What am I actually trying to solve?
Make many variable by a few line code and save time and size app!
-Why do I have ~300 classes and why are you trying to create them in a loop at once?
This is about to data of request application!
-What do these classes do that you unconditionally need one of each all at the same time?
Because those data would show at first time!
First, it is better to store the classes in an Array or Object rather than an external variable for each item. if you want to access them by name, better to use object:
var classList:Object=new Object();
Then in your loop:
for(var i:uint=1;i<NumberOfClasses;i++){
classList["cm"+i.toString()]=new (getDefinitionByName("Cm"+i.toString()) as Class)();
}
getDefinitionByName is used to make Constructors using String;
Note: if your classes contain a package directory, you should include it. for example:
getDefinitionByName("myclasses.cm.Cm123")();
Then you can access them using Bracket syntax:
classList["cm123"].prop=val;
And don't forget to:
import flash.utils.getDefinitionByName;
I Hope it will help.
EDIT
to use Array instead of object, the loop should be:
for(var i:uint=1;i<NumberOfClasses;i++){
classList[i]=new (getDefinitionByName("Cm"+i.toString()) as Class)();
}
then to access them:
addChild(classList[0]);//0 or any other index;

Swift - Append to array in struct

I am currently learning swift and am experimenting with data structures. In may code I have certain routines with a name(String) and several tasks(Array of Strings). These values are in a structure.
So I am trying to add another value to the array after it has been initialized. My code is actually working, however I really think it very weird and odd and DO NOT think, that it is the way it should be done.
var routineMgr: routineManager = routineManager();
struct routine{
var name = "Name";
var tasks = [String]();
}
class routineManager: NSObject {
var routines = [routine]();
func addTask(name: String, desc: String){
//init routines with name and an array with certain values, here "Hallo" & "Moin"
routines.append(routine(name: name, tasks: ["Hallo","Moin"]));
//so i just put this part here to make the example shorter, but it would be in ad different function to make more sense
//adding a new value ("Salut") to the tasks array in the first routine
//getting current array
var tempArray = routines[0].tasks;
//appending new value to current value
tempArray.append("Salut");
//replacing old routine with a copy (same name), but the new array (with the appended salut)
routines[0] = routine(name: routines[0].name, tasks: tempArray);
}
}
I have tried some (to me) "more correct" ways, like:
routines[0].tasks.append("Salut");
But I always got tons of errors, which I also did not understand.
So my question now: How is it actually done correctly? And why does the second way not work?
Your help and advice is really appreciated!
You can create a function to append the values in the struct (that is what I would do). You can even use it to validade values or anything else you need to do before append, it can also return a boolean to let your code know if the value was successfully appended or not
var routineMgr: routineManager = routineManager();
struct routine{
var name = "Name";
var tasks = [String]();
mutating func addTask(task: String){
tasks.append(task)
}
}
class routineManager: NSObject {
var routines = [routine]();
func addTask(name: String, desc: String){
routines.append(routine(name: name, tasks: ["Hallo","Moin"]));
routines[0].addTask("Salut")
}
}
I hope that helps

Having array problems in Swift

I am learning how to build apps and working with Swift for this project.
I had a buddy help me pull data in from a website and it looks like he created classes with variables and mapped them to certain extensions (IE "Username") so when I call the variable data such as profile I would call it. The below uses luck_30 able to store "Stats.luck_30"
luck_30.text = profile.luck_30
So inside one of my variables that is in this "Profile" class is setup into an array. I can pull the array out of the class, but I can't seem to do for while statement replacing the [#] with a variable from the for command.
func aliveWorkers(profile: Profile) -> NSNumber{
var myworkers : Array = profile.workers!
//this test works and returns the proper value
var testworker: NSNumber = myworkers[0].alive!
println("The satus of the test worker is " + testworker.description)
/* This code is giving error "Could not find member alive" it does not ifor var
for ifor in myworkers{
var thisworker: NSNumber = myworkers[ifor].alive! as NSNumber
}
*/
return 42
}
Your variable ifor is not a counter, it is an actual object. You could do something like this:
for worker in myWorkers {
let workerIsAlive = worker.alive!
}
Alternatively, if you need the index,
for i in 0 ..< myWorkers.count {
let worker = myWorkers[i]
let workerIsAlive = worker.alive!
}
If you need both:
for (i, worker) in enumerate(myWorkers) {
let workerIsAlive = worker.alive!
}
And as a matter of style, I would stay away from NSNumber and use Int or Bool or whatever the data actually is. Also, it looks like the alive variable should not be optional, as you're unwrapping it everywhere. To avoid "mysterious" crashes later, you may want to think about making it a non-optional type.
when using a for in loop, your loop variable isn't an index, its the objects you're looping through. so..
func aliveWorkers() {
var myworkers = [1, 2, 3]
//this test works and returns the proper value
let testworker = myworkers[0]
print("The satus of the test worker is \(testworker)")
for ifor in myworkers {
print(ifor)
}
}
Notice a few things... you don't need to use + to concatenate those strings. you can just use string interpolation. \(variable) inserts the value of variable in the string.
Try to use let instead of var when you don't change the variable. You don't need to explicitly define type on variables either.

Instantiation attempted on a non-constructor

I'm trying to make a bomb catching game (I'm actually using the code from the AS3 Classroom in a Book on arrays). As soon as I changed the word fruit to bomb in the code I got error 1007. With the exception of changing basket_mc to eod_mc and fruit to bomb (I used command-F and replaced with case sensitive on) I haven't changed much. It worked with eod_mc, but doesn't with bomb.
var bombArray:Array = new Array(bomb);
var bombsOnstage:Array = new Array();
var bombsCollected:int = 0;
var bombsLost:int = 0;
for (var i:int = 0; i<20; i++) {
var pickBomb = bombArray[int(Math.random() * bombArray.length)];
var bomb:MovieClip = new pickBomb();
addChild(bomb);
bomb.x = Math.random() * stage.stageWidth-bomb.width;// bomb.width is subtracted from the random x position to elimate the slight possibility that a clip will be placed offstage on the right.
bomb.y = Math.random() * -500;
bomb.speed = Math.random() * 15 + 5;
bombsOnstage.push(bomb);
}
eod_mc.addEventListener(MouseEvent.MOUSE_DOWN, dragEod);
stage.addEventListener(MouseEvent.MOUSE_UP, dragStop);
function dragEod(e:Event):void {
eod_mc.startDrag();
}
function dragStop(e:Event):void {
eod_mc.stopDrag();
}
stage.addEventListener(Event.ENTER_FRAME, catchBomb);
function catchBomb(e:Event):void {
for (var i:int = bombsOnstage.length-1; i > -1; i--) {
var currentBomb:MovieClip = bombsOnstage[i];
currentBomb.y += currentBomb.speed;
if (currentBomb.y > stage.stageHeight - currentBomb.height) {
currentBomb.y = 0 - currentBomb.height;
bombsLost++;
field2_txt.text = "Total Bombs Detonated: " + bombsLost;
}
if (currentBomb.hitTestObject(eod_mc)) {
bombsCollected++;
removeChild(currentBomb);
bombsOnstage.splice(i,1);
field1_txt.text = "Total Bombs Caught: " + bombsCollected;
if (bombsCollected >= 20) {
eod_mc.gotoAndStop(20);
} else if (bombsCollected > 15) {
eod_mc.gotoAndStop(15);
} else if (bombsCollected>10) {
eod_mc.gotoAndStop(10);
} else if (bombsCollected>5) {
eod_mc.gotoAndStop(5);
}
}
}
if (bombsOnstage.length <= 0) {
field1_txt.text = "You Win! You have defused the bombs.";
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchBomb);
}
if (bombsLost >= 20) {
field1_txt.text = "Sorry you lose. You have lost your foot!";
field2_txt.text = "";
stage.removeEventListener(Event.ENTER_FRAME, catchBomb);
for (var j:int = bombsOnstage.length-1; j > -1; j--) {
currentBomb = bombsOnstage[j];
removeChild(currentBomb);
bombsOnstage.splice(j,1);
}
}
}
Maybe to avoid making your programming life more twisted than it is now...
There are objects and classes in programming, a class is a description of a set of objects, say "table" (or, as it's better to differ in names for classes and variables, "Table", first letter capitalized) is a name of a class. An instance or an object is a structure that belongs to one or more classes, with Object being the topmost, as everything in programming is either an object or a "simple variable", that is, a number, a true/false, a string of characters (these are object types in AS3 too, though, Number, Boolean, String, but these generally not need to be instantiated via new) or probably some other simple type I don't remember right now.
Classes have properties and methods. A property is something that can be requested off any object of the class, say "height" for tables. Properties can be of any type, including nested objects, depending on what your base class is. Say stage in AS3 is a property of any DisplayObject which is used to get the only Stage object there is at runtime[1]. Methods are what any object of a class can be told to do. Say, bombs fall, explode, MovieClips can be told to stop(), etc. You write class code keeping in mind that all of the objects of this class will have to behave exactly like you've written, but since they can differ in properties, you can give them conditional behavior. For example, if a bomb has already exploded, it cannot blow up once more.
A variable, whether a property or a standalone var (if you declare one in a function) is a reference to an object of a given type. Say var i:int refers to some kind of an integer. Simple type vars are containers instead, that is, i=2; will place a 2 in the referred integer, and i=j; will copy the value from j into i, while var theStage:Stage=this.stage will instead create a reference to an existing object, and if that object will change, the reference will give you the changed object instead of its previous state. An array is a collection of variables, reachable by indexes, in AS3 they don't have to be of one type, and a Vector is a typed array.
Next, the lifetime of objects. An object only lives while there's an active reference to it, whether in a property of another alive object, or in a visible variable, or in an event listener (AS3 specific). An object is created via new ClassName(<parameters>), lives while you can reach it somehow, and is destroyed once you have no active links to it and Flash player decides to run garbage collector. Prior to this programmers had to deallocate objects themselves, a rudiment can be seen at BitmapData.dispose(). So, in order to avoid Flash player to run out of free memory, take full control over creation and destruction of links. You don't need to care for simple vars, they are being cared for by Flash player.
A lot of basic functions for interactions has already been implemented in AS3, look for them and examples of how they work in Adobe's manual, navigate through packages in the lower left, most of the interactive stuff is in flash.display package, refer to other packages as necessary.
Hope this will bring you some insight into programming basics.
[1]: There is one stage unless you're doing a load of an SWF, then there could be more, one Stage per one SWF.

Resources