scope + delegates = irritating

Hendrik Renken funsheep at gmx.net
Tue Apr 10 14:32:50 PDT 2007


I am having some problems with delegates in classes or structs.

i would like to write a simple SDL KeyMapper. It should store delegates 
in a associative array, so i know what to invoke on which key, pressed 
on the keyboard.

for mainscope foo and modulescope foo (see below) it works perfect, but 
for the foo delegate defined within the struct, with dmd 1.010 i get a 
segmentationfault on the line "keymap[3]()".

what do i have to do, to invoke the foo, defined in the struct?

thanks in advance
hendrik


module KeyManager;

import std.stdio;
import std.string;

private void delegate()[int] keymap;


public void setKey(int key, void delegate() dg)
{
	keymap[key] = dg;
}

public bool isSetKey(int key)
{
	return keymap[key] != null;
}


void moduleScopeTest()
{
	void foo()
	{
		writefln("modulescope was invoked ");
	}
	setKey(2, &foo);
}

struct scopeTestStruct
{
	void foo()
	{
		writefln("structscope was invoked");
	}

}

void main()
{
	scopeTest();

	void foo()
	{
		writefln("mainscope was invoked ");
	}
	setKey(1, &foo);

	scopeTestStruct c;
	setKey(3, &c.foo);

	if (isSetKey(1)) writefln("1 is set");
	if (isSetKey(3)) writefln("3 is set");

	keymap[1](); //mainscope   foo
	keymap[2](); //modulescope foo
	keymap[3](); //structscope foo
}


More information about the Digitalmars-d-learn mailing list