2

I'm running this function a lot which shortens the name of a string:

function shorten(st) return string.sub(st,6) end function test(input) local h = shorten(input) print(""..h) end test("helloworld") 

I want to write it with a colon like the other functions in this context, which all go like world():context():manager(), not manager(context(world())). I read that using the syntax with the colon passes the first as an argument into the latter, but this does not work:

function shorten(st) return string.sub(st,6) end function test(input) local h = input:shorten() print(""..h) end test("helloworld") 

Is there a way to do this?

1
  • 1
    if it is ok that :shorten() can be used on every string in your program that's probably fine. just add it to the string library as shown in the answer below. I personally would simply use :sub(6) so I don't have to think about what :shorten() actually does. but if shortenning to 6 characters is what you always do, go ahead. Commented Feb 3, 2022 at 16:22

1 Answer 1

2

depending on your flavor of lua, you can simply define shorten as string.shorten

This works because the metatable for all strings references the string library. That is why adding a function to string will add make it accessible to any defined strings.

function string.shorten(st) return string.sub(st,6) end function test(input) local h = input:shorten() print(h) end test("helloworld") 

Output:

world


Your example of colon syntax is not exactly how it works. It is syntactic sugar

someClassInstance:method("arg") 

is equivalent to

someClassInstance.method(someClassInstance, "arg") 

You often see colon syntax used to improve readability of OO style lua, and is described here in Programing in Lua: 16 – Object-Oriented Programming


side note: you did print(""..h) which seems weird since it is functionally identical to just doing print(h) but is more expensive.

Sign up to request clarification or add additional context in comments.

3 Comments

"This works because the metatable for strings is the string table. " no. string refers to Lua's string library. So does the __index field of the metatable all strings have in common. that's two different tables.
@Piglet fair point I did over simplify that. does this sound better? "This works because the metatable for all strings references the string library."
kind of :-) picky Germans...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.