3

Following up with my previous question (link here: Lua How to create custom function that can be used on variables?), is there a way to create the same kind of function that works for other things other than tables? For example,

str = "stuff"
letter = str:foo() --Maybe have the foo function extract the first letter?

Is there a way to create a function that works in the same way that

lowerCasestr = str:lower()

works?

1 Answer 1

7

All strings share the same metatable, add your custom function to its __index table:

function first_letter(str)
  return str:sub(1, 1)
end

local mt = getmetatable("")
mt.__index["first_letter"] = first_letter

local str = "stuff"
print(str:first_letter())
Sign up to request clarification or add additional context in comments.

1 Comment

What about objects like files? Do they have separate metatables as well? For the matter, do all types of objects in Lua have metatables?

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.