Why don't tables have methods?

I’m pretty sure a lot of us are aware about how strings have methods. For instance:

string.split(str," ") --> The "natural" way of splitting.
str:split(" ") --> The methodic way of splitting.

I went to a Communications Server in regards to ROBLOX Scripting and I asked if you could use methods for tables and they unfortunately said no. If you don’t know what I’m talking about, I’ll show an example of what I was talking about below.

local tbl = {
"Hi!",
"My",
"name",
"is", 
"R3KEA!"
}

table.concat(tbl," ") --> Correct way.
tbl:concat(" ") --> Non-existent way.

I made a whole “documentation” on how Roblox could implement this. But can anyone tell me if there would be any errors with this.

tbl:concat(" ")
tbl:foreach(functionVar)
tbl:foreachi(functionVar)
tbl:getn()
tbl:insert(1,"Kewl")
tbl:remove(2)
tbl:sort(functionComp)
tbl:pack() --> Variant values
tbl:unpack()
table.create() --> Wouldn't work in this case
tbl:clear()
tbl:find(needle,init)

I apologize if this was a bit messy.

3 Likes

metatables have methods… make the table a metatable…

3 Likes
local myTable = {};
setmetatable(myTable, {__index = table});

myTable:insert(1, "Hello World");
print(myTable[1]);
--output: Hello World

Unsure the exact reason why, but the above code works fine if you need them as methods hopefully anyways.

Strings have methods since they were a thing in vanilla Lua, so chances are Roblox never added it since there really wasn’t a reason to, since workarounds are pretty easy.

1 Like

Strings have a metatable. Roblox locks it though. =getmetatable("") should get you “The metatable is locked”. But tables don’t come with one. =getmetatable({ }) should get you nil.

So just do above and give it a metatable, set its __index to table and it will work fine.

2 Likes

Thank you! This actually did help a lot.