Game crashes for me inside "CheckVotes()" because law=nil.
It happened when I was testing out mod and I accepted,rejected some random laws that I made.
I think it happens when rejected law is not last one on list, because in code :
local function CheckVotes()
local laws = global.laws
for i=1, #laws do
law = laws[i]
if not law.passed and not law.linked_law and game.tick >= law.vote_end_tick then
local votes = GetLawVotes(law)
if votes.ayes > votes.noes then
game.print({"lawful-evil.messages.law-is-passed", law.title, votes.ayes, votes.noes})
PassLaw(law)
else
game.print({"lawful-evil.messages.law-is-not-passed", law.title, votes.ayes, votes.noes})
RevokeLaw(law, law.index)
end
end
end
-- Refresh Lawful Gui.
RefreshAllLawfulEvilGui()
end
Function RevokeLaw removes item from table, causing "for loop" to operate in invalid range.
After adding 2 lines of code in loop :
game.print("law : " .. i)
game.print("total : " .. #laws)
I got crash right after game prints "law : 4 total : 3"
I tried deep-copying global.laws instead of assigning reference, but then it caused passed laws to not get passed.
I thought of several other solutions, but I went for simple one (though maybe not elegant)
local function CheckVotes()
local laws = global.laws
local i=1;
while i<=#laws do
law = laws[i]
i=i+1
if not law.passed and not law.linked_law and game.tick >= law.vote_end_tick then
local votes = GetLawVotes(law)
if votes.ayes > votes.noes then
game.print({"lawful-evil.messages.law-is-passed", law.title, votes.ayes, votes.noes})
PassLaw(law)
else
game.print({"lawful-evil.messages.law-is-not-passed", law.title, votes.ayes, votes.noes})
RevokeLaw(law, law.index) --we change count of laws table elements(!)
i=i-1 --table is now 1 smaller.
end
end
end
-- Refresh Lawful Gui.
RefreshAllLawfulEvilGui()
end
More elegant solution, that I thought about : don't delete law from global.laws in RevokeLaw function. Instead mark it as rejected and delete it.... Somewhere later. Ideally RevokeLaw shouldn't care about law.index and law shouldn't store it's index.
Another "elegant" solution : start for loop on last element and move backwards (for i=#laws,1,-1)? That way you don't shift table when you remove element.
But I only tested if game doesn't crash now. I guess it should just work well, unless I misunderstand how things work in this mod ( I just glanced at code )