WurstScript icon indicating copy to clipboard operation
WurstScript copied to clipboard

Add error for using `destroy this` in constructor

Open PhoenixZeng opened this issue 7 years ago • 4 comments

class B
    int a = 1
    construct(int a)
        if a == 0
            destroy this
        this.a = a //error in here

PhoenixZeng avatar Nov 08 '18 17:11 PhoenixZeng

Hey @PhoenixZeng thanks for the reports. Please remember that these are not plugin issues, but the language server which resides in the main repo. wurst4vscode issues must be related to its code.

Regarding the issue, it's a new error we introduced. You may not access instances that might have been destroyed earlier anymore. In your example, in case a == 0, the instance is destroyed and you are trying to access it. This is now illegal. Putting it into the else branch of your if would be any easy fix.

Frotty avatar Nov 08 '18 17:11 Frotty

yes. i know that. But I think this should be a warning rather than a error. Because this behavior is logically reasonable, because conditions are very rare in many cases.

PhoenixZeng avatar Nov 08 '18 18:11 PhoenixZeng

Because this behavior is logically reasonable

I would argue that it was a neat hack. Not really logically reasonable to access or modify a member of a class after it has been destroyed. There can be many possible side effects due to deconstructors, new allocations and reassignments leading to strange and hard to debug issues in-game. We want to guarantee more safety and prevent such bugs from happening in the first place.

Frotty avatar Nov 08 '18 18:11 Frotty

Actually, we should also add an error when using destroy this in the constructor. You should rewrite your code to something like this:

class B
    int a = 1
    construct(int a)
        this.a = a

function createB(int a) returns B
    if a == 0
        return null
    return new B(a)

If you destroy the object in the constructor, the expression new B(0) would return an invalid object and the caller would have no way to tell whether it was successful or not.

peq avatar Nov 08 '18 19:11 peq