Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

allow assigning values to nested dictionaries #440

Merged
merged 1 commit into from
Mar 4, 2024
Merged

Conversation

Jamiras
Copy link
Owner

@Jamiras Jamiras commented Feb 28, 2024

Fixes an issue where modifying a nested dictionary did not work:

dict = {"a": {"b": 3} }
dict["a"]["b"] = 5
achievement("test", "test", dict["a"]["b"], trigger=...)

Would generate an achievement worth 3 points, not 5.

This is a result of the temporary variable used for storing dict["a"] evaluating the dictionary instead of referencing it. By evaluating it, a copy was made, and the ["b"] = 5 modification was applied to the copy.

The same problem occurs when using a non-anonymous intermediate variable:

dict = {"a": {"b": 3} }
t = dict["a"]
t["b"] = 5
achievement("test", "test", dict["a"]["b"], trigger=...)

t was a copy of dict["a"], so the modification was applied to the copy.

When dictionaries (or arrays) are passed to a function, they're done so by reference, so the function can modify the dictionary. I've extended that logic to do assignments of dictionaries (and arrays) by reference. As such, both t and the temporary variable in the first example are references to the nested dictionary, allowing the modification to go through.

NOTE: This eliminates the ability to copy a dictionary (or array) just through assignment:

function MergeArrays(arr1, arr2)
{
    newArr = arr1 // <-- this now creates a reference
    for i in arr2
    {
        array_push(newArr, i) // <-- so i is now actually being pushed onto arr1
    }
    return newArr
}

needs to be changed to:

function MergeArrays(arr1, arr2)
{
    newArr = []
    for i in arr1
    {
        array_push(newArr, i)
    }
    for i in arr2
    {
        array_push(newArr, i)
    }
    return newArr
}

This also provides a performance improvement when working with nested dictionaries as copies of the subdictionaries are no longer made just to pull values from them.

@Jamiras Jamiras added this to the 1.13.0 milestone Feb 29, 2024
@Jamiras Jamiras merged commit ca4433c into master Mar 4, 2024
1 check passed
@Jamiras Jamiras deleted the nested_dict_assign branch March 4, 2024 15:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant