On Thursday, 2 June 2016 at 00:37:58 UTC, WhatMeWorry wrote:
I've got a fairly complex D project (25+ modules) that has
grown haphazardly over time. So it is not well designed. But I
want to get the thing fully ported before refining the code.
(that's called refactoring, I believe?)
Anyway, there is a new module called audio.d which which has
all the sound functionality.
And in the (main.d) module is a code snippet like so
void main(string[] argv)
{
// . . .
auto blop = new AlurePlaySound("../bleep.wav");
blop.play();
// . . .
}
So all is well and good except I need to place the sound in
another module (game.d) where
collisions are detected.
I tried:
module game;
import main; // is this as ugly as I think it is?
if (collision[0]) // If collision make sound
blop.play();
but this returns: game.d(501): Error: undefined identifier
'blop'
So can someone tell me what various solutions to this problem
or type of problems? I presume there are quick and dirty
solutions (like here) and more elegant solutions?
Would this type of problem fall under the domain of "scope".
Like in global scope. But I don't think D has such a concept.
Thanks.
Since blop is being declared inside your main() function, it
isn't visible to other modules or functions. You're right that
the issue is a problem of "scope".
Importing your main module will work, but you must declare your
as a global variable outside the main() function.
i.e.
----------------------
module main;
AlurePlaySound blop;
void main()
{
//etc...
blop = new AlurePlaySound("../beep.wav");
//etc...
}
----------------------
module game;
import main;
void collision()
{
blop.play(); //or whatever
}
If your game loop is running in a separate thread, then I think
you'll want to use:
__gshared AlurePlaySound blop;
for the declaration, since variables are thread-local by default.
Using global variables is generally frowned upon for production
code because you can never be sure which functions are modifying
it. But for a quick hack, it works! A better option might be to
make a third module with a class containing all your audio
objects, initialize it in main(), and then pass it to your main
game loop.
-Jon