Іншими мовами:

User:Ucrij fender/Tutorial:Modding tutorial/Gangsir/uk

From Official Factorio Wiki
Revision as of 17:06, 15 March 2020 by Ucrij fender (talk | contribs)
Jump to navigation Jump to search
 '''Стаття ще не перекладена повністю.''' 

Це туторіал по модінгу для Factorio 0.17. В ньому автор пояснить, що твориться за кулісою Factorio, як модифікувати Factorio, де знайти документацію та пояснить поняття.

Загальні відомості

Перед початком, декілька зауважень:

Код виділений зеленим кольором, як цей, має бути включеним до складу модифікації цього навчального посібника, звісно якщо читач слідує цьому довіднику. Найкращий спосіб це скопіювати та вставити, для забезпечення вірного відтворення.
Щоразу, коли код доданий до модифікації, коментар Lua з ім'ям файлу буде на початку зеленої коробки. Скопіюйте код у вікні у файл з такою назвою. Наприклад:
--control.lua
Код виділений фіолетовим кольором, як цей, не має бути включеним до складу модифікації, це просто приклади.

Цей посібник був оновлений до версії 0.17, тому в майбутньому, ви повинні відзначити, що деякі незначні зміни можуть бути внесені, і варто переглядати журнали змін до поточної версії.

Термінологія

Перш ніж розпочати, слід вияснити кілька термінів та визначень для кращого розуміння.

Модифікація/Мод/Mod
Сценарій(скрипт) або серія скриптів, що дозволяють змінювати гру через API.
Суб'єкт/Сутність/Entity
Суб’єкт у Factorio - це все в грі, яке не є типом, змінною, поняттям, подією чи плиткою. Приклади об'єктів включають символи, складальну машину, кусаку і т.д. Це можуть бути "машини" або об'єкти, що рухаються, як гравець.
Персонаж/Character
Фактична сутність, через яку гравець маніпулює світом.
Гравець/Player
Усі дані, що визначають гравця, такі як ім'я користувача, положення в таблиці гравців тощо. Усі гравці мають персонажа, але всередині персонажа не має гравців.
Прототип/Об'єкт/Prototype
Прототип описує якусь сутність, трохи схожу на шаблон. Він визначає статистику(stats, наприклад здоров'я), що таке сутність насправді і т.д. Прототип використовується для створення сутності, і багато функціонально-однакових сутностей будуть використовувати один і той же прототип.
Поверхня/Surface
Поверхня трохи схожа на вимір(dimension, простір, в математичному значенні). Вона складається з місцевості, наприклад трави, піску, води та всіх структур на поверхні. За замовчуванням у Factorio є лише одна поверхня, яку внутрішньо називають "nauvis" або game.surfaces, але модифікації можуть створювати додаткові поверхні за допомогою API.
Подія/Event
Подія - це повторювана ... подія, що викликається грою всередині. Існує кілька подій, які модифікації можуть підключати до функції, такі як on_entity_died, тощо.

Докладніше про це в розділі контрольних сценаріїв.

Перед початком модифікування

Перш ніж ми зможемо почати модифікувати Factorio, ми повинні зрозуміти, що таке Factorio. Ви можете прочитати about page, але саме так зробив би гравець. Оскільки ми намагаємося стати розробником модів, нам потрібно більш детальне пояснення. Factorio - це гра, написана мовою програмування C++, з API, розробленим Wube (розробниками Factorio) для модифікації Factorio на мові програмування Lua(версії 5.2.1). Це API дозволяє додавати скрипти до процесу ініціалізації Factorio, змінювати його без викриття вихідного коду базової гри або зміни пам'яті. Це може відрізнятися від інших ігор, які пропонують модинг, але це більш професійний і правильний спосіб підтримки модінгу.

Щоб допомогти у використанні цього API, розробники люб'язно надали досить вичерпну документацію на своєму API сайті. Звикайте використовувати цей сайт, оскільки ви будете часто відвідувати цей сайт, коли розробляєте модифікації. Він містить інформацію про класи, інформацію про поняття та інформацію про події, які ви можете підключити. Вам потрібно буде часто перевіряти цей сайт, тому автор рекомендує зробити закладку на ньому. Окрім цього веб-сайту, існує також багато ресурсів, створених спільнотою, наприклад, цей посібник.

Налаштування

Найкращий спосіб розробити мод - це розробити його там, де його можна легко перевірити. Крім того, рекомендується використовувати редактор, що дозволяє легко вводити текст та підтримувати мову Lua. Emacs, Vim, Sublime Text, VSCode та Notepad++ - рекомендовані кандидати. Цей автор віддає перевагу Emacs, але це не має значення в самому моді.

Як Factorio завантажує модифікації

Послідовність завантаження

На етапі завантажування модів, вони завантажуються залежно, потім за алфавітом. Це дуже важливо, щоб зрозуміти, оскільки це може спричинити проблеми, якщо ви нехтуєте цим і намагаєтеся додати модифікацію в інший мод.

Factorio має три види залежності. Існують необхідні та необов'язкові залежності. Третій вид, обмежуючі залежності, не впливають на порядок модифікацій, а натомість запобігають завантаженню гри, якщо знайдеться інший мод. Потрібні залежності завантажуються першими завжди. Гра не ініціалізується, якщо якогось мода немає. Необов'язкові залежності завантажуються спочатку, якщо вони є, але не повинні бути присутніми. Це корисно для включення бонусних функцій, якщо моднифікації використовуються разом. Необхідні залежності повинні використовуватися для бібліотек модифікацій та подібих інфраструктур.

Стадія налаштування

Найперша стадія - це етап налаштувань. В ній визначаються всі параметри модів, які згодом відображаються в інтерфейсі GUI з налаштуваннями ігрового режиму, без інших функцій чи можливостей. Під час запуску цього етапу гра переглядає всі моди для файлів, назви яких були записані в settings.lua. Після ініціалізації settings.lua для всіх модів, виконується ініціалізація settings-updates.lua і нарешті settings-final-fixes.lua. Ці 3 різні фази етапу налаштування дозволяють змінювати налаштування інших модів, без потреби покладатися на залежність для останнього. Усі інші файли для завантаження потрібні. Усі файли, запущені тут, не повинні щось містити, крім встановлення визначень та коду для створення визначень параметрів.

Етап налаштувань не має доступу до прототипів або бібліотеки середовища виконання, оскільки це було завантажене на попередньому етапі. Очікується, що налаштування матимуть певний формат, а весь додатковий код буде відкинутий після завершення етапу.

Налаштування модів не охоплені в цьому підручнику, див. Tutorial:Mod settings для отримання додаткової інформації.

Стадія даних

Це найбільш обмежена частина ініціалізації програми Factorio, тут ви майже нічого не можете, крім декларування прототипів для технологій та об'єктів. Такі речі, як маніпулювання файлами, які впливають на світ або інше блокуються/недоступні. Насправді будь-які внесені функції або зміни будуть відкинуті, оскільки сеанс Lua припиняється. Ви також не можете взаємодіяти з таблицею даних, але це буде визначено помилкою або ігноруватися. Використовуючи data:extend({}), воно очікуватиме певного формату, докладніше про це пізніше.

Під час запуску цього етапу гра переглядає всі моди для файлу під назвою data.lua. Після того, як data.lua виконано для всіх модів виконується data-updates.lua, і нарешті, ініціалізується data-final-fixes.lua. Ці 3 різні фази на етапі даних дозволяють змінювати дані інших мод без необхідності покладатися на залежності для завантаження останнього. Наприклад, базовий мод створює рецепти стволів для всіх наявних рідин у data-updates.lua. Це означає, що якщо ви додасте рідину в data.lua, базовий мод data-updates.lua додасть для нього рецепти "крафтингу"(barreling recipes,барелінгу), незалежно від відповідності версії вашого моду від бази(base mode). Звичайно, це також означає, що якщо ви додаєте рідину в data-final-fixes.lua, вона створюється після запуску коду барелінгу в data-updates.lua, тому що жоден рецепт не створюється навіть за бажанням, щоб виключити рідину з барелінгу створіть її в data.lua та використовуйте "auto_barrel = false" на рідині. Через такі та подібні модифікаційні взаємодії рекомендується створювати прототипи якомога раніше.

Усі інші файли для завантаження повинні бути. Усі файли, запущені тут, не повинні містити нічого, крім визначення прототипу та коду для створення визначень прототипу. Детальніше про необхідність файлів пізніше.

Міграції(Migrations)

Міграції це сценарії, які використовуються для "виправлення" збереження після оновлення модів. Кожного разу, коли прототипи змінюються в межах модифікації, необхідно мігрувати, щоб виправити всі старі екземпляри прототипованої сутності у світі. Це потрібно зробити для всіх оновлених об'єктів, інакше старі об'єкти будуть видалені зі світу, що є непрофесійним резервом, який змушує користувачів не любити вас. Хоча цей посібник не буде обговорювати міграції, є багато ресурсів щодо міграцій, які можна знайти у спільноті та на веб-сайті API.

are scripts that are used to "fix" a save after a mod updates. Whenever prototypes change within a mod, migrations must be setup to correct all the old instances of the prototyped entity in the world. This must be done for all updated entities, or the old entities will be removed from the world, which is an unprofessional fallback that makes users dislike you. While this tutorial will not discuss migrations, there are many resources on migrations to be found around the community, and the API site.

To avoid having to write migrations, avoid making changes to prototypes that effect prototype name, type, recipe, or technology. These things cannot be dynamically changed, and resetting techs or recipes may be necessary. Try to avoid these changes after shipping the mod out to the public. Try to come up with a finalized version of the prototype that you can base the mod around. Of course, migrations are unnecessary if the user simply starts a new world with each mod update, but do not expect the community to do this.

Контроль

У більшості модифікацій є файл, який називається control.lua. Цей файл містить сценарії, які змушують мод робити речі під час гри, а не просто додавати суб'єкти до гри. Під час цього етапу запускається control.lua кожного мода, в його власномій інстанції lua (це означає відсутність взаємозв'язку без спеціальних налаштувань), яким він буде володіти на протязі решти сеансу відтворення. Оскільки це запускається щоразу, коли файл збереження створюється або завантажується, вам не потрібно перезапускати гру, щоб побачити зміни, внесені до файлу control.lua. Просто перезапуск або перезавантаження збереження повторно запустить цей етап. На цьому етапі є кілька інших застережень. Ознайомитися з ними можна на сторінці життєвих циклів даних на веб-сайті API.

Час виконання(Runtime)

На цьому етапі мод встановлюється, і збереження працює. Доступ до всіх таблиць, що надаються в грі, можна зробити всередині обробників подій. (Більше про те, що нижче).

Основні компоненти будь-якої модифікації Factorio

В більшості випадків модифікації мають декілька компонентів, які змушують функціонувати мод.

Модам, що визначають нові сутності, потрібно буде оголосити ці сутності в data.lua, data-updates.lua, data-final-fixes.lua , або інший файл необхідний одному з цих трьох.

Модам з ігровими ефектами також знадобиться файл control.lua, щоб додати сценарій.

Моди з налаштованими налаштуваннями користувача будуть використовувати ettings.lua для опису цих параметрів.

Моди, що визначають будь-який ігровий елемент з читабельним іменем, також можуть містити каталог locale та підкаталоги з іменами/описами на одній або кількох мовах.

Мод, який ми будемо робити в цьому підручнику, буде включати в себе як прототипи data.lua, так і сценарії control.lua, щоб ви змогли ознайомитися з обома.

З часом спільнота визначилася з деякими умовами щодо того, як повинна виглядати структура каталогів модів. Дотримуватися їх до точно не потрібно, але слідуючи стандартам, можна покращити читабельність скриптів та полегшити обговорення помилок модів. Детальніше про структуру каталогів нижче.

Туторіал

А тепер мить на яку ви чекали. Тож почнемо робити свій перший мод. Вам знадобиться:

  • Власне сама Factorio
  • Текстовий редактор або пре-процесор
  • Розуміння написаного вище
  • Розуміння Lua як мови програмування. Досить знати синтаксис і як він працює. Якщо у вас є попередній досвід програмування, працювати з ним не мусить бути складним.

Після того, як у вас з’явиться все це, ми можемо почати.

Для цього мода ми зробимо набір броні, який залишає вогонь позаду вас під час прогулянки. Броня буде повністю стійка до вогню, але слабша до фізичного пошкодження, ніж важка болня, зробивши її бронею для тактики "стріляй та біжи"(run&gun).

Створення структури каталогів

Як було згадано раніше, існує загальний неофіційний стандарт того, як робиться структура модифікації. Це в поєднанні зі стандартами самої гри трохи обмежує нас. Для початку створіть папку у папці каталогу даних користувача/модів. Ця папка повинна мати конкретне ім'я, FireArmor_0.1.0. Закінчивши, каталог моди повинен виглядати так:

  • (каталог користувача, наприклад .factorio)
    • mods
      • FireArmor_0.1.0

Потім всередині FireArmor_0.1.0 створіть два файли, info.json та data.lua. Тепер каталог повинен виглядати так:

  • (каталог користувача, наприклад .factorio)
    • mods
      • FireArmor_0.1.0
        • data.lua
        • info.json

info.json

Потім всередині info.json скопіюйте та вставте в нього:

{
    "name": "FireArmor",
    "version": "0.1.0",
    "title": "Fire Armor",
    "author": "You",
    "contact": "",
    "homepage": "",
    "factorio_version": "0.17",
    "dependencies": ["base >= 0.17"],
    "description": "This mod adds in fire armor that leaves behind damaging fire as you walk around."
}

Для пояснень:

Об'єкт Пояснення
name Внутрішнє ім'я модифікації, воно використовується для ідентифікації вашого мода в коді.
version Версія модифікації. Це може бути все, що завгодно, за умови, що це числа розділені точками. Деякі моди починаються з 0.0.1 або 0.1.0, а інші слідують за версіями Factorio і починаються з 0.17.0 (для версії Factorio 0.17.x)
title Примітна назва вашого мода, це відображатиметься на екрані управління модифікаціями та під час надсилання його на портал модів.
author Назвисько(nickname) або ім'я.
contact Контактна інформація, щоб хтось міг знайти вас у разі проблеми.
homepage Ваш власний веб-сайт свого мода. Не вимагається.
factorio_version Версія гри для якої призначений мод, вона повинна відповідати версії, для якої ви розробляєте мод, 0.17 в цьому випадку.
dependencies Будь-які залежності вашого мода. "base" завжди мусить бути тут, тому база спочатку завантажується.
description Короткий опис модифікації

І це все, щодо info.json! Наступний файл - це data.lua:

--data.lua

require("prototypes.item")

Це досить простий файл, все, що ми робимо тут, - це лише змушуємо гру виконати файл під назвою item.lua в прототипах, який ми збираємося створити. Створіть у FireArmor_0.1.0 папку під назвою prototypes, потім всередині прототипів створіть файл під назвою item.lua. Ваш каталог мод тепер повинен відповідати цим знімкам github.

Зверніть увагу на зазначення каталогів та файлів.

Prototype creation

Now, there are two ways to create prototypes in Factorio. There's the short way, and the long way. The long way requires copying an existing definition from one of the default lua files provided with an install of Factorio, and the short way just uses a lua function to copy and modify a definition. For the sake of this tutorial, we'll do it the short way.

In item.lua, copy and paste the following:

--item.lua

local fireArmor = table.deepcopy(data.raw.armor["heavy-armor"])

fireArmor.name = "fire-armor"
fireArmor.icons= {
   {
      icon=fireArmor.icon,
      tint={r=1,g=0,b=0,a=0.3}
   },
}

fireArmor.resistances = {
   {
      type = "physical",
      decrease = 6,
      percent = 10
   },
   {
      type = "explosion",
      decrease = 10,
      percent = 30
   },
   {
      type = "acid",
      decrease = 5,
      percent = 30
   },
   {
      type = "fire",
      decrease = 0,
      percent = 100
   },
}

local recipe = table.deepcopy(data.raw.recipe["heavy-armor"])
recipe.enabled = true
recipe.name = "fire-armor"
recipe.ingredients = {{"copper-plate",200},{"steel-plate",50}}
recipe.result = "fire-armor"

data:extend{fireArmor,recipe}

What we've just done here is we've copied the definition of heavy armor, then changed it's properties, and injected it into the Factorio init with data:extend. The first line of code is probably the most interesting. table.deepcopy copies a table fully into another table. We do this from data.raw. The data part is a table, which will be used by game to setup the Factorio universe. In fact, it contains the function extend(self,prototypes) and a table called raw. The former is customary way to add new stuff to the latter. It is actually data.raw that holds the prototypes for the game. (You can view the implementation in the file /factorio/data/core/lualib/dataloader.lua). It is important to note that data.raw only exists during the data loading stage of the game. During the control stage, when the game is running and being played, you cannot read this data; instead you read processed values through the API from the various types like LuaEntityPrototype.

In addition to defining the item prototype, we also define a recipe for it. This is necessary if you want to be able to craft the thing. We also set it to enabled so it doesn't need a technology to unlock.

At this point, the mod looks like this.

More on data.raw

When Factorio initializes, all prototypes are put into a table called data.raw. This table holds all types, and within those types, individual entities. You saw earlier how we deepcopied from the definition of heavy armor, and modified some fields. In fact, let's go over each part of the deepcopy line:

local fireArmor = table.deepcopy(data.raw.armor["heavy-armor"])

We assign a variable called fireArmor that holds our copy of the heavy armor definition. Notice how in data.raw, there is a type table that holds all armors, and the specific armor we're looking for is called heavy-armor. For example, the player's prototype would be:

data.raw.player["player"]

Because the player is the player, his type matches his name. You could define a new type of player with a mod. You can see all the prototype fields for an entity in it's long declaration in the Factorio install, at (Install)/data/base/prototypes.

You may be thinking at this point, "Can I modify Factorio's existing prototypes without making new ones?" Well, the answer is yes! You would simply access the data.raw table during init, in data-final-fixes.lua, and change a property. For example, make the iron chest instead have 1000 health:

data.raw.container['iron-chest'].max_health = 1000

The reason why this code must be in data-final-fixes.lua or data-updates.lua is because that is the last file run, after all mod files have been run. This prevents (to a degree) your changes from being messed with by other mods. Of course, it is still possible to have incompatibilities. You should note any that you know of in your mod's description. Again, the dev's documentation on this should be looked at.

This can also be applied to other mods, not just Factorio's base. You could mod a mod, as long as you add the mod (that you modified with your mod) to your dependencies so it gets loaded first.

The control scripting

And now, to finalize the mod, we have to make it be more than just simple armor. Let's think about what we want the armor to do. We want the armor to periodically create fire on the ground as we walk with the armor on. The event we're going to use is called on_tick, since we want the fire to be periodically created.

In our mod folder, create a file called control.lua. The game will automatically execute this file, so requiring it is not necessary.

Inside control.lua, copy and paste the following:

--control.lua

script.on_event({defines.events.on_tick},
   function (e)
      if e.tick % 30 == 0 then --common trick to reduce how often this runs, we don't want it running every tick, just every 30 ticks, so twice per second
         for index,player in pairs(game.connected_players) do  --loop through all online players on the server
            
            --if they're wearing our armor
            if player.character and player.get_inventory(defines.inventory.character_armor).get_item_count("fire-armor") >= 1 then
               --create the fire where they're standing
               player.surface.create_entity{name="fire-flame", position=player.position, force="neutral"} 
            end
         end
      end
   end
)

I've used lua comments in the code above to explain each step. It's fairly easy to understand, and it shows how you would get the current armor that the player is wearing, with defines.inventory.character_armor, which is an inventory constant. You can read the list of defines here.

At this point, the mod will look like this.

Locale

If you've already tried loading up Factorio and trying the mod so far (which you can at this point without it crashing), you may have noticed that the item name of the armor says "Unknown key". This means that Factorio has the internal name, but it doesn't know what it should look like to the user. So, we need to create locale for our mod.

In the mod folder, create a folder called locale, then create another folder inside that called en, then a file called config.cfg.

If you know another language, you can also translate your mod by making other language code files inside locale, such as de for German.

Inside config.cfg, paste the following:


[item-name]
fire-armor=Fire armor

[item-description]
fire-armor=An armor that seems to catch the ground itself on fire when you take a step. It's warm to the touch.

Notice how this is not a lua file. Locale is handled with C config files, so the format is different.

Finally, the mod will look like this.

The finished tutorial mod

Well, the mod is finished. Since this mod is only a tutorial, there isn't much balance to it. Additionally, don't try submitting it to the mod portal as your own, since it's from the Wiki.

However, you're free to take this mod and modify it for your own use, changing recipes, adding technologies, whatever.

Resolving common errors in modding

As you continue to write mods from scratch instead of from a tutorial, you may encounter the infamous error. There are several types of errors that you can encounter in modding Factorio, and knowing how to deal with these errors will allow you to continue working.

Syntax errors

The lua programming language expects things to be laid out a certain way. If you miss a bracket, = sign, or dot, you will encounter a syntax error. As an example, see the error below:

Failed to load mods: __FireArmor__/data.lua:1:__FireArmor__/prototypes/item.lua:36: syntax error near 'true'

As of version 0.15, you'll see an error like the one above whenever you make a syntax error within the prototype definitions. The game will offer to restart, disable the troubling mod, disable all mods, or exit. Let's dissect the error, shall we?

Right away, we see the reason why Factorio didn't start normally. "Failed to load mods:". So, we know that it's a mod that messed up, and by extension, we know it's our mod. Whenever the lua engine of Factorio has a syntax error, it will print a mini stack-trace that follows through all requires, listing the call order. First, we see that the problem was indirectly caused by line 1 of data.lua. There's no problem there, so it must be the next entry, line 36 of prototypes/item.lua. After stating where it is line-wise, it will attempt to give you an estimate of where in the line the problem is. Don't trust this estimate, only roughly trust the line number, plus or minus a few lines.

Going to line 36 of item.lua, we find:

recipe.enabled true

Hmm, that doesn't look right. Can you see what's missing? We left off an = between enabled and true. Thus, syntax error. Fixing these can be difficult for new programmers, who don't know what to look for.

Illogical actions, indexing nil

In lua, "nothing" is defined as the keyword nil. This is similar to null in other programming languages. Whenever the programmer tries to access something in a table that is nil, they will get an error like the following:

Error while running event FireArmor::on_tick (ID 0)
__FireArmor__/control.lua:3: attempt to index field '?' (a nil value)

The "attempt to index field ..." error is often caused by the modder making an assumption that didn't work out. These types of errors will always be identifiable by their signature line, "attempt to index field". If we look at line 3 of control.lua (where the error is), we see:

game.print(game.players[23])

What assumption has the modder made here? Well, there's actually two problems with this line. The first thing is that the modder has assumed that game.players[23] is a valid player, which isn't the case; this is why we get the "index field '?'" bit. The game doesn't know what the field is that we tried to index, because it hasn't been created yet. These errors are difficult to debug unless you know the ins and outs of the modding API well.

The second issue is a lot more subtle, and won't work. The modder is attempting to print a userdata table. A player is a table of several values. Trying to print it will error, instead a function to print it is needed.

Error while running event

Another common type of error in Factorio is the "Error while running event" error. This type of error only happens in control.lua scripting, and it happens when something goes wrong in an event function, such as a syntax error. Note that syntax errors in control.lua do not stop the game from starting, but may trigger after a save is loaded. There are a great deal of errors under this broad category, here's an example:

Error while running event FireArmor::on_tick (ID 0)
Unknown entity name: fire-flam
stack traceback:
__FireArmor__/control.lua:6: in function <__FireArmor__/control.lua:2>

As you saw with the prototypes syntax error, Factorio gives a small traceback and the error name itself. In this case, we've attempted to spawn an entity called "fire-flam" on line 6 of control.lua, inside of an on_tick event hook. Fire-flam isn't a real entity type, so we crashed.

These types of errors can range from being a simple fix (like the one above, add the missing e), or can be very difficult.

Internal errors

The most rare form of error and the worst form is the internal error. This is an error with the C++ code of the game, and there's nothing you can do but report it to the devs. Mods occasionally cause these, and almost all of them are considered bugs, as mods should not be able to cause these, if that makes sense. They often get thrown into the logs.

An example:

696.148 Error FlowStatistics.cpp:236: FlowStatistics attempted to save value larger than uint16 as uint16. Exiting to prevent save corruption.
Logger::writeStacktrace skipped.
696.148 Error CrashHandler.cpp:106: Map tick at moment of crash: 432029
696.148 Error Util.cpp:76: Unexpected error occurred. If you're running the latest version of the game you can help us solve the problem by posting the contents of the log file on the Factorio forums.

Multiplayer and desyncs

The reader may be wondering at this point how Factorio handles multiplayer with mods. It's fairly simple, but is still worth considering.

Factorio is deterministic, which means that when you provide a constant input, you get a constant output, with no variance. Every client and the server all reach the same points at the same time in simulation, so they all agree on what happened. When this differs, the players experience a desync.

Desync
Misalignment with server and clients. Client 1 expected A, but got B. All other clients got A. Thus, Client 1 will desync. Desync can also happen when all clients have information (for example a variable) but a client that recently joined the game doesn't. That client will be desynced.
See also: Desynchronization

Desyncs happen a lot to new devs of Factorio mods, because they are unaware that a particular piece of code they used causes desyncs. As a general rule, there are a few things that should never be done.

Use local variables that are not final outside of event hooks

local globalLocal = 1
script.on_event(defines.events.on_player_built_item, function()
    globalLocal = math.random()
end)

If the modder places a local variable outside of an event hook that gets changed during runtime, desyncs will happen when that variable is utilised to modify the game state (i.e. manipulate an entity, print text to players). If making a "global" variable is necessary, place the variable in the global table instead. The game syncs this table between all clients, so they can all be aware of and reach the same conclusion as each other.

Selective requiring

if setting1 then
   require("settingOne.lua")
end

Selective requiring, aka requiring different lua files based on settings or other criteria will also cause desyncs, and in some cases can cause connection rejections as the checksum of the mods will not match, as they load different data. All clients' mods must require the same series of files.

Conditional event subscribing

Mods in factorio may subscribe to events in order to be notified when they happen. This allows mods to react to events when they occur. Typically, event subscription is done at the top level of a lua file.

Doing event subscription inside of a conditional, function, or other event is dangerous, as doing it incorrectly will lead to desyncs. Basically, since both the server and client need to reach the same conclusion after running code, conditional subscription can lead to certain clients or the server being subscribed to an event when the others are not, causing desyncs.

Improper use of on_load

Another way to cause desyncs is to make improper actions inside of an on_load call, which some players new to modding might try to do. According to the documentation, the on_load functionality is meant for 3 purposes only:

  • Re-register conditional event handlers
  • Re-setup meta tables
  • Create local references to tables stored in the global table

Doing anything else will cause desyncs. The game will catch most attempts, crashing instead and terminating the mod.

Extended learning

One of the best ways to learn how to mod beyond this is to look at other mods. As all mods can be opened and looked at, looking at the mods of experienced modders can help significantly when making your own mod.

Keeping your mod working

As Factorio evolves, things will change. Previously, you probably ignored the modding part of the changelog, you now need to read it and see if any changes affect your mod(s). If so, you'll need to fix them. If there's something wrong with your mod, the game will fail to init and explain why.

See also