Lua: Can I use colon syntax here?

Viewed 66

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 Answers

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.

Related