2

I'm working on a graphing program and the function of a line needs to be printed to the screen. However, if a math function is in the line's function (ex:)

function(x) return math.atan(x) end

then I want to remove the 'math.' part. I also want to remove any spaces in the function, as well as other patterns I may think of in the future. This is what I currently have (simplified, of course)

local func = "math.atan( x )"
print(func:gsub("[math%. ]", "")) --look for math. or a space
--OUTPUT: n(x)

I realize I don't need the spaces in-between the parenthesis, but those are there just for testing purposes. I was hoping for the output to say "atan(x)"

1
  • 2
    Your pattern matches the individual characters m, a, t, h, ., and space, not math.. There's no way to do this without multiple calls to gsub Commented Sep 21, 2014 at 18:20

1 Answer 1

1

The easiest way to do this is just to chain a bunch of gsub calls together. In this case, you could use

local func = "math.atan( x )"
print(func:gsub("math", ""):gsub("%s", "")) --> atan(x)

You could write a shorthand method to hide the gsub chaining if you really want to even:

local function chainremove(source, ...)
    for index, value in ipairs({...}) do
        source = source:gsub(value, "")
    end

    return source
end

Which could make your concept of "other patterns [you] may think of in the future" as a single method call on the surface:

local func = "math.atan( x )"
print(chainremove(func, "math", "%s"))

If you do add patterns later, do remember to escape your percent signs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.