Generating tables with unique addresses

I am attempting to insert a series of tables that have values generated by a function. I have noticed that the generated tables all have the same address and thusly only the most recently generated table is recognized in my program.

The below represents code in a file the main program is fetching from.

a.lua

local a = {}
local b = {}

b.x = 0
b.y = 0
b.z = 'Static'

function a.new(x, y)
    b.x = x
    b.y = y
    return b
end

What follows is an example of how the above code is implemented.

b.lua

a = require 'a'

d = {}

table.insert(d, a.new(1, 2))
table.insert(d, a.new(2, 3))

The tables generated by a.new all have identical addresses (ie 0x0000001). Because of this, the last table.insert is overwriting the previous table that was generated and there are various entries into the “d” table all pointing to the same location.

How can I go about generating tables in this way with unique addresses?

Does b need to be like this or can you simply modify a.lua like so?

local a = {}

function a.new(x, y)
    x = x or 0
    y = y or 0
    local b = {}
    b.x = x
    b.y = y
    b.z = 'Static'
    return b
end
-- b.lua
d = {}

table.insert(d, a.new(1, 2))
table.insert(d, a.new(2, 3))

for k, v in pairs(d) do
    print(k, v.x, v.y)
end

Leave a Comment