How do I add an Object to a Table? Let's say I have a Table called Insert
, ok. Then I want to add objects to it, How would I do that?
local Insert={}
There are multiple ways to add indexes to a table..
When you just add it into the table with the definition of the table
local Table = {'Object',2,workspace.Part,function() end}
When you use the table.insert
function to add an index to the table
local Table = {} table.insert(Table,1) print(unpack(Table)) --[[ The 'unpack' function returns a tuple value of all the index values in the table.. so this code essentially prints out the table. > 1 ]]
When you define an aspect of the table by 'indexing' it through a parent-child order
local Table = {} Table.Hello = 5 --[[ Now, you can access it by saying 'Table.Hello'. The table looks like this now; local Table = { Hello = 5 } print(Table.Hello) --> 5 ]]
When you set a specific index of a table to a value
local Table = {} Table[1] = 3 --[[ The cool thing about this is that it allows for the action of changing indexes.. so if you have; local Table = {1,4,5} And go; Table[2] = nil The table will now look like; local Table = {1,nil,5} ]]
To add objects to a table is quite simple actually. Here's an example of what it would be like, using your table:
local Insert={"Apple" , 1 , true , game.Players.TheContinentofEurope} --Just examples
Tables can store data types including: Strings, Bools , Numbers, and even Objects. All of these are in the example given above. To write data to a table that already exists, we need to access the table, and add the new variable.
As an example, we'll create a script that sets a function, then adds the same variables in the script above. Here we go:
local Table={} Table[1]="Apple" Table[2]=1 Table[3]=true Table[4]=game.Players.TheContinentofEurope
Notice how I used brackets [ ]
to access the table. These are necessary when reading/writing to a table.
Now, just for a better understanding of how tables work, i'll show you some different things you can do with them.
1. Tables can return numbers, based on the amount of variables within them
local Table={"Apple" , 1 , true , game.Players.TheContinentofEurope} print(#Table) --This will print "4" because there are 4 variables inside of the table.
2. Tables are extremely useful with "for" loops.
local Table={"Apple" , 1 , true , game.Players.TheContinentofEurope} for i=1, #Table do --This runs through the table, and prints out every single variable contained within it. print(Table[i]) end
3. Tables can contain themselves!
local DaddyTable={BabyTable2={"Apple" , 1 , true , game.Players.TheContinentofEurope}, "Just a lonely string next to a table, inside of a table..."}
Now, that last one may look kinda confusing, but just think about it the same way you would when adding anything else, such as a string or a number.
So, I think that i'm going to wrap this up now. Anyways, If you have any questions, or need me to clear something up, please leave a comment below. Hope I helped :P