简体   繁体   English

如何读取具有多个表的 .lua 文件?

[英]How to read .lua file with multiple tables?

Hello I have never used Lua before and just wanted to simply take a .lua file, parse it, and turn it into some json.您好,我以前从未使用过 Lua,只是想简单地获取一个.lua文件,解析它,然后将其转换为一些 json。 I was able to do so with a file with a single table like so:我能够使用一个带有单个表的文件来做到这一点,如下所示:

return { ["Thing"] = { ["SubThing"] = {} } }

What I am struggling to figure out is how to parse a .lua file that has multiple tables defined (I think?).我正在努力弄清楚的是如何解析定义了多个表的.lua文件(我认为?)。 Instead of having a single return, it looks like:而不是有一个单一的回报,它看起来像:

SomeVariable = { ["Thing1"] = { ["SubThing"] = {} } }
SomeOtherVariable = { ["Thing2"] = { ["SubThing2"] = {} } }
SomeLastVariable = { ["Thing3"] = { ["SubThing3"] = {} } }

Since the json library I am using requires a single table to parse, I'm not sure what to do.由于我使用的json 库需要一个表来解析,我不知道该怎么做。 Any help would be greatly appreciated.任何帮助将不胜感激。

My end goal is to parse that file and have those three variables just be the top level keys of a hash.我的最终目标是解析该文件并使这三个变量只是哈希的顶级键。

Old_G = {}
for k, v in pairs(_G) do
   Old_G[k] = v
end

dofile('file_name.lua')
--SomeVariable = { ["Thing1"] = { ["SubThing"] = {} } }
--SomeOtherVariable = { ["Thing2"] = { ["SubThing2"] = {} } }
--SomeLastVariable = { ["Thing3"] = { ["SubThing3"] = {} } }


local new_keys = {}
for k, v in pairs(_G) do
   if Old_G[k] ~= v then
      new_keys[k] = v
   end
end
Old_G = nil
return new_keys

If this is a separate file, you can do the following:如果这是一个单独的文件,您可以执行以下操作:

local json = require 'cjson'
-- Using cjson because it's the one I know, I assume your library is similar

local env = setmetatable({}, {__index=_G})
-- Create a new "env" table that will look up missing keys in the global environment

loadfile(
   "tables.lua", -- Your file
   "t", -- Only read Lua source file, no bytecode
   env -- Load the code with "env" as its environment
)() -- Run the code right after loading it

print(json.encode(env))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM