main.lua 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. -- LuaTools需要PROJECT和VERSION这两个信息
  2. PROJECT = "strtest"
  3. VERSION = "2.0.0"
  4. --[[
  5. 本demo演示 string字符串的基本操作
  6. 1. lua的字符串是带长度, 这意味着, 它不依赖0x00作为结束字符串, 可以包含任意数据
  7. 2. lua的字符串是不可变的, 就不能直接修改字符串的一个字符, 修改字符会返回一个新的字符串
  8. ]]
  9. -- sys库是标配
  10. _G.sys = require("sys")
  11. sys.taskInit(function ()
  12. sys.wait(1000) -- 免得看不到日志
  13. local tmp
  14. ----------------------------------------------
  15. --================================================
  16. -- 字符串的声明和生成
  17. --================================================
  18. -- 常量声明
  19. local str = "123455"
  20. log.info("str", str)
  21. -- 合成式
  22. str = string.char(0x31, 0x32, 0x33, 0x34)
  23. log.info("str", str)
  24. -- lua的字符串可以包含任意数据, 包括 0x00
  25. str = string.char(0x12, 0x00, 0xF1, 0x3A)
  26. log.info("str", str:toHex()) -- 注意, 这里用toHex(), 因为包含了不可见字符
  27. -- 使用转义字符
  28. str = "\x00\x12ABC"
  29. log.info("str", str:toHex()) -- 注意, 这里用toHex(), 因为包含了不可见字符
  30. str = "ABC\r\n\t"
  31. log.info("str", str:toHex()) -- 注意, 这里用toHex(), 因为包含了不可见字符
  32. -- 解析生成
  33. str = string.fromHex("AABB00EE")
  34. log.info("str", str:toHex())
  35. str = string.fromHex("393837363433")
  36. log.info("str", #str, str)
  37. -- 连接字符串, 操作符 ".."
  38. str = "123" .. "," .. "ABC"
  39. log.info("str", #str, str)
  40. -- 格式化生成
  41. str = string.format("%s,%d,%f", "123", 45678, 1.5)
  42. log.info("str", #str, str)
  43. --================================================
  44. -- 字符串的解析与处理
  45. --================================================
  46. -- 获取长度
  47. str = "1234567"
  48. log.info("str", #str)
  49. -- 获取字符串的HEX字符串显示
  50. log.info("str", str:toHex())
  51. -- 获取指定位置的值, 注意lua的下标是1开始的
  52. str = "123ddss"
  53. log.info("str[1]", str:byte(1))
  54. log.info("str[4]", str:byte(4))
  55. log.info("str[1]", string.byte(str, 1))
  56. log.info("str[4]", string.byte(str, 4))
  57. -- 按字符串分割
  58. str = "12,2,3,4,5"
  59. tmp = str:split(",")
  60. log.info("str.split", #tmp, tmp[1], tmp[3])
  61. tmp = string.split(str, ",") -- 与前面的等价
  62. log.info("str.split", #tmp, tmp[1], tmp[3])
  63. str = "/tmp//def/1234/"
  64. tmp = str:split("/")
  65. log.info("str.split", #tmp, json.encode(tmp))
  66. -- 2023.04.11新增的, 可以保留空的分割片段
  67. tmp = str:split("/", true)
  68. log.info("str.split", #tmp, json.encode(tmp))
  69. -- 更多资料
  70. -- https://wiki.luatos.com/develop/hex_string.html
  71. -- https://wiki.luatos.com/_static/lua53doc/manual.html#3.4
  72. end)
  73. -- 用户代码已结束---------------------------------------------
  74. -- 结尾总是这一句
  75. sys.run()
  76. -- sys.run()之后后面不要加任何语句!!!!!