BlueWolf
BlueWolf

Reputation: 35

Function returns nil when called inside constructor

I just started programming in lua and I created sort of oop structure following this tutorial: http://tylerneylon.com/a/learn-lua/

Problem is, when I created function that returns object or table of objects and call it inside constructor, it returns nil.

Here is my code for first object:

require "ObjectB"

ObjectA = {}

function ObjectA:new(num)
    newInstance = {}

    newInstance.var = self:foo(num)

    self.__index = self
    return setmetatable(newInstance, self)
end

function ObjectA:foo(num)
    return ObjectB:new(num)
end

, and for second object:

ObjectB = {}

function ObjectB:new(num)
    newInstance = {}

    newInstance.num = num

    self.__index = self
    return setmetatable(newInstance, self)
end

When I do this:

myObject = ObjectA:new(5)
print(myObject.var.num)

, I get error: "Error: main.lua:14: attempt to index field 'var' (a nil value)". But when I do this:

myObject = ObjectA:new(5)
myObject.var = ObjectA:foo(5) //setting var by calling foo outside of constructor
print(myObject.var.num)

, everything seems to work fine and print result is really 5. Can anyone tell me what is reason for this strange behaviour or what am I doing wrong here?

Upvotes: 3

Views: 123

Answers (1)

Yu Hao
Yu Hao

Reputation: 122493

Variables are global by default, so the two variables newInstance in ObjectA:new and ObjectB:new are the same global variables, you assign it a new value, the previous value is gone.

Instead, use local variables like this:

function ObjectA:new(num)
    local newInstance = {}
    --the rest
end

and

function ObjectB:new(num)
    local newInstance = {}
    --the rest
end

Upvotes: 4

Related Questions