java-script variable scope problem

Place for questions and answers for all newcomers and new coders. This is a free for all forum, no question is too stupid and to noob.
Post Reply
ShawnSwander
Posts: 53
Joined: Thu May 17, 2012 12:31 am

java-script variable scope problem

Post by ShawnSwander »

So I think I have a missed concept here related to variable scope I tried to declare the varriable from_sql outside of the functions that use it... I console.logged where I lose the varriable
the input is player_id = varries with player
itemlist = null (not needed for the instance I'm having issues)
item_id = 1 //won't matter either
move_from = 1
move_to = 0

The varriable I need to pass is getting nulled where I made the comment "//lost from_sql here"

Code: Select all

   socket.on('moveitem', function (player_id,itemlist_id,item_id,move_from,move_to,posx,posy,land){
      connection.escape(player_id,itemlist_id,item_id,move_from,move_to,posx,posy,land)
      console.log(player_id,itemlist_id,item_id,move_from,move_to)
      
      var to_sql = null;
      var from_sql = null;
      var to_data = null;
      var from_data = null;
      
      sql ="SELECT next_turn,action_time,posx,posy FROM game_moblist WHERE id = "+player_id;
      connection.query(sql, function(err, rows, fields) {if (err) throw err
         if ((rows[0])&&rows[0].next_turn < new Date().getTime()){
            if (move_from!=move_to&&move_to!=null){
               sql="UPDATE game_moblist SET `next_turn`="+(new Date().getTime()+rows[0].action_time);
               connection.query(sql, function(err, rows, fields) {if (err) throw err;});
               switch(move_from){
               case 0://ground
                  //check if its last item in hex here
                  from_sql = "DELETE FROM `game_itemlist` WHERE `id` ="+itemlist_id;
               break;
               case 1://sack
                  sql = "SELECT sack FROM `game_moblist` WHERE id="+player_id;
                  connection.query(sql, function(error, rows, fields){
                     var sack = rows[0].sack.split(",")
                     for (i=0;i<sack.length;i++){
                        if (sack[i]==item_id.toString()){
                           sack[i]="0";
                           sack = sack.join();   
                           from_sql="UPDATE game_moblist SET sack='"+sack+"' WHERE id="+player_id
                           i=sack.length
                        }
                     }
                  });
                  //lost from_sql here
                  console.log(from_sql)
               break;
               }
      
               switch(move_to){
               case 0:
                  to_sql="INSERT INTO game_itemlist (id,posx,posy,land) VALUES "+item_id+","+posx+","+posy+",'"+land+"'";
               break;
               case 1://sack
                  sql ="SELECT sack FROM `game_moblist` WHERE id="+player_id;
                  connection.query(sql, function(error, rows, fields){
                     var sack = rows[0].sack.split(",")
                        for (i=0;i<sack.length;i++){
                           if (sack[i]=="0"){
                              if(typeof item_id === "number"){
                                 sack[i]= item_id.toString()
                                 sack = sack.join();   
                                 to_sql ="UPDATE game_moblist SET sack='"+sack+"' WHERE id="+player_id
                                 i=sack.length
                                 to_data = sack;
                              }
                           }
                        }
                  });
               break;
               }
                  console.log(from_sql,to_sql)
      
               if (from_sql&&to_sql){
                  connection.query(from_sql, function(error, rows, fields){if (error) socket.emit('error', error);})
                  connection.query(to_sql, function(error, rows, fields){if (error) socket.emit('error', error);})
                  io.sockets.emit('moveitemresult',player_id,itemlist_id,item_id,move_from,move_to,to_data )
               }
            }
         }
      });
   });
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: java-script variable scope problem

Post by Xaleph »

So scope is the thing you don`t understand? In Javascript, it`s quite easy, as long as you dont forget the following rules:

1. Anything declared outside of a function is global scope : allways reachable, but dangerous
2. Anything declared inside a function is function scope: only usable INSIDE this function.
3. Callback functions act the same as normal functions, except they don`t have to be declared.

So, if you need to do some SQL or do some math, but you want to keep the results performed, you should RETURN the information in the function. A function can be anything from a static function to a method on an object/prototype. They act the same.

So :

function DoOne(){
var answer = 1 + 1;
}

// answer is not accessible!

but:

function DoOne(){
var answer = 1+1;
return answer;
}

Now it is, the only thing is, you didn`t assign it to anything.

So to assign the answer, all you have to do is:

var answer = DoOne(); // answer will be 2

So, connection.query(sql, callback(){}); is where the "magic" happens, unless i didn`t read it right, but you are performing the query inside it, so a logical thing would be to return the from_sql back to a variable, so you can use it. You can also ( it`s a "trick" most programmers use ) use a container. So you declare it somewhere in the top ( inside the object scope ) which would act as nothing more then a cart where you can throw stuff in, like doing groceries shopping, so anything you are going deeper in scope, that shopping cart is still available ( you declared it on top) so now, you can throw ingredients in it and use them later on, once you`re outside that scope again.
ShawnSwander
Posts: 53
Joined: Thu May 17, 2012 12:31 am

Re: java-script variable scope problem

Post by ShawnSwander »

@Xaleph
thanks for the reply. I tried to use the container method in my code by declaring from_sql before I started queries but I lost the value somehow. I must be doing something wrong that I don't see. Perhaps you could show me an example because returning the value doesn't seem to work it was returning [function] when I tried that.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: java-script variable scope problem

Post by Jackolantern »

And although you didn't ask about it, there is one other odd thing to JS scope, and that is prototype scope. The main scope chain is always searched first, and if the variable or object member was not found, then the prototype chain is searched.
The indelible lord of tl;dr
ShawnSwander
Posts: 53
Joined: Thu May 17, 2012 12:31 am

Re: java-script variable scope problem

Post by ShawnSwander »

I feel more confused than when I started.

If I could simplify my question it might help.

Code: Select all

connect.query(arg1,function(error,rows,fields){
  //get info I need for setting variable
   var I_need_this = true;
});
//I need to access that variable here outside the function
This doesn't work

Code: Select all

var I_need_this
connect.query(arg1,function(error,rows,fields){
  //get info I need for setting variable
   var I_need_this = true;
});
This doesn't either

Code: Select all

var I_need_this
connect.query(arg1,container = function(error,rows,fields){
  //get info I need for setting variable
   var I_need_this = true;
return I_need_this; 
});
Nor this

Code: Select all

container =connect.query(arg1,container = function(error,rows,fields){
  //get info I need for setting variable
   var I_need_this = true;
return I_need_this; 
});
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: java-script variable scope problem

Post by Jackolantern »

You were really close to it with:

Code: Select all

var I_need_this
connect.query(arg1,function(error,rows,fields){
  //get info I need for setting variable
   var I_need_this = true;
});
However, this code has an error, in that you are redefining the variable again since you re-use the "var" keyword inside the function. This will work:

Code: Select all

var I_need_this
connect.query(arg1,function(error,rows,fields){
  //get info I need for setting variable
   I_need_this = true;
});

alert(I_need_this); 
The indelible lord of tl;dr
ShawnSwander
Posts: 53
Joined: Thu May 17, 2012 12:31 am

Re: java-script variable scope problem

Post by ShawnSwander »

ugh I tried it... not working.

Code: Select all

var from_sql
                  connection.query(sql, function(error, rows, fields){
                     var sack = rows[0].sack.split(",")
                     for (i=0;i<sack.length;i++){
                        if (sack[i]==item_id.toString()){
                           sack[i]="0";
                           sack = sack.join();   
                           from_sql="UPDATE game_moblist SET sack='"+sack+"' WHERE id="+player_id
                           i=sack.length
                        }
                     }
                  });
                  console.log(from_sql)
outputs "undefined" outside the function and my query shows in within the function
Xaleph
Posts: 897
Joined: Mon Feb 07, 2011 2:55 am

Re: java-script variable scope problem

Post by Xaleph »

Well, you are not really following the rules here. Anything declared at outer scope is global, what Jack said should be right, but only if it is within a function or object scope. Another thing is, the container should be an array, otherwise values are flows are going to get fuzzy at some point.

Ok, let`s see:

var some_object = {}; // now it`s an object ( not required, but "best" practices )

so, some_object.function(); // is a method inside the object

so, some_object.some_value; // is now a field on this object

All things considering, I assume your connection.query() is called somewhere inside an object, that object logically speaking, can have fields, and one of those fields should be your container, so that you can store it at any time there.

And if NOTHING else is working for you, try it by simply passing the object inside the function header, giving it as a parameter, it`s by no means required, but it works, at all times.
User avatar
Jackolantern
Posts: 10891
Joined: Wed Jul 01, 2009 11:00 pm

Re: java-script variable scope problem

Post by Jackolantern »

The only real reason I could see that not working correctly is if a closure was formed, in which case "var declarations" become inaccessible outside of the original function's scope. If this is inside a function that is assigned to a variable, you can make it "this.I_need_this" and then reference the variable holding the function to get the value:

Code: Select all

alert(containingFunction.I_need_this);
You may have inadvertently created a private variable, since privacy works differently in Javascript than in other OO languages. Private variables will show as "undefined" when they are attempted to be accessed outside of the function. Can we see the whole script?
The indelible lord of tl;dr
Post Reply

Return to “Beginner Help and Support”