Search code examples
javascriptnode.jsobjectsocket.ioeval

Javascript problem with object cloning and eval()


I'm programming a little game with socketio and nodejs server and that is quite new for me. When someone creates a game it sends to the server the info and the server creates an object with all the game info. I'm using the eval() to make the object named after the game-name like "bob_game = {...}". Here is my code :

games.push("Partie de " + data.pseudo);
gamesStatus.push("lobby");
eval("var " + data.pseudo + "_game = {name :'" + data.pseudo + "',status : 2,playerNb : 1,maxPlayerNb :" + data.nbPlayers + ",players : ['" + data.pseudo + "'], xCoords : [], yCoords : [], directions : []}");
io.emit(data.pseudo, {command : "joinGame", game : data.pseudo});
io.emit("updateGameList", {command : "updateGameList", game : games, gameStatus : gamesStatus});

This all works correctly and i'm able to send back all the info to other users saying a game has been created ! On the website their is a button for every joinable game. When you press one of them, it sends to the server a joinGameRequest with game id and the player's name. All the info is collected correctly and i'm able to set a temporary object replacing the bob_game object :

game = eval(gameName + "_game");

This avoids me calling the original object, bob_game, when I want to make a change otherwise I would put eval() everywhere cause bob isn't always called bob... But, I know that after all the changes made to "game", I have to transfer all the propeties back to bob_game "to save everything in a way". That is where I'm having a problem ... I says game is not defined ... Even though i've been making changes few lines above and I'm able to log the playerNb of game ... So game is defined ...

console.log(game.playerNb);
eval(gameName + "_game = game");

I need help pls xD


Solution

  • don't do this:

    eval("var " + data.pseudo + "_game = {
    

    If you need to have something called 'bob_game', put it inside of an object

    var games = {};
    var newGameKey = data.pseudo + "_game";
    games[newGameKey] = {...};
    

    Then you can always access it by that key.