LumiJay
LumiJay

Reputation: 31

LUA: Simpler string pattern solution

I'm studying LUA on my own and would like a little help on this next piece of code:

offset= "1h2m3s4f"

off_h = offset:match("(%d+)h")
off_m = offset:match("(%d+)m")
off_s = offset:match("(%d+)s")
off_f = offset:match("(%d+)f")

print(off_h)
print(off_m)
print(off_s)
print(off_f)

I've tried everything to concat the pattern into a single line offset:match but after reading many ressources online I am still clueless how to do it. The problem is, the user might enter only 2m3s4f without any numbers for h or he might enter only 1m2f.

My tests on a single pattern check were resulting in full nil values when I removed one of the pattern condition. I tried adding the magic char ? to the different patterns but that didn't do the trick. Any pointer would be appreciated! Thanks,

Upvotes: 2

Views: 109

Answers (1)

Egor Skriptunoff
Egor Skriptunoff

Reputation: 23747

for _, offset in ipairs{"1h2m3s4f", "2m3s4f", "1m2f"} do
   local fields = {}
   offset:gsub("(%d+)([hmsf])", function(n,u) fields[u] = n end)
   print(fields.h, fields.m, fields.s, fields.f)
end

Output:

1    2    3    4
nil  2    3    4
nil  1    nil  2

-- Shortest, but slowest variant
for _, offset in ipairs{"1h2m3s4f", "2m3s4f", "1m2f"} do
   local h, m, s, f = offset:match"^(%d-)h?(%d-)m?(%d-)s?(%d-)f?$"
   print(h, m, s, f)
end

Output:

1  2  3  4
   2  3  4
   1     2

Upvotes: 2

Related Questions