How can I add a table to an existing table?

Currently stuck on this part. I’m trying to add a new table to a table that already exist. In the output, it says [Workspace.Script:7: attempt to index field ‘?’ (a nil value)]

Here is my failed code…

local Table = {Test = "Noob"}

print(Table["Test"])

local function idk(MainTable, SubTable, InfoWanted1, Info1)
Table[MainTable] = {SubTable = {InfoWanted1 = Info1}}
print(Table[MainTable][SubTable][InfoWanted1])
end

idk("Test", "SubTest", "Cost", 500)
---

Semi off topic but, instead of just printing the table like you’re doing, you should use JSONEncode to visualize the tables better. It makes debugging a lot easier

local HttpService = game:GetService('HttpService')
local ExampleTable = {Coins = 20, Wins = 30}

print(HttpService:JSONEncode(ExampleTable)) --> prints: {Coins = 20, Wins = 30}

Also, have you tried using table.insert()?

thanks for the tip! and no i have not tried it

When creating a value and key in a dictionary if your using a variable value or something that isn’t just a key name like {key = "value"} you have to do {[keyVariable] = "value"} or {[“keyString”] = “value”}. So in your case you need to do:

local Table = {Test = "Noob"}

print(Table["Test"])

local function idk(MainTable, SubTable, InfoWanted1, Info1)
Table[MainTable] = {[SubTable] = {[InfoWanted1] = Info1}} -- i just put brackets around the variables telling lua its a variable not just a key name.
print(Table[MainTable][SubTable][InfoWanted1])
end

idk("Test", "SubTest", "Cost", 500)

Thanks A LOT!

I’d strongly advise you try for yourself before telling the OP to try it. Because in the end this would not have solved the problem.

One problem, this works, but if i wanted to add another subtable with a different name to the maintable it will overwrite the first subtable i added.

The solution is easy because all you need to do is set Table.Test to an Array in your code. I kept the original ‘Test’ as a string, setting it to an array after it prints the first time.
After that all you need to do is create a new value in the table which is shown in the code below.

local Table = {Test = "Noob"}

print(Table["Test"]) --Output: "Noob"

Table.Test = {}

local function idk(MainTable, SubTable, InfoWanted1, Info1)
	Table[MainTable][SubTable] = {[InfoWanted1] = Info1}
	print(Table[MainTable][SubTable][InfoWanted1])
end

idk("Test", "SubTest", "Cost", 500)
idk("Test", "SubTest1", "Cost", 6700)

print(Table["Test"]["SubTest"]["Cost"]) --Output: 500
print(Table["Test"]["SubTest1"]["Cost"]) --Output: 6700

This keeps the MainTable instead of creating a new one each time you need to add a ‘SubTable’

Something that would help typing it easier;

You don’t need to index it with brackets if it’s a string key unless it has spaces.

print(Table.Test.SubTest.Cost)

This would still print 500.