我正在开发一款游戏,根据项目中或外部通过mod文件定义的一些约束,动态生成一堆字符。我正在使用MoonSharp Lua(5.2)解释器来连接我的C#代码,并使用Lua表来存储约束预设。举个例子:
require "Defaults"
AgePresets = {}
-- Single value
AgePresets.Newborn = 0
-- Simple ranges
AgePresets.Default = defaultAgeRange --referring to the Defaults require
AgePresets.Child = {1, 12}
AgePresets.Teenager = {13, 19}
AgePresets.YoungAdult = {20, 29}
AgePresets.Adult = {30, 40}
AgePresets.MiddleAge = {40, 60}
AgePresets.Senior = {61, 80}
AgePresets.Elder = {81, 99}
AgePresets.Methuselah = {100, 150}
AgePresets.Methuselah2 = {150, 200}
-- Weighted ranges // again referring to previously defined elements to keep things concise
AgePresets.Tween = {
{weight = 1, minmax = AgePresets.Teenager },
{weight = 1, minmax = AgePresets.YoungAdult }
}
这很好用,但从最终用户的角度来看,涉及到很多不必要的打字。我们在这里显然正在研究AgePresets,但在每个成员名称之前仍然提到它作为前缀。
我当然可以将AgePresets定义为一个数组,例如AgePresets = {Child = {},Teenager = {}},但问题是我不能引用数组中先前定义的元素。
这不起作用:
AgePresets = {
Child = {1,12},
RefToChild = Child, //attempt to index a nil value exception
Teen = {13,19}
}
我理想情况下想要实现的是用户输入此数据的简洁方式,就像在第一个示例中一样,但不必放置AgePresets。一切前的前缀。如何在文件中声明范围,以便文件中定义的所有后续成员都在该范围内,同时保持引用先前在范围中定义的其他成员的能力?
答案 0 :(得分:1)
AgePresets = setmetatable({}, {__index = _G})
do
local _ENV = AgePresets
Newborn = 0
Child = {1,12}
RefToChild = Child -- this ref is Ok
Teen = {13,19}
YoungAdult = {20,29}
Tween = {
{weight = 1, minmax = Teen },
{weight = 1, minmax = YoungAdult }
}
rnd = math.random(10) -- global functions are available here
end
setmetatable(AgePresets, nil)
答案 1 :(得分:0)
你可以混合两种样式:表构造函数用于不需要引用不在范围内的变量的字段,其次是其余的赋值语句。
除非代码中字段的顺序显着增强了理解力,否则我会这样做。