设置属性的问题

时间:2013-05-09 01:26:05

标签: lua corona

以下是我遇到问题的系统的要点。我似乎理解自己,。,和:。我似乎错过了一些东西。发生的事情是当它调用“Object:setSomeObjectIsAttachedTo()”时,如果我只是打印“self”,我会得到一个打印的表地址。如果我更进一步尝试打印“self.someObject”我得到nil,这不应该发生,因为在Object中它有一个键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 File

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

1 个答案:

答案 0 :(得分:1)

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

附录

修改后的代码,Object在您致电someObject之前没有字段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();