Howdy, Stranger!

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

How to set arrays and datamaps in SugarCube...

I am currently learning how to use SugarCube (and trying to port my Harlowe story into SugarCube) and can't find information on how to set a datamap.

I understand that to set an array in SugarCube, you use the following syntax:
<<set $array= ["zero", "one", "two", "three"]>>

How do you set a datamap?

Comments

  • SugarCube does not have a (datamap:) as such but it does support standard Javascript data types and structures.

    The nearest equivalent to a datamap in standard Javascript would be an object (also known as an associate array), and one of the ways you define an object is as follows:
    <<set $person to {name: "bob", age: 18}>>
    
    Your name is: <<print $person.name>> and you are <<print $person.age>> years old.
    
  • edited November 2016
    If I had multiple names and ages and wanted to print one of the names, would there be a way of doing thi
    <<set $objects =
    { nameitem: 'wallet', agevalue: true },
    { nameitem: "bob", agevalue: 30 }
    >>

    would there be a way , and ive tried to no success, to call on just the first line, or just nameitem's, or just agevalue's, and print all of those?

    <<print $objects.nameoritem>> only outputs the first one.
    'Wallet'

    in this case.

    Say I had a bob and a jill and wanted to call on jill instead.

    Your name is <<print $person.name2>> would suffice, but is there another way of doing it if the array was set up like this
    <<set $person to {name: "bob", age: 18}, {name:"Jill", age:18}>>
    


    I know I could use prototypes, but would I need the <<Script>> tag to enclose everything or can I do it all with twine:
    <<set $person to {name: , age:}>>
    <<set $newperson = new $person("jill", 18);
    
    something like that?

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
  • Your first example is not an array because it is missing the open/close square brackets required to declare one, what you are doing is assigning the first object to the $objects variable which is why you are getting the result you are. It should be something like:
    <<set $objects = [
    	{ nameitem: 'wallet', agevalue: true },
    	{ nameitem: "bob", agevalue: 30 }
    ] >>
    
    ... you can then use the index of the array element to access it, indexes are zero based because it represents the offset from the start of the array.
    First element's nameitem: <<print $objects[0].nameitem
    
    Second element's nameitem: <<print $objects[1].nameitem
    

    note: Your first $person variable example suffers from the same problem.
Sign In or Register to comment.