Tables in classes

I am new to Corona and Lua, and I can’t find a nice way to do this.

I have a class that emulates a graph, and to store graph values I use a table.

[lua]

graph = {dataPoints = {}}

function graph:addValue(val)
    print(self.dataPoints)
    table.insert(self.dataPoints, 0, val) – Insert value first
end

function graph:new (o)
      o = o or {}
      setmetatable(o, self)
      self.__index = self
      return o
end

[/lua]

However, since tables are shared, all objects get the same instance of the table and thus all graphs have the same content. How do I separate them so that each instance has its own table, while still being able to call addValue?

As you probably know, Lua is not an object oriented language. It looks like you’re attempting to use metatables to emulate classes, but aren’t doing it correctly. Check out this tutorial, if you haven’t already.

http://lua-users.org/wiki/ObjectOrientationTutorial

Also, keep an eye out for variable declarations like

graph = ...

This declares a global variable, which is not what you want in most cases (and certainly not in this case). You need to use the “local” keyword to declare a local variable.

As you probably know, Lua is not an object oriented language. It looks like you’re attempting to use metatables to emulate classes, but aren’t doing it correctly. Check out this tutorial, if you haven’t already.

http://lua-users.org/wiki/ObjectOrientationTutorial

Also, keep an eye out for variable declarations like

graph = ...

This declares a global variable, which is not what you want in most cases (and certainly not in this case). You need to use the “local” keyword to declare a local variable.