local obj = {}
obj.__index = obj
function obj.new(someProperty)
local newObj = {}
setmetatable(newObj,obj)
newObj.someIndex = someProperty
return newObj
end
for i = 1, 10 do
obj.new("some value")
end
How would I receive every single object of the obj class? Pardon any errors with the code, I threw this together just right now
I would simply make a table of all objects that are instantiated;
like this:
local obj = {}
obj.__index = obj
local objects={}
function obj.new(someProperty)
local newObj = {}
setmetatable(newObj,obj)
newObj.someIndex = someProperty
table.insert(objects, newObj);
return newObj
end
for i = 1, 10 do
obj.new("some value")
end
@blokav, @Fionist12, I considered both of these approaches before posting but I also require a way to remove it from the “objects” folder, which I can’t find a way to accomplish.
function obj:Destroy()
setmetatable(self,nil)
-- code to remove obj from table
end
Using this doesn’t seem to cut it:
function obj:Destroy()
setmetatable(self,nil)
objects[table.find(objects,self)] = nil
end
you could add a destructor to each object. A destructor is basically a method that you call to to destroy an object. This is the approach that languages like C++, and Java take, and I believe is what happens when you do Instance:Destroy()
so something like: obj:Destruct(), and all that it would do is remove the object from the table
oh wait, i’m sorry, I didn’t read the proceeding post correctly;
u could add another function to the class - not the objects - that takes an object and removes it from the table.
That’s precisely what I’m having trouble with. When using table.insert, it doesn’t give me the key that the value was assigned with, leaving me with no way to locate the object in the table and call Destroy on it.
function obj.new()
local newObj = blah blah blah...
objects[newObj] = true
end
function obj:Destroy()
objects[self] = nil
end
for object, _ in pairs(objects) do
print(object.someProperty)
end
if you can do: table.insert(objects, obj) then it means you already have access to the objects; so from that you can then simply do obj:Destroy() or classname:Remove(obj)
Tables aren’t like other data types in that they are unique to themselves, regardless of what they contain. This is why you have to deep copy tables and more. If you index by the object itself, it wouldn’t get confused with identical objects.
Edit: You should try to learn more about lua on your own before incorrectly discrediting other users’ suggestions. Indexes can be data types other than numbers and strings. Indexing the object itself should have no problem with “identical objects”.