解析LUA中的字符串

问题描述 投票:-2回答:1

我一直在环顾四周,已经阅读了很多不同的答案,但似乎没有人回答我的具体要求。

我使用名为“WATCHMAKER”的应用程序为Wear OS 2制作表面,并使用LUA作为语言。我想根据连接到身体的发射器发送的血糖值,制作一个带有指向数字的特殊时钟的表盘。

我要解析的字符串值遵循以下语法:

<DECIMAL NUMBER> <ARROW> (<TIME>)

一个例子是

5,6 -> (1m)

我想提取阅读中的<DECIMAL NUMBER>部分。在上面的例子中,我想要值5,6

每5分钟,发射器发送另一个读数,所有这些信息都会改变:5,8 - (30 secondes)

非常感谢

parsing lua
1个回答
1
投票

假设您在LUA,s="14,11 -> (something)"中有一个字符串,并且您希望将第一个字符串数解析为浮点数,以便您可以对其进行数学运算。

s='9,6 -> (24m)'
-- Now we use so called regular expressions
-- to parse the string
new_s=string.match(s, '[0-9]+,[0-9]+')
-- news now has the number 9,6. Which is now parsed
-- however it's still a string and to be able to treat
-- it like a number, we have to do more:
-- But we have to switch the comma for a period
new_s=new_s:gsub(",",".")
-- Now s has "9.6" as string
-- now we convert it to a number
number = string.format('%.10g', tonumber(new_s))
print(number)

现在number包含数字9.6

© www.soinside.com 2019 - 2024. All rights reserved.