Search code examples
functionluametatable

Lua String Append


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

Solution

  • 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.