So basically, I want to make something like:
local Table = {1,2,3}
so if u do Table[1], it will be the first value, but if you just print(Table). It has its own value?
kinda like:
local Table = {"Item1", "Item2", "Item3"}
print(Table[1]) -- Item1
print(Table) -- "A string value"
That doesn’t make any sense, a table is a value, doing that is the same thing as having a variable equal a string and a number. How will the program know when Table should represent the table and when it should represent the string value?
So let’s get this straight, you want to make print()
print something else other it’s type and hexadecimal memory address when printing a table, is that correct?
Yes but it would be very useful to me.
like Table = {something}, but if you don’t index the table, it returns another value
Yes, that is correct, when the table is indexed, it will print the indexed value, but without using the index, I want it to print another possible value
You need to use a metatable and __tostring
metamethod to do that.
What if you don’t want to index something in a table but want to get the table itself, it would just keep sending you the string. For example, if you want to have a table store other tables in it, and you wanted to get those tables directly to store it, you wouldn’t be able to.
Can you provide me an example? I don’t know which metatables to use
I think he wants it that the variable returns the string instead of the table whenever he uses it, not just when he prints it
Yes thats the point, I don’t need it to send me the hex value of the table
I wasn’t trying to elaborate on your point, I was trying to show how I don’t think your idea would be plausible.
No I want it like:
local Table = game.Workspace
local Table = {"i"}
print(Table[1]) -- "i"
print(Table) -- Workspace
Do you only want it to work like this when you print the variable or also in other cases?
Then you need to do something like this:
local MetaTable = {
__tostring = function()
return "A string"
end
}
local TestTable = setmetatable({},MetaTable)
print(TestTable)
--Output
-->A string
2 Likes
Thanks, would it work if it returns and instance instead of a string?
Ah alright I think I see how this would work, sorry for misunderstanding what you meant.
1 Like
It should has to return a string, you have to turn the value in to a string with tostring()
function if it’s not a string.
1 Like