parsing - 在 LUA 中解析字符串
问题描述
我一直在环顾四周,并阅读了很多不同的答案,但似乎没有一个能回答我的具体要求。
我使用名为“WATCHMAKER”的应用程序为 Wear OS 2 制作表盘,女巫使用 LUA 作为语言。我想制作一个带有特殊时钟的表盘,该时钟指向一个数字,该数字取决于连接到身体的发射器发送的血糖值。
我要解析的字符串值遵循以下语法:
<DECIMAL NUMBER> <ARROW> (<TIME>)
一个例子是
5,6 -> (1m)
我想提取<DECIMAL NUMBER>
阅读的部分。在上面的示例中,我想要 value 5,6
。
每 5 分钟,发射器发送另一个读数,所有这些信息都会发生变化:5,8 - (30 秒)
太感谢了
解决方案
假设您在 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
。
推荐阅读
- azure - 在不删除资源组中现有 Azure Functions 的情况下创建新的 Azure Function App
- python - 无法打开第二个窗口,事件循环已在运行 - PyQt5
- android - 观察到领域随机崩溃“致命信号 6 (SIGABRT),tid 28688 (RealmFinalizing) 中的代码 -6 (SI_TKILL),pid 28451”
- javascript - 如何在 TypeScript 中重载泛型方法
- java - 字符串可以包含 <0x00> 以及 java 中的赋值吗
- clang - 在 Clang DiagnosticBuilder 中显示多个范围
- python - 保存选择时 Django 生产服务器错误 13 [已解决]
- php - jQuery PHP 使用向上和向下箭头键选择搜索结果
- javascript - CKEditor 4:在源视图和常规视图之间切换时 Javascript 消失
- reactjs - axios 没有获取 API