Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

Inserting a dictionary in a table?

Asked by
Mr_Pure 129
5 years ago

Is there a direct way to insert a dictionary into a table to reference back to. EX:

local MyTable = {}

table.insert(MyTable, 1, key = 1)

--clearly wont work. but i just wanted to know if there was a good way to insert a dictionary into a table

1 answer

Log in to vote
1
Answered by
xPolarium 1388 Moderation Voter
5 years ago
Edited 5 years ago

Adding a dictionary to a table can be done by indexing the table with the key:

local MyTable = {} --New table reference
MyTable.key = 1

print(MyTable.key) --Prints 1 in output

table.insert() is used to add a value to an array. An array is a numerically-indexed table. It would look like:

local array = {11, 12, 13, 14}

print(array[3]) --Would print 13 in the output.

You don't use table.insert() to add a key-value pair to a table.


Let me know if you need me to explain something or I had missed anything.

Tables

Edit:

You would give an index in the existing table to reference a new table. Then you use the previous method to set any keys with their values.

local myTable = {
    someKey = 3
}

myTable.newTable = {} --construct table in existing table under an index
myTable.newTable.Key = 1 --Same as my answer before

print(myTable.newTable.Key) --Prints 1 to output
0
This was a very well constructed answer and has bettered my understanding of dictionaries, ty. Mr_Pure 129 — 5y
Ad

Answer this question