Matt W
Matt W

Reputation: 12434

lua gsub special replacement producing invalid capture index

I have a piece of lua code (executing in Corona):

local loginstr = "emailAddress={email} password={password}"
print(loginstr:gsub( "{email}", "[email protected]" ))

This code generates the error:

invalid capture index

While I now know it is because of the curly braces not being specified appropriately in the gsub pattern, I don't know how to fix it.

How should I form the gsub pattern so that I can replace the placeholder string with the email address value?

I've looked around on all the lua-oriented sites I can find but most of the documentation seems to revolve around unassociated situations.

Upvotes: 3

Views: 7064

Answers (3)

John Tribe
John Tribe

Reputation: 1632

I had this in value part so You need to escape value with: value:gsub("%%", "%%%%").

Example of replacing "some value" in json:

local resultJSON = json:gsub(, "\"SOME_VALUE\"", value:gsub("%%", "%%%%"))

Upvotes: 0

vhallac
vhallac

Reputation: 13957

As I've suggested in the comments above, when the e-mail is encoded as a URL parameter, the %40 used to encode the '@' character will be used as a capture index. Since the search pattern doesn't have any captures (let alone 40 of them), this will cause a problem.

There are two possible solutions: you can either decode the encoded string, or encode your replacement string to escape the '%' character in it. Depending on what you are going to do with the end result, you may need to do both.

the following routine (I picked up from here - not tested) can decode an encoded string:

function url_decode(str)
  str = string.gsub (str, "+", " ")
  str = string.gsub (str, "%%(%x%x)",
      function(h) return string.char(tonumber(h,16)) end)
  str = string.gsub (str, "\r\n", "\n")
  return str
end

For escaping the % character in string str, you can use:

str:gsub("%%", "%%%%")

The '%' character is escaped as '%%', and it needs to be ascaped on both the search pattern and the replace pattern (hence the amount of % characters in the replace).

Upvotes: 8

mu is too short
mu is too short

Reputation: 434985

Are you sure your problem isn't that you're trying to gsub on loginurl rather than loginstr?

Your code gives me this error (see http://ideone.com/wwiZk):

lua: prog.lua:2: attempt to index global 'loginurl' (a nil value)

and that sounds similar to what you're seeing. Just fixing it to use the right variable:

print(loginstr:gsub( "{email}", "[email protected]" ))

says (see http://ideone.com/mMj0N):

[email protected] password={password}

as desired.

Upvotes: 3

Related Questions