Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 350
Matt W Avatar asked Mar 25 '26 11:03

Matt W


2 Answers

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).

like image 129
vhallac Avatar answered Mar 27 '26 10:03

vhallac


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.

like image 34
mu is too short Avatar answered Mar 27 '26 12:03

mu is too short



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!