2

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,

1

1 Answer 1

2
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
Sign up to request clarification or add additional context in comments.

4 Comments

Any reason for doing the reverse in first approach? I mean is it faster?
Yes, I understand that. My question was, how is that any different from "^(%d-)h?(%d-)m?(%d-)s?(%d-)f?$" pattern match? And since there are no reverse involved; wouldn't it be faster?
@hjpotter92 - Yes, reverse()-version is not any better than the last variant. Removed it.
Huge thanks guys! I'll study both answers posted to increase my LUA knowledge. Thanks a bunch for the answers!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.