Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How are you able to call methods on a string?

I've recently gotten curious about this, but why does this work?

local s = "some string"
--calling a method on a string
print(s:sub(n, n,)

--following the principle of the colon syntax, it should be the same as this:
local s = "some string"
print(string.sub(s, n, n)

Obviously, the string doesn't actually contain the function, right?

So, I'd imagine there's a metamethod being fired whenever the function is called on the string. Could anyone go into more detail?

Some guy in Hidden Devs told me it was "faster," is that true as well? And if it is "faster," is it even significant?

4 comments

1

Not sure if this helps, but from the Lua reference manual it says, "The string library provides all its functions inside the table string. It also sets a metatable for strings where the __index field points to the string table. Therefore, you can use the string functions in object-oriented style.", https://www.lua.org/manual/5.1/manual.html#5.4

1

It's not faster. And even if it is, it is so tiny I couldn't detect it

0

Thanks so much @Denny9876, as i expected!

0

@mybituploads thanks a lot

1 answer

The string library provides all its functions inside the table string. It also sets a metatable for strings where the __index field points to the string table. Therefore, you can use the string functions in object-oriented style. For instance, string.byte(s, i) can be written as s:byte(i).

https://www.lua.org/manual/5.1/manual.html#5.4

Courtesy of @Denny9876

This discussion is preserved as it was. New answers, comments, and votes are closed.