Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

How can I create a global object in a script file that can be seen in a different script file?

I have created plenty of functions that work this way by simply defining the function as "window.funcName = function()", but if I try to create a global object (or variable) by either "var objectName = {//actual object stuff here}" outside of any function, or "window.objectName = {}", I get thrown a "objectName is undefined" error whenever I "Test From Here".

According to all the javascript resources I've read, this should work. Is Twine doing something strange? Is there anyway I can see what strange-ness is going on?

*Note
Using SugarCane 1.4.2.

Comments

  • note: Your statement is not clear about what you mean by script file, you could be talking about two script tagged passages or you could be talking about two external js files. I am going to assume you meant two script tagged passages.

    It is a good idea to only have a single script tagged passage in a story, especially if you have a piece of javascript that rely's on a different piece of javascript.

    The reason for this is that the order that javascript code gets loaded is very important and there is no way to control the order that script tagged passages get loaded.

    My guess is that the code that is trying to access your objectName object is getting loaded before the code that initializes the objectName object and so you get the error.
  • The var issue is due to scoping. Local variables only exist within the scope in which they're created and each script passage is executed within its own scope, so you can only access local variables within the same script passage.

    The auto-global issue shouldn't be happening. Where are you declaring the properties on window and where are you trying to access them? If you're declaring them in one script passage and accessing them in another script passage (among other places), you may be running into an order of execution issue (i.e. it's possible that the accessing script passage is executing before the declaring one). If you're declaring them in a script passage (or StoryInit) and accessing them in normal passages, then that should definitely work, so I don't know.

    It would be helpful if you actually showed what you're having issues with. Sometimes descriptions are sufficient, but often times they are not and giving actual details/examples never hurts.
Sign In or Register to comment.