问题
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