Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading