On Saturday, 23 August 2014 at 10:19:59 UTC, nikki wrote:
I am learning SDL by following the lazyfoo SDL2 tuorials, I am
alos new to D so I have a question:
I the lazyfoo tutorials there are many functions that have a
bool success whiich gets set at various places when something
goes wrong to be returned afterwards.
http://lazyfoo.net/tutorials/SDL/02_getting_an_image_on_the_screen/index.php
for example:
[code]
bool init()
{
//Initialization flag
bool success = true;
//Initialize SDL
if( SDL_Init( SDL_INIT_VIDEO ) < 0 )
{
printf( "SDL could not initialize! SDL_Error: %s\n",
SDL_GetError() );
success = false;
}
else
{
//Create window
gWindow = SDL_CreateWindow( "SDL Tutorial",
SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, SCREEN_WIDTH,
SCREEN_HEIGHT, SDL_WINDOW_SHOWN );
if( gWindow == NULL )
{
printf( "Window could not be created! SDL_Error:
%s\n", SDL_GetError() );
success = false;
}
else
{
//Get window surface
gScreenSurface = SDL_GetWindowSurface( gWindow );
}
}
return success;
}
[/code]
in my D code I just change the NULL into null and the printf to
a fitting writeln.
But I am wondering if D offers me much cleaner ways of writing
this, I am guessing the scope() but what would be the best/D
way of writing this function?
How would you write it?
How about this?
----
import std.exception; // enforce() is declared in std.exception
void init()
{
// enforce() throws an exception if condition is false
enforce(SDL_Init( SDL_INIT_VIDEO ) >= 0, "SDL could not
initialize!");
// enforce() throws if SDL_CreateWindow returns null
gWindow = SDL_CreateWindow(/* ... */).enforce("Window could not
be created!");
// ditto
gScreenSurface = SDL_GetWindowSurface(gWindow).enforce("Surface
could not be created!");
}
----