Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

How to use tables inside tables?

Sorry for asking such a simple question, but for some reason I can't figure out why this table isn't working?

items = {}
items[1]['Name'] = 'A killing machine'
items[1]['Desc'] = "Nobody can afford it.. it's unknown why it's so expensive.."
items[1]['Cost'] = 9999999999999999999999999999999999999999999999999999999999999999999

I also tried..

items = {}
items[1]['Name'] = {'A killing machine'}
items[1]['Desc'] = {"Nobody can afford it.. it's unknown why it's so expensive.."}
items[1]['Cost'] = {9999999999999999999999999999999999999999999999999999999999999999999}

I have plenty of experience, am I just forgetting something again?

2 answers

✓ Accepted answer

When you have tables inside tables it is commonly called a nested table.

The problem with your code is that you have not added this nested table in, so to resolve this simply add a table in at the index e.g.:-

items = {}
items[1] = {} -- adds a table in index 1
items[1]['Name'] = 'A killing machine'
items[1]['Desc'] = "Nobody can afford it.. it's unknown why it's so expensive.."
items[1]['Cost'] = 9999999999999999999999999999999999999999999999999999999999999999999

print(items[1]['Name'])

Hope this helps.

Here's a clearer way to think about it:

-- on its own, an item is an object:
local item = {}
item.Name = "Blah"
item.Desc = "foo foo foo"
item.Cost = 999
-- (it exists without having to worry about its context,`items`)

-- you just happen to put that object into another one:
items[1] = item

Of course, you can also write this as table literals:

local item = {
	Name = "Blah",
	Desc = "foo foo foo",
	Cost = 999
}

items = {item}

This discussion is preserved as it was. New answers, comments, and votes are closed.