tl icon indicating copy to clipboard operation
tl copied to clipboard

Unable to extend the methods of string type

Open cyril0124 opened this issue 7 months ago • 1 comments

In Lua, the following code snippet is feasible.

string.test = function(self)
    return self .. "_test"
end

local n = (""):test()
assert(n == "_test") -- n is "_test"

I tried to do the same in Teal, but it failed.

global record string
    test: function(self: string): string
end

string.test = function(self: string): string
    return self .. "_test"
end

local n = (""):test()
assert(n == "_test")

and i got the following error message: Image

Can Teal support such a feature that allows users to extend the functionality of Lua's stdlib?

cyril0124 avatar Jun 06 '25 07:06 cyril0124

Quick hack without changing standart strings

local type my_string = record
    	type test = function(self: my_string): string
	--Put all string methods here
end

do 
	-- Should be:
	-- (string as my_string).test = function(str:my_string):string
	(string as {string:any}).test = function(str:my_string):string
	    return (str as string) .. "_test"
	end
end

--Cast string to custom record
local macroexp S(str:string):my_string
    return str
end
local n = S(""):test()
assert(n == "_test") -- n is "_test"

print(S(""):test())

sadSader avatar Jun 16 '25 11:06 sadSader