To keep this short and simple, I am trying to place objects in arrays to get information from them.
For example,
local mod = require(game.ServerStorage.ModuleScript)
local obj1 = mod.new("Name")
local obj2 = mod.new("Name2")
local array = {
[1] = obj1,
[2] = obj2
}
for i = 1,#array,1 do
print(array[i]:getName())
end
However for some reason when I use table.insert for an object, it results in it skipping the rest on the function.
local array = {}
local function addObj(obj)
table.insert(array,obj)
print(array[1]:getName())
end
The output in this scenario turns up blank.
Is there a way I can put objects into tables like this similar to something like Java, or is this not possible?
The second array I used as an example to show that it wouldn’t add into the array. All I’m really needing it to do is to add the object into the table using table.insert()
local mod = require(game.ServerStorage.ModuleScript)
local obj1 = mod.new("Name")
local obj2 = mod.new("Name2")
local array = {obj1,obj2}
local function addObj(obj)
local obj = mod.new("Name3")
table.insert(array,1,obj)
print(array[1]:getName())
end
for i = 1,#array,1 do
print(array[i]:getName())
end
you are adding the object to the Same Index every time.
So, it’s overwriting that index.
So you can switch table.insert(array,1,obj) with table.insert(array,#array+1,obj) where the # operator will return the number of elements in an array. So you are basically giving a new index position each time by adding 1.
It’s also overwriting the others too though. I tried printing the first object’s name before the addobject method and it said it was the second one despite what is shown in the array. They are overwriting each other.
What is your Source Code for adding objects though? You have given us the addobj function. But how are you adding objects to it? Can I see the source code for that?
local mod = require(game.ServerScriptService.Slot)
local obj1 = mod.new("Name")
local obj2 = mod.new("Name2")
local array = {obj1,obj2}
print(array[1]:getName())
Module
local slot = {}
slot.__index = slot
function slot.new(index)
local newSlot = {}
setmetatable(newSlot,slot)
slot.Index = index
return newSlot
end
function slot:getName()
return self.Index
end
return slot
local mod = require(game.ServerStorage.ModuleScript)
local obj1 = mod.new("Name")
local obj2 = mod.new("Name2")
local array = {obj1,obj2}
local function addObj(obj)
local obj = mod.new("Name3")
table.insert(array,1,obj)
print(array[1]:getName())
end
addObj()
for i = 1,#array,1 do
print(array[i]:getName())
end