SuperSaiyanGod
SuperSaiyanGod

Reputation: 131

Is there some easy to locate all string literals in a Lua file?

In my project, I find it very useful if there's a way to locate all string literals in a Lua file, because my team requires that every string literal containing any non-English character must be placed in some given definition files and I occasionally violates this rule. If such a way is available, then I can further examine them and easily extract those with non-English characters. The "locate" here means to output the positions in the console or a file, of course.

Certainly, the most obvious way is to find all double quotes in the given Lua file, but that will include string literals in comments, and it's also too brutal. So I wonder if there's some elegant way to achieve that? Many thanks!

Upvotes: 1

Views: 285

Answers (1)

lhf
lhf

Reputation: 72392

You can use luac -p -l -l foo.lua, which will list the constants used in foo.lua, including strings.

If you can use an external tool, try also my ltokenp, which uses the Lua lexer.

Here is a sample script to get you started. Save it as strings.lua and process your files with ltokenp -s strings.lua foo.lua bar.lua.

-- token filter: extract strings

local FILE

function FILTER(line,token,text,value)
    if text=="<file>" then
        FILE=value:sub(2)
    elseif text=="<string>" then
        print(FILE,line,string.format("%q",value))
    end
end

Upvotes: 2

Related Questions