3

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?

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

1 Comment

The tutorial that the OP links to makes the same mistake. It doesn't use the 'local' keyword anywhere in its OOP section. Forgetting 'local' can lead to some very frustrating bugs.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.