I’m learning about metatables and an example that I have set up is throwing an error that I’m not sure about.
I’m just trying to make it print out “Default” as the name of the table to further my understanding. Purely a test project. If you notice anything here that you think might be me miss-understanding something please do tell me. This is mostly new ground for me and I have to write several “prototypes” to really grasp new concepts.
But I’m trying to overload the tostring method so that instead of printing the table’s memory location, it prints the name of the table instead. I’d read that was proper usage but I could be missunderstanding
local GunClassMetaTable = {}
GunClassMetaTable.__tostring = function(self)
return self.Name
end
local GunClassInstance = {Name = "Default"}
local newGun = setmetatable(GunClassInstance, GunClassMetaTable)
print(newGun)
setmetatable can be used as setmetatable(mytable,mymetatable). Your original code only sets the metatable of an anonymous table that you declared inside of the setmetatable method.
With your original code, simply do local newGun = setmetatable({Name = "Default"}, GunClass)
self.Name is nil, thus the reason for the exception.
local newGun = setmetatable({ Name = "newGun" }, GunClass)
Also remember that tables are anonymous, which means they don’t have names. So I just used the same name you used for the identifier
Also you should refrain from posting images of code/exceptions. Images are often hard to read and can only contain so much information. Also we can’t copy the text from the image to edit in a fix.