0

以下是我遇到问题的系统的要点。我似乎理解自我,.,和:。我只是似乎错过了一些东西。发生的事情是,当它调用“Object:setSomeObjectIsAttachedTo()”时,如果我简单地打印“self”,我会得到一个打印的表地址。如果我更进一步并尝试打印“self.someObject”,我会得到 nil,这不应该发生,因为在 Object 中它有一个 key someObject,它是在“Object.new(args)”开始时创建的,当然如果试图更进一步,它甚至无法去那里,因为它为零。请帮忙!!

目标文件

Object = {};

ObjectMeta = {__index = Object};

function Object.new(args)
    Obj = {};
    Object.someObject = OtherObject.new(args)
    return setmetatable(Obj,ObjectMeta );
end

function Object:setSomeObjectIsAttachedTo()
    --OtherObject instance Should set its attached property to 
    --This instance of Object
    self.someObject.ObjectImAttachedTo = self;
end

--Calls after new to set the ObjectImAttachedTo Property, So it isnt nil
Object:setSomeObjectIsAttachedTo();

return Object;

其他对象文件

OtherObject = {};

OtherObjectMeta = {__index = OtherObject};

function OtherObject.new(args)
    Obj = {};
    Obj.ObjectImAttachedTo =nil;
    return setmetatable(Obj,ObjectMeta );
end
return Object;

更新

场景

Scene = {};

ObjectContainer = {};

function Scene.new()

end

function Scene.addObjects()
    local Object= require "Object"
    local StartX = 50;
    local StartY = 20;
    local counter = 0;
    for i=0, 17 do
         ObjectContainer[i] = Object.new({x=StartX,y=StartY});
    end
end

Scene.addObjects();
return Scene
end
4

1 回答 1

1

该表Object没有名为 的字段someObject,但返回的实例Object.new()确实具有该字段。这是两个不同的表,大致对应一个类和它的一个实例。

附录

使用修改后的代码,ObjectsomeObject您调用Object.new(). 所以,你必须先打电话Object.new(),然后再打电话Object:setSomeObjectIsAttachedTo();。注意OtherObject.new()必须先定义后才能调用Object.new()

ADDENDUM2 回答问题“那么你建议我做什么来解决这个问题?”

function Object.new(args)
    Obj = {};
    Obj.someObject = OtherObject.new(args)
    Obj.someObject.ObjectImAttachedTo = Obj;
    return setmetatable(Obj,ObjectMeta );
end

并摆脱Object:setSomeObjectIsAttachedTo();

于 2013-05-09T02:48:53.803 回答