soerface
soerface

Reputation: 6853

Search for a key in lua which contains a certain string

I have multiple lua files which contain information I would like to extract via Python. To use Lua inside Python I'm using lunatic-python, but thats not a requirement - if you have other approaches that would also be fine.

The lua files look like that:

source = {
    licences = {
        "GPL",
        "MIT",
    },
    env = {
        MYTOOL_VERSION = "1.2.3",
        OTHER_KEY = "OTHER_VALUE",
    },
    some_other_keys = {
        ...
    },
}

The value I'm interested in is source.env.MYTOOL_VERSION, while MYTOOLis always something different. Since I have no experience in lua, I have no Idea how to tell it to "get the value of the key which contains the string VERSION". I read some tutorials about the tables concept in Lua (which still seems a bit weird to me), and I guess the functions next or pairs could be usefull for my case. Though those functions still confuse me, in the examples I found they are always used in loop, but when I do something like this:

x = next(source.env)

instead of

k, v = next(source.env)

it seems that x now only contains the key, not the value. And when using pairs instead of next, I get a function, but I have no idea how to call it.

My Pythonscript currently looks like this:

import lua

with open(project_path) as f:
    script = f.read()

lua.execute(script)

i = 1

licences = []

while True:
    data = lua.globals().source.licences[i]
    if data is None:
        break
    licences.append(data)
    i += 1

version = lua.eval('source.env[next(source.env)]') if lua.globals().source.env is not None else 'unkown',

Which just gets the value of any key in the env table, not necessarily the one which contains VERSION.

So, what is an elegant solution to fetch the desired data of this file to use it with Python?

Upvotes: 0

Views: 458

Answers (1)

Alex
Alex

Reputation: 1017

If you execute this script

function version(t)
    for k,v in pairs(t) do
        if k:match"._VERSION$" then return v end
    end
end

And then eval version(source.env), I would expect it to return the 1.2.3 for you

Upvotes: 2

Related Questions