---
title: "Lua 解析C++代码tokens简单函数"
author: "lua"
date: "2009-09-25T10:15:01Z"
tags: []
slug: "lua-c-tokens"
draft: false
lastmod: "2009-09-25T10:15:01Z"
id: 477032
url: "https://lua.iteye.com/blog/477032"
---

function get\_tokens(str)

    local string = string  
    local table = table  
    local tokens = {}  
    local stringbuffer = ""  
    local numberbuffer = ""

    local previous\_is\_number = false  
    local previous\_is\_string = false  
    local previous\_is\_quote = false  
    local has\_process = false  
    local is\_X16mode = false

    for i = 1, #str do  
        local char = string.sub(str, i, i)  
        has\_process = false

        if previous\_is\_number == false and    (string.find(char, "%a") or string.find(char, "\_")  
                                            or (string.find(char, "%d") and previous\_is\_string)    )  
            then  
            stringbuffer = string.format("%s%s", stringbuffer, char)  
            previous\_is\_string = true  
            has\_process = true  
        end

        if not (previous\_is\_number and char == ".") and (has\_process == false and string.find(char, "%p")) then  
            if stringbuffer ~= "" then  
                table.insert(tokens, stringbuffer)  
                stringbuffer = ""  
                previous\_is\_string = false  
            end

            if numberbuffer ~= "" then  
                table.insert(tokens, numberbuffer)  
                numberbuffer = ""  
                previous\_is\_number = false  
                is\_X16mode = false  
            end

            table.insert(tokens, char)  
            previous\_is\_quote = true  
            has\_process = true  
        end

        if has\_process == false and ((string.find(char, "%d") or (numberbuffer ~= "" and string.find(char, "%.")))  
            or (is\_X16mode and string.find(char, "%x"))    ) then

            if (previous\_is\_number == false) then  
                local nextchar = string.sub(str, i+1, i+1)  
                if nextchar and (nextchar == "x" or nextchar == "X") then  
                    is\_X16mode = true  
                    i = i+1  
                    char = char .. nextchar  
                end  
            end

            numberbuffer = string.format("%s%s", numberbuffer, char)  
            previous\_is\_number = true  
            has\_process = true  
        end  
    end

    print\_table(tokens)  
    return tokens  
end

--local str = \[\[dequeOf.use("1155.321"). STRINGI.push\_back(CComVariant("{"));]]  
\--local str = \[\[if ((vtVal.vt != VT\_I4) || (0x0000FFFF&lt;(DWORD)vtVal.lVal))]]  
\--local str = \[\[333, 0xB3667A2E, 0xC4614AB8, 0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B, 0x2D02EF8D};]]

--get\_tokens(str)