This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Awesome As's profile picture

String function - get parameter

Started by Awesome As, 09 June 2013 - 02:42 PM
Awesome As #1
Posted 09 June 2013 - 04:42 PM
Hello guys!

While working on a project, I found that a function seems to give some pretty strange results. I have tested this function in other programs allowing Lua, and the function worked perfect there. Though here… noep.

So, the function below will find the value of a parameter, like the ones in URLs: "somesite.blah?param1=1&param2=test&param3=ect" and can be seen here:

function getParam(str, param)
local retVal = ""
if str:find(param .. "=") then
for i = str:find(param .. "=") + #param + 1, #str do
if str:sub(i, i) == "&" then
break
else
retVal = retVal .. str:sub(i, i)
end
end
end
return retVal
end

Any idea why this might be the case? I tried adding tons of prints and tests.. When I did print(str:sub(str:find("action="))) in a string including "action=", it gave me a part of the string that was… deeper into the string than what was expected.

- As
Orwell #2
Posted 09 June 2013 - 06:02 PM
I can't really spot the error. But it isn't how I'd do it anyway. So here is my suggestion:

function getParams(str)
  -- create a map that will match the keys of the parameters to their values
  local map = {}
  -- match all 'a=b' instances, split them up and put them in a map
  -- this does not work for keyless parameters, you can adapt it to do so
  for key,value in str:gmatch('[?&]([^=]*)=([^&]*)') do
	map[key]=value
  end
  return map
end

-- just a test:
local url = "http://www.example.com?par1=foo&par2=bar&action=nothing"
local params = getParams(url)
print(params['action'])
Awesome As #3
Posted 09 June 2013 - 06:14 PM
Ah, nice stuff. Tried it in the other program, will try CC later. Hrm, it can be modified a bit to just do 1 match and ignore the name of the parameter. Yeh, that or… maybe your is better? People somewhere else is just talking about it's expensive to look into tables… well, I'll try it out. Thanks! :D/> Though it's weird that my function on CC acts… completely different from all other places.

- As
Orwell #4
Posted 09 June 2013 - 06:29 PM
Ah, nice stuff. Tried it in the other program, will try CC later. Hrm, it can be modified a bit to just do 1 match and ignore the name of the parameter. Yeh, that or… maybe your is better? People somewhere else is just talking about it's expensive to look into tables… well, I'll try it out. Thanks! :D/> Though it's weird that my function on CC acts… completely different from all other places.

- As
The point with tables is that you can match all of the parameters once and access all of them later. If you always need only one parameter, you can adapt the pattern to match exactly that parameter. If you want to match stuff like 'http://example.com?value', then well.. fiddle with it. :)/>