Using DMD. v2.098-beta-2
Not sure if right terminology. But I just wrote a nested function that uses a variable outside its body. The capture (right term?) is obvious where the invocation is. However, I have to move the declaration of the variable to above the nested function for it to compile.
Here is the code that wont compile:
void execute()
{
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
ALLEGRO_EVENT event;
// later
isKey(ALLEGRO_KEY_W);
// main.d(491): Error: undefined identifier `event`
This however, will compile:
void execute()
{
ALLEGRO_EVENT event; // <--Only change
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
// later
isKey(ALLEGRO_KEY_W);
It appears the nested function's variable capture depends on forward declaration (the right term?). Whereas, I was under the impression most/all of D worked on a multiple pass compilation so the order of declarations shouldn't matter.
Is this a D spec, or a compiler parsing error/oversight?
I guess if I had two different variables called event, this could become confusing code to read except that, mentally these should still link up, right?
Hypothetical:
void execute()
{
bool isKey(ALLEGRO_KEY key)
{
return (event.keyboard.keycode == key);
}
{
ALLEGRO_EVENT event;
isKey(ALLEGRO_KEY_W);
} //lets say this does some memory housekeeping/deleting so that's why we use scope
{
ALLEGRO_EVENT event; //new 'event', same name, new memory
isKey(ALLEGRO_KEY_W);
}
}
in this case, 'event' under-the-hood could be renamed, say, "event2" and have the same expected compile time symbol linking occur. The second isKey call is obviously connected to the second 'event' variable.
I imagine this is a really odd edge case but it's piqued my interest.