0
function genEnemy(a) {
 //javascript:alert(en[0]+'\n'+genEnemy(en[0])+'\n'+en[0])
 with (Math) {
  a[1]=round(a[1]*(.5+random()))
  a[2]=round(a[2]*(1+random()))
  for (var b=0;b<5;b++) a[3][b]=round(a[3][b]*(a[3][b]/2+random()*a[3][b]/10))
  for (var b=0;b<a[4].length;b++) random()<it[a[4][b]][3]/10?a[4][b]=0:0
  }
 return a
 }

Script to generate an enemy's stats given the bases each enemy array. (RPG game) The problem is, when I am expecting it to return an array containing the new stats, it also sets the enemy array to the new one. Why is this? Obviously you can see how problems are caused by this (the bases being changed so a weak enemy can become uber powerful). How would I stop it from setting the array in en (array of enemy values)?

2
  • 2
    I'm not following what you want it to do, your variable names make it hard to decode your code based o the description. Commented Nov 15, 2010 at 0:11
  • 2
    with (Obj) can be dangerous, make sure you read this. Commented Nov 15, 2010 at 0:26

2 Answers 2

6

Objects are passed by reference in JavaScript. That means any changes you make to the array a inside genEnemy is reflected on the original array that was passed in. You need to make a deep copy of the array and return this copy. Here is a function that will do it for you:

function cloneArray(a) {
  var b = [];
  for (var i = 0; i < a.length; i++)
    if (a[i] instanceof Array)
      b[i] = cloneArray(a[i]);
    else
      b[i] = a[i];
  return b;
}

Inside genEnemy, you would then do:

a = cloneArray(a);
// make changes to the new array
return a;

Also, don't forget to include semicolons in your code. Even though they are optional, you may run into unexpected problems if you get into the habit of omitting them.

Sign up to request clarification or add additional context in comments.

8 Comments

Is there a way to do this without another function? I just hate adding functions for little things.
@Ruffian Take out the function body and run it procedurally and you don't have a function :P But remember turning often used and useful code into a function is a good thing.
@Ruffian: If there was a built-in function, I would have definitely suggested that. Unfortunately there isn't.
Meh. I'll just take out the genEnemy function and find a way to put it into a larger function to set up the whole fight. Thanks anyway.
@Ruffian be careful with that thinking - Abstraction into separate functions is a good thing!
|
0

Are you passing array en to your getEnemy() function? If so then it will change the values in en array as it's passed by reference not by value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.