How to prefix a Lua table?

大憨熊 提交于 2019-12-23 12:51:06

问题


I have a lua file whose content is lua Table as below: A={}, A.B={}, A.B.C=0;,

The problem is I want to add prefix XYZ before each above statements. So after the parse the database should have something loke this: XYZ.A={}, XYZ.A.B={}, XYZ.A.B.C={},

Any ideas? Thanks in advance


回答1:


You can load the file with XYZ as is environment: loadfile("mydata","t",XYZ). See loadfile in the manual.

This works in Lua 5.2. For Lua 5.1, use loadfile followed by setfenv.




回答2:


If you can afford polluting your global space with A, simply assign it later:

-- load the file
-- if XYZ doesn't exist, XYZ = { A = A } would be probably shorter
XYZ.A = A
A = nil



回答3:


I think this is what you want:

XYZ = {}
XYZ.A = {}
XYZ.A.B = {}
XYZ.A.B.C = 0



回答4:


How about you simply do:

XYZ = {
    A = {
        B = {
            C = 0
        }
    }
}

If you don't want to nest objects so deep then you may do:

XYZ = {
    A = A
}

A = nil

This assumes that you have already declared the object A before.



来源:https://stackoverflow.com/questions/17525622/how-to-prefix-a-lua-table

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!