Trying to convert plugin to Lua need help with URI encoding

Posted by Cage_fire_2000 on Fri 05 Sep 2008 02:09 PM — 4 posts, 21,453 views.

USA #0
Hi, I have a plugin which allows you to launch web searches from MUSHclient, right now it's written in JScript, and I use encodeURIComponent() to encode the search parameters, is there anything equivilant in Lua? I'd rather not code it from scratch since I'm not that familiar with Lua yet, and it just seems like a lot of work for little benefit.

Edit: Oh, and before I forget I'd also need something like encodeURI().
Amended on Fri 05 Sep 2008 02:10 PM by Cage_fire_2000
#1
No - the Lua libraries are somewhat sparse for various reasons, while Javascripts are somewhat large for various other reasons.

With the usefulness that is the added utils functions in MUSHClient, though, you can throw together something like this fairly easily:



-- Modes: 1 - escape, 2 - encodeURI, 3 - encodeURIComponent
function escapeURIs(sIn, mode)
  find=string.find -- Shortcut to avoid repeat lookups
  sOut=""

  -- Characters to omit for escape, encodeURI 
  --   and encodeURIcomponent respectively
  searchStrings={[[@*/+]], [[~!@#$&*()=:/,;?+']], [[~!*()']]}
  search = searchStrings[mode]

  -- Iterate over each character in the string
  for char in string.gmatch(sIn, ".") do

    -- Check character against omissions and convert
    if find(search, char, 1, true) == nil then 
      sOut=sOut..'%'..utils.tohex(char) 
    else 
      sOut=sOut..char 
    end
  end

  return sOut
end


This should serve your needs, but be aware it's not comprehensively tested. (I checked it against a few strings in each mode, but that's it.)
USA #2
You could probably lift this function from one of the various Lua web modules, like Kepler (www.keplerproject.org) -- that would be likely to be quite tested and handle the various subtle issues that this kind of thing runs into. Furthermore, the license is very liberal (MIT) so you wouldn't have issues with that.
Australia Forum Administrator #3
See:

http://www.gammon.com.au/forum/?id=8319

There are a few other pages that describe connecting to the Internet with Lua using luasocket.