Howdy, Stranger!

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

two questions about javascript object variables

Hi all,

I noticed something strange in a project I'm working on that uses javascript objects.

I declared multiple (nested) objects at the beginning of a file:
<<set $Alice = {Eliza:{tru:2, adm:-1, aff:3, att:-3}}>>
<<set $Eliza = {Alice:{tru:-1, adm:2, aff:1, att:1}}>>

<<set $matrix = {Alice:$Alice, Eliza:$Eliza}
and then I print out the $matrix object in a later passage:
<<print JSON.stringify($matrix)>>
...I noticed that the first element, Alice, was printing as 0. If I swapped Alice and Eliza, then Eliza was printing as 0. So I declared a "dummy object" before everything (
<<set $foo = {}>>
) and finally everything printed out the way I expected. Seems like a bug! Or is there some sensible explanation for this behavior?

I have a second question as well. It seems that indexing objects by Twine variables, e.g.
<<print JSON.stringify($matrix.$char)>>
where $char can be set to "Alice" or "Eliza", does not work. I get a red Twine error saying that $char is not defined. Is there any way to make this work right?

Thanks,
Chris

Comments

  • For the second one try:
    $matrix[$char]
    Using the . notation, you can only use a constant value.
  • I've tried that notation, and it doesn't work, either.
  • Here's something I don't understand: why are you defining the objects like this
    <<set $Alice = {Eliza:{tru:2, adm:-1, aff:3, att:-3}}>>
    <<set $Eliza = {Alice:{tru:-1, adm:2, aff:1, att:1}}>>
    Instead of like this?
    <<set $Alice = {tru:2, adm:-1, aff:3, att:-3}>>
    <<set $Eliza = {tru:-1, adm:2, aff:1, att:1}>>
    Because, with the way you've presently set it up, $matrix would become this structure:

    $matrix = {
    Alice: {
    Alice: {
    tru:2, adm:-1, aff:3, att:-3
    }
    }
    Eliza: {
    Eliza: {
    tru:-1, adm:2, aff:1, att:1
    }
    }
    }
    which, as you can see, has the actual data one layer deeper than what it ought.

    Also, I recommend using JSON.stringify(variableName, null, true) instead of plain JSON.stringify(variableName), because it prints in a more readable fashion.

    As for the first error.... would it be OK to show me a HTML file where the bug occurs? I can't seem to replicate it.
Sign In or Register to comment.