Shawn
Shawn

Reputation: 911

losing global variable value

This is for a gameing application I declare the variable skipnpc which is designed as an indicator that a non player character has used his turn and any AI code related to his behavior is skipped for a period of time. the problem I have is I am loosing the value of skipnpc somehow I indicated where in the console.log commands I issue is related to varaible scope but I don't understand how to fix it.

function npcMovement() {
    skipnpc = false;...
    sql4 = "SELECT id FROM game_moblist WHERE spawn_id =" + spawnid + " AND posx=" + parseInt(mobpathx[mobpathx.length - 1]) + " AND posy=" + parseInt(mobpathy[mobpathy.length - 1])
    connection.query(sql4, function (err, send, fields) {
        console.log("skipnpc pathing")
        io.sockets.emit('groupmoveresult', send, parseInt(mobpathx[mobpathx.length - 1]), parseInt(mobpathy[mobpathy.length - 1]))
        skipnpc = true
        console.log("skipnpc=true:" + skipnpc)
    });
    console.log("skipnpc = false:" + skipnpc)

Later I use

if (skipnpc==false){
  ...

before any further AI code is attempted

Upvotes: 1

Views: 687

Answers (2)

ebohlman
ebohlman

Reputation: 15003

To put it real simply, skipnpc is guaranteed to still be false by the time you hit your last console.log(...). You're not giving your connection.query(...) any time to execute before trying to look at its result. Anything that relies on the result of connection.query(...) has to be executed as part of the callback you passed to it; otherwise none of the results will have come in when you try to access them.

Asynchronous programming takes some getting used to. You might be able to reorganize your code using the async module and using its waterfall(...) method so everything doesn't wind up deeply nested. But you've got to realize that if you make an asynchronous call, your code will flow right past it.

Upvotes: 1

Roest
Roest

Reputation: 818

connection.query is executed asynchronous. Thus you get to your final line here before it is done.

Upvotes: 2

Related Questions