Parsing uptime info

Posted by Vincitore on Mon 14 Feb 2011 04:59 AM — 4 posts, 19,878 views.

#0
The game I play gives uptime in this format:
Game has been up for 2d 10h 13m 49s.

If any of those numbers is zero, it's left out, such as:
Game has been up for 5h 13s.

I'm trying to break this down into seconds total, minus any full two-hour blocks. My understanding of Lua is practically nonexistent, though, so I'm not entirely sure how to proceed. My assumption is that I would use utils.split to get each figure into a table, check each value in the table for the associated letter, multiply the numeric part accordingly, add that to a variable, and loop until everything was done. Then I'd subtract 86400 from the variable in another loop until the variable was less than 86400. I just have no idea how to do any of these things. :( Any help would be appreciated.
USA #1
Coming up with the algorithm is half the battle! :) Have you ever programmed in another language before?

I don't have access to MUSHclient right now so I can't give you a full alias, but here's what you'd basically need to do:

-- Assuming the alias is:
-- ^Game has been up for (.+)\.$
-- and "Regular expression" is checked

-- Split the uptime into a table of units
local times = utils.split("%1", " ")

-- Begin with a total of 0 seconds
local seconds = 0

-- For each unit, turn it into seconds
-- and add it to the total.
for _,v in ipairs(times) do
  -- Split "10d" into 10 and "d"
  local time, unit = tonumber(v:sub(1, -2)), v:sub(-1)
  
  -- Turn days into hours
  if unit == "d" then
    time = time * 24
    unit = "h"
  end
  
  -- Hours into minutes
  if unit == "h" then
    time = time * 60
    unit = "m"
  end
  
  -- Minutes into seconds
  if unit == "m" then
    time = time * 60
    unit = "s"
  end
  
  -- Add the seconds to the total
  if unit == "s" then
    seconds = seconds + time
  end
end

-- Modulo returns the remainder of division
seconds = seconds % 86400


It's probably not the most efficient way to do it, but it should work and I think it's pretty clear. You can also easily add new units (like "y" for year).

Also, modulo is a faster and more concise way of subtracting X from a number until it's less than X. These two come to the same result:

seconds = seconds % 86400
-- versus
while seconds > 86400 do
  seconds = seconds - 86400
end
#2
Worked like a charm, thanks. :)

I've only done coding in antediluvian languages like COBOL, so this stuff is rather foreign to me. Was able to slap together the other necessary parts of the clock without TOO much difficulty, though, once I had this to work with.
USA #3
Glad to hear it worked out for you. :)

You might get quite a bit of mileage out of the official "Programming in Lua" book [1]. It's available online for Lua 5.0 (MUSHclient uses 5.1), but there are few major changes between the two in the language itself.

[1] http://www.lua.org/pil/