Trying to understand a few things…

About Monkey 2 Forums Monkey 2 Programming Help Trying to understand a few things…

This topic contains 2 replies, has 3 voices, and was last updated by  Danilo 6 months, 1 week ago.

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
  • #15850


    I’m trying to learn the language but I’m not understanding why this won’t build.  I’m assuming that we can’t define variables outside of a function?  I hope this isn’t the case as it would make things extremely ugly.  I’m trying to port some old code and I need to define a map of a few dozen items.  Having to do it inside of a function just seems strange to me.  Is there something that I’m missing?



    That’s basically right, though simple assignments can be done if you can define them on the same line, eg. Global a:=1.

    You can of course assign them in Main, which, if you think about it, is really what defining variables ‘outside of functions’ was in Blitz & co. Monkey/Monkey2 just adopted the more formal approach of having an explicit Main…

    I tried a few variations but I don’t think there’s a way to initiate the string data on the global line in this case. (Could be wrong… )



    It is possible if you use your own class that extends Map.

    With simple-type Arrays it is possible to initialize when declaring it:


    Now we can use that principle and write a generic class that extends Map<K,V>, let’s call it MapEx<K,V>.

    We then add a constructor (“New”) that takes an array of Value+Key pairs for initializing the Map.


    That would look like this:

    Okay, that works. But that constructs for initializing the Map are very big.


    By using two ‘Alias’ we can shorten it:

    With those two Alias, we can now write a simpler global Map initialization:

    Looks better, doesn’t it? 😉

    Here the final code:

Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.