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
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)
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’