All Questions



line_data.buttons VS line_data["buttons"] ?

Since line_data is a dictionnary with 3 entries, "text", "expression" and "buttons", I assumed that we could access the buttons with the usual dictionnary syntax, i.e. line_data["buttons"], as we did for "text" and "expression" (btw I tried and it works).

But in the code presented here we use line_data.buttons (not unlike when we access node properties such as .texture or .bbcode_text).

Could somebody explain why this works (what kind of trick it is), and if there are some merits to this syntax ?

  • Nathan Lovato replied

    You can give keys to dictionaries in two ways:

    1. By passing a value in square brackets, e.g. ["buttons"], but also [1], [Vector2.RIGHT], or even using a variable like [position].
    2. By writing a string key after a dot, as in .buttons

    The second syntax is the one we use the most to access variables on nodes: for example, in node.position or node.rotation. Using it also with dictionaries can make your code a little easier to read.

    The first syntax with the square brackets is more powerful because it allows you to use all kinds of values and calculations to find the key. You will see some examples of that in the course, starting with the random rocks series.

    We need to show you both syntaxes just so that you know they exist and get used to working with them.

    It goes a little further than that because you can actually use those two syntaxes with any node: node["position"] also works to access a node's position member variable.

  • T
    Tapewormer replied

    Maybe it was mentioned in the app/course but I did not catch on the alternative syntax for dictionary keys, so thanks a lot for the detailed and fast reply ! I take it from your answer that it's nice/reasonable practice to use dot syntax when possible (easier to read) and brackets when not.