lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Ryanne Thomas Dolan write:

>In Lua the problem is not pointers but references to tables.  To fix the
>problem you can either initialize the references manually or in your
>constructor:

>Example = {
>   member1 = "hello world";
>  member2 = {};
>};

>function Example:new (obj)
>   obj = obj or {};
>    obj.member2 = {};  --initialize member table references
>...
As a class, it is well, but if we want to make inheritance,  it has a problem.
function Example:new (obj)
   obj = obj or {};
    obj.member2 = {};  --initialize member table references
...
end

NewClass = Example:new()

function NewClass:new (obj)
   obj = obj or {};
    setmetatable(obj, self)
   ...
end 

a = NewClass:new()
b = NewClass:new()

a.member2 and b.member2 still have the same reference. of course, we can do that 
function NewClass:new (obj)
   obj = obj or {};
    obj.member2 = {};  --initialize member table references
    setmetatable(obj, self)
    ...
end 
Then we must initialize member table references in all the inheritance class, But it make the code ugly! how to resolve it gracefully!


 bean