lua 中判断字符串前缀
一个 lua 的小技巧
在写 lua debugger 的时候,我需要判断一个字符串的前缀是不是 "@" 。
有三个方案:
- 比较直观的是 string.sub(str,1,1) == "@"
- 感觉效率比较高的是 string.byte(str) == 64
- 或者是 string.find(str,"@") == 1
我推荐第三种。(注:在此特定运用环境下。因为用于判定 source 的文件名,大多数情况都是 @ 开头。如果结果为非,则性能较低)
第一方案 string.sub 会在生成子串的时候做一次字符串 hash ,感觉效率会略微低一些。
第二方案效率应该是最好,但是需要记住 @ 的 ascii 码 64 。如果前缀是多个字符也不适用。
Comments
Posted by: mayao11 | (13) July 29, 2015 10:21 AM
Posted by: SloanYi | (12) June 8, 2012 02:31 PM
Posted by: Atry | (11) May 29, 2009 01:39 PM
Posted by: SunJian | (10) May 28, 2009 10:56 PM
Posted by: 桂林旅游 | (9) May 28, 2009 09:35 PM
Posted by: Cloud | (8) May 27, 2009 08:02 PM
Posted by: iTana | (7) May 27, 2009 07:50 PM
Posted by: 也许知道 | (6) May 27, 2009 05:16 PM
Posted by: 半瓶墨水 | (5) May 27, 2009 12:29 PM
Posted by: 半瓶墨水 | (4) May 27, 2009 12:27 PM
Posted by: Cloud | (3) May 27, 2009 11:46 AM
Posted by: 半瓶墨水 | (2) May 27, 2009 11:15 AM
Posted by: 文 | (1) May 27, 2009 10:16 AM