Mixins [In Planning] - Paramecium13/LSN GitHub Wiki

Introduction

Mixins offer a unique and powerful way to reuse code.

Examples

Example 1A

// mixins/src/greeter.lsn
mixin Greeter {        
    // Function
    fn Greet(name : string) {
        Say "Hello " + name + "!";
    }
}

// src/MyScript.lsn
import "greeter"
Host interface ICharacter {
    event TalkedTo(talker : string);
}

Script Class MyScript < ICharacter {
    include Greeter {
        out {
            Greet = Talk;
        }
    }
    
    on TalkedTo(talker: string) {
        Talk(talker);
    }
}

Example 1B

Now lets add an input parameter to our mixin. Lets make it have a name that it will use in its Say statement. We'll add a field to the mixin called MyName.

// mixins/src/greeter.lsn
mixin Greeter {
    MyName : string; // field
    
    // Function 
    fn Greet(subject : string) {
        Say "Hello " + subject + "!" as MyName;
    }
}

Now in our script class's import structure, we add an in structure...

// src/MyScript.lsn
import "greeter"
Host interface ICharacter {
    event TalkedTo(talker : string);
}

Script Class MyScript < ICharacter {
    include Greeter {
        in {
            MyName = Name;
        out {
            Greet = Talk;
        }
    }
    mut Name : string; // Field
    
    on TalkedTo(talker: string) {
        Talk(talker);
    }
}

Example 1C

// mixins/src/greeter.lsn
mixin Greeter {
    expression MyName;
    
    // Function 
    fn Greet(subject : string) {
        Say "Hello " + subject + "!" as MyName;
    }
}

// src/MyScript.lsn
import "greeter"
Host interface ICharacter {
    event TalkedTo(talker : string);
    fn GetName()->string;
}

Script Class MyScript < ICharacter {
    include Greeter {
        in {
            MyName = host.GetName();
        out {
            Greet = Talk;
        }
    }
    
    on TalkedTo(talker: string) {
        Talk(talker);
    }
}

Misc. Notes

  • Mixins are not types and thus do not offer a means to implement polymorphism. I would like to implement polymorphism in the future though.