2
我輸入的格式如下表:填寫表格保存規則
_input = {
["Item1"] = {
min = 1,
max = 1,
pos = {
[1] = nil,
[2] = {--[[somedata]]},
[3] = nil,
[4] = {--[[somedata]]},
[5] = nil,
[6] = {--[[somedata]]},
[7] = nil,
[8] = {--[[somedata]]},
},
},
["Item2"] = {
min = 1,
max = 1,
pos = {
[1] = nil,
[2] = nil,
[3] = nil,
[4] = {--[[somedata]]},
[5] = {--[[somedata]]},
[6] = {--[[somedata]]},
[7] = nil,
[8] = nil,
},
},
["Item3"] = {
min = 1,
max = 2,
pos = {
[1] = nil,
[2] = {--[[somedata]]},
[3] = nil,
[4] = {--[[somedata]]},
[5] = {--[[somedata]]},
[6] = {--[[somedata]]},
[7] = nil,
[8] = nil,
},
},
["Item4"] = {
min = 1,
max = 3,
pos = {
[1] = {--[[somedata]]},
[2] = {--[[somedata]]},
[3] = {--[[somedata]]},
[4] = nil,
[5] = nil,
[6] = nil,
[7] = {--[[somedata]]},
[8] = {--[[somedata]]},
},
},
}
在_input
每個條目的領域min
,max
和pos
,而pos
本身包含8個條目,要麼nil
或填充與數據。 在_input
中並不總是給出四個項目。可以有更多的項目或更少的項目。
我的目標是從_input
創建可以生成單個表的算法,填充有適當的值和保存min
/max
規則(即:在最後的表從pos
數據項的最小/最大數量。最終輸出中必須有min
項目,最終輸出中可能有max
項目)。
給定上述輸入,輸出可能看起來像這樣:
_output = {
[1] = {
type = "Item4",
data = {--[[the data from _input["Item4"].pos[1] ]]},
},
[2] = {
type = "Item1",
data = {--[[the data from _input["Item1"].pos[2] ]]},
},
[3] = {
type = "Item4",
data = {--[[the data from _input["Item4"].pos[3] ]]},
},
[4] = {
type = "Item3",
data = {--[[the data from _input["Item3"].pos[4] ]]},
},
[5] = nil,
[6] = {
type = "Item2",
data = {--[[the data from _input["Item2"].pos[6] ]]},
},
[7] = {
type = "Item4",
data = {--[[the data from _input["Item4"].pos[7] ]]},
},
[8] = nil,
}
不是在輸出的每個字段具有被填充:
5
和8
是在上面的例子中爲零。
5
無法填充,因爲唯一可能的項目將是Item2
和Item3
。 Item2
已達到最大金額,Item3
不必達到最大金額。
8
無法填充,因爲可能的項目Item1
和Item4
都已達到其最大數量。
這是迄今爲止我的方法,但它不保留所有規則併產生「錯誤」輸出。此外,我希望每次都不要從相同的輸入中獲得相同的結果。
local _output = {
[1] = nil,
[2] = nil,
[3] = nil,
[4] = nil,
[5] = nil,
[6] = nil,
[7] = nil,
[8] = nil,
}
for key in pairs(_input) do
local _item = _input[key]
for i=0,math.random(_item.min, _item.max),1 do
-- I omit deepCopy() for readability
local _possibleCopy = deepCopy(_item.pos)
for i=1,8,1 do
if _output[i] ~= nil then
_possibleCopy[i] = nil
end
end
local _possibleSlots = {}
for i=1,8,1 do
if _possibleCopy[i] ~= nil then
_possibleSlots[#_possibleSlots+1] = i
end
end
local _slot = _possibleSlots[math.random(1,#_possibleSlots)]
if _slot then
_output[_slot] = {
type = key,
data = _item.pos[_slot],
}
end
end
end
我欠你一個啤酒。你救了我很多頭痛!謝謝!出於好奇的一個問題:你寫了'不是v.pos [i]' - 是否有雙重原因? –
這是顯式轉換爲布爾值(數組將僅包含布爾值而不是nils和表)。當然,你可以省略'not not',那不會改變任何東西。 –