Thread overview
class that is initialized becomes null when outside of function
Jul 09, 2018
Flaze07
Jul 09, 2018
Flaze07
Jul 09, 2018
ag0aep6g
Jul 09, 2018
Flaze07
July 09, 2018
I am using DSFML
module game;

import core.time;

import std.stdio: writeln;

import dsfml.graphics;

import dsfgui.button;

import apple;
import snake;

class Game
{
private:
    enum State { menu, playing }
    State state;
    Font font;
    Button playBtn;
    Snake snake;
    Apple apple;
    RenderWindow win;
    int size;
protected:
    this(){}
public:
    void init()
    {
        import std.exception : enforce;

        size = 10;

        auto win = new RenderWindow( VideoMode( 600, 600 ), "snake" );

        font = new Font;
        enforce( font.loadFromFile( "media/arial.ttf" ), "failed to load font arial" );

        playBtn = new Button( "play", font );
        playBtn.position = Vector2f( 300, 300 );

        snake = new Snake( size, 3, Vector2f( win.size.x, win.size.y ) );
        apple = new Apple( size / 2, Vector2f( win.size.x, win.size.y ) );
    }
    void run()
    {
        auto clock = new Clock;
        writeln( win is null );
        while( win.isOpen() )
        {
            writeln("lol" );
        }
    }
}

the problem here is, during init(), the writeln will output false, which means yes win is initialized, however during run(), suddenly win is null becomes true...

and here is my main()
void main( string[] args )
{
    myGame.init();
    myGame.run();
}

P.S I tested this with int* and it don't become null when function ends
July 09, 2018
On Monday, 9 July 2018 at 09:18:50 UTC, Flaze07 wrote:
> I am using DSFML
> module game;
>
> [...]

oh, and I forgot, I had

Game myGame;
static this()
{
    myGame = new Game;
}

below the Game class
July 09, 2018
On 07/09/2018 11:18 AM, Flaze07 wrote:
> class Game
> {
[...]
>      RenderWindow win;
[...]
>      void init()
>      {
[...]
>          auto win = new RenderWindow( VideoMode( 600, 600 ), "snake" );
[...]
>      }
>      void run()
>      {
[...]
>          writeln( win is null );
[...]
>      }
> }
> 
> the problem here is, during init(), the writeln will output false, which means yes win is initialized, however during run(), suddenly win is null becomes true...

The `win` you're creating in `init` is a function-local variable. It ceases to exist when `init` returns. It's not `this.win`.

In `run`, you're accessing `this.win`. It's still null because you never assigned anything there.

So change `auto win = ...;` to `this.win = ...;` or simply `win = ...;`.
July 09, 2018
On Monday, 9 July 2018 at 09:38:30 UTC, ag0aep6g wrote:
> The `win` you're creating in `init` is a function-local variable. It ceases to exist when `init` returns. It's not `this.win`.
>
> In `run`, you're accessing `this.win`. It's still null because you never assigned anything there.
>
> So change `auto win = ...;` to `this.win = ...;` or simply `win = ...;`.

oops, I forgot... haha what a silly mistake, thank you