Lee Yi
Lee Yi

Reputation: 527

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

Upvotes: 5

Views: 5196

Answers (1)

Sneftel
Sneftel

Reputation: 41474

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.

Upvotes: 5

Related Questions