1

Is it possible to override some methods of standard string class so they can be invoked with the dot operator? For example:

s = "hello world"
print(s.len())
5
  • You can set call metatable, but you would have to store the string in some containing object. But not with the string itself, if I am right. using # is probably easier. Commented Sep 2, 2016 at 20:57
  • I don't see any link between the title of the question and the content of the question. Commented Sep 2, 2016 at 21:48
  • 1
    Your question is unclear - the title and the body are inconsistent after your edit. Self-referential methods are called with the colon notation (s:len()) - unless you want to write s.len(s). Have you read Programming in Lua: OOP? Commented Sep 2, 2016 at 21:49
  • sorry, i forgot to update the title... Commented Sep 2, 2016 at 22:43
  • "can be invoked with the dot operator": Any function can be invoked with "with the dot operator" and with the colon operator. Whether it has a desirable effect is a different question. @Oka explained. There is no "override" intrinsic to Lua like in other languages because that implies a class system-but you could replace. Commented Sep 3, 2016 at 13:43

1 Answer 1

2

For types which are not tables or full userdata, each type has a metatable. That is, rather than each individual string having its own metatable, all strings share the same metatable.

The Lua standard string library, by default, assigns this metatable to the string table. So if you want, you can add entries to string.

Granted, len makes no sense, as we have # to compute that. And you would need to use : calling syntax if you want to pass the string as the first parameter.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.