开发者

Extracting information in a string

开发者 https://www.devze.com 2022-12-18 07:01 出处:网络
I would like to parse strings with an arbitrary number of parameters, such as P1+05 or P2-01 all put together like P1+05P2-02. I can get that data from strings with a rather large (too much to post ar

I would like to parse strings with an arbitrary number of parameters, such as P1+05 or P2-01 all put together like P1+05P2-02. I can get that data from strings with a rather large (too much to post around...) IF tree and a variable keeping track of the position within the string. When reaching a key letter (like P) it knows how many characters to read and proceeds accordingly, nothing special. In this example say I got two players in a game and I want to give +05 and -01 health to players 1 and 2, respectively. (hence the +-, I want them to be somewhat readable).

It works, but I feel this could be done better. I am using Lua to parse the strings, so开发者_运维问答 maybe there is some built-in function, within Lua, to ease that process? Or maybe some general hints , or references for better approaches?


Here is some code:

for w in string.gmatch("P1+05P2-02","%u[^%u]+") do
    print(w)
end

It assumes that each "word" begins with an uppercase letter and its parameters contain no uppercase letters.

0

精彩评论

暂无评论...
验证码 换一张
取 消