1

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?

1 Answer 1

4

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

1 Comment

Simple solution that I overlooked. I did not consider the fact that the declaration of b outside of the function meant that it would not be unique every time. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.