When using __index to return functions, how do I get the arguments passed?

So I am working on a function that returns a “mutable string” which is just a table.

I want to be able to use string library functions like gsub, format, etc.

So I am using __index here.

Here is what I have so far

local function __index(self, k)
	if type(k) == "number" then
		return string.sub(table.concat(self), k, k)
	end
	
	if string[k] then
		return string[k] -- Stuck here
	end
end

local mt =
{
	__index = __index -- There are more metamethods that are added, but this is all you need
}

local function MutableString(s) -- Constructs a new MutableString object
	local ms = string.split(s, "")
	ms.rawstr = s
	return setmetatable(ms, mt)

return MutableString

I am stuck in the __index function. Would I have to wrap each function to modify the MutableString? Sounds like a lot of work.

So how do I get arguments? I don’t even care how anymore I just want to do it.

ok ok ok ok

so what I am trying to do is, if you call :gsub like this for example

-- What I want
local ms = MutableString("heyo")
ms:gsub("o", "a")
print(ms) --> heya [__tostring is used]

__index would be invoked.

How can I get the arguments "o" and "a".

Rather than return string[k], wrap it in a function;

return function(...) return string[k](...) end

and then you have access to the arguments in ...

2 Likes