Replicating table.insert()

Is there anyway to replicate Roblox table.insert() function but it does like this.

local A , B = 1 , {}
table.insert(B , A)
B[1] = 2
print(A)

2

As what i tested, that method doesn’t work. But i needed that to be working for some table related stuff.

table.insert(B,1,A)

1 Like

I think he wants it so that when the variable A is inserted to the table B at index 1, modifying B[1] will also modify the value of A.

This isn’t possible. Things are inserted into the table by value, not by reference.

If you let A be a table, you can insert it into table B, and when you index it from B and modify it, the contents of table A should be modified, too.

local A = {}
local B = {}
A[1] = 1
table.insert(B, A)
B[1][1] = 2
print(A[1]) --> prints 2

But this level of indirection probably wasn’t what you were hoping for. Sorry.

1 Like

Let’s review:

local A, B = 1, {} -- A is 1, B is an empty table.

-- Insert the value of A into B. No position was indicated, so it will be placed in B[table size + 1]
table.insert(B, A)

print(B[1]) -- Output: 1

B[1] = 2 -- B[1] = 2, overwriting its previous value.

print(A) -- Output: 1
print(B[1]) -- Output: 2

You cannot expect A to be overwritten. A and B[1] are pointing to different locations in memory. Therefore, you must do one of the following for A to be 2.

A = 2
A = B[1]

Remember, A and B are two different variables.

you got a point. So after that, will it follow B[1]?

No. Modifying B[1] will not modify the value of A. You can test this yourself.

Nope! Again, A and B are pointing to two different locations in memory.
By saying A = B, you are setting the value of A to the value of B, overwriting the old value of A.

The wiki is a great place to find more information on variables.

1 Like