Problem with table.create

So I was experimenting with table.create and I am a little bit confused as to what’s happening here:

local myTable = table.create(4,{})

for i = 1, #myTable do
	print(myTable[i])
	myTable[i][1] = "string"
end

If I understand this correctly, it should print out something like this:

  19:48:32.483  {}  -  Server - Test:4
  19:48:32.483  {}  -  Server - Test:4
  19:48:32.484  {}  -  Server - Test:4
  19:48:32.484  {}  -  Server - Test:4

But instead, I got this:

  19:50:46.553  {}  -  Server - Test:4
  19:50:46.553   ▼  {
                    [1] = "string"
                 }  -  Server - Test:4
  19:50:46.554   ▼  {
                    [1] = "string"
                 }  -  Server - Test:4
  19:50:46.554   ▼  {
                    [1] = "string"
                 }  -  Server - Test:4

I then changed the first line of code to this:

local myTable = {{},{},{},{}}

and it seems to be working as expected.

I tried looking at the documentation for table.create to find out what’s happening but I can’t seem to find the issue.

Does anyone know what’s happening here?

1 Like

Try this:

local myTable = table.create(4,{})

for i = 1, #myTable, 1 do
print(myTable[i])
myTable[i][1] = “string”
end

You forgot to increment the i variable.

1 Like

I don’t think you have to do that because it increments by 1 on default but I tried it anyway and got the same results:

  20:14:19.671  {}  -  Server - Test:4
  20:14:19.672   ▼  {
                    [1] = "string"
                 }  -  Server - Test:4
  20:14:19.672   ▼  {
                    [1] = "string"
                 }  -  Server - Test:4
  20:14:19.673   ▼  {
                    [1] = "string"
                 }  -  Server - Test:4

this happens because every single table has the same memory address, enabling log mode on the output will print

table: 0xb96a774d762f6436 (x4) (well the address will always be random but u can see it prints the same address 4 times)

so doing

local myTable = table.create(4,{})

myTable[1][1]="hi"
print(myTable);

should show “hi” on every table even though i only put it on one

solution: don’t use table.create for this type of situation

local myTable = {};
for i=1,4 do
   table.insert(myTable,{});
end;

for i = 1, #myTable do
    print(myTable[i])
    myTable[i][1] = "string"
end
1 Like

Thank you for the valuable insight!