Skip to content

Instantly share code, notes, and snippets.

@cxmeel
Created April 30, 2020 05:17
Show Gist options
  • Save cxmeel/91c0e8a2dd03a21f640a78860f1edbaa to your computer and use it in GitHub Desktop.
Save cxmeel/91c0e8a2dd03a21f640a78860f1edbaa to your computer and use it in GitHub Desktop.
Wrap any object to extend its methods and properties.
local Polyfill = {}; do
function Polyfill.new(base)
local Poly; Poly = setmetatable({}, {
__index = function(self, key)
if (Poly[key]) then
return Poly[key]
end
return base[key]
end
})
return Poly
end
Polyfill.__index = Polyfill
Polyfill.__newindex = nil
Polyfill.__metatable = nil
Polyfill = setmetatable({}, Polyfill)
end
local string = Polyfill.new(string)
function string.split(str, sep)
local tstr, tsep = type(str), type(sep)
assert(tstr == "string", ("Attempted to call string.split on a %s."):format(tstr))
assert(tsep == "string" or tsep == "nil", "Attempted to call string.split with invalid separator.")
sep = tsep == "nil" and "," or sep
local result = {}
for match in ("%s%s"):format(str, sep):gmatch(("(.-)%s"):format(sep)) do
result[#result + 1] = match
end
return result
end
print(string.split("hello,world")[2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment