开发者

Can I somehow save circular data structures with JSON or something similar?

开发者 https://www.devze.com 2023-04-08 23:14 出处:网络
When trying to save some data about the game world in a file using JSON, I get that good ol\' JSON circular reference error. Is there a way to save circular data types? Also, I\'m running this with no

When trying to save some data about the game world in a file using JSON, I get that good ol' JSON circular reference error. Is there a way to save circular data types? Also, I'm running this with node.js, not inside a browser.

Basically, over time, the player gets some units. These units are saved to a list inside the player object, but are given the player himself as an argument, so they know who's their owner. Something like this:

Player = function()
{
    this.power = 0
    this.units = 开发者_运维技巧[new Unit(this)];
}

Unit = function(owner)
{
    owner.power++;   
}


@Bane, in answer to how to include the cycle.js

Put it in your lib folder for your project and include it via a script tag if you're doing it on the client side.

On the server side you could include the code in the file that you need the circular reference in; that's simple but really the wrong way to work. Better bet is to build it out as a module, check this tutorial on howtonode.org for the specifics.

Your overall best bet though is to refactor so that you don't need the circular reference.

0

精彩评论

暂无评论...
验证码 换一张
取 消