Difference between revisions of "String extensions"

(Created page with 'This code modifies the metatable of the string type to add some useful functionality. <source lang="lua"> local meta = getmetatable("") -- get the string metatable meta.__add =…')
 
m (Added missing properties for the category page.)
 
(One intermediate revision by one other user not shown)
Line 14: Line 14:
 
meta.__mul = function(a,b) -- the * operator
 
meta.__mul = function(a,b) -- the * operator
 
     return a:rep(b)
 
     return a:rep(b)
 +
end
 +
 +
-- if you have string.explode (check out the String exploding snippet) you can also add this:
 +
meta.__div = function(a,b) -- the / operator
 +
    return a:explode(b)
 
end
 
end
  
Line 29: Line 34:
 
print("foo the bar" - " the ") --> foobar
 
print("foo the bar" - " the ") --> foobar
 
print("repetition is repetetive " * 3) --> repetition is repetetive repetition is repetetive repetition is repetetive  
 
print("repetition is repetetive " * 3) --> repetition is repetetive repetition is repetetive repetition is repetetive  
 +
tbl = "foo bar" / " "
 +
print(tbl[1]) --> foo
 
mystring = "abc"
 
mystring = "abc"
 
print(mystring[2]) --> b
 
print(mystring[2]) --> b
Line 34: Line 41:
  
 
[[Category:Snippets]]
 
[[Category:Snippets]]
 +
{{#set:LOVE Version=any}}
 +
{{#set:Description=Adds additional functions to the string metatable.}}

Latest revision as of 19:35, 11 November 2016

This code modifies the metatable of the string type to add some useful functionality.

local meta = getmetatable("") -- get the string metatable

meta.__add = function(a,b) -- the + operator
    return a..b
end

meta.__sub = function(a,b) -- the - operator
    return a:gsub(b,"")
end

meta.__mul = function(a,b) -- the * operator
    return a:rep(b)
end

-- if you have string.explode (check out the String exploding snippet) you can also add this:
meta.__div = function(a,b) -- the / operator
    return a:explode(b)
end

meta.__index = function(a,b) -- if you attempt to do string[id]
    if type(b) ~= "number" then
        return string[b]
    end
    return a:sub(b,b)
end

Once you've applied this code, you'll be able to do this:

print("foo" + "bar") --> foobar
print("foo the bar" - " the ") --> foobar
print("repetition is repetetive " * 3) --> repetition is repetetive repetition is repetetive repetition is repetetive 
tbl = "foo bar" / " "
print(tbl[1]) --> foo
mystring = "abc"
print(mystring[2]) --> b