5

So I created a function that all strings can use and it's called append.

local strmt = getmetatable("")
function strmt.__index.append(self, str)
  self = self..str
  return self
end

The function is then used like this:

self = self:append("stuff")

Is there a way to create a function that does just this:

local stuff = "hi "
stuff:append("bye")
print(stuff)

And produces

hi bye
Lee Yi
  • 517
  • 6
  • 17
  • BTW, your first function I don't think you need to mess you meta-tables. This should be enough: function string:append(s) return self .. s end – tonypdmtr Mar 07 '15 at 14:27

1 Answers1

5

No. Strings in Lua are immutable; if you set stuff to "hi ", it will equal "hi " until you set it to something else. "hi " will never become "hi bye", any more than 3 will become 4.

Sneftel
  • 40,271
  • 12
  • 71
  • 104