Maverick Jones
Maverick Jones

Reputation: 434

Inconsistent variable output

A few days ago I made a lord generator for a game called Broken History I play with my mates, I started the code myself but ended up getting help with the code to finish it.

I then set about making a char gen for the same game, using the exact same methods that worked before, everything was looking good every element did what it was supposed to. However, when I got the resulting text the first time the variable curFaction was called it read undefined the second time it read the faction the user chose in the select box i.e. Saxathia. The variable is assigned in the $(document).ready() function so in theory is should be assigned before it is called right?

I can't think why this happens, the variable is called as part of an array does that make any difference?

enter image description here

Here is the jsLint http://jsfiddle.net/CYe8J/31/

Upvotes: 1

Views: 86

Answers (1)

RB.
RB.

Reputation: 37192

Your problem is that you are setting the character description string when the page is loaded, before the user has selected a faction.

// curFaction is undefined here, as user cannot select a faction 
// *before* the page is loaded!!
var aLevel[1] = "Description1 of guy from " + curFaction + ".";

The quickest fix is to generate the description as and when it is required. One way to do this would be to store a function in aLevel, rather than a string, like the following:

var aLevel[1] = function () { "Description1 of guy from " + curFaction + "."; };
var aLevel[2] = function () { "Description2 of guy from " + curFaction + "."; };
var aLevel[3] = function () { "Description3 of guy from " + curFaction + "."; };

Then, when you need your description, call the function:

// Original code:
"Stuff about claim on throne. " + aLevel[temp6] + ".";

// New code - note brackets after "aLevel[temp6]"
"Stuff about claim on throne. " + aLevel[temp6]() + ".";

I've created a Fiddle showing this.

As an aside, your code could generally be refactored quite a lot - as a rule, if you find you are writing the same algorithm over and over again, then you need to remember the DRY principle :)

Upvotes: 1

Related Questions