kitlang / kit

Kit: a magical, high performance programming language, designed for game development.
https://www.kitlang.org
Other
1.02k stars 29 forks source link

Can't return a pointer to a local value #57

Closed Gamerfiend closed 5 years ago

Gamerfiend commented 5 years ago

Describe the problem. What did you see? What did you expect to see?

https://github.com/Gamerfiend/kit-ecs/blob/master/src/ecs.kit Using the above code, when trying to get a component you get the following error:

Error: src/ecs.kit:49: Can't return a pointer to a local value

  @src/ecs.kit:49:20-38
      49                return this.components.get(typeIdentifier).unwrap();
                               ^^^^^^^^^^^^^^^^^^^

If this is a code issue, provide a minimal code example:

import kit.vector;
import kit.map;

trait Component {
    function typeIdentifier(): CString;
    function component(): Ptr[Void];
}

struct Entity {
    //will be changed to a hashmap when it is avalible for use
    private var components: Map[CString, Box[Component]]; 
    public var uniqueID: Uint32;
    public var name: CString;
    private var allocator: Box[Allocator];

    private static var id: Uint32 = 0;

    public static function new(allocator: Box[Allocator], name: CString): Entity using implicit allocator
    {
        var components = Map.new(10);
        var uniqueID: Uint32 = Entity.id++;

        return struct Self
        {
            components,
            uniqueID,
            name,
            allocator
        };
    }

    public function addComponent(component: Box[Component])
    {
        if(!(this.contains(component)))
        {
            this.components.put(component.typeIdentifier(), component);
        }
        else
        {
            this.components.remove(component.typeIdentifier());
            this.components.put(component.typeIdentifier(), component);
        }
    }

    public function getComponent(typeIdentifier: CString): Box[Component]
    {
        if(this.components.exists(typeIdentifier))
        {
            return this.components.get(typeIdentifier).unwrap();
        }
    }

    private function contains(component: Box[Component]): Bool
    {
        return this.components.exists(component.typeIdentifier());
    }
}

struct PositionComponent{
    var x: Float;
    var y: Float;
    var z: Float;
}

implement Component for PositionComponent{
    function typeIdentifier(): CString{
        return "Position";
    }

    function component(): Ptr[Void]
    {
        return &this;
    }
}

function main()
{
    var entity1 : Entity = Entity.new("Apple");
    var entity2 : Entity = Entity.new("Orange");

    var positionComponent = struct PositionComponent{
        x: 12.0,
        y: 12.0,
        z: 12.0
    };

    var boxComponent: Box[Component] = positionComponent;
    entity1.addComponent(boxComponent);

    var returnedBoxedComponent: Box[Component] = entity1.getComponent("Position");
}