I tried that:
string.startswith = function(self, str)
return self:find('^' .. str) ~= nil
end
local ss1 = "hello my name is ..."
print(ss1:startswith('hello'))
Error: Attempt to modify a readonly table
so how can i do it?
I tried that:
string.startswith = function(self, str)
return self:find('^' .. str) ~= nil
end
local ss1 = "hello my name is ..."
print(ss1:startswith('hello'))
Error: Attempt to modify a readonly table
so how can i do it?
i think the issue is the first line. You are trying to allocate a new function the string, which is not possible. Try replacing the first string with another name (even String would work, it just cant be the exact same)
What about:
local _string = string -- Preserve old string library
local string = {}
setmetatable(string, {__index = _string}) -- Make references to original string library
function string.startsWith(...)
...
end
Keep in mind you will have to put this in every script and you probably can’t do it from a module script. (You can store the other functions sure, but to replace string you will have to put that code in your script directly.)
Error: attempt to call a nil value on line 10
code:
local _string = string -- Preserve old string library
local string = {}
setmetatable(string, {__index = _string}) -- Make references to original string library
function string.startsWith(...)
print(...)
end
local ss1 = "hello my name is ..."
print(ss1:startsWith("hello")) -- line 10
Warning: Unknown global 'String’
Ah, well you will have to use string.startsWith in that case. You cannot call a function on a string literal directly because that will reference the original string library.
String = {}
String.startswith = function(self, str)
return self:find('^' .. str) ~= nil
end
local ss1 = "hello my name is ..."
print(String.startswith(ss1, 'hello'))
but I want prototype like:
ss1:startsWith("hello")
as far as I can tell, that wouldn’t be possible. Using the String.startswith() would be the only option