Help With Attaching A Value To Each Index In A Table?

I’m trying to attach a certain value to each index in a given table with metamethods, but I don’t know exactly how to do it. For example, if I have an object[1], I want to get its object[1].Name.

This is my attempt at it.

local KnivesTable = {}
table.insert(KnivesTable, workspace.Knife1)
table.insert(KnivesTable, workspace.Knife2)

local mt = setmetatable(KnivesTable, {
	__tostring = function(obj)
		return obj.Parent.Name
	end
})

print(mt[1].__tostring) -- errors. I'm trying to get the name of each table object's parent.
2 Likes

The way __tostring works is that it detects when someone tries to do tostring(KnivesTable). I don’t think that’s the metamethod you wanted to use here, but I might be wrong.

2 Likes

I am using index now, but how am I supposed to obtain the returned value through outside of the metatable? I tried print(mt[1].__index) but that doesn’t work of course.

I recommend reading this section of PIL about __index since it’ll explain how it works better than I can. The most important bits for you are the code samples and their descriptions.

2 Likes

I have the basic concept on how it works, however I don’t know how to apply the syntax to my current situation. Thanks for the link though, it clarified a lot for me. One question, are metatables able to be used in non OOP forms?

You can use a metatable on any table you want, not necessarily just with a class set up like in their example.

1 Like

Not exactly sure what you’re trying to do here.

From what I can see,
KnivesTables is an array with 2 instances, which then gets a metatable with a __tostring metamethod which makes no sense.
You then index the first instance under KnivesTable which errors because there is no child under it named “__tostring”.

Why are you capturing the return of setmetatable? mt will just be the same table as KnivesTable, did you think it was returning the metatable?

The obj will the be KnivesTable, so it should error as the table has no value for key “Parent” and then it proceeds to index a nil value.

Were you trying to do something like this?

local KnivesTable = {
    workspace.Knife1,
    workspace.Knife2
}
local mt = {
    __call = function(self,key)
        return self[key].Parent.Name
    end
}
setmetatable(KnivesTable,mt)
print(KnivesTable(1)) -- Workspace

This will get the name of the object’s parent.

2 Likes

Seriously, thank you so much. Yes, that is what I was trying to do. I’ve never used metatables and I’ve been trying to wrap my mind around this. However though, is self a primitive or is it supposed to represent the table?

self or this is usually used to represent the table. You can technically use anything though.

2 Likes

The first paramater in __call will be the table which was called.

2 Likes