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

Matching a conventional Lua number

Started by Sewbacca, 14 January 2017 - 09:34 PM
Sewbacca #1
Posted 14 January 2017 - 10:34 PM
Hey guys,
as the title says, i wanna match a conventional Lua number, like 10 or 10.0 or 10.6e12.
I thought out such a pattern:
'[+-]?%d-[%.]?%d-?[eE]?',
but it doesn't seem perfect.
Do you guys know a common pattern?
Thanks in advance
Edited on 19 January 2017 - 11:59 AM
Lyqyd #2
Posted 15 January 2017 - 12:36 AM
Things like + and - have meaning in patterns and must be escaped. I'd try something like:


"[%+%-]?%d+%.?%d*%-?[eE]?%d*"
Exerro #3
Posted 16 January 2017 - 01:32 PM
You can't actually match it with one pattern, sadly. Lyqyd's suggestion ("[%+%-]?%d+%.?%d*%-?[eE]?%d*") is close, but it won't match '.1' and it will match '1.3e'.

You should should use the following instead:

str:match "[%+%-]?%d*%.?%d+[eE][%+%-]%d+" or str:match "[%+%-]?%d*%.?%d+"
Edited on 16 January 2017 - 12:32 PM
Sewbacca #4
Posted 16 January 2017 - 06:25 PM
I tried your suggestions and got the following result:
"[%+%-]?%d+%.?%d*%-?[eE]?%d*" (Lyquid's) accepted -1-11 (could he prevent that) and 1e
"[%+%-]?%d*%.?%d+[eE][%+%-]%d+" (Exerro 1th one) doesn't accepted something like 1e[+-]?1.1 so
"[%+%-]?%d*%.?%d+[eE][%+%-]%d*%.?%d+" should do it.
"[%+%-]?%d*%.?%d+" seemed to work fine.
Exerro #5
Posted 17 January 2017 - 07:44 PM
It was intentional to not allow decimals after the 'e':

I doubt LuaJ/CC's Lua would be any different.

'5e1' means '5 * 10 ^ 1', so '5e1.1' would mean '5 * 10 ^ 1.1', which is just a bit pointless. I never use it myself, but if you're doing anything measurementy it'll come in handy, e.g. the speed of light '3e8'.
Edited on 17 January 2017 - 06:47 PM
Sewbacca #6
Posted 17 January 2017 - 09:25 PM
It was intentional to not allow decimals after the 'e':

I doubt LuaJ/CC's Lua would be any different.

'5e1' means '5 * 10 ^ 1', so '5e1.1' would mean '5 * 10 ^ 1.1', which is just a bit pointless. I never use it myself, but if you're doing anything measurementy it'll come in handy, e.g. the speed of light '3e8'.

Oh thanks ^^.
Edited on 17 January 2017 - 08:30 PM