首页 > 解决方案 > 在 LUA 中解析字符串

问题描述

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

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

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

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

一个例子是

5,6 -> (1m)

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

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

太感谢了

标签: parsinglua

解决方案


假设您在 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


推荐阅读