Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Trying to access table in class

in Questions Posts: 7

I'm trying on adding data to a table that I have within a class. No matter what I try, the table is nil.

TestClass = class()

function TestClass:init(x)
     self.x = x
     self.numbers={}
end

function TestClass:insertNumber(number)
    table.insert(self.numbers,number)
end

--Main
function setup()
    tests={}

    table.insert(tests,TestClass)
    table.insert(tests,TestClass)

    tests[1]:insertNumber(5)
end
 

I get the error on the first table.insert

Mike

Comments

  • dave1707dave1707 Mod
    edited July 29 Posts: 6,392

    @mikeyleo Here's how to do it.

    --Main
    function setup()
        a=TestClass(12345)
        b=TestClass(324)
    
        a:insertNumber(25)
        a:insertNumber(32)
        a:insertNumber(12)
    
        b:insertNumber(65)
        b:insertNumber(72)
        b:insertNumber(28)
    
        a:print("a")
        b:print("b")    
    end
    
    
    TestClass = class()
    
    function TestClass:init(x)
         self.x = x
         self.numbers={}
    end
    
    function TestClass:insertNumber(number)
        table.insert(self.numbers,number)
    end
    
    function TestClass:print(val)
        print("Class instance  "..val)
        print("value of x "..self.x)
        print("table values")
        for a,b in pairs(self.numbers) do
            print(b)
        end
    end
    
  • Posts: 213

    @mikeyleo Your mistake was saying:

    table.insert(tests,TestClass)
    

    in the setup. The class function is setup so that when you use parentheses, then it calls the init function. Therefore, you have to insert a TestClass(), which instantiates a new TestClass that will have it's own number table. So,

    table.insert(tests,TestClass())
    
  • Posts: 7

    The parentheses did the trick. Thanks to both of you!

Sign In or Register to comment.