Howdy, Stranger!

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

Best way to access twine objects with javascript?

This is something that has been bugging me recently. I've got a way that works, but its not what I would call a good way.

Here's what I know works:
Twine
<<set $cat to {
    name: "felix",
    //...
}>>
<<set $dog to {
    name: "lassie",
    //...
}>>

Javascript
function GetPetName(pet){
    var petname = "";
    if(pet == "cat"){
        petname = state.active.variables.cat.name;
    }else if(pet == "dog"){
        petname = state.active.variables.dog.name;
    }
}

And here's what I'd like to do:
function GetPetName(pet){
    var newpet = state.active.variables.pet;
    var petname = newpet.name;
}

I know the second method doesn't work as I've written it, but I hope its clear what I'm going for.
Is there a way to do it like that? In a function where I need to reference the object a lot, it would be much cleaner to do it that way than having to put state.active.variables.... every time.

Comments

  • edited November 2015
    You want the square bracket notation. For example:
    function GetPetName(petType) {
    	var pet = state.active.variables[petType];
    	//…
    }
    
    And if this is actually for SugarCube 2, I'd recommend the shorter: (note the case difference, State vs. state)
    function GetPetName(petType) {
    	var pet = State.variables[petType];
    	//…
    }
    
  • edited November 2015
    Thanks, your first method works (I'll try it in SugarCube 2 another time)
    I'll have to compare this to what I tried last night once I'm back on that machine, because I could have sworn I tried it the same way you've presented it here. Probably missed something obvious.

    edit: I had a follow up question but I realized my error immediately after posting it.
Sign In or Register to comment.