我在lua中有一张表:
enUS = {
LOCALE_STHOUSANDS = ",", --Thousands separator e.g. comma
patNumber = "%d+["..LOCALE_STHOUSANDS.."%d]*", --regex to find a number
["PreScanPatterns"] = {
["^("..patNumber..") Armor$"] = "ARMOR",
}
}
所以你看到这个表中有一整串自我引用:
LOCAL_STHOUSANDS
patNumber
["^("..patNumber..") Armor$"]
如何在lua表中执行自引用?
我不想做的是必须硬替换值;有数百个参考文献:
enUS = {
LOCALE_STHOUSANDS = ",", --Thousands separator e.g. comma
patNumber = "%d+[,%d]*", --regex to find a number
["PreScanPatterns"] = {
["^(%d+[,%d]*) Armor$"] = "ARMOR",
}
}
答案 0 :(得分:5)
如何在lua表中执行自引用?
你没有。
Lua不是C.在构造表之前,不存在任何表条目。因为表本身尚不存在。因此,您不能在表构造函数中有一个条目引用不存在的表中的另一个条目。
如果你想减少重复输入,那么你应该使用局部变量和do/end
块:
do
local temp_thousands_separator = ","
local temp_number_pattern = "%d+["..LOCALE_STHOUSANDS.."%d]*"
enUS = {
LOCALE_STHOUSANDS = temp_thousands_separator, --Thousands separator e.g. comma
patNumber = "%d+["..temp_thousands_separator.."%d]*", --regex to find a number
["PreScanPatterns"] = {
["^("..temp_number_pattern..") Armor$"] = "ARMOR",
}
}
end
do/end
块在那里,以便临时变量不存在于表创建代码之外。
或者,您可以分阶段进行构建:
enUS = {}
enUS.LOCALE_STHOUSANDS = ",", --Thousands separator e.g. comma
enUS.patNumber = "%d+["..enUS.LOCALE_STHOUSANDS.."%d]*", --regex to find a number
enUS["PreScanPatterns"] = {
["^("..enUS.patNumber..") Armor$"] = "ARMOR",
}
答案 1 :(得分:3)
在构造函数本身内部无法做到这一点,但你可以在创建表之后这样做:
enUS = {
LOCALE_STHOUSANDS = ","
}
enUS.patNumber = "%d+["..enUS.LOCALE_STHOUSANDS.."%d]*"
enUS.PreScanPatterns = {
["^("..enUS.patNumber..") Armor$"] = "ARMOR",
}
如果你特别需要引用当前表,Lua提供了一个“self”参数,但它只能在函数中访问。
local t = {
x = 1,
y = function(self) return self.x end
}
-- this is functionally identical to t.y
function t:z() return self.x end
-- these are identical and interchangeable
print(t:y(), t.z(t))
-- 1, 1