diff --git a/.github/workflows/dev-deploy.yml b/.github/workflows/dev-deploy.yml new file mode 100644 index 0000000000..418d1360ed --- /dev/null +++ b/.github/workflows/dev-deploy.yml @@ -0,0 +1,39 @@ +name: Dev Deploy + +on: + push: + branches: + - dev + paths-ignore: + - 'docs/**' + - '.luacheckrc' + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - name: Checkout repo + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Install Lua + uses: leafo/gh-actions-lua@v5 + + - name: Install LuaRocks + uses: leafo/gh-actions-luarocks@v2 + + - name: Install LDoc + run: luarocks install ldoc 1.4.4-1 + + - name: Generate Documents + working-directory: docs + run: ldoc -i . + + - name: Commit changes + uses: EndBug/add-and-commit@v4 + with: + message: "Automatic Doc Update" + add: "./docs/** .luacheckrc" + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/.github/workflows/pr-checker.yml b/.github/workflows/pr-checker.yml new file mode 100644 index 0000000000..77e50408f5 --- /dev/null +++ b/.github/workflows/pr-checker.yml @@ -0,0 +1,41 @@ +name: CI PR Checker + +on: pull_request + +jobs: + luacheck: + runs-on: ubuntu-latest + steps: + - name: Checkout repo + uses: actions/checkout@v2 + + - name: Extract branch name + shell: bash + run: echo "##[set-output name=branch;]$(echo ${GITHUB_BASE_REF#refs/heads/})" + id: extract_branch + + - name: Lint + uses: Roang-zero1/factorio-mod-luacheck@master + with: + luacheckrc_url: https://raw.githubusercontent.com/explosivegaming/scenario/${{ steps.extract_branch.outputs.branch }}/.luacheckrc + + docs: + runs-on: ubuntu-latest + steps: + - name: Checkout repo + uses: actions/checkout@v2 + with: + fetch-depth: 0 + + - name: Install Lua + uses: leafo/gh-actions-lua@v5 + + - name: Install LuaRocks + uses: leafo/gh-actions-luarocks@v2 + + - name: Install LDoc + run: luarocks install ldoc 1.4.4-1 + + - name: Generate Documents + working-directory: docs + run: ldoc -i . \ No newline at end of file diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index 522fac3216..0000000000 --- a/.gitmodules +++ /dev/null @@ -1,3 +0,0 @@ -[submodule "Factorio-luacheckrc"] - path = Factorio-luacheckrc - url = https://github.com/Nexela/Factorio-luacheckrc diff --git a/.luacheckrc b/.luacheckrc index 98d8fa3e4a..0550e04230 100644 --- a/.luacheckrc +++ b/.luacheckrc @@ -70,6 +70,14 @@ do -- Assume Factorio Control Stage as Default } end +do -- RedMew and ExpGaming overrides + globals = { + 'math', 'table', + 'print', 'require', 'unpack', 'inspect', 'loadstring', 'ServerCommands', 'Debug', + '_C', '_DEBUG', '_CHEATS', '_DUMP_ENV', '_LIFECYCLE', '_STAGE', + } +end + do -- Set default prototype files files['**/data.lua'].std = STD_DATA files['**/data-updates.lua'].std = STD_DATA diff --git a/Factorio-luacheckrc b/Factorio-luacheckrc deleted file mode 160000 index 0c0518d165..0000000000 --- a/Factorio-luacheckrc +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 0c0518d165b0fcee714f9e00b014afd7aba9fbee diff --git a/README.md b/README.md index 851be090d1..08e9c873b2 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ All are welcome to make pull requests and issues for this scenario, if you are i | Scenario Version* | Version Name | Factorio Version** | |---|---|---| +| [v6.1][s6.1] | External Data Overhaul | [v1.0.0][f1.0.0] | | [v6.0][s6.0] | Gui / 0.18 Overhaul | [v0.18.17][f0.18.17] | | [v5.10][s5.10] | Data Store Rewrite | [v0.17.71][f0.17.71] | | [v5.9][s5.9] | Control Modules and Documentation | [v0.17.63][f0.17.63] | @@ -80,6 +81,7 @@ All are welcome to make pull requests and issues for this scenario, if you are i \*\* Factorio versions show the version they were made for, often the minimum requirement. +[s6.1]: https://github.com/explosivegaming/scenario/releases/tag/6.1.0 [s6.0]: https://github.com/explosivegaming/scenario/releases/tag/6.0.0 [s5.10]: https://github.com/explosivegaming/scenario/releases/tag/5.10.0 [s5.9]: https://github.com/explosivegaming/scenario/releases/tag/5.9.0 @@ -98,6 +100,7 @@ All are welcome to make pull requests and issues for this scenario, if you are i [s1.0]: https://github.com/explosivegaming/scenario/releases/tag/v1.0 [s0.1]: https://github.com/explosivegaming/scenario/releases/tag/v0.1 +[f1.0.0]: https://wiki.factorio.com/Version_history/1.0.0#1.0.0 [f0.18.17]: https://wiki.factorio.com/Version_history/0.18.0#0.18.17 [f0.17.71]: https://wiki.factorio.com/Version_history/0.17.0#0.17.71 [f0.17.63]: https://wiki.factorio.com/Version_history/0.17.0#0.17.63 diff --git a/config/_file_loader.lua b/config/_file_loader.lua index c78f6bde67..be200bf32a 100644 --- a/config/_file_loader.lua +++ b/config/_file_loader.lua @@ -6,11 +6,12 @@ return { --'example.file_not_loaded', 'modules.factorio-control', -- base factorio free play scenario - -- Game Commands + 'expcore.player_data', + + --- Game Commands 'modules.commands.me', 'modules.commands.kill', 'modules.commands.admin-chat', - 'modules.commands.tag', 'modules.commands.teleport', 'modules.commands.cheat-mode', 'modules.commands.ratio', @@ -25,11 +26,10 @@ return { 'modules.commands.spawn', 'modules.commands.warnings', 'modules.commands.find', - 'modules.commands.bonus', 'modules.commands.home', - -- QoL Addons - 'modules.addons.station-auto-name', - 'modules.addons.greetings', + 'modules.commands.connect', + + --- Addons 'modules.addons.chat-popups', 'modules.addons.damage-popups', 'modules.addons.death-logger', @@ -38,11 +38,21 @@ return { 'modules.addons.compilatron', 'modules.addons.scorched-earth', 'modules.addons.pollution-grading', - 'modules.addons.random-player-colours', + 'modules.addons.station-auto-name', 'modules.addons.discord-alerts', 'modules.addons.chat-reply', 'modules.addons.tree-decon', - -- GUI + + --- Data + 'modules.data.statistics', + 'modules.data.player-colours', + 'modules.data.greetings', + 'modules.data.quickbar', + 'modules.data.alt-view', + 'modules.data.tag', + 'modules.data.bonus', + + --- GUI 'modules.gui.readme', 'modules.gui.rocket-info', 'modules.gui.science-info', @@ -51,10 +61,11 @@ return { 'modules.gui.player-list', 'modules.gui.server-ups', 'modules.commands.debug', - -- Config Files + + --- Config Files 'config.expcore.command_auth_admin', -- commands tagged with admin_only are blocked for non admins 'config.expcore.command_auth_roles', -- commands must be allowed via the role config 'config.expcore.command_runtime_disable', -- allows commands to be enabled and disabled during runtime 'config.expcore.permission_groups', -- loads some predefined permission groups 'config.expcore.roles', -- loads some predefined roles -} \ No newline at end of file +} diff --git a/config/advanced_start.lua b/config/advanced_start.lua index c5b5685445..ef827f1c78 100644 --- a/config/advanced_start.lua +++ b/config/advanced_start.lua @@ -4,15 +4,17 @@ --- These are called factories because they return another function -- use these as a simple methods of adding new items -- they will do most of the work for you --- ['item-name']=factory(params) +-- ['item-name'] = factory(params) +-- luacheck:ignore 212/amount_made 212/items_made 212/player -- Use these to adjust for ticks ie game.tick < 5*minutes +-- luacheck:ignore 211/seconds 211/minutes 211/hours local seconds, minutes, hours = 60, 3600, 216000 --- Use to make a split point for the number of items given based on time --- ['stone-furnace']=cutoff_time(5*minutes,4,0) -- before 5 minutes give four items after 5 minutes give none -local function cutoff_time(time,before,after) - return function(amount_made,items_made,player) +-- ['stone-furnace']=cutoff_time(5*minutes, 4,0) -- before 5 minutes give four items after 5 minutes give none +local function cutoff_time(time, before, after) + return function(amount_made, items_made, player) if game.tick < time then return before else return after end @@ -20,9 +22,9 @@ local function cutoff_time(time,before,after) end --- Use to make a split point for the number of items given based on amount made --- ['firearm-magazine']=cutoff_amount_made(100,10,0) -- give 10 items until 100 items have been made -local function cutoff_amount_made(amount,before,after) - return function(amount_made,items_made,player) +-- ['firearm-magazine']=cutoff_amount_made(100, 10, 0) -- give 10 items until 100 items have been made +local function cutoff_amount_made(amount, before, after) + return function(amount_made, items_made, player) if amount_made < amount then return before else return after end @@ -30,9 +32,9 @@ local function cutoff_amount_made(amount,before,after) end --- Same as above but will not give any items if x amount has been made of another item, useful for tiers --- ['light-armor']=cutoff_amount_made_unless(5,0,1,'heavy-armor',5) -- give light armor once 5 have been made unless 5 heavy armor has been made -local function cutoff_amount_made_unless(amount,before,after,second_item,second_amount) - return function(amount_made,items_made,player) +-- ['light-armor']=cutoff_amount_made_unless(5, 0,1,'heavy-armor',5) -- give light armor once 5 have been made unless 5 heavy armor has been made +local function cutoff_amount_made_unless(amount, before, after, second_item, second_amount) + return function(amount_made, items_made, player) if items_made(second_item) < second_amount then if amount_made < amount then return before else return after @@ -43,11 +45,11 @@ local function cutoff_amount_made_unless(amount,before,after,second_item,second_ end -- Use for mass production items where you want the amount to change based on the amount already made --- ['iron-plate']=scale_amount_made(5*minutes,10,10) -- for first 5 minutes give 10 items then after apply a factor of 10 -local function scale_amount_made(amount,before,scalar) - return function(amount_made,items_made,player) +-- ['iron-plate']=scale_amount_made(5*minutes, 10, 10) -- for first 5 minutes give 10 items then after apply a factor of 10 +local function scale_amount_made(amount, before, scalar) + return function(amount_made, items_made, player) if amount_made < amount then return before - else return (amount_made*scalar)/math.pow(game.tick/minutes,2) + else return (amount_made*scalar)/math.pow(game.tick/minutes, 2) end end end @@ -65,30 +67,30 @@ return { skip_intro=true, --- @setting skip_intro skips the intro given in the default factorio free play scenario skip_victory=true, --- @setting skip_victory will skip the victory screen when a rocket is launched disable_base_game_silo_script=true, --- @setting disable_base_game_silo_script will not load the silo script at all - research_queue_from_start=true, --- @setting research_queue_from_start when true the research queue is useible from the start + research_queue_from_start=true, --- @setting research_queue_from_start when true the research queue is useable from the start friendly_fire=false, --- @setting friendly_fire weather players will be able to attack each other on the same force enemy_expansion=false, --- @setting enemy_expansion a catch all for in case the map settings file fails to load chart_radius=10*32, --- @setting chart_radius the number of tiles that will be charted when the map starts items = { --- @setting items items and there condition for being given - -- ['item-name'] = function(amount_made,production_stats,player) return end -- 0 means no items given + -- ['item-name'] = function(amount_made, production_stats, player) return end -- 0 means no items given -- Plates - ['iron-plate']=scale_amount_made(100,10,10), - ['copper-plate']=scale_amount_made(100,0,8), - ['steel-plate']=scale_amount_made(100,0,4), + ['iron-plate']=scale_amount_made(100, 10, 10), + ['copper-plate']=scale_amount_made(100, 0,8), + ['steel-plate']=scale_amount_made(100, 0,4), -- Secondary Items - ['electronic-circuit']=scale_amount_made(1000,0,6), - ['iron-gear-wheel']=scale_amount_made(1000,0,6), + ['electronic-circuit']=scale_amount_made(1000, 0,6), + ['iron-gear-wheel']=scale_amount_made(1000, 0,6), -- Starting Items - ['burner-mining-drill']=cutoff_time(10*minutes,4,0), - ['stone-furnace']=cutoff_time(10*minutes,4,0), + ['burner-mining-drill']=cutoff_time(10*minutes, 4,0), + ['stone-furnace']=cutoff_time(10*minutes, 4,0), -- Armor - ['light-armor']=cutoff_amount_made_unless(5,0,1,'heavy-armor',5), - ['heavy-armor']=cutoff_amount_made(5,0,1), + ['light-armor']=cutoff_amount_made_unless(5, 0,1,'heavy-armor',5), + ['heavy-armor']=cutoff_amount_made(5, 0,1), -- Weapon - ['pistol']=cutoff_amount_made_unless(0,1,1,'submachine-gun',5), - ['submachine-gun']=cutoff_amount_made(5,0,1), + ['pistol']=cutoff_amount_made_unless(0, 1,1,'submachine-gun',5), + ['submachine-gun']=cutoff_amount_made(5, 0,1), -- Ammo - ['firearm-magazine']=cutoff_amount_made_unless(100,10,0,'piercing-rounds-magazine',100), - ['piercing-rounds-magazine']=cutoff_amount_made(100,0,10), + ['firearm-magazine']=cutoff_amount_made_unless(100, 10, 0,'piercing-rounds-magazine',100), + ['piercing-rounds-magazine']=cutoff_amount_made(100, 0,10), } } diff --git a/config/chat_reply.lua b/config/chat_reply.lua index 2f65356971..c8ce740778 100644 --- a/config/chat_reply.lua +++ b/config/chat_reply.lua @@ -4,115 +4,117 @@ local Async = require 'expcore.async' local format_time = _C.format_time --- @dep expcore.common +-- eg Async(async_message, is_command or player, message) local async_message = Async.register(function(player, message) - player.print(message) + if player == true then game.print(message) else player.print(message) end end) +-- luacheck:ignore 212/player 212/is_command return { allow_command_prefix_for_messages = true, --- @setting allow_command_prefix_for_messages when true any message trigger will print to all player when prefixed messages = { --- @setting messages will trigger when ever the word is said - ['discord']={'info.discord'}, - ['expgaming']={'info.website'}, - ['website']={'info.website'}, - ['wiki']={'info.wiki'}, - ['status']={'info.status'}, - ['github']={'info.github'}, - ['patreon']={'info.patreon'}, - ['donate']={'info.patreon'}, - ['command']={'info.custom-commands'}, - ['commands']={'info.custom-commands'}, - ['softmod']={'info.softmod'}, - ['script']={'info.softmod'}, - ['loop']={'chat-bot.loops'}, - ['rhd']={'info.lhd'}, - ['lhd']={'info.lhd'}, - ['roundabout']={'chat-bot.loops'}, - ['roundabouts']={'chat-bot.loops'}, - ['redmew']={'info.redmew'}, - ['afk']=function(player) - local max=player - for _,next_player in pairs(game.connected_players) do + ['discord'] = {'info.discord'}, + ['expgaming'] = {'info.website'}, + ['website'] = {'info.website'}, + ['wiki'] = {'info.wiki'}, + ['status'] = {'info.status'}, + ['github'] = {'info.github'}, + ['patreon'] = {'info.patreon'}, + ['donate'] = {'info.patreon'}, + ['command'] = {'info.custom-commands'}, + ['commands'] = {'info.custom-commands'}, + ['softmod'] = {'info.softmod'}, + ['script'] = {'info.softmod'}, + ['loop'] = {'chat-bot.loops'}, + ['rhd'] = {'info.lhd'}, + ['lhd'] = {'info.lhd'}, + ['roundabout'] = {'chat-bot.loops'}, + ['roundabouts'] = {'chat-bot.loops'}, + ['redmew'] = {'info.redmew'}, + ['afk'] = function(player) + local max = player + for _, next_player in pairs(game.connected_players) do if max.afk_time < next_player.afk_time then - max=next_player + max = next_player end end - return {'chat-bot.afk',max.name,format_time(max.afk_time,{minutes=true,seconds=true,long=true})} + return {'chat-bot.afk', max.name, format_time(max.afk_time, {minutes = true, seconds = true, long = true})} end, - ['players']=function() - return {'chat-bot.players',#game.players} + ['players'] = function() + return {'chat-bot.players', #game.players} end, - ['online']=function() - return {'chat-bot.players-online',#game.connected_players} + ['online'] = function() + return {'chat-bot.players-online', #game.connected_players} end, - ['r!verify']=function(player) - return {'chat-bot.verify',player.name} + ['r!verify'] = function(player) + return {'chat-bot.verify', player.name} end, }, command_admin_only = false, --- @setting command_admin_only when true will only allow chat commands for admins command_permission = 'command/chat-bot', --- @setting command_permission the permission used to allow command prefixes command_prefix = '!', --- @setting command_prefix prefix used for commands below and to print to all players (if enabled above) commands = { --- @setting commands will trigger only when command prefix is given - ['dev']={'chat-bot.not-real-dev'}, - ['blame']=function(player) - local names = {'Cooldude2606','arty714','badgamernl', 'mark9064', 'aldldl', 'Drahc_pro',player.name} - for _,next_player in pairs(game.connected_players) do + ['dev'] = {'chat-bot.not-real-dev'}, + ['blame'] = function(player) + local names = {'Cooldude2606', 'arty714', 'badgamernl', 'mark9064', 'aldldl', 'Drahc_pro', player.name} + for _, next_player in pairs(game.connected_players) do names[#names + 1] = next_player.name end - return {'chat-bot.blame',table.get_random_dictionary_entry(names)} + return {'chat-bot.blame', table.get_random_dictionary_entry(names)} end, - ['magic']={'chat-bot.magic'}, - ['aids']={'chat-bot.aids'}, - ['riot']={'chat-bot.riot'}, - ['lenny']={'chat-bot.lenny'}, - ['hodor']=function() - local options = {'?','.','!','!!!'} - return {'chat-bot.hodor',table.get_random_dictionary_entry(options)} + ['magic'] = {'chat-bot.magic'}, + ['aids'] = {'chat-bot.aids'}, + ['riot'] = {'chat-bot.riot'}, + ['lenny'] = {'chat-bot.lenny'}, + ['hodor'] = function() + local options = {'?', '.', '!', '!!!'} + return {'chat-bot.hodor', table.get_random_dictionary_entry(options)} end, - ['evolution']=function() - return {'chat-bot.current-evolution',string.format('%.2f',game.forces['enemy'].evolution_factor)} + ['evolution'] = function() + return {'chat-bot.current-evolution', string.format('%.2f', game.forces['enemy'].evolution_factor)} end, - ['makepopcorn']=function(player) + ['makepopcorn'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.get-popcorn-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.get-popcorn-2',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.get-popcorn-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.get-popcorn-2', player.name}}) end, - ['passsomesnaps']=function(player) + ['passsomesnaps'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.get-snaps-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.get-snaps-2',player.name}}) - Async.wait(timeout*(math.random()+0.5),async_message,player,{'chat-bot.reply',{'chat-bot.get-snaps-3',player.name}}) + Async(async_message, player, {'chat-bot.reply', {'chat-bot.get-snaps-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.get-snaps-2', player.name}}) + Async.wait(timeout*(math.random()+0.5), async_message, true, {'chat-bot.reply', {'chat-bot.get-snaps-3', player.name}}) end, - ['makecocktail']=function(player) + ['makecocktail'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.get-cocktail-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.get-cocktail-2',player.name}}) - Async.wait(timeout*(math.random()+0.5),async_message,player,{'chat-bot.reply',{'chat-bot.get-cocktail-3',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.get-cocktail-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.get-cocktail-2', player.name}}) + Async.wait(timeout*(math.random()+0.5), async_message, true, {'chat-bot.reply', {'chat-bot.get-cocktail-3', player.name}}) end, - ['makecoffee']=function(player) + ['makecoffee'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.make-coffee-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.make-coffee-2',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.make-coffee-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.make-coffee-2', player.name}}) end, - ['orderpizza']=function(player) + ['orderpizza'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.order-pizza-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.order-pizza-2',player.name}}) - Async.wait(timeout*(math.random()+0.5),async_message,player,{'chat-bot.reply',{'chat-bot.order-pizza-3',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.order-pizza-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.order-pizza-2', player.name}}) + Async.wait(timeout*(math.random()+0.5), async_message, true, {'chat-bot.reply', {'chat-bot.order-pizza-3', player.name}}) end, - ['maketea']=function(player) + ['maketea'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.make-tea-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.make-tea-2',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.make-tea-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.make-tea-2', player.name}}) end, - ['meadplease']=function(player) + ['meadplease'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.get-mead-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.get-mead-2',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.get-mead-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.get-mead-2', player.name}}) end, - ['passabeer']=function(player) + ['passabeer'] = function(player) local timeout = math.floor(180*(math.random()+0.5)) - Async(async_message,player,{'chat-bot.reply',{'chat-bot.get-beer-1'}}) - Async.wait(timeout,async_message,player,{'chat-bot.reply',{'chat-bot.get-beer-2',player.name}}) + Async(async_message, true, {'chat-bot.reply', {'chat-bot.get-beer-1'}}) + Async.wait(timeout, async_message, true, {'chat-bot.reply', {'chat-bot.get-beer-2', player.name}}) end } } diff --git a/config/expcore/command_auth_admin.lua b/config/expcore/command_auth_admin.lua index 5f2b872391..360e6ee8c7 100644 --- a/config/expcore/command_auth_admin.lua +++ b/config/expcore/command_auth_admin.lua @@ -1,11 +1,12 @@ ---- This is a very simple config file which adds a admin only auth functio; +--- This is a very simple config file which adds a admin only auth function; -- not much to change here its more so it can be enabled and disabled from ./config/file_loader.lua; -- either way you can change the requirements to be "admin" if you wanted to -- @config Commands-Auth-Admin local Commands = require 'expcore.commands' --- @dep expcore.commands -Commands.add_authenticator(function(player,command,tags,reject) +-- luacheck:ignore 212/command +Commands.add_authenticator(function(player, command, tags, reject) if tags.admin_only then if player.admin then return true diff --git a/config/expcore/command_auth_roles.lua b/config/expcore/command_auth_roles.lua index cb7e0db9a6..3fb6f968cc 100644 --- a/config/expcore/command_auth_roles.lua +++ b/config/expcore/command_auth_roles.lua @@ -4,7 +4,8 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands local Roles = require 'expcore.roles' --- @dep expcore.roles -Commands.add_authenticator(function(player,command,tags,reject) +-- luacheck:ignore 212/tags +Commands.add_authenticator(function(player, command, tags, reject) if Roles.player_allowed(player,'command/'..command) then return true else diff --git a/config/expcore/command_general_parse.lua b/config/expcore/command_general_parse.lua index 7b9e282a32..2cc88b7345 100644 --- a/config/expcore/command_general_parse.lua +++ b/config/expcore/command_general_parse.lua @@ -1,7 +1,7 @@ --[[-- This file contains some common command param parse functions; this file is less of a config and more of a requirement but you may wish to change how some behave; as such you need to be confident with lua but you edit this config file; -use Commands.add_parse('name',function(input,player,reject) end) to add a parse; +use Commands.add_parse('name',function(input, player, reject) end) to add a parse; see ./expcore/commands.lua for more details @config Commands-Parse @usage Adds Parses: @@ -20,11 +20,9 @@ see ./expcore/commands.lua for more details ]] local Commands = require 'expcore.commands' --- @dep expcore.commands -local Game = require 'utils.game' --- @dep utils.game - - -Commands.add_parse('boolean',function(input,player,reject) +-- luacheck:ignore 212/player +Commands.add_parse('boolean',function(input, player) if not input then return end -- nil check input = input:lower() if input == 'yes' @@ -37,18 +35,13 @@ Commands.add_parse('boolean',function(input,player,reject) end end) -Commands.add_parse('string-options',function(input,player,reject,options) +Commands.add_parse('string-options',function(input, player, reject, options) if not input then return end -- nil check - input = input:lower() - for option in options do - if input == option:lower() then - return true - end - end - return reject{'reject-string-options',options:concat(', ')} + local option = _C.auto_complete(options, input) + return option or reject{'expcore-commands.reject-string-options', table.concat(options, ', ')} end) -Commands.add_parse('string-max-length',function(input,player,reject,max_length) +Commands.add_parse('string-max-length',function(input, player, reject, max_length) if not input then return end -- nil check local length = input:len() if length > max_length then @@ -58,7 +51,7 @@ Commands.add_parse('string-max-length',function(input,player,reject,max_length) end end) -Commands.add_parse('number',function(input,player,reject) +Commands.add_parse('number',function(input, player, reject) if not input then return end -- nil check local number = tonumber(input) if not number then @@ -68,7 +61,7 @@ Commands.add_parse('number',function(input,player,reject) end end) -Commands.add_parse('integer',function(input,player,reject) +Commands.add_parse('integer',function(input, player, reject) if not input then return end -- nil check local number = tonumber(input) if not number then @@ -78,29 +71,29 @@ Commands.add_parse('integer',function(input,player,reject) end end) -Commands.add_parse('number-range',function(input,player,reject,range_min,range_max) - local number = Commands.parse('number',input,player,reject) +Commands.add_parse('number-range',function(input, player, reject, range_min, range_max) + local number = Commands.parse('number',input, player, reject) if not number then return end -- nil check if number < range_min or number > range_max then - return reject{'expcore-commands.reject-number-range',range_min,range_max} + return reject{'expcore-commands.reject-number-range',range_min, range_max} else return number end end) -Commands.add_parse('integer-range',function(input,player,reject,range_min,range_max) - local number = Commands.parse('integer',input,player,reject) +Commands.add_parse('integer-range',function(input, player, reject, range_min, range_max) + local number = Commands.parse('integer',input, player, reject) if not number then return end -- nil check if number < range_min or number > range_max then - return reject{'expcore-commands.reject-number-range',range_min,range_max} + return reject{'expcore-commands.reject-number-range',range_min, range_max} else return number end end) -Commands.add_parse('player',function(input,player,reject) +Commands.add_parse('player',function(input, player, reject) if not input then return end -- nil check - local input_player = Game.get_player_from_any(input) + local input_player = game.players[input] if not input_player then return reject{'expcore-commands.reject-player',input} else @@ -108,8 +101,8 @@ Commands.add_parse('player',function(input,player,reject) end end) -Commands.add_parse('player-online',function(input,player,reject) - local input_player = Commands.parse('player',input,player,reject) +Commands.add_parse('player-online',function(input, player, reject) + local input_player = Commands.parse('player',input, player, reject) if not input_player then return end -- nil check if not input_player.connected then return reject{'expcore-commands.reject-player-online'} @@ -118,8 +111,8 @@ Commands.add_parse('player-online',function(input,player,reject) end end) -Commands.add_parse('player-alive',function(input,player,reject) - local input_player = Commands.parse('player-online',input,player,reject) +Commands.add_parse('player-alive',function(input, player, reject) + local input_player = Commands.parse('player-online',input, player, reject) if not input_player then return end -- nil check if not input_player.character or not input_player.character.health or input_player.character.health <= 0 then return reject{'expcore-commands.reject-player-alive'} @@ -128,7 +121,7 @@ Commands.add_parse('player-alive',function(input,player,reject) end end) -Commands.add_parse('force',function(input,player,reject) +Commands.add_parse('force',function(input, player, reject) if not input then return end -- nil check local force = game.forces[input] if not force then @@ -138,7 +131,7 @@ Commands.add_parse('force',function(input,player,reject) end end) -Commands.add_parse('surface',function(input,player,reject) +Commands.add_parse('surface',function(input, player, reject) if not input then return end local surface = game.surfaces[input] if not surface then diff --git a/config/expcore/command_role_parse.lua b/config/expcore/command_role_parse.lua index 12e76bbc51..9faabf94a7 100644 --- a/config/expcore/command_role_parse.lua +++ b/config/expcore/command_role_parse.lua @@ -12,14 +12,15 @@ local Roles = require 'expcore.roles' --- @dep expcore.roles local auto_complete = _C.auto_complete --- @dep expcore.common require 'config.expcore.command_general_parse' -Commands.add_parse('role',function(input,player,reject) +-- luacheck:ignore 212/player +Commands.add_parse('role',function(input, player, reject) if not input then return end local roles = Roles.config.order local rev_roles = {} - for i=#roles,1,-1 do - table.insert(rev_roles,roles[i]) + for i=#roles, 1,-1 do + table.insert(rev_roles, roles[i]) end - local role = auto_complete(rev_roles,input) + local role = auto_complete(rev_roles, input) role = Roles.get_role_by_name(role) if not role then return reject{'expcore-role.reject-role'} @@ -28,8 +29,8 @@ Commands.add_parse('role',function(input,player,reject) end end) -Commands.add_parse('player-role',function(input,player,reject) - local input_player = Commands.parse('player',input,player,reject) +Commands.add_parse('player-role',function(input, player, reject) + local input_player = Commands.parse('player',input, player, reject) if not input_player then return end -- nil check local player_highest = Roles.get_player_highest_role(player) local input_player_highest = Roles.get_player_highest_role(input_player) @@ -40,14 +41,14 @@ Commands.add_parse('player-role',function(input,player,reject) end end) -Commands.add_parse('player-role-online',function(input,player,reject) - local input_player = Commands.parse('player-role',input,player,reject) +Commands.add_parse('player-role-online',function(input, player, reject) + local input_player = Commands.parse('player-role',input, player, reject) if not input_player then return end -- nil check - return Commands.parse('player-online',input_player,player,reject) + return Commands.parse('player-online',input_player.name, player, reject) end) -Commands.add_parse('player-role-alive',function(input,player,reject) - local input_player = Commands.parse('player-role',input,player,reject) +Commands.add_parse('player-role-alive',function(input, player, reject) + local input_player = Commands.parse('player-role',input, player, reject) if not input_player then return end -- nil check - return Commands.parse('player-alive',input_player,player,reject) + return Commands.parse('player-alive',input_player.name, player, reject) end) \ No newline at end of file diff --git a/config/expcore/command_runtime_disable.lua b/config/expcore/command_runtime_disable.lua index 204869f576..1d6cde0334 100644 --- a/config/expcore/command_runtime_disable.lua +++ b/config/expcore/command_runtime_disable.lua @@ -6,7 +6,7 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands local Global = require 'utils.global' --- @dep utils.global local disabled_commands = {} -Global.register(disabled_commands,function(tbl) +Global.register(disabled_commands, function(tbl) disabled_commands = tbl end) @@ -22,7 +22,8 @@ function Commands.enable(command_name) disabled_commands[command_name] = nil end -Commands.add_authenticator(function(player,command,tags,reject) +-- luacheck:ignore 212/player 212/tags +Commands.add_authenticator(function(player, command, tags, reject) if disabled_commands[command] then return reject{'command-auth.command-disabled'} else diff --git a/config/expcore/permission_groups.lua b/config/expcore/permission_groups.lua index 6a78e02648..2e893e77fa 100644 --- a/config/expcore/permission_groups.lua +++ b/config/expcore/permission_groups.lua @@ -5,7 +5,6 @@ -- @config Permission-Groups --local Event = require 'utils.event' -- @dep utils.event ---local Game = require 'utils.game' -- @dep utils.game local Permission_Groups = require 'expcore.permission_groups' --- @dep expcore.permission_groups Permission_Groups.new_group('Admin') @@ -120,17 +119,17 @@ local function assign_group(player) end Event.add(defines.events.on_player_joined_game,function(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] assign_group(player) end) Event.add(defines.events.on_player_promoted,function(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] assign_group(player) end) Event.add(defines.events.on_player_demoted,function(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] assign_group(player) end) diff --git a/config/expcore/roles.lua b/config/expcore/roles.lua index 763fd13272..df05955963 100644 --- a/config/expcore/roles.lua +++ b/config/expcore/roles.lua @@ -49,6 +49,7 @@ Roles.new_role('Administrator','Admin') :allow{ 'gui/warp-list/bypass-cooldown', 'gui/warp-list/bypass-proximity', + 'command/connect-all', } Roles.new_role('Moderator','Mod') @@ -75,6 +76,7 @@ Roles.new_role('Moderator','Mod') 'command/home-set', 'command/home-get', 'command/return', + 'command/connect-player', 'gui/rocket-info/toggle-active', 'gui/rocket-info/remote_launch', 'fast-tree-decon', @@ -140,7 +142,7 @@ Roles.new_role('Sponsor','Spon') 'command/home-set', 'command/home-get', 'command/return', - 'fast-tree-decon', + 'fast-tree-decon' } Roles.new_role('Supporter','Sup') @@ -150,7 +152,8 @@ Roles.new_role('Supporter','Sup') :set_parent('Veteran') :allow{ 'command/jail', - 'command/unjail' + 'command/unjail', + 'command/join-message' } Roles.new_role('Partner','Part') @@ -185,7 +188,8 @@ Roles.new_role('Member','Mem') 'gui/task-list/add', 'gui/task-list/edit', 'gui/warp-list/add', - 'gui/warp-list/edit' + 'gui/warp-list/edit', + 'command/save-quickbar' } Roles.new_role('Regular','Reg') @@ -218,6 +222,10 @@ local default = Roles.new_role('Guest','') 'command/report', 'command/ratio', 'command/server-ups', + 'command/save-data', + 'command/preference', + 'command/set-preference', + 'command/connect', 'gui/player-list', 'gui/rocket-info', 'gui/science-info', diff --git a/config/gui/player_list_actions.lua b/config/gui/player_list_actions.lua index 1bd19bbfd7..2d956e94ce 100644 --- a/config/gui/player_list_actions.lua +++ b/config/gui/player_list_actions.lua @@ -7,19 +7,15 @@ local Gui = require 'expcore.gui' --- @dep expcore.gui local Roles = require 'expcore.roles' --- @dep expcore.roles -local Store = require 'expcore.store' --- @dep expcore.store -local Game = require 'utils.game' --- @dep utils.game local Reports = require 'modules.control.reports' --- @dep modules.control.reports local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings local Jail = require 'modules.control.jail' --- @dep modules.control.jail local Colors = require 'utils.color_presets' --- @dep utils.color_presets local format_chat_player_name = _C.format_chat_player_name --- @dep expcore.common -local selected_player_store = '' -local selected_action_store = '' -local function set_store_uids(player,action) - selected_player_store = player - selected_action_store = action +local SelectedPlayer, SelectedAction +local function set_datastores(player, action) + SelectedPlayer, SelectedAction = player, action end -- auth that will only allow when on player's of lower roles @@ -33,13 +29,13 @@ end -- gets the action player and a coloured name for the action to be used on local function get_action_player_name(player) - local selected_player_name = Store.get(selected_player_store,player) - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player_name = SelectedPlayer:get(player) + local selected_player = game.players[selected_player_name] local selected_player_color = format_chat_player_name(selected_player) return selected_player_name, selected_player_color end --- telports one player to another +-- teleports one player to another local function teleport(from_player,to_player) local surface = to_player.surface local position = surface.find_non_colliding_position('character',to_player.position,32,1) @@ -67,7 +63,7 @@ end local goto_player = new_button('utility/export',{'player-list.goto-player'}) :on_click(function(player) local selected_player_name = get_action_player_name(player) - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player = game.players[selected_player_name] if not player.character or not selected_player.character then player.print({'expcore-commands.reject-player-alive'},Colors.orange_red) else @@ -80,7 +76,7 @@ end) local bring_player = new_button('utility/import',{'player-list.bring-player'}) :on_click(function(player) local selected_player_name = get_action_player_name(player) - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player = game.players[selected_player_name] if not player.character or not selected_player.character then player.print({'expcore-commands.reject-player-alive'},Colors.orange_red) else @@ -93,7 +89,7 @@ end) local kill_player = new_button('utility/too_far',{'player-list.kill-player'}) :on_click(function(player) local selected_player_name = get_action_player_name(player) - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player = game.players[selected_player_name] if selected_player.character then selected_player.character.die() else @@ -109,7 +105,7 @@ local report_player = new_button('utility/spawn_flag',{'player-list.report-playe if Reports.is_reported(selected_player_name,player.name) then player.print({'expcom-report.already-reported'},Colors.orange_red) else - Store.set(selected_action_store,player,'command/report') + SelectedAction:set(player, 'command/report') end end) @@ -125,7 +121,7 @@ end -- @element warn_player local warn_player = new_button('utility/spawn_flag',{'player-list.warn-player'}) :on_click(function(player) - Store.set(selected_action_store,player,'command/give-warning') + SelectedAction:set(player, 'command/give-warning') end) local function warn_player_callback(player,reason) @@ -143,7 +139,7 @@ local jail_player = new_button('utility/multiplayer_waiting_icon',{'player-list. if Jail.is_jailed(selected_player_name) then player.print({'expcom-jail.already-jailed', selected_player_color},Colors.orange_red) else - Store.set(selected_action_store,player,'command/jail') + SelectedAction:set(player, 'command/jail') end end) @@ -162,7 +158,7 @@ local temp_ban_player = new_button('utility/warning_white',{'player-list.temp-ba if Jail.is_jailed(selected_player_name) then player.print({'expcom-jail.already-banned', selected_player_color},Colors.orange_red) else - Store.set(selected_action_store,player,'command/temp-ban') + SelectedAction:set(player, 'command/temp-ban') end end) @@ -177,7 +173,7 @@ end -- @element kick_player local kick_player = new_button('utility/warning_icon',{'player-list.kick-player'}) :on_click(function(player) - Store.set(selected_action_store,player,'command/kick') + SelectedAction:set(player, 'command/kick') end) local function kick_player_callback(player,reason) @@ -189,7 +185,7 @@ end -- @element ban_player local ban_player = new_button('utility/danger_icon',{'player-list.ban-player'}) :on_click(function(player) - Store.set(selected_action_store,player,'command/ban') + SelectedAction:set(player, 'command/ban') end) local function ban_player_callback(player,reason) @@ -198,7 +194,7 @@ local function ban_player_callback(player,reason) end return { - set_store_uids = set_store_uids, + set_datastores = set_datastores, buttons = { ['command/teleport'] = { auth=function(player,selected_player) diff --git a/config/gui/warps.lua b/config/gui/warps.lua index d1710ba8c9..3e8b272b06 100644 --- a/config/gui/warps.lua +++ b/config/gui/warps.lua @@ -10,7 +10,7 @@ return { -- Warp cooldowns bypass_warp_cooldown = 'expcore.roles', --- @setting bypass_warp_cooldown dictates who the warp cooldown is applied to; values: all, admin, expcore.roles, none expcore_roles_bypass_warp_cooldown = 'gui/warp-list/bypass-cooldown', --- @setting expcore_roles_bypass_warp_cooldown if expcore.roles is used then this is the required permission - cooldown_duraction = 60, --- @setting cooldown_duraction the duration of the warp cooldown in seconds + cooldown_duration = 60, --- @setting cooldown_duration the duration of the warp cooldown in seconds -- Warp proximity bypass_warp_proximity = 'expcore.roles', --- @setting bypass_warp_proximity dictates who the warp proximity is applied to; values: all, admin, expcore.roles, none diff --git a/config/preset_player_quickbar.lua b/config/preset_player_quickbar.lua new file mode 100644 index 0000000000..de0ea7effa --- /dev/null +++ b/config/preset_player_quickbar.lua @@ -0,0 +1,6 @@ +--- Preset quickbar items that players can load +-- @config Preset-Player-Quickbar + +return { + dangerarea = {"transport-belt", "underground-belt", "splitter", "pipe", "pipe-to-ground", "inserter", "fast-inserter", "long-handed-inserter", "stack-inserter", "roboport", "small-electric-pole", "medium-electric-pole", "big-electric-pole", "substation", nil, "rail", "rail-signal", "rail-chain-signal", "landfill", "cliff-explosives", "fast-transport-belt", "fast-underground-belt", "fast-splitter", "pipe", "pipe-to-ground", "fast-inserter", "long-handed-inserter", "stack-inserter", "stack-filter-inserter", "roboport", [81] = "red-wire", [82] = "green-wire", [83] = "arithmetic-combinator", [84] = "decider-combinator", [85] = "constant-combinator", [86] = "power-switch", [91] = "logistic-chest-active-provider", [92] = "logistic-chest-passive-provider", [93] = "logistic-chest-storage", [94] = "logistic-chest-buffer", [95] = "logistic-chest-requester", [96] = "roboport"} +} diff --git a/config/statistics.lua b/config/statistics.lua new file mode 100644 index 0000000000..856af59d4d --- /dev/null +++ b/config/statistics.lua @@ -0,0 +1,46 @@ +--- A list of all tracked statistics and the events which trigger them +-- @config Statistics + +local e = defines.events -- order as per lua api as it was easier just to go down the list +return { + Playtime = true, --- @setting Playtime If playtime is tracked for a player, play time measured in minutes + AfkTime = true, --- @setting AfkTime If afk time is tracked for a player, play time measured in minutes, afk is once a player does nothing for 5 minutes + DistanceTravelled = true, --- @setting DistanceTravelled If distance Travelled is checked, only counts if not afk + MachinesRemoved = true, --- @setting MachinesRemoved If removed machines are tracked, includes marked for decon and player mined entity + TreesDestroyed = true, --- @setting OreMined If ore mined is tracked for a player, includes marked for decon and player mined entity but only trees + OreMined = true, --- @setting OreMined If ore mined is tracked for a player, includes player mined entity but only ore + DamageDealt = true, --- @setting DamageDealt If damage dealt is tracked for a player, includes any damage to entities not on the same force or neutral + Kills = true, --- @setting Kills If kills are tracked for a player, includes all kills not on same force or neutral + RocketsLaunched = true, --- @setting RocketsLaunched If the number of rockets launched should be tracked, done for all players on the force + ResearchCompleted = true, --- @setting ResearchCompleted If the number of researches completed should be tracked, done for all players on the force + counters = { --- @setting counters Simple statistics that just go up by one each time an event happens + MachinesBuilt = e.on_built_entity, + MapTagsMade = e.on_chart_tag_added, + ChatMessages = e.on_console_chat, + CommandsUsed = e.on_console_command, + ItemsPickedUp = e.on_picked_up_item, + TilesBuilt = e.on_player_built_tile, + ItemsCrafted = e.on_player_crafted_item, + MapsPlayed = e.on_player_created, + DeconstructionPlannerUsed = e.on_player_deconstructed_area, + Deaths = e.on_player_died, + JoinCount = e.on_player_joined_game, + TilesRemoved = e.on_player_mined_tile, + CapsulesUsed = e.on_player_used_capsule, + EntityRepaired= e.on_player_repaired_entity + }, + display_order = { --- @setting display_order The order that the statistics should be shown in when in a gui or command + 'Playtime', 'AfkTime', + 'MapsPlayed', 'JoinCount', + 'ChatMessages', 'CommandsUsed', + 'RocketsLaunched', 'ResearchCompleted', + 'MachinesBuilt', 'MachinesRemoved', + 'TilesBuilt', 'TilesRemoved', + 'TreesDestroyed', 'OreMined', + 'ItemsCrafted', 'ItemsPickedUp', + 'Kills', 'Deaths', + 'DamageDealt', 'DistanceTravelled', + 'CapsulesUsed', 'EntityRepaired', + 'DeconstructionPlannerUsed', 'MapTagsMade', + } +} \ No newline at end of file diff --git a/control.lua b/control.lua index 7856526966..ea6df602b1 100644 --- a/control.lua +++ b/control.lua @@ -22,23 +22,23 @@ log('[INFO] Getting file loader config') local files = require 'config._file_loader' --- @dep config._file_loader -- Loads all files from the config and logs that they are loaded -local total_file_count = string.format('%3d',#files) +local total_file_count = string.format('%3d', #files) local errors = {} -for index,path in pairs(files) do +for index, path in pairs(files) do -- Loads the next file in the list - log(string.format('[INFO] Loading file %3d/%s (%s)',index,total_file_count,path)) - local success,file = pcall(require,path) + log(string.format('[INFO] Loading file %3d/%s (%s)', index, total_file_count, path)) + local success, file = pcall(require, path) -- Error Checking if not success then -- Failed to load a file log('[ERROR] Failed to load file: '..path) - table.insert(errors,'[ERROR] '..path..' :: '..file) + table.insert(errors, '[ERROR] '..path..' :: '..file) elseif type(file) == 'string' and file:find('not found') then -- Returned a file not found message log('[ERROR] File not found: '..path) - table.insert(errors,'[ERROR] '..path..' :: Not Found') + table.insert(errors, '[ERROR] '..path..' :: Not Found') end end @@ -49,5 +49,5 @@ require 'overrides.require' -- Logs all errors again to make it make it easy to find log('[INFO] All files loaded with '..#errors..' errors:') -for _,error in pairs(errors) do log(error) end +for _, error in pairs(errors) do log(error) end log('[END] -----| Explosive Gaming Scenario Loader |-----') \ No newline at end of file diff --git a/docs/addons/Advanced-Start.html b/docs/addons/Advanced-Start.html index 1d7173181d..535e9bfd8a 100644 --- a/docs/addons/Advanced-Start.html +++ b/docs/addons/Advanced-Start.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -243,9 +259,6 @@

Dependencies

utils.event - utils.game - - config.advanced_start @@ -275,31 +288,6 @@

Depend - - - - - - - -
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -347,7 +335,7 @@

Depend generated by LDoc

diff --git a/docs/addons/Chat-Popups.html b/docs/addons/Chat-Popups.html index 7f17c3a964..3f44253630 100644 --- a/docs/addons/Chat-Popups.html +++ b/docs/addons/Chat-Popups.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -348,7 +364,7 @@

Depend generated by LDoc diff --git a/docs/addons/Chat-Reply.html b/docs/addons/Chat-Reply.html index d7927bc851..6db112aefc 100644 --- a/docs/addons/Chat-Reply.html +++ b/docs/addons/Chat-Reply.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -220,7 +236,7 @@

Jump to Section

Chat-Reply addon

-

Adds auto replies to chat messages; aswell as chat commands

+

Adds auto replies to chat messages; as well as chat commands

@@ -243,9 +259,6 @@

Dependencies

utils.event - utils.game - - expcore.roles @@ -278,31 +291,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -375,7 +363,7 @@

Depend generated by LDoc

diff --git a/docs/addons/Compilatron.html b/docs/addons/Compilatron.html index 5b569aae9a..bda49f7a7f 100644 --- a/docs/addons/Compilatron.html +++ b/docs/addons/Compilatron.html @@ -57,9 +57,8 @@

Addons

- + - @@ -73,10 +72,12 @@

Core

+ + + - @@ -110,12 +111,25 @@

Guis

+ @@ -187,8 +203,8 @@

Modules

@@ -248,9 +264,6 @@

Dependencies

utils.global - utils.game - - utils.task @@ -327,31 +340,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -483,7 +471,7 @@

Functionsstring) - the name of the location that the complitron is at + the name of the location that the compilatron is at @@ -584,7 +572,7 @@

Functionsgenerated by LDoc

diff --git a/docs/addons/Damage-Popups.html b/docs/addons/Damage-Popups.html index 48df3a68b1..003e30f872 100644 --- a/docs/addons/Damage-Popups.html +++ b/docs/addons/Damage-Popups.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -348,7 +364,7 @@

Depend generated by LDoc diff --git a/docs/addons/Death-Logger.html b/docs/addons/Death-Logger.html index a7b1b93758..601263fa97 100644 --- a/docs/addons/Death-Logger.html +++ b/docs/addons/Death-Logger.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -243,9 +259,6 @@

Dependencies

utils.event - utils.game - - utils.global @@ -281,31 +294,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -403,7 +391,7 @@

Depend generated by LDoc

diff --git a/docs/addons/Discord-Alerts.html b/docs/addons/Discord-Alerts.html index 78f0bcd637..b0d5befb55 100644 --- a/docs/addons/Discord-Alerts.html +++ b/docs/addons/Discord-Alerts.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -243,9 +259,6 @@

Dependencies

utils.event - utils.game - - utils.color_presets @@ -287,31 +300,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -459,7 +447,7 @@

Depend generated by LDoc

diff --git a/docs/addons/Inventory-Clear.html b/docs/addons/Inventory-Clear.html new file mode 100644 index 0000000000..8141780079 --- /dev/null +++ b/docs/addons/Inventory-Clear.html @@ -0,0 +1,371 @@ + + + + + + + + Inventory-Clear addon + + + + + + + +
+
+ + + + + + + +
+ + + + + + + + +

Inventory-Clear addon

+

Will move players items to spawn when they are banned or kicked, option to clear on leave

+

+ + + + + + + + + + + + + +

Dependencies

+ + + + + + + + + + + + + +
utils.event
config.inventory_clear
expcore.common
+ + +
+ + +

Dependencies

+
+
+
+
+ # + utils.event +
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+ # + config.inventory_clear +
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+ # + expcore.common +
+
+
+
+ + + + + + + + + + + + + + + +
+
+ + + +
+
+
+ + + + diff --git a/docs/addons/Player-Colours.html b/docs/addons/Player-Colours.html index a9b88d406b..1e0d5afc0c 100644 --- a/docs/addons/Player-Colours.html +++ b/docs/addons/Player-Colours.html @@ -57,6 +57,7 @@

Addons

+ @@ -72,8 +73,10 @@

Core

+ + @@ -123,6 +126,7 @@

Commands

+ @@ -157,9 +161,11 @@

Configs

+ + @@ -186,8 +192,8 @@

Modules

@@ -403,7 +409,7 @@

Depend generated by LDoc diff --git a/docs/addons/Pollution-Grading.html b/docs/addons/Pollution-Grading.html index d7166cc920..0683847c44 100644 --- a/docs/addons/Pollution-Grading.html +++ b/docs/addons/Pollution-Grading.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -319,7 +335,7 @@

Depend generated by LDoc diff --git a/docs/addons/Scorched-Earth.html b/docs/addons/Scorched-Earth.html index 464c0bf397..118b6491ae 100644 --- a/docs/addons/Scorched-Earth.html +++ b/docs/addons/Scorched-Earth.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -243,9 +259,6 @@

Dependencies

utils.event - utils.game - - utils.global @@ -281,31 +294,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -403,7 +391,7 @@

Depend generated by LDoc

diff --git a/docs/addons/Spawn-Area.html b/docs/addons/Spawn-Area.html index 27174f1c39..8b40d24b95 100644 --- a/docs/addons/Spawn-Area.html +++ b/docs/addons/Spawn-Area.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -246,9 +262,6 @@

Dependencies

utils.event - utils.game - - config.spawn_area @@ -303,31 +316,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -375,7 +363,7 @@

Depend generated by LDoc

diff --git a/docs/addons/Tree-Decon.html b/docs/addons/Tree-Decon.html index 1ae7cd9409..be69c73207 100644 --- a/docs/addons/Tree-Decon.html +++ b/docs/addons/Tree-Decon.html @@ -56,9 +56,8 @@

Addons

- + - @@ -72,10 +71,12 @@

Core

+ + + - @@ -109,12 +110,25 @@

Guis

+ @@ -186,8 +202,8 @@

Modules

@@ -243,9 +259,6 @@

Dependencies

utils.event - utils.game - - utils.global @@ -278,31 +291,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -375,7 +363,7 @@

Depend generated by LDoc

diff --git a/docs/addons/greetings.html b/docs/addons/greetings.html index 88bcabfbbb..9ff8d6d787 100644 --- a/docs/addons/greetings.html +++ b/docs/addons/greetings.html @@ -57,6 +57,7 @@

Addons

+ @@ -72,8 +73,10 @@

Core

+ + @@ -123,6 +126,7 @@

Commands

+ @@ -157,9 +161,11 @@

Configs

+ + @@ -186,8 +192,8 @@

Modules

@@ -375,7 +381,7 @@

Depend generated by LDoc diff --git a/docs/commands/Admin-Chat.html b/docs/commands/Admin-Chat.html index e2928b14e2..36f3cb7a7a 100644 --- a/docs/commands/Admin-Chat.html +++ b/docs/commands/Admin-Chat.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -387,7 +403,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Bonus.html b/docs/commands/Bonus.html index b4acd3f85a..ce7bd2f04a 100644 --- a/docs/commands/Bonus.html +++ b/docs/commands/Bonus.html @@ -62,6 +62,7 @@

Commands

+ @@ -80,8 +81,10 @@

Core

+ + @@ -113,6 +116,7 @@

Addons

+ @@ -158,9 +162,11 @@

Configs

+ + @@ -187,8 +193,8 @@

Modules

@@ -499,7 +505,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Cheat-Mode.html b/docs/commands/Cheat-Mode.html index bd44f02456..f5e8e3410a 100644 --- a/docs/commands/Cheat-Mode.html +++ b/docs/commands/Cheat-Mode.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -360,7 +376,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Clear-Inventory.html b/docs/commands/Clear-Inventory.html index 8c73ddea44..13ecb39ad5 100644 --- a/docs/commands/Clear-Inventory.html +++ b/docs/commands/Clear-Inventory.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -387,7 +403,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Connect.html b/docs/commands/Connect.html new file mode 100644 index 0000000000..d1d7e4788c --- /dev/null +++ b/docs/commands/Connect.html @@ -0,0 +1,614 @@ + + + + + + + + Connect commands + + + + + + + +
+
+ + + + + + + +
+ + + + + + + + +

Connect commands

+

Commands Module - Connect + - Adds a commands that allows you to request a player move to another server

+

+ + + + + + + + + + + + + +

Dependencies

+ + + + + + + + + + + + + +
expcore.async
expcore.external
expcore.commands
+ + +

Commands

+ + + + + + + + + + + + + + + + +
connectConnect to a different server
connect-playerConnect a player to a different server
connect-allConnect all players to a different server
+ + +
+ + +

Dependencies

+
+
+
+
+ # + expcore.async +
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+ # + expcore.external +
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+ # + expcore.commands +
+
+
+
+ + + + + + + + + + + + + + + +
+
+

Commands

+
+
+
+
+ # + connect +
+
+
+
+ +

Connect to a different server

+

+ + + Command Parameters: + +
    + + + + + +
  • + + server + + : + + (string) + + The address or name of the server to connect to + +
  • + + + + + +
  • + + is_address + + : + + (boolean) + + If an address was given for the server param + + (default: false) +
  • + + +
+ + + + + + + + + + + + + +
+
+
+
+ # + connect-player +
+
+
+
+ +

Connect a player to a different server

+

+ + + Command Parameters: + +
    + + + + + +
  • + + address + + : + + (string) + + The address or name of the server to connect to + +
  • + + + + + +
  • + + player + + : + + (LuaPlayer) + + The player to connect to a different server + +
  • + + + + + +
  • + + is_address + + : + + (boolean) + + If an address was given for the server param + + (default: false) +
  • + + +
+ + + + + + + + + + + + + +
+
+
+
+ # + connect-all +
+
+
+
+ +

Connect all players to a different server

+

+ + + Command Parameters: + +
    + + + + + +
  • + + address + + : + + (string) + + The address or name of the server to connect to + +
  • + + + + + +
  • + + is_address + + : + + (boolean) + + If an address was given for the server param + + (default: false) +
  • + + +
+ + + + + + + + + + + + + +
+
+ + + +
+
+
+ + + + diff --git a/docs/commands/Debug.html b/docs/commands/Debug.html index dc8bd63005..7cf7af9a53 100644 --- a/docs/commands/Debug.html +++ b/docs/commands/Debug.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -364,7 +380,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Find.html b/docs/commands/Find.html index fa39eb7d59..b2d8c3c66e 100644 --- a/docs/commands/Find.html +++ b/docs/commands/Find.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -359,7 +375,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Help.html b/docs/commands/Help.html index 8d75f6dbfd..55d85b6d5d 100644 --- a/docs/commands/Help.html +++ b/docs/commands/Help.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -403,7 +419,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Home.html b/docs/commands/Home.html index 512a2ee638..200237e777 100644 --- a/docs/commands/Home.html +++ b/docs/commands/Home.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -457,7 +473,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Interface.html b/docs/commands/Interface.html index 2f43cbd69b..3f6ab5ebed 100644 --- a/docs/commands/Interface.html +++ b/docs/commands/Interface.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -248,9 +264,6 @@

Dependencies

utils.global - - expcore.common - @@ -261,7 +274,7 @@

Commands

- +
interfaceSends an innovation to be ran and returns the result.Sends an invocation to be ran and returns the result.
@@ -315,31 +328,6 @@

Depend - - - - - - -

-
-
-
- # - expcore.common -
-
-
-
- - - - - - - - - @@ -360,7 +348,7 @@

Commands
-

Sends an innovation to be ran and returns the result.

+

Sends an invocation to be ran and returns the result.

@@ -374,7 +362,7 @@

Commands - innovation + invocation : @@ -415,7 +403,7 @@

Commandsgenerated by LDoc

diff --git a/docs/commands/Jail.html b/docs/commands/Jail.html index f7cdeb46a4..3e1719ab1d 100644 --- a/docs/commands/Jail.html +++ b/docs/commands/Jail.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -610,7 +626,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Kill.html b/docs/commands/Kill.html index 085d3e433d..043d511c2a 100644 --- a/docs/commands/Kill.html +++ b/docs/commands/Kill.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -388,7 +404,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Me.html b/docs/commands/Me.html index c8286186d1..4f483e18c6 100644 --- a/docs/commands/Me.html +++ b/docs/commands/Me.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -359,7 +375,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Quickbar.html b/docs/commands/Quickbar.html new file mode 100644 index 0000000000..46575536fd --- /dev/null +++ b/docs/commands/Quickbar.html @@ -0,0 +1,409 @@ + + + + + + + + Quickbar commands + + + + + + + +
+
+ + + + + + + +
+ + + + + + + + +

Quickbar commands

+

Commands Module - Quickbar + - Adds a command that allows players to load Quickbar presets

+

+ + + + + + + + + + + + + +

Dependencies

+ + + + + + + + + + +
expcore.commands
config.preset_player_quickbar
+ + +

Commands

+ + + + + + + + + + + + +
load-quickbarLoads your quickbar preset
save-quickbarSaves your quickbar preset to the script-output folder
+ + +
+ + +

Dependencies

+
+
+
+
+ # + expcore.commands +
+
+
+
+ + + + + + + + + + + + + + + +
+
+
+
+ # + config.preset_player_quickbar +
+
+
+
+ + + + + + + + + + + + + + + +
+
+

Commands

+
+
+
+
+ # + load-quickbar +
+
+
+
+ +

Loads your quickbar preset

+

+ + + + + + + + + + + + + + +
+
+
+
+ # + save-quickbar +
+
+
+
+ +

Saves your quickbar preset to the script-output folder

+

+ + + + + + + + + + + + + + +
+
+ + + +
+
+
+ + + + diff --git a/docs/commands/Rainbow.html b/docs/commands/Rainbow.html index 38c038a6fc..e18bab98e8 100644 --- a/docs/commands/Rainbow.html +++ b/docs/commands/Rainbow.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -387,7 +403,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Repair.html b/docs/commands/Repair.html index 0a156f7b7d..2a80c50075 100644 --- a/docs/commands/Repair.html +++ b/docs/commands/Repair.html @@ -50,9 +50,9 @@

Sections

Commands

@@ -79,10 +78,12 @@

Core

+ + + - @@ -111,9 +112,8 @@

Addons

- + - @@ -136,6 +136,19 @@

Guis

+ @@ -320,7 +336,7 @@

Depend generated by LDoc diff --git a/docs/commands/Reports.html b/docs/commands/Reports.html index 88e9d0d0fd..2dc4b1607b 100644 --- a/docs/commands/Reports.html +++ b/docs/commands/Reports.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -584,7 +600,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Roles.html b/docs/commands/Roles.html index 9ca693d659..9261bfe712 100644 --- a/docs/commands/Roles.html +++ b/docs/commands/Roles.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -556,7 +572,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Spawn.html b/docs/commands/Spawn.html index 479f275093..42a8ca98f6 100644 --- a/docs/commands/Spawn.html +++ b/docs/commands/Spawn.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -388,7 +404,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Tag.html b/docs/commands/Tag.html index c21383cd1b..976e9558d3 100644 --- a/docs/commands/Tag.html +++ b/docs/commands/Tag.html @@ -62,6 +62,7 @@

Commands

+ @@ -80,8 +81,10 @@

Core

+ + @@ -113,6 +116,7 @@

Addons

+ @@ -158,9 +162,11 @@

Configs

+ + @@ -187,8 +193,8 @@

Modules

@@ -442,7 +448,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Teleport.html b/docs/commands/Teleport.html index b343424be2..b5a24b0ab4 100644 --- a/docs/commands/Teleport.html +++ b/docs/commands/Teleport.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -483,7 +499,7 @@

Commandsgenerated by LDoc diff --git a/docs/commands/Warnings.html b/docs/commands/Warnings.html index ab2e9aed00..1acded0901 100644 --- a/docs/commands/Warnings.html +++ b/docs/commands/Warnings.html @@ -51,9 +51,9 @@

Sections

Commands

@@ -80,10 +79,12 @@

Core

+ + + - @@ -112,9 +113,8 @@

Addons

- + - @@ -137,6 +137,19 @@

Guis

+ @@ -568,7 +584,7 @@

Commandsgenerated by LDoc diff --git a/docs/config.ld b/docs/config.ld index 43e5bfdc28..68c0c7a507 100644 --- a/docs/config.ld +++ b/docs/config.ld @@ -1,4 +1,4 @@ -file = '../' +file = { '../', exclude = { '../.install', '../.lua', '../.luarocks' } } dir = '../docs' project = 'ExpGaming Scenario' title = 'ExpGaming Scenario' @@ -19,6 +19,7 @@ new_type("core", "Core", true) new_type("control", "Control", true) new_type("addon", "Addons", true) new_type("gui", "Guis", true) +new_type("data", "Data", true) new_type("commands", "Commands", true) new_type("config", "Configs", true, "Settings") diff --git a/docs/configs/Advanced-Start.html b/docs/configs/Advanced-Start.html index bb43343811..5312c2fa56 100644 --- a/docs/configs/Advanced-Start.html +++ b/docs/configs/Advanced-Start.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -364,7 +380,7 @@

Settings

-

when true the research queue is useible from the start

+

when true the research queue is useable from the start

@@ -473,7 +489,7 @@

Settings

items and there condition for being given - ['item-name'] = function(amount_made,production_stats,player) return end -- 0 means no items given + ['item-name'] = function(amount_made, production_stats, player) return end -- 0 means no items given Plates

@@ -505,7 +521,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Bonuses.html b/docs/configs/Bonuses.html index ed9c3bd197..e5d87a5159 100644 --- a/docs/configs/Bonuses.html +++ b/docs/configs/Bonuses.html @@ -60,12 +60,15 @@

Configs

+ + + @@ -77,10 +80,12 @@

Core

+ + + - @@ -109,9 +114,8 @@

Addons

- + - @@ -134,12 +138,25 @@

Guis

+ @@ -236,7 +252,7 @@

Bonuses conf generated by LDoc diff --git a/docs/configs/Chat-Reply.html b/docs/configs/Chat-Reply.html index f7c4bca2b3..5c7b01d6d5 100644 --- a/docs/configs/Chat-Reply.html +++ b/docs/configs/Chat-Reply.html @@ -69,12 +69,15 @@

Configs

+ + + @@ -86,10 +89,12 @@

Core

+ + + - @@ -118,9 +123,8 @@

Addons

- + - @@ -143,12 +147,25 @@

Guis

+ @@ -484,7 +500,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Commands-Auth-Admin.html b/docs/configs/Commands-Auth-Admin.html index 9da0f41133..2b3a8e1bd2 100644 --- a/docs/configs/Commands-Auth-Admin.html +++ b/docs/configs/Commands-Auth-Admin.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -220,7 +236,7 @@

Jump to Section

Commands-Auth-Admin config

-

This is a very simple config file which adds a admin only auth functio; +

This is a very simple config file which adds a admin only auth function; not much to change here its more so it can be enabled and disabled from ./config/file_loader.lua; either way you can change the requirements to be "admin" if you wanted to

@@ -293,7 +309,7 @@

Depend generated by LDoc diff --git a/docs/configs/Commands-Auth-Roles.html b/docs/configs/Commands-Auth-Roles.html index 477cb804cc..20eb310955 100644 --- a/docs/configs/Commands-Auth-Roles.html +++ b/docs/configs/Commands-Auth-Roles.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -319,7 +335,7 @@

Depend generated by LDoc diff --git a/docs/configs/Commands-Auth-Runtime-Disable.html b/docs/configs/Commands-Auth-Runtime-Disable.html index 1636ab351c..11984c797b 100644 --- a/docs/configs/Commands-Auth-Runtime-Disable.html +++ b/docs/configs/Commands-Auth-Runtime-Disable.html @@ -69,12 +69,15 @@

Configs

+ + + @@ -86,10 +89,12 @@

Core

+ + + - @@ -118,9 +123,8 @@

Addons

- + - @@ -143,12 +147,25 @@

Guis

+ @@ -441,7 +457,7 @@

Functionsgenerated by LDoc diff --git a/docs/configs/Commands-Parse-Roles.html b/docs/configs/Commands-Parse-Roles.html index 9d4292cacd..e62239d9a9 100644 --- a/docs/configs/Commands-Parse-Roles.html +++ b/docs/configs/Commands-Parse-Roles.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -353,7 +369,7 @@

Depend generated by LDoc diff --git a/docs/configs/Commands-Parse.html b/docs/configs/Commands-Parse.html index 234392ad35..d6317fc35d 100644 --- a/docs/configs/Commands-Parse.html +++ b/docs/configs/Commands-Parse.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -223,7 +239,7 @@

Commands-ParseThis file contains some common command param parse functions; this file is less of a config and more of a requirement but you may wish to change how some behave; as such you need to be confident with lua but you edit this config file; -use Commands.add_parse('name',function(input,player,reject) end) to add a parse; +use Commands.add_parse('name',function(input, player, reject) end) to add a parse; see ./expcore/commands.lua for more details

@@ -260,9 +276,6 @@

Dependencies

expcore.commands - - utils.game - @@ -290,31 +303,6 @@

Depend - - - - - - -

-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -337,7 +325,7 @@

Depend generated by LDoc

diff --git a/docs/configs/Compilatron.html b/docs/configs/Compilatron.html index dec0e5299c..aab7d22062 100644 --- a/docs/configs/Compilatron.html +++ b/docs/configs/Compilatron.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -353,7 +369,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Death-Logger.html b/docs/configs/Death-Logger.html index 67857decb4..7995c602f4 100644 --- a/docs/configs/Death-Logger.html +++ b/docs/configs/Death-Logger.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -415,7 +431,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Discord-Alerts.html b/docs/configs/Discord-Alerts.html index 5ea0212051..d328ccb8f7 100644 --- a/docs/configs/Discord-Alerts.html +++ b/docs/configs/Discord-Alerts.html @@ -60,12 +60,15 @@

Configs

+ + + @@ -77,10 +80,12 @@

Core

+ + + - @@ -109,9 +114,8 @@

Addons

- + - @@ -134,12 +138,25 @@

Guis

+ @@ -236,7 +252,7 @@

Discord-Alertsgenerated by LDoc diff --git a/docs/configs/File-Loader.html b/docs/configs/File-Loader.html index 3a9716cfd9..41edc429ef 100644 --- a/docs/configs/File-Loader.html +++ b/docs/configs/File-Loader.html @@ -60,12 +60,15 @@

Configs

+ + + @@ -77,10 +80,12 @@

Core

+ + + - @@ -109,9 +114,8 @@

Addons

- + - @@ -134,12 +138,25 @@

Guis

+ @@ -239,7 +255,7 @@

File-Loader generated by LDoc diff --git a/docs/configs/Permission-Groups.html b/docs/configs/Permission-Groups.html index 3abffdaa4b..6570152592 100644 --- a/docs/configs/Permission-Groups.html +++ b/docs/configs/Permission-Groups.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -294,7 +310,7 @@

Depend generated by LDoc diff --git a/docs/configs/Player-List.html b/docs/configs/Player-List.html index cfda426196..5fdf4cf245 100644 --- a/docs/configs/Player-List.html +++ b/docs/configs/Player-List.html @@ -69,12 +69,15 @@

Configs

+ + + @@ -86,10 +89,12 @@

Core

+ + + - @@ -118,9 +123,8 @@

Addons

- + - @@ -143,12 +147,25 @@

Guis

+ @@ -252,12 +268,6 @@

Dependencies

expcore.roles - expcore.store - - - utils.game - - modules.control.reports @@ -368,56 +378,6 @@

Depend - - - - - - -

-
-
-
- # - expcore.store -
-
-
-
- - - - - - - - - - - - - - - -
-
-
-
- # - utils.game -
-
-
-
- - - - - - - - - @@ -811,7 +771,7 @@

Elementsgenerated by LDoc

diff --git a/docs/configs/Pollution-Grading.html b/docs/configs/Pollution-Grading.html index 6be165c4d7..3823f6a060 100644 --- a/docs/configs/Pollution-Grading.html +++ b/docs/configs/Pollution-Grading.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -383,7 +399,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Popup-Messages.html b/docs/configs/Popup-Messages.html index 4f9f85b0dc..a8d55d5806 100644 --- a/docs/configs/Popup-Messages.html +++ b/docs/configs/Popup-Messages.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -413,7 +429,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Preset-Player-Colours.html b/docs/configs/Preset-Player-Colours.html index 723391f49b..7adb397469 100644 --- a/docs/configs/Preset-Player-Colours.html +++ b/docs/configs/Preset-Player-Colours.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -323,7 +339,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Preset-Player-Quickbar.html b/docs/configs/Preset-Player-Quickbar.html new file mode 100644 index 0000000000..1d158db02a --- /dev/null +++ b/docs/configs/Preset-Player-Quickbar.html @@ -0,0 +1,260 @@ + + + + + + + + Preset-Player-Quickbar config + + + + + + + +
+
+ + + + + + + +
+ + + + + + + + +

Preset-Player-Quickbar config

+

Preset quickbar items that players can load

+

+ + + + + + + + + + + + + +
+ + + + + +
+
+
+ + + + diff --git a/docs/configs/Repair.html b/docs/configs/Repair.html index e8582c36de..eeef92dc7e 100644 --- a/docs/configs/Repair.html +++ b/docs/configs/Repair.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -413,7 +429,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Rockets.html b/docs/configs/Rockets.html index 0db5696af6..ddad5eca07 100644 --- a/docs/configs/Rockets.html +++ b/docs/configs/Rockets.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -833,7 +849,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Roles.html b/docs/configs/Roles.html index a6816311b1..a6b6b5e745 100644 --- a/docs/configs/Roles.html +++ b/docs/configs/Roles.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -291,7 +307,7 @@

Depend generated by LDoc diff --git a/docs/configs/Science.html b/docs/configs/Science.html index 332659e6ec..a74159a3c5 100644 --- a/docs/configs/Science.html +++ b/docs/configs/Science.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -243,7 +259,7 @@

Settings

show_eta - color_clamp + color_cutoff color_flux @@ -287,15 +303,15 @@

Settings
- # - color_clamp + # + color_cutoff

-

the amount required for the text to show as green or red

+

the amount that production can fall before the text changes color

@@ -322,7 +338,7 @@

Settings

-

the ammount of flucuation allowed in production before icon change

+

the amount of fluctuation allowed in production before the icon changes color

@@ -353,7 +369,7 @@

Settingsgenerated by LDoc

diff --git a/docs/configs/Scorched-Earth.html b/docs/configs/Scorched-Earth.html index a55e5c6be0..358d6ab665 100644 --- a/docs/configs/Scorched-Earth.html +++ b/docs/configs/Scorched-Earth.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -387,7 +403,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Spawn-Area.html b/docs/configs/Spawn-Area.html index 663572130a..6e5a52ccd6 100644 --- a/docs/configs/Spawn-Area.html +++ b/docs/configs/Spawn-Area.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -743,7 +759,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Statistics.html b/docs/configs/Statistics.html new file mode 100644 index 0000000000..a7b2ec849c --- /dev/null +++ b/docs/configs/Statistics.html @@ -0,0 +1,647 @@ + + + + + + + + Statistics config + + + + + + + +
+
+ + + + + + + +
+ + + + + + + + +

Statistics config

+

A list of all tracked statistics and the events which trigger them

+

+ + + + + + + + + + + + + +

Settings

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
Playtime
AfkTime
DistanceTravelled
MachinesRemoved
OreMined
OreMined
DamageDealt
Kills
RocketsLaunched
ResearchCompleted
counters
display_order
+ + +
+ + +

Settings

+
+
+
+
+ # + Playtime +
+
+
+
+ +

+

If playtime is tracked for a player, play time measured in minutes

+ + + + + + + + + + + + + + +
+
+
+
+ # + AfkTime +
+
+
+
+ +

+

If afk time is tracked for a player, play time measured in minutes, afk is once a player does nothing for 5 minutes

+ + + + + + + + + + + + + + +
+
+
+
+ # + DistanceTravelled +
+
+
+
+ +

+

If distance Travelled is checked, only counts if not afk

+ + + + + + + + + + + + + + +
+
+
+
+ # + MachinesRemoved +
+
+
+
+ +

+

If removed machines are tracked, includes marked for decon and player mined entity

+ + + + + + + + + + + + + + +
+
+
+
+ # + OreMined +
+
+
+
+ +

+

If ore mined is tracked for a player, includes marked for decon and player mined entity but only trees

+ + + + + + + + + + + + + + +
+
+
+
+ # + OreMined +
+
+
+
+ +

+

If ore mined is tracked for a player, includes player mined entity but only ore

+ + + + + + + + + + + + + + +
+
+
+
+ # + DamageDealt +
+
+
+
+ +

+

If damage dealt is tracked for a player, includes any damage to entities not on the same force or neutral

+ + + + + + + + + + + + + + +
+
+
+
+ # + Kills +
+
+
+
+ +

+

If kills are tracked for a player, includes all kills not on same force or neutral

+ + + + + + + + + + + + + + +
+
+
+
+ # + RocketsLaunched +
+
+
+
+ +

+

If the number of rockets launched should be tracked, done for all players on the force

+ + + + + + + + + + + + + + +
+
+
+
+ # + ResearchCompleted +
+
+
+
+ +

+

If the number of researches completed should be tracked, done for all players on the force

+ + + + + + + + + + + + + + +
+
+
+
+ # + counters +
+
+
+
+ +

+

Simple statistics that just go up by one each time an event happens

+ + + + + + + + + + + + + + +
+
+
+
+ # + display_order +
+
+
+
+ +

+

The order that the statistics should be shown in when in a gui or command

+ + + + + + + + + + + + + + +
+
+ + + +
+
+
+ + + + diff --git a/docs/configs/Tasks.html b/docs/configs/Tasks.html index f3bf9416cd..9194d7c8a0 100644 --- a/docs/configs/Tasks.html +++ b/docs/configs/Tasks.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -383,7 +399,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Warnings.html b/docs/configs/Warnings.html index 77d8481edf..c306d3f151 100644 --- a/docs/configs/Warnings.html +++ b/docs/configs/Warnings.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -354,7 +370,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/Warps.html b/docs/configs/Warps.html index 81f0ffecfb..8215cf4c5b 100644 --- a/docs/configs/Warps.html +++ b/docs/configs/Warps.html @@ -68,12 +68,15 @@

Configs

+ + + @@ -85,10 +88,12 @@

Core

+ + + - @@ -117,9 +122,8 @@

Addons

- + - @@ -142,12 +146,25 @@

Guis

+ @@ -255,7 +271,7 @@

Settings

expcore_roles_bypass_warp_cooldown - cooldown_duraction + cooldown_duration bypass_warp_proximity @@ -437,8 +453,8 @@

Settings
- # - cooldown_duraction + # + cooldown_duration
@@ -773,7 +789,7 @@

Settingsgenerated by LDoc diff --git a/docs/configs/inventory_clear.html b/docs/configs/inventory_clear.html new file mode 100644 index 0000000000..bec18e6f6a --- /dev/null +++ b/docs/configs/inventory_clear.html @@ -0,0 +1,260 @@ + + + + + + + + inventory_clear config + + + + + + + +
+
+ + + + + + + +
+ + + + + + + + +

inventory_clear config

+

Config to control when players items are removed, this is a list of event names that will trigger inventory clear

+

+ + + + + + + + + + + + + +
+ + + + + +
+
+
+ + + + diff --git a/docs/control/Jail.html b/docs/control/Jail.html index f66c278913..18ae5fca81 100644 --- a/docs/control/Jail.html +++ b/docs/control/Jail.html @@ -69,10 +69,12 @@

Core

+ + + - @@ -87,9 +89,8 @@

Addons

- + - @@ -112,12 +113,25 @@

Guis

+ @@ -189,8 +205,8 @@

Modules

@@ -242,15 +258,15 @@

Usage

-- This will move 'MrBiter' to the jail role and remove all other roles from them -- the player name and reason are only so they can be included in the event for user feedback - Jail.jail_player('MrBiter','Cooldude2606','Likes biters too much') + Jail.jail_player('MrBiter', 'Cooldude2606', 'Likes biters too much') -- This will give 'MrBiter' all his roles back and remove him from jail -- again as above the player name is only used in the event for user feedback - Jail.unjail_player('MrBiter','Cooldude2606') + Jail.unjail_player('MrBiter', 'Cooldude2606') -- Temp ban works the same as jail but will store the reason and move the players items to spawn -- this is meant to be used as a more permiment jail but not as strong as a ban - Jail.temp_ban_player('MrBiter','Cooldude2606','Likes biters too much') + Jail.temp_ban_player('MrBiter', 'Cooldude2606', 'Likes biters too much') @@ -1207,7 +1223,7 @@

Temp ban < generated by LDoc diff --git a/docs/control/Production.html b/docs/control/Production.html index 66ab08bb75..a92429495c 100644 --- a/docs/control/Production.html +++ b/docs/control/Production.html @@ -42,9 +42,9 @@

Sections

@@ -69,10 +69,12 @@

Core

+ + + - @@ -87,9 +89,8 @@

Addons

- + - @@ -112,12 +113,25 @@

Guis

+ @@ -189,8 +205,8 @@

Modules

@@ -204,9 +220,9 @@

Topics

Jump to Section

@@ -247,21 +263,21 @@

Usage

-- The get production function is used to get production, consumion and net -- it may be used for any item and with any precision level, use total for total - Production.get_production(game.forces.player,'iron-plate',defines.flow_precision_index.one_minute) +
Production.get_production(game.forces.player, 'iron-plate', defines.flow_precision_index.one_minute) -- The fluctuations works by compearing recent production with the average over time -- again any precision may be used, apart from one_thousand_hours as there would be no valid average - Production.get_fluctuations(game.forces.player,'iron-plate',defines.flow_precision_index.one_minute) + Production.get_fluctuations(game.forces.player, 'iron-plate', defines.flow_precision_index.one_minute) -- ETA is calculated based on what function you use but all share a similar method -- for production eta it will take current production average given by the precision -- and work out how many ticks it will require to make the required amount (1000 by default) - Production.get_production_eta(game.forces.player,'iron-plate',defines.flow_precision_index.one_minute,250000) + Production.get_production_eta(game.forces.player, 'iron-plate', defines.flow_precision_index.one_minute, 250000) -- Both get_color and format_number are helper functions to help format production stats - -- get_color will return green,orange,red,or grey based on the active_value - -- the passive_value is used when active_value is 0 and can only return orange,red,or grey - Production.get_color(clamp,active_value,passive_value) + -- get_color will return green, orange, red, or grey based on the active_value + -- the passive_value is used when active_value is 0 and can only return orange, red, or grey + Production.get_color(clamp, active_value, passive_value) @@ -283,22 +299,6 @@

Dependencies

-

Formating

- - - - - - - - - - - - -
get_color(clamp, active_value, passive_value)Returns a color value bassed on the value that was given
format_number(value)Returns three parts used to format a number
- -

Precision

@@ -349,6 +349,22 @@

Statistics

+ + +

Formating

+ + + + + + + + + + + + +
get_color(cutoff, active_value, passive_value)Returns a color value based on the value that was given
format_number(value)Returns three parts used to format a number

@@ -399,159 +415,6 @@

Depend - - - - - - -

- -

Formating

-
-
-
-
- # - get_color(clamp, active_value, passive_value) -
-
-
-
- -

Returns a color value bassed on the value that was given

-

- - - Parameters: - -
    - - - - - -
  • - - clamp - - : - - (number) - - value which seperates the different colours - -
  • - - - - - -
  • - - active_value - - : - - (number) - - first value tested, tested against clamp - -
  • - - - - - -
  • - - passive_value - - : - - (number) - - second value tested, tested against 0 - -
  • - - -
- - - - - Returns: -
    -
  • - (table) - contains r,g,b keys -
  • -
- - - - - - - - - -
-
-
-
- # - format_number(value) -
-
-
-
- -

Returns three parts used to format a number

-

- - - Parameters: - -
    - - - - - -
  • - - value - - : - - (number) - - the value to format - -
  • - - -
- - - - - Returns: -
    -
  • - (string) - the sign for the number -
  • -
  • - (string) - the surfix for any unit used -
  • -
- - - @@ -1306,6 +1169,159 @@

Statistics + + + + + + +

+
+

Formating

+
+
+
+
+ # + get_color(cutoff, active_value, passive_value) +
+
+
+
+ +

Returns a color value based on the value that was given

+

+ + + Parameters: + +
    + + + + + +
  • + + cutoff + + : + + (number) + + value which separates the different colours + +
  • + + + + + +
  • + + active_value + + : + + (number) + + first value tested, tested against cutoff + +
  • + + + + + +
  • + + passive_value + + : + + (number) + + second value tested, tested against 0 when active is 0 + +
  • + + +
+ + + + + Returns: +
    +
  • + (table) + contains r,g,b keys +
  • +
+ + + + + + + + + +
+
+
+
+ # + format_number(value) +
+
+
+
+ +

Returns three parts used to format a number

+

+ + + Parameters: + +
    + + + + + +
  • + + value + + : + + (number) + + the value to format + +
  • + + +
+ + + + + Returns: +
    +
  • + (string) + the sign for the number +
  • +
  • + (string) + the surfix for any unit used +
  • +
+ + + @@ -1328,7 +1344,7 @@

Statistics generated by LDoc

diff --git a/docs/control/Reports.html b/docs/control/Reports.html index 09e64549e4..6103bd7701 100644 --- a/docs/control/Reports.html +++ b/docs/control/Reports.html @@ -69,10 +69,12 @@

Core

+ + + - @@ -87,9 +89,8 @@

Addons

- + - @@ -112,12 +113,25 @@

Guis

+ @@ -189,8 +205,8 @@

Modules

@@ -243,13 +259,13 @@

Usage

-- This will place a report on "MrBiter" (must be a valid player) the report will have been made -- by "Cooldude2606" (must be the player name) with the reason 'Liking biters too much' this can be -- seen by using Reports.get_report. - Reports.report_player('MrBiter','Cooldude2606','Liking biters too much') -- true + Reports.report_player('MrBiter', 'Cooldude2606', 'Liking biters too much') -- true -- The other get methods can be used to get all the reports on a player or to test if a player is reported. - Reports.get_report('MrBiter','Cooldude2606') -- 'Liking biters too much' + Reports.get_report('MrBiter', 'Cooldude2606') -- 'Liking biters too much' -- This will remove the warning on 'MrBiter' (must be a valid player) which was made by 'Cooldude2606'. - Reports.remove_report('MrBiter','Cooldude2606') -- true + Reports.remove_report('MrBiter', 'Cooldude2606') -- true -- This will remove all the report that have been made against 'MrBiter'. Note that the remove event will -- be triggered once per report issused. @@ -543,6 +559,38 @@

Events< + + + +
  • + + batch_count + + : + + (number) + + the number of reports removed in this batch, always one when not a batch + +
  • + + + + + +
  • + + batch + + : + + (number) + + the index of this event in a batch, always one when not a batch + +
  • + + @@ -1109,7 +1157,7 @@

    Setters generated by LDoc diff --git a/docs/control/Rockets.html b/docs/control/Rockets.html index d1bcf8234e..0373496851 100644 --- a/docs/control/Rockets.html +++ b/docs/control/Rockets.html @@ -68,10 +68,12 @@

    Core

    + + + - @@ -86,9 +88,8 @@

    Addons

    - + - @@ -111,12 +112,25 @@

    Guis

    + @@ -188,8 +204,8 @@

    Modules

    @@ -249,10 +265,10 @@

    Usage

    Rockets.get_silos('player') -- You can get the launch time for a rocket, meaning what game tick the 50th rocket was launched - Rockets.get_rocket_time('player',50) + Rockets.get_rocket_time('player', 50) -- The rolling average will work out the time to launch one rocket based on the last X rockets - Rockets.get_rolling_average('player',10) + Rockets.get_rolling_average('player', 10) @@ -983,7 +999,7 @@

    Fields< generated by LDoc diff --git a/docs/control/Tasks.html b/docs/control/Tasks.html index d8fe98bf54..b82f48a1ad 100644 --- a/docs/control/Tasks.html +++ b/docs/control/Tasks.html @@ -68,10 +68,12 @@

    Core

    + + + - @@ -86,9 +88,8 @@

    Addons

    - + - @@ -111,12 +112,25 @@

    Guis

    + @@ -188,8 +204,8 @@

    Modules

    @@ -235,9 +251,9 @@

    Tasks contro

    Usage

    -- Making and then editing a new task
    -local task_id = Tasks.add_task(game.player.force.name,nil,game.player.name)
    +local task_id = Tasks.add_task(game.player.force.name, nil, game.player.name)
     
    -Tasks.update_task(task_id,'We need more iron!',game.player.name)
    +Tasks.update_task(task_id, 'We need more iron!', game.player.name) @@ -250,14 +266,11 @@

    Dependencies

    - expcore.store + expcore.datastore utils.global - - utils.token - @@ -318,8 +331,8 @@

    Depend
    - # - expcore.store + # + expcore.datastore
    @@ -358,31 +371,6 @@

    Depend - - - - - - -

    -
    -
    -
    - # - utils.token -
    -
    -
    -
    - - - - - - - - - @@ -585,7 +573,7 @@

    Getters Usage:
    -- Check if a player is editing a task or not
    -local editing = Tasks.get_editing(task_id,game.player.name)
    +
    local editing = Tasks.get_editing(task_id, game.player.name)

    @@ -699,7 +687,7 @@

    Setters Usage:
    -- Adding a new task for your force
    -local task_id = Tasks.add_task(game.player.force.name,nil,game.player.name)
    +
    local task_id = Tasks.add_task(game.player.force.name, nil, game.player.name) @@ -838,7 +826,7 @@

    Setters Usage:
    -- Updating the message for on a task
    -Task.update_task(task_id,'We need more iron!',game.player.name)
    +
    Task.update_task(task_id, 'We need more iron!', game.player.name) @@ -923,7 +911,7 @@

    Setters Usage:
    -- Setting your editing state to true
    -Tasks.set_editing(task_id,game.player.name,true)
    +
    Tasks.set_editing(task_id, game.player.name, true) @@ -997,7 +985,7 @@

    Setters generated by LDoc diff --git a/docs/control/Warnings.html b/docs/control/Warnings.html index 7465e0154f..50f158affe 100644 --- a/docs/control/Warnings.html +++ b/docs/control/Warnings.html @@ -68,10 +68,12 @@

    Core

    + + + - @@ -86,9 +88,8 @@

    Addons

    - + - @@ -111,12 +112,25 @@

    Guis

    + @@ -188,8 +204,8 @@

    Modules

    @@ -239,17 +255,17 @@

    Usage

    local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings -- This will add a warning to the player - Warnings.add_warning('MrBiter','Cooldude2606','Killed too many biters') + Warnings.add_warning('MrBiter', 'Cooldude2606', 'Killed too many biters') -- This will remove a warning from a player, second name is just who is doing the action - Warnings.remove_warning('MrBiter','Cooldude2606') + Warnings.remove_warning('MrBiter', 'Cooldude2606') -- Script warning as similar to normal warning but are designed to have no effect for a short amount of time -- this is so it can be used for greifer protection without being too agressive - Warnings.add_script_warning('MrBiter','Killed too many biters') + Warnings.add_script_warning('MrBiter', 'Killed too many biters') -- Both normal and script warnings can also be cleared, this will remove all warnings - Warnings.clear_warnings('MrBiter','Cooldude2606') + Warnings.clear_warnings('MrBiter', 'Cooldude2606') @@ -273,6 +289,9 @@

    Dependencies

    + + +
    config.warnings
    expcore.player_data
    @@ -295,7 +314,7 @@

    Events

    - +
    on_script_warning_removedWhen a warning is remnoved from a player, by the scriptWhen a warning is removed from a player, by the script
    @@ -307,7 +326,7 @@

    Functions

    get_warnings(player) - Gets an array of warnings that the player has, always returns a list even if emtpy + Gets an array of warnings that the player has, always returns a list even if empty count_warnings(player) @@ -319,7 +338,7 @@

    Functions

    remove_warning(player, by_player_name) - Removes a warning from a player, always removes the earlyist warning, fifo + Removes a warning from a player, always removes the earliest warning, fifo clear_warnings(player, by_player_name) @@ -447,6 +466,31 @@

    Depend + + + + + + +

    +
    +
    +
    + # + expcore.player_data +
    +
    +
    +
    + + + + + + + + + @@ -638,6 +682,38 @@

    Events< + + + +
  • + + batch_count + + : + + (number) + + the number of warnings removed in this batch, always one when not a batch + +
  • + + + + + +
  • + + batch + + : + + (number) + + the index of this event in a batch, always one when not a batch + +
  • + + @@ -745,7 +821,7 @@

    Events<
    -

    When a warning is remnoved from a player, by the script

    +

    When a warning is removed from a player, by the script

    @@ -814,7 +890,7 @@

    Functions
    -

    Gets an array of warnings that the player has, always returns a list even if emtpy

    +

    Gets an array of warnings that the player has, always returns a list even if empty

    @@ -1018,7 +1094,7 @@

    Functions
    -

    Removes a warning from a player, always removes the earlyist warning, fifo

    +

    Removes a warning from a player, always removes the earliest warning, fifo

    @@ -1464,7 +1540,7 @@

    Functionsgenerated by LDoc

    diff --git a/docs/control/Warps.html b/docs/control/Warps.html index f3a3b9f2e6..6d8f1f9d70 100644 --- a/docs/control/Warps.html +++ b/docs/control/Warps.html @@ -44,7 +44,7 @@

    Sections

    - + @@ -69,10 +69,12 @@

    Core

    + + + - @@ -87,9 +89,8 @@

    Addons

    - + - @@ -112,12 +113,25 @@

    Guis

    + @@ -189,8 +205,8 @@

    Modules

    @@ -206,7 +222,7 @@

    Jump to Section

    - + @@ -239,14 +255,14 @@

    Usage

    -- Making a new spawn warp
     local player = game.player
     local force = player.force
    -local spawn_id = Warps.add_warp(force.name,player.surface,player.position,player.name,'Spawn')
    +local spawn_id = Warps.add_warp(force.name, player.surface, player.position, player.name, 'Spawn')
     
     Warps.set_spawn_warp(spawn_id, force)
     Warps.make_warp_tag(spawn_id)
    -- Making a new warp with a warp area
     local player = game.player
     local force = player.force
    -local warp_id = Warps.add_warp(force.name,player.surface,player.position,player.name)
    +local warp_id = Warps.add_warp(force.name, player.surface, player.position, player.name)
     
     Warps.make_warp_area(warp_id)
     Warps.make_warp_tag(warp_id)
    @@ -262,15 +278,12 @@

    Dependencies

    - expcore.store + expcore.datastore utils.global - utils.token - - config.warps @@ -329,7 +342,7 @@

    Setters

    -

    Map Intergration

    +

    Map Integration

    @@ -369,8 +382,8 @@

    Depend
    - # - expcore.store + # + expcore.datastore
    @@ -409,31 +422,6 @@

    Depend - - - - - - -

    -
    -
    -
    - # - utils.token -
    -
    -
    -
    - - - - - - - - - @@ -721,7 +709,7 @@

    Getters Usage:
    -- Check if a player is editing a warp or not
    -local editing = Warps.get_editing(warp_id,game.player.name)
    +
    local editing = Warps.get_editing(warp_id, game.player.name)

    @@ -851,7 +839,7 @@

    Setters Usage:
    -- Adding a new warp for your force at your position
     local player = game.player
    -local warp_id = Warps.add_warp(player.force.name,player.surface,player.position,player.name)
    +local warp_id = Warps.add_warp(player.force.name, player.surface, player.position, player.name) @@ -1008,7 +996,7 @@

    Setters Usage:
    -- Changing the name and icon for a warp
    -Warps.update_warp(warp_id,'My Warp','iron-plate',game.player.name)
    +
    Warps.update_warp(warp_id, 'My Warp', 'iron-plate', game.player.name) @@ -1093,7 +1081,7 @@

    Setters Usage:
    -- Setting your editing state to true
    -Warps.set_editing(warp_id,game.player.name,true)
    +
    Warps.set_editing(warp_id, game.player.name, true) @@ -1153,7 +1141,7 @@

    Setters -

    Map Intergration

    +

    Map Integration

    @@ -1446,7 +1434,7 @@

    -- Set your forces spawn to a warp -Warps.set_spawn_warp(warp_id,game.player.force) +Warps.set_spawn_warp(warp_id, game.player.force) @@ -1515,7 +1503,7 @@

    -- Teleport yourself to a warp point -Warps.teleport_player(warp_id,game.player) +Warps.teleport_player(warp_id, game.player) @@ -1534,7 +1522,7 @@

    LDoc diff --git a/docs/core/Async.html b/docs/core/Async.html index 6a6a6a2d81..bc1d3caa4b 100644 --- a/docs/core/Async.html +++ b/docs/core/Async.html @@ -53,10 +53,12 @@

    Core

    + + + - @@ -85,9 +87,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Guis

    + @@ -187,8 +203,8 @@

    Modules

    @@ -245,11 +261,11 @@

    Usage

    end) -- This will allow us to bypass the error by running one tick later outside of any player scope -Async(promote_player,game.player) +Async(promote_player, game.player) -- Here we make an sync function that we want to have a delay, note the delay is not defined here local print_message = -Async.register(function(player,message) +Async.register(function(player, message) player.print(message) end) @@ -597,7 +613,7 @@

    Functionsgenerated by LDoc diff --git a/docs/core/Commands.html b/docs/core/Commands.html index 512c965ac0..0411c95005 100644 --- a/docs/core/Commands.html +++ b/docs/core/Commands.html @@ -44,9 +44,9 @@

    Sections

    - - + + @@ -59,10 +59,12 @@

    Core

    + + + - @@ -91,9 +93,8 @@

    Addons

    - + - @@ -116,12 +117,25 @@

    Guis

    + @@ -193,8 +209,8 @@

    Modules

    @@ -210,9 +226,9 @@

    Jump to Section

    - - + + @@ -244,19 +260,17 @@

    Commands cor

    Usage

    -
    --- Full code example, see below for explaination
    +    
    --- Full code example, see below for explanation
     Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.')
    -:add_param('repeat-count', false, 'number-range-int', 1, 5) -- required int in range 1 to 5 inclusive
    +:add_param('repeat-count', 'number-range-int', 1, 5) -- required int in range 1 to 5 inclusive
     :add_param('smiley', true, function(input, player, reject) -- optional boolean default false
         if not input then return end
    -    if input:lower() == 'true' or input:lower() == 'yes' then
    -        return true
    -    else
    -        return false
    -    end
    +    input = input:lower()
    +    if input == 'true' or input == 'yes' then return true end
    +    return false
     end)
    -:set_defaults{ smiley=false }
    -:set_flag('admin_only', true) -- command is admin only
    +:set_defaults{ smiley = false }
    +:set_flag('admin_only') -- command is admin only
     :add_alias('name', 'rname') -- allow alias: name and rname
     :register(function(player, repeat_count, smiley, raw)
         game.print(player.name..' used a command with input: '..raw)
    @@ -266,93 +280,89 @@ 

    Usage

    msg = ':'..msg end - for 1 = 1,repeat_count do + for 1 = 1, repeat_count do Command.print(1..msg) end end)
    -
    --- Example Command:
    --- How for the fun part making the commands, the commands can be set up with any number of params and flags that you want,
    --- you can add aliases for the commands and set default values for optional params and of course register your command callback
    --- in our example we will just have a command that will repeat the users name in chat X amount of times and only allow admins to use it.
    +    
    --- Example Command Explanation:
    +-- Making commands basics, the commands can be set up with any number of params and flags that you want,
    +-- you can add aliases for the commands and set default values for optional params and of course register your command callback.
    +-- In our example we will have a command that will repeat the users name in chat X amount of times and only allow admins to use it.
     
    --- First we create the new command, nb this will not register the command to the game this is done at the end, we will call
    --- the command "repeat-name" and set the help message as follows:
    +-- First we create the new command, note this will not register the command to the game this is done at the end.
    +-- We will call the command "repeat-name" and set the help message as follows:
     Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.')
     
    --- Now for our first param we will call "repeat-count" and it will be a required value between 1 and 5 inclusive:
    -:add_param('repeat-count', false, 'number-range-int', 1, 5)
    +-- Now for our first param, we have named it "repeat-count" and it will be a required value, between 1 and 5 inclusive:
    +-- By using "number-range-int" we are saying to use this parser to convert our input text, common ones exist in config.expcore.command_general_parse
    +:add_param('repeat-count', 'number-range-int', 1, 5)
     
    --- Our second param we need a custom parse for but we have not defined it, this is an option for when it is unlikely for
    --- any other command to use the same input type; however in our case it will just be a boolean which should be noted as being
    --- included in the general command parse config. As for the param its self it will be called "smiley" and will be optional with
    --- a default value of false:
    +-- Our second param needs a custom parser, meaning it isnt defined with add_parser, this is an option for when it is unlikely for
    +-- any other command to use the same input type. In the example it is a boolean type and we are just showing it here as part of the example.
    +-- As for the param its self it will be called "smiley" and will be optional with a default value of false:
     :add_param('smiley', true, function(input, player, reject)
    -    -- since it is optional the input can be nil, in which case we just return
    +    -- Since it is optional the input can be nil, in which case we just return
         if not input then return end
    -    -- if it is not nil then we check for a truthy value
    -    if input:lower() == 'true' or input:lower() == 'yes' then
    -        return true
    -    else
    -        -- note that because we did not return nil or reject then false will be passed to command callback, see example parse
    -        return false
    -    end
    +    -- If it is not nil then we check for a truthy value
    +    if input == 'true' or input == 'yes' then return true end
    +    -- Note that because we did not return nil or reject then false will be passed to command callback, see example parse
    +    return false
     end)
     
    --- Once all params are defined you can now define some default values if you have optional params, the default value will be used only
    --- when no value is given as input, if an invalid value is given then the command will still fail and this value will not be used, the
    --- default can also be a function which is passed the player using the command and returns a value. Here we set the default for "smiley" to false:
    +-- Once all params are defined you can add some default values for your optional params, the default value will be used only
    +-- when no value is given as input, if an invalid value is given then the command will fail and the default will not be used, the
    +-- default can also be a function which is passed the player as an argument and should return a value to be the default.
    +-- Here we set the default for "smiley" to false:
     :set_defaults{smiley=false}
     
     -- Another example of defaults if we have: item, amount[opt], player[opt]
     :set_defaults{
    -    amount = 50, -- more than one value can be set at a time
    -    player = function(player)
    -        return player -- default is the player using the command
    -    end
    -}
    -
    --- Now the params are set up we can alter how the command works, we can set auth flags, add aliases to this command or enable "auto concat"
    --- which is when you want all extra words to be concatenated onto the end of the last param, useful for reason or messages:
    -:set_flag('admin_only', true) -- in our case we want "admin_only" to be set to true so only admins can use the command
    -:add_alias('name', 'rname') -- we also add two aliases here: "name" and "rname" which point to this command
    --- :enable_auto_concat() we do not use this in our case but this can also be used to enable the "auto concat" feature
    +    amount = 50, -- More than one value can be set at a time
    +    player = function(player) return player end -- Default is the player using the command
    +}
    +
    +-- Now the params are set up we can alter how the command works, we can set auth flags, add aliases, or enable "auto concat":
    +:set_flag('admin_only') -- In our case we want "admin_only" to be set to true so only admins can use the command
    +:add_alias('name', 'rname') -- We also add two aliases here: "name" and "rname" which point to this command
    +-- :enable_auto_concat() -- We do not use this in our case but this can also be used to enable the "auto concat" feature
     
     -- And finally we want to register a callback to this command, the callback is what defines what the command does, can be as complex as you
    --- want it to be to as simple as our example; the command receives two params plus all that you have defines:
    +-- want it to be, or as simple as our example; the command receives two params plus all param you have defined:
     -- 1) the player who used the command
     -- 2) in our case repeat_count which will be a number
     -- 3) in our case smiley which will be a boolean
     -- 4) the raw input; this param is always last as is always present as a catch all
     :register(function(player, repeat_count, smiley, raw)
    -    -- this is to show the value for raw as this is an example command, the log file will also show this
    +    -- This is to show the value for raw as this is an example command, the log file will also show this
         game.print(player.name..' used a command with input: '..raw)
         local msg = ') '..player.name
    +
         if smiley then
    -        -- this is where that smiley param is used
    -        msg = ':'..msg
    +        msg = ':'..msg
         end
    -    for 1 = 1,repeat_count do
    +
    +    for 1 = 1, repeat_count do
             -- this print function will return ANY value to the user in a desync safe manor, this includes if the command was used through rcon
             Command.print(1..msg)
         end
    -    -- see below for what else can be used here
    +    -- See below for what can be used here
     end)
     
    --- Other values that can be returned from register
    -Commands.print(any,colour[opt]) -- this will return any value value to the user including if it is ran through rcon console
    -Commands.error(message[opt]) -- this returns a warning to the user, aka an error that does not prevent execution of the command
    -return Commands.error(message[opt]) -- this returns an error to the user, and will halt the command execution, ie no success message is returned
    -Commands.success(message[opt]) -- used to return a success message however don't use this method see below
    -return Commands.success(message[opt]) -- will return the success message to the user and your given message, halts execution
    -return <any> -- if any value is returned then it will be returned to the player via a Commands.success call
    +-- Values that can be returned from register callback
    +Commands.print(any, colour[opt]) -- This will return any value value to the user including if it is ran through rcon console
    +Commands.error(message[opt]) -- This returns a warning to the user, aka an error that does not prevent execution of the command
    +return Commands.error(message[opt]) -- This returns an error to the user, and will halt the command execution, ie no success message is returned
    +Commands.success(message[opt]) -- Used to return a success message however don't use this method, see below
    +return Commands.success(message[opt]) -- Will return the success message to the user and your given message, halts execution
    +return <any> -- If any value is returned then it will be returned to the player via a Commands.success call
     
    --- Example Authenticator:
     -- The command system is best used when you can control who uses commands;
    --- to do this would would need to define an authenticator which is ran every time a command is run;
    +-- to do this you need to define an authenticator which is ran every time a command is run;
     -- in this example I will show a simple one that requires certain commands to require the user to be a game admin.
     
     -- For our admin only example we will set a flag to true when we want it to be admin only;
    --- when we define the command will will use :set_flag('admin_only', true);
    +-- when we define the command will will use :set_flag('admin_only');
     -- then inside the authenticator we will test if the flag is present using: if flags.admin_only then
     
     -- When the authenticator is called by the command handler it will be passed 4 arguments:
    @@ -366,11 +376,11 @@ 

    Usage

    -- 1) when the "admin_only" flag is not set, which we take assume that any one can use it -- 2) when the "admin_only" flag is set, and the player is admin --- When want to prevent exicution of the command we must reject it, listed is how that can be done: +-- When want to prevent execution of the command we must reject it, listed is how that can be done: -- 1) return false -- this is the most basic rejection and should only be used while testing -- 2) return reject -- returning the reject function is as a fail safe in case you forget to call it, same as returning false --- 3) reject() -- this will block execution without to allowing further code to be ran in your authenticator --- 4) reject('This command is for admins only!') -- Using reject as a function allows a error message to be returned +-- 3) reject() -- this will block execution while allowing further code to be ran in your authenticator +-- 4) reject('This command is for admins only!') -- using reject as a function allows a error message to be returned -- 5) return reject() -- using return on either case above is best practice as you should execute all your code before rejecting -- Example Code: @@ -384,15 +394,15 @@

    Usage

    return true end end)
    -
    --- Example Parse:
    +    
    --- Example Parser:
     -- Before you make a command it is important to understand the most powerful feature of this command handler;
     -- when you define a command you are able to type the params and have then be parsed and validated before your command is executed;
    --- This module should is paired with a general command parse but you may want to create your own.
    +-- This module should be paired with a general command parse but you may want to create your own.
     
     -- For our example we will create a parse to accept only integer numbers in a given range:
     -- 1) we will give it the name "number-range-int" this is the "type" that the input is expected to be
     -- 2) when we define the type we will also define the min and max of the range so we can use the function more than once
    -:add_param('repeat_count', false, 'number-range-int', 5, 10) -- "repeat_count" is required "number-range-int" in a range 5 to 10 inclusive
    +:add_param('repeat_count', 'number-range-int', 5, 10) -- "repeat_count" is a required "number-range-int" in a range 5 to 10 inclusive
     
     -- The command parse will be passed 3 arguments plus any other which you define, in our case:
     -- 1) input - the input that has been given by the user for this param, the role of this function is to transform this value
    @@ -417,7 +427,7 @@ 

    Usage

    if not input then return end -- nil check -- Example Code: -Commands.add_parse('number-range-int',function(input, player, reject, range_min, range_max) +
    Commands.add_parse('number-range-int', function(input, player, reject, range_min, range_max) local rtn = tonumber(input) and math.floor(tonumber(input)) or nil -- converts input to number if not rtn or rtn < range_min or rtn > range_max then -- the input is either not a number or is outside the range @@ -454,23 +464,23 @@

    Tables

    - + - + - - + + - + - +
    definesValues returned by the signal functions to cause the command system to reactConstant values used by the command system
    commandsCustom command data will be stored hereAn array of all custom commands that are registered
    authorizationCustom function are stored here which control who can use what commandsauthenticatorsAn array of all custom authenticators that are registered
    parse_functionsparsers Used to store default functions which are common parse function such as player or number in range
    _prototypeUsed to store functions which gets added to new custom commandsThe command prototype which stores all command defining functions
    @@ -481,65 +491,69 @@

    Fields

    - authorization_fail_on_error - Set true to have authorize fail if a callback fails to run, more secure + authorization_failure_on_error + When true any authenticator error will result in authorization failure, more secure + + + print + Returns a value to the player, different to success as this does not signal the end of your command -

    Authenication

    +

    Authentication

    - - + + - - + + - +
    add_authenticator(callback)Adds an authorization callback, function used to check if a player if allowed to use a commandadd_authenticator(authenticator)Adds an authorization function, function used to check if a player if allowed to use a command
    remove_authenticator(callback)Removes an authorization callbackremove_authenticator(authenticator)Removes an authorization function, can use the index or the function value
    authorize(player, command_name)Mostly used internally, calls all authorization callbacks, returns if the player is authorizedMostly used internally, calls all authenticators, returns if the player is authorized
    -

    Getters

    +

    Parse

    - - + + - - + + + + + +
    get([player])Gets all commands that a player is allowed to use, game commands are not includedadd_parse(name, parser)Adds a parse function which can be called by name (used in add_param) +nb: this is not required as you can use the callback directly this just allows it to be called by name
    search(keyword[, player])Searches command names and help messages to find possible commands, game commands are includedremove_parse(name)Removes a parse function, see add_parse for adding them, cant be done during runtime
    parse(name, input, player, reject)Intended to be used within other parse functions, runs a parse and returns success and new value
    -

    Parse

    +

    Getters

    - - - - - - + + - - + +
    add_parse(name, callback)Adds a parse function which can be called by name (used in add_param) -nb: this is not required as you can use the callback directly this just allows it to be called by name
    remove_parse(name)Removes a parse function, see add_parse for adding themget([player])Gets all commands that a player is allowed to use, game commands are not included
    parse(name, input, player, reject)Intended to be used within other parse functions, runs a parse and returns success and new valuesearch(keyword[, player])Searches command names and help messages to find possible commands, game commands are included
    @@ -551,33 +565,32 @@

    Creation

    new_command(name, help) - Creates a new command object to added details to, note this does not register the command to the game api + Creates a new command object to added details to, this does not register the command to the game api - Commands._prototype:add_param(name[, optional=false][, parse=pass function through][, ...]) + Commands._prototype:add_param(name[, optional=false][, parse][, ...]) Adds a new param to the command this will be displayed in the help and used to parse the input Commands._prototype:set_defaults(defaults) - Add default values to params, only as an effect if the param is optional, if default value is a function it is called with acting player + Add default values to params, only as an effect if the param is optional, if default value is a function it is called with the acting player Commands._prototype:set_flag(name[, value=true]) - Adds a tag to the command which is passed via the flags param to the authenticators, can be used to assign command roles or type + Adds a flag to the command which is passed via the flags param to the authenticators, can be used to assign command roles or usage type - Commands._prototype:add_alias(any) - Adds an alias, or multiple, that will also be registered with the same callback, eg /teleport can be used as /tp + Commands._prototype:add_alias(...) + Adds an alias, or multiple, that will be registered to this command, eg /teleport can be used as /tp Commands._prototype:enable_auto_concat() - Enables auto concatenation of any params on the end so quotes are not needed for last param -nb: this will disable max param checking as they will be concatenated onto the end of that last param -this can be useful for reasons or longs text, can only have one per command + Enables auto concatenation for this command, all params after the last are added to the last param, useful for reasons or other long text input +nb: this will disable max param checking as they will be concatenated onto the end of that last param Commands._prototype:register(callback) - Adds the callback to the command and registers all aliases, params and help message with the game api + Adds the callback to the command and registers: aliases, params and help message with the base game api nb: this must be the last function ran on the command and must be done for the command to work @@ -589,23 +602,22 @@

    Status

    - error([error_message=''][, play_sound=utility/wire_pickup]) - Sends an error message to the player and when returned will stop exicution of the command -nb: this is for non fatal errors meaning there is no log of this event, use during register callback + success([value]) + Sends a value to the player, followed by a command complete message, returning a value will trigger this automatically - internal_error(success, command_name, error_message) - Sends an error to the player and logs the error, used with pcall within command handler please avoid direct use -nb: use error(error_message) within your callback to trigger do not trigger directly as code exictuion may still continue + print(value, colour) + Sends a value to the player, different to success as this does not signal the end of your command - success([value]) - Sends a value to the player, followed by a command complete message -nb: returning any value from your callback will trigger this function, return this function to prevent duplicate messages + error([error_message=''][, play_sound=utility/wire_pickup]) + Sends an error message to the player and when returned will stop execution of the command +nb: this is for non fatal errors meaning there is no log of this event, use during register callback - print(value, colour) - Sends a value to the player, different to success as this does not signal the end of your command + internal_error(success, command_name, error_message) + Sends an error to the player and logs the error, used internally please avoid direct use +nb: use error(error_message) within your callback to trigger do not trigger directly as code execution may still continue run_command(command_event) @@ -683,7 +695,7 @@

    Tables<
    -

    Values returned by the signal functions to cause the command system to react

    +

    Constant values used by the command system

    @@ -759,7 +771,7 @@

    Tables<
    -

    Custom command data will be stored here

    +

    An array of all custom commands that are registered

    @@ -779,14 +791,14 @@

    Tables<
    - # - authorization + # + authenticators
    -

    Custom function are stored here which control who can use what commands

    +

    An array of all custom authenticators that are registered

    @@ -806,8 +818,8 @@

    Tables<
    - # - parse_functions + # + parsers
    @@ -840,7 +852,7 @@

    Tables<
    -

    Used to store functions which gets added to new custom commands

    +

    The command prototype which stores all command defining functions

    @@ -863,14 +875,41 @@

    Fields<
    - # - authorization_fail_on_error + # + authorization_failure_on_error
    -

    Set true to have authorize fail if a callback fails to run, more secure

    +

    When true any authenticator error will result in authorization failure, more secure

    +

    + + + + + + + + + + + + + + +
    +
    +
    +
    + # + print +
    +
    +
    +
    + +

    Returns a value to the player, different to success as this does not signal the end of your command

    @@ -888,19 +927,19 @@

    Fields<

    -

    Authenication

    +

    Authentication

    # - add_authenticator(callback) + add_authenticator(authenticator)
    -

    Adds an authorization callback, function used to check if a player if allowed to use a command

    +

    Adds an authorization function, function used to check if a player if allowed to use a command

    @@ -914,13 +953,13 @@

    Auth
  • - callback + authenticator : (function) - the callback you want to register as an authenticator + The function you want to register as an authenticator
  • @@ -934,7 +973,7 @@

    Auth
    • (number) - the index it was inserted at use to remove the callback, if anon function used + The index it was inserted at, used to remove the authenticator
    @@ -945,11 +984,11 @@

    Auth Usage: -
    -- Test if a command is admin only and if the player is admin
    +    
    -- If the admin_only flag is set, then make sure the player is an admin
     local admin_authenticator =
     Commands.add_authenticator(function(player, command, flags, reject)
    -    if flags.admin_only then
    -        return player.admin or reject('This command is for admins only!')
    +    if flags.admin_only and not player.admin then
    +        return reject('This command is for admins only!')
         else
             return true
         end
    @@ -961,13 +1000,13 @@ 

    Auth
    # - remove_authenticator(callback) + remove_authenticator(authenticator)
    -

    Removes an authorization callback

    +

    Removes an authorization function, can use the index or the function value

    @@ -981,13 +1020,13 @@

    Auth
  • - callback + authenticator : (function or number) - the callback to remove, an index returned by add_authenticator can be passed + The authenticator to remove, either the index return from add_authenticator or the function used
  • @@ -1001,7 +1040,7 @@

    Auth
    • (boolean) - if the callback found and removed successfuly + If the authenticator was found and removed successfully
    @@ -1012,7 +1051,7 @@

    Auth Usage: -
    -- Removing the admin authenticator, can not be done dueing runtime
    +    
    -- Removing the admin authenticator, can not be done during runtime
     Commands.remove_authenticator(admin_authenticator)
    @@ -1027,7 +1066,7 @@

    Auth
    -

    Mostly used internally, calls all authorization callbacks, returns if the player is authorized

    +

    Mostly used internally, calls all authenticators, returns if the player is authorized

    @@ -1047,7 +1086,7 @@

    Auth (LuaPlayer) - the player that is using the command, passed to callbacks + The player who is using the command, passed to authenticators @@ -1063,7 +1102,7 @@

    Auth (string) - the command that is being used, passed to callbacks + The name of the command being used, passed to authenticators @@ -1077,22 +1116,22 @@

    Auth
    • (boolean) - true player is authorized + true Player is authorized
    • (string) - commands const for success + commands Define value for success
    Or
    • (boolean) - false player is unauthorized + false Player is unauthorized
    • (string or locale_string) - the reason given by the authenticator + The reason given by the failed authenticator
    @@ -1109,19 +1148,20 @@
    Or

    -

    Getters

    +

    Parse

    - # - get([player]) + # + add_parse(name, parser)
    -

    Gets all commands that a player is allowed to use, game commands are not included

    +

    Adds a parse function which can be called by name (used in add_param) +nb: this is not required as you can use the callback directly this just allows it to be called by name

    @@ -1135,15 +1175,30 @@

    Getters - player + name : - (LuaPlayer) + (string) - the player that you want to get commands of, nil will return all commands + The name of the parse, should describe a type of input such as number or player, must be unique + + + + + + + +
  • + + parser + + : + + (function) + + The function that is ran to parse the input string - (optional)
  • @@ -1155,8 +1210,8 @@

    Getters Returns:
    • - (table) - all commands that that player is allowed to use, or all commands + (boolean) + Was the parse added, will be false if the name is already used
    @@ -1167,24 +1222,31 @@

    Getters Usage: -
    -- Get the command you are allowed to use
    -local commands = Commands.get(game.player)
    -
    -- Get all commands that are registered
    -local commands = Commands.get()
    +
    -- Adding a parse to validate integers in a given range
    +Commands.add_parse('number-range-int', function(input, player, reject, range_min, range_max)
    +    local rtn = tonumber(input) and math.floor(tonumber(input)) or nil -- converts input to number
    +    if not rtn or rtn < range_min or rtn > range_max then
    +        -- The input is either not a number or is outside the range
    +        return reject('Number entered is not in range: '..range_min..', '..range_max)
    +    else
    +        -- Returns the input as a number rather than a string, thus the param is now the correct type
    +        return rtn
    +    end
    +end)

    - # - search(keyword[, player]) + # + remove_parse(name)
    -

    Searches command names and help messages to find possible commands, game commands are included

    +

    Removes a parse function, see add_parse for adding them, cant be done during runtime

    @@ -1198,31 +1260,14 @@

    Getters - keyword + name : (string) - the word which you are trying to find in your search - - - - - + The name of the parse to remove - -
  • - - player - - : - - (LuaPlayer) - - the player to get allowed commands of, if nil all commands are searched - - (optional)
  • @@ -1231,13 +1276,6 @@

    Getters - Returns: -
      -
    • - (table) - all commands that contain the key word, and allowed by player if player given -
    • -
    @@ -1246,28 +1284,22 @@

    Getters Usage: -
    -- Get all commands which "repeat"
    -local commands = Commands.search('repeat')
    -
    -- Get all commands which "repeat" and you are allowed to use
    -local commands = Commands.search('repeat', game.player)
    +
    -- Removing a parse
    +Commands.remove_parse('number-range-int')

    -
    -

    Parse

    -
    - # - add_parse(name, callback) + # + parse(name, input, player, reject)
    -

    Adds a parse function which can be called by name (used in add_param) -nb: this is not required as you can use the callback directly this just allows it to be called by name

    +

    Intended to be used within other parse functions, runs a parse and returns success and new value

    @@ -1287,7 +1319,7 @@

    Parse string) - the name of the parse, should be the type like player or player_alive, must be unique + The name of the parse to call, must be a registered parser @@ -1297,13 +1329,45 @@

    Parse - callback + input + + : + + (string) + + The input to pass to the parse, must be a string but not necessarily the original input + + + + + + + +
  • + + player + + : + + (LuaPlayer) + + The player that is using the command, pass directly from your arguments + +
  • + + + + + +
  • + + reject : (function) - the callback that is ran to parse the input + The reject function, pass directly from your arguments
  • @@ -1316,8 +1380,8 @@

    Parse Returns:
    • - (boolean) - was the parse added will be false if the name is already used + (any) + The new value for the input, if nil is return then either there was an error or the input was nil
    @@ -1328,31 +1392,35 @@

    Parse Usage: -
    -- Adding a parse to validate ints in a given range
    -Commands.add_parse('number-range-int', function(input, player, reject, range_min, range_max)
    -    local rtn = tonumber(input) and math.floor(tonumber(input)) or nil -- converts input to number
    -    if not rtn or rtn < range_min or rtn > range_max then
    -        -- the input is either not a number or is outside the range
    -        return reject('Number entered is not in range: '..range_min..', '..range_max)
    -    else
    -        -- returns the input as a number rather than a string, thus the param is now the correct type
    -        return rtn
    -    end
    +    
    -- Parsing an int after first checking it is a number
    +Commands.add_parse('number', function(input, player, reject)
    +    local number = tonumber(input)
    +    if number then return number end
    +    return reject('Input must be a number value')
    +end)
    +
    +Commands.add_parse('number-int', function(input, player, reject)
    +    local number = Commands.parse('number', input, player, reject)
    +    if not number then return end
    +    return math.floor(number)
     end)

    +
    +

    Getters

    +
    - # - remove_parse(name) + # + get([player])
    -

    Removes a parse function, see add_parse for adding them

    +

    Gets all commands that a player is allowed to use, game commands are not included

    @@ -1366,14 +1434,15 @@

    Parse - name + player : - (string) + (LuaPlayer) - the name of the parse to remove + The player that you want to get commands of, nil will return all commands + (optional) @@ -1382,6 +1451,13 @@

    Parse + Returns: +
      +
    • + (table) + All commands that that player is allowed to use, or all commands +
    • +
    @@ -1390,22 +1466,24 @@

    Parse Usage: -
    -- Removing a parse
    -Commands.remove_parse('number-range-int')
    +
    -- Get the commands you are allowed to use
    +local commands = Commands.get(game.player)
    +
    -- Get all commands that are registered
    +local commands = Commands.get()

    - # - parse(name, input, player, reject) + # + search(keyword[, player])
    -

    Intended to be used within other parse functions, runs a parse and returns success and new value

    +

    Searches command names and help messages to find possible commands, game commands are included

    @@ -1419,29 +1497,13 @@

    Parse - name - - : - - (string) - - the name of the parse to call, must be registered parse - - - - - - - -
  • - - input + keyword : (string) - string the input to pass to the parse, must be a string but not necessarily the original input + The word which you are trying to find in your search
  • @@ -1457,24 +1519,9 @@

    Parse LuaPlayer) - the player that is using the command - - - - - - - -
  • - - reject - - : - - (function) - - the reject function that was passed by the command hander + The player to get allowed commands of, if nil all commands are searched + (optional)
  • @@ -1486,8 +1533,8 @@

    Parse Returns:
    • - (any) - the new value for the input, may be nil, if nil then either there was an error or input was nil + (table) + All commands that contain the key word, and allowed by the player if a player was given
    @@ -1498,9 +1545,10 @@

    Parse Usage: -
    -- Parsing a int in a given range
    -local parsed_input = Commands.parse('number-range-int', '7', player, reject, 1, 10) -- valid range 1 to 10
    -
    +
    -- Get all commands which "repeat"
    +local commands = Commands.search('repeat')
    +
    -- Get all commands which "repeat" and you are allowed to use
    +local commands = Commands.search('repeat', game.player)

    @@ -1517,7 +1565,7 @@

    Creation <
    -

    Creates a new command object to added details to, note this does not register the command to the game api

    +

    Creates a new command object to added details to, this does not register the command to the game api

    @@ -1537,7 +1585,7 @@

    Creation < (string) - the name of the command to be created + The name of the command to be created @@ -1553,7 +1601,7 @@

    Creation < (string) - the help message for the command + The help message for the command @@ -1566,8 +1614,8 @@

    Creation < Returns:
    • - (Commands._prototype) - this will be used with other functions to generate the command functions + (table) + This will be used with other functions to define the new command
    @@ -1579,8 +1627,7 @@

    Creation < Usage:
    -- Define a new command
    -local command =
    -Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.')
    +
    Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.')

    @@ -1588,7 +1635,7 @@

    Creation <
    # - Commands._prototype:add_param(name[, optional=false][, parse=pass function through][, ...]) + Commands._prototype:add_param(name[, optional=false][, parse][, ...])
    @@ -1614,7 +1661,7 @@

    Creation < (string) - the name of the new param that is being added to the command + The name of the new param that is being added to the command @@ -1630,7 +1677,7 @@

    Creation < (boolean) - is this param required for this command, these must be after all required params + Is this param optional, these must be added after all required params (default: false) @@ -1647,9 +1694,9 @@

    Creation < (string or function) - this function will take the input and return a new (or same) value + This function will take the input and return a new value, if not given no parse is done - (default: pass function through) + (optional) @@ -1662,8 +1709,9 @@

    Creation < : + (any) - extra args you want to pass to the parse function; for example if the parse is general use + Extra args you want to pass to the parse function; for example if the parse is general use (optional) @@ -1677,8 +1725,8 @@

    Creation < Returns:
    • - (Commands._prototype) - pass through to allow more functions to be called + (table) + Pass through to allow more functions to be called
    @@ -1689,9 +1737,9 @@

    Creation < Usage: -
    -- Adding a param which has an parse defined
    -command:add_param('repeat-count', false, 'number-range-int', 1, 5)
    -
    -- Adding a param which has a custom parse, see Commands.add_parse for details
    +    
    -- Adding a required param which has a parser pre-defined
    +command:add_param('repeat-count', 'number-range-int', 1, 5)
    +
    -- Adding an optional param which has a custom parse, see Commands.add_parse for details
     command:add_param('smiley', true, function(input, player, reject)
         if not input then return end
         return input:lower() == 'true' or input:lower() == 'yes' or false
    @@ -1709,7 +1757,7 @@ 

    Creation <
    -

    Add default values to params, only as an effect if the param is optional, if default value is a function it is called with acting player

    +

    Add default values to params, only as an effect if the param is optional, if default value is a function it is called with the acting player

    @@ -1729,7 +1777,7 @@

    Creation < (table) - table which is keyed by the name of the param and the value is the default value + A table which is keyed by the name of the param and the value is the default value for that param @@ -1742,8 +1790,8 @@

    Creation < Returns:
    • - (Commands._prototype) - pass through to allow more functions to be called + (table) + Pass through to allow more functions to be called
    @@ -1775,7 +1823,7 @@

    Creation <
    -

    Adds a tag to the command which is passed via the flags param to the authenticators, can be used to assign command roles or type

    +

    Adds a flag to the command which is passed via the flags param to the authenticators, can be used to assign command roles or usage type

    @@ -1795,7 +1843,7 @@

    Creation < (string) - the name of the tag to be added, set to true if no value is given + The name of the flag to be added, set to true if no value is given @@ -1811,7 +1859,7 @@

    Creation < (any) - the tag that you want can be anything that the authenticators are expecting + The value for the flag, can be anything that the authenticators are expecting (default: true) @@ -1825,8 +1873,8 @@

    Creation < Returns:
    • - (Commands._prototype) - pass through to allow more functions to be called + (table) + Pass through to allow more functions to be called
    @@ -1848,13 +1896,13 @@

    Creation <
    # - Commands._prototype:add_alias(any) + Commands._prototype:add_alias(...)
    -

    Adds an alias, or multiple, that will also be registered with the same callback, eg /teleport can be used as /tp

    +

    Adds an alias, or multiple, that will be registered to this command, eg /teleport can be used as /tp

    @@ -1868,13 +1916,13 @@

    Creation <
  • - any + ... : (string) - ... amount of aliases that you want this command to be callable with + Any amount of aliases that you want this command to be callable with
  • @@ -1887,8 +1935,8 @@

    Creation < Returns:
    • - (Commands._prototype) - pass through to allow more functions to be called + (table) + Pass through to allow more functions to be called
    @@ -1914,9 +1962,8 @@

    Creation <
    -

    Enables auto concatenation of any params on the end so quotes are not needed for last param -nb: this will disable max param checking as they will be concatenated onto the end of that last param -this can be useful for reasons or longs text, can only have one per command

    +

    Enables auto concatenation for this command, all params after the last are added to the last param, useful for reasons or other long text input +nb: this will disable max param checking as they will be concatenated onto the end of that last param

    @@ -1926,8 +1973,8 @@

    Creation < Returns:
    • - (Commands._prototype) - pass through to allow more functions to be called + (table) + Pass through to allow more functions to be called
    @@ -1953,7 +2000,7 @@

    Creation <
    -

    Adds the callback to the command and registers all aliases, params and help message with the game api +

    Adds the callback to the command and registers: aliases, params and help message with the base game api nb: this must be the last function ran on the command and must be done for the command to work

    @@ -1974,7 +2021,7 @@

    Creation < (function) - the callback for the command, will receive the player running command, and params added with add_param + The callback for the command, will receive the player running command, and any params added with add_param @@ -1992,12 +2039,12 @@

    Creation < Usage: -
    -- Registering your command to the game api
    -command:register(function(player, repeat_count, smiley, _)
    +    
    -- Registering your command to the base game api
    +command:register(function(player, repeat_count, smiley, raw)
         local msg = ') '..player.name
         if smiley then msg = ':'..msg end
     
    -    for 1 = 1,repeat_count do
    +    for 1 = 1, repeat_count do
             Command.print(1..msg)
         end
     end)
    @@ -2010,15 +2057,14 @@

    Status
    - # - error([error_message=''][, play_sound=utility/wire_pickup]) + # + success([value])
    -

    Sends an error message to the player and when returned will stop exicution of the command -nb: this is for non fatal errors meaning there is no log of this event, use during register callback

    +

    Sends a value to the player, followed by a command complete message, returning a value will trigger this automatically

    @@ -2032,32 +2078,15 @@

    Status
  • - error_message - - : - - (string) - - an optional error message that can be sent to the user - - (default: '') -
  • - - - - - -
  • - - play_sound + value : - (string) + (any) - the sound to play for the error + The value to return to the player, if nil then only the success message is returned - (default: utility/wire_pickup) + (optional)
  • @@ -2069,8 +2098,8 @@

    Status Returns:
    • - (Commands.defines.error) - return this to command handler to exit execution + (Commands.defines.success) + Return this to the command handler to prevent two success messages
    @@ -2081,23 +2110,24 @@

    Status Usage: -
    -- Send an error message to the player, and stops further code running
    -return Commands.error('The player you selected is offline')
    +
    -- Print a custom success message
    +return Commands.success('Your message has been printed')
    +
    -- Returning the value has the same result
    +return 'Your message has been printed'

    - # - internal_error(success, command_name, error_message) + # + print(value, colour)
    -

    Sends an error to the player and logs the error, used with pcall within command handler please avoid direct use -nb: use error(error_message) within your callback to trigger do not trigger directly as code exictuion may still continue

    +

    Sends a value to the player, different to success as this does not signal the end of your command

    @@ -2111,29 +2141,13 @@

    Status
  • - success - - : - - (boolean) - - the success value returned from pcall, or just false to trigger error - -
  • - - - - - -
  • - - command_name + value : - (string) + (any) - the name of the command this is used within the log + The value that you want to return to the player
  • @@ -2143,13 +2157,13 @@

    Status
  • - error_message + colour : - (string) + (table) - the error returned by pcall or some other error, this is logged and not returned to player + The colour of the message that the player sees
  • @@ -2159,13 +2173,6 @@

    Status - Returns: -
      -
    • - (boolean) - the opposite of success so true means to cancel execution, used internally -
    • -
    @@ -2174,26 +2181,23 @@

    Status Usage: -
    -- Used in the command system to log handler errors
    -local success, err = pcall(command_data.callback, player, unpack(params))
    -if Commands.internal_error(success, command_data.name, err) then
    -    return command_log(player, command_data, 'Internal Error: Command Callback Fail', raw_params, command_event.parameter, err)
    -end
    +
    -- Output a message to the player
    +Commands.print('Your command is in progress')

    - # - success([value]) + # + error([error_message=''][, play_sound=utility/wire_pickup])
    -

    Sends a value to the player, followed by a command complete message -nb: returning any value from your callback will trigger this function, return this function to prevent duplicate messages

    +

    Sends an error message to the player and when returned will stop execution of the command +nb: this is for non fatal errors meaning there is no log of this event, use during register callback

    @@ -2207,15 +2211,32 @@

    Status
  • - value + error_message : - (any) + (string) - the value to return to the player, if nil then only success message returned + An optional error message that can be sent to the user - (optional) + (default: '') +
  • + + + + + +
  • + + play_sound + + : + + (string) + + The sound to play for the error + + (default: utility/wire_pickup)
  • @@ -2227,8 +2248,8 @@

    Status Returns:
    • - (Commands.defines.success) - return this to the command handler to prevent two success messages + (Commands.defines.error) + Return this to command handler to terminate execution
    @@ -2239,24 +2260,23 @@

    Status Usage: -
    -- Print a custom success message
    -return Commands.success('Your message has been printed')
    -
    -- Returning the value has the same result
    -return 'Your message has been printed'
    +
    -- Send an error message to the player, and stops further code running
    +return Commands.error('The player you selected is offline')

    - # - print(value, colour) + # + internal_error(success, command_name, error_message)
    -

    Sends a value to the player, different to success as this does not signal the end of your command

    +

    Sends an error to the player and logs the error, used internally please avoid direct use +nb: use error(error_message) within your callback to trigger do not trigger directly as code execution may still continue

    @@ -2270,13 +2290,13 @@

    Status
  • - value + success : - (any) + (boolean) - the value that you want to return to the player + The success value returned from pcall, or just false to trigger error
  • @@ -2286,13 +2306,29 @@

    Status
  • - colour + command_name : - (table) + (string) - the colour of the message that the player sees + The name of the command this is used within the log + +
  • + + + + + +
  • + + error_message + + : + + (string) + + The error returned by pcall or some other error, this is logged and not returned to player
  • @@ -2302,6 +2338,13 @@

    Status + Returns: +
      +
    • + (boolean) + The opposite of success so true means to cancel execution, used internally +
    • +
    @@ -2310,8 +2353,11 @@

    Status Usage: -
    -- Output a message to the player
    -Commands.print('Your command is in progress')
    +
    -- Used in the command system to log handler errors
    +local success, err = pcall(command_data.callback, player, unpack(params))
    +if Commands.internal_error(success, command_data.name, err) then
    +    return command_log(player, command_data, 'Internal Error: Command Callback Fail', raw_params, command_event.parameter, err)
    +end

    @@ -2345,7 +2391,7 @@

    Status (table) - passed directly from command event from the add_command function + Passed directly from the add_command function @@ -2382,7 +2428,7 @@

    Status generated by LDoc

    diff --git a/docs/core/Common.html b/docs/core/Common.html index 2adc2dbf06..355d0dc236 100644 --- a/docs/core/Common.html +++ b/docs/core/Common.html @@ -44,7 +44,7 @@

    Sections

    - + @@ -56,10 +56,12 @@

    Core

    + + + - @@ -88,9 +90,8 @@

    Addons

    - + - @@ -113,12 +114,25 @@

    Guis

    + @@ -190,8 +206,8 @@

    Modules

    @@ -207,7 +223,7 @@

    Jump to Section

    - + @@ -353,7 +369,7 @@

    Value Returns

    -

    Formating

    +

    Formatting

    @@ -747,7 +763,7 @@

    Type Usage:
    -- Check for a string or table
    -local is_string_or_table = multi_type_check(value, {'string','table'})
    +
    local is_string_or_table = multi_type_check(value, {'string', 'table'}) @@ -855,7 +871,7 @@

    Type Usage:
    -- Raise error if value is not a string or table
    -multi_type_error('foo', {'string','table'}, 'Value must be a string or table')
    +multi_type_error('foo', {'string', 'table'}, 'Value must be a string or table') @@ -1075,9 +1091,9 @@

    Type Usage:
    -- Output: "Bad argument #2 to "<anon>"; argument is of type number expected string or table"
    -validate_argument_type(value, {'string','table'}, 2)
    +validate_argument_type(value, {'string', 'table'}, 2)
    -- Output: "Bad argument #2 to "<anon>"; "player" is of type number expected string or table"
    -validate_argument_type(value, {'string','table'}, 2, 'player')
    +validate_argument_type(value, {'string', 'table'}, 2, 'player') @@ -1948,7 +1964,7 @@

    Valu -

    Formating

    +

    Formatting

    @@ -2056,7 +2072,7 @@

    Formating table) - a color which contains r,g,b as its keys + a color which contains r, g, b as its keys @@ -2132,7 +2148,7 @@

    Formating table) - a color which contains r,g,b as its keys + a color which contains r, g, b as its keys @@ -2480,7 +2496,7 @@

    Factorio < (table) - the position that the items will be moved to {x=100,y=100} + the position that the items will be moved to {x=100, y=100} (default: {0) @@ -2540,7 +2556,7 @@

    Factorio < Usage: -
    -- Copy all the items in a players inventory and place them in chests at {0,0}
    +    
    -- Copy all the items in a players inventory and place them in chests at {0, 0}
     move_items(game.player.get_main_inventory().get_contents())
    @@ -2678,7 +2694,7 @@

    Factorio < Usage: -
    -- Place a 0 at {0,0}
    +    
    -- Place a 0 at {0, 0}
     print_grid_value(0, game.player.surface, { x=0, y=0 })
    @@ -2751,7 +2767,7 @@

    Factorio < generated by LDoc diff --git a/docs/core/Datastore.html b/docs/core/Datastore.html new file mode 100644 index 0000000000..062ec7f025 --- /dev/null +++ b/docs/core/Datastore.html @@ -0,0 +1,2972 @@ + + + + + + + + Datastore core + + + + + + + +
    +
    + + + + + + + +
    + + + + + + + + +

    Datastore core

    +

    Core Module - Datastore +- A module used to store data in the global table with the option to have it sync to an external source.

    +

    + + + + + + +

    Usage

    +
    -- Types of Datastore
    +-- This datastore will not save data externally and can be used to watch for updates on values within it
    +-- A common use might be to store data for a gui and only update the gui when a value changes
    +local LocalDatastore = Datastore.connect('LocalDatastore')
    +
    +-- This datastore will allow you to use the save and request method, this allows you to have persistent data
    +-- Should be used over auto save as it creates less save requests, but this means you need to tell the data to be saved
    +-- We use this type for player data as we know the data only needs to be saved when the player leaves
    +local PersistentDatastore = Datastore.connect('PersistentDatastore', true) -- save_to_disk
    +
    +-- This datastore is the same as above but the save method will be called automatically when ever you change a value
    +-- An auto save datastore should be used if the data does not change often, this can be global settings and things of that sort
    +-- If it is at all possible to setup events to unload and/or save the data then this is preferable
    +local AutosaveDatastore = Datastore.connect('AutosaveDatastore', true, true) -- save_to_disk, auto_save
    +
    +-- Finally you can have a datastore that propagates its changes to all other connected servers, this means request does not need to be used
    +-- This should be used when you might have data conflicts while saving, this is done by pushing the saved value to all active servers
    +-- The request method has little use after server start as any external changes to the value will be pushed automatically
    +-- Auto save can also be used with this type and you should follow the same guidelines above for when this should be avoided
    +local PropagateDatastore = Datastore.connect('PropagateDatastore', true, false, true) -- save_to_disk, propagate_changes
    +
    +
    -- Using Datastores Locally
    +-- Once you have your datastore connection setup, any further requests with connect will return the same datastore
    +-- This is important to know because the settings passed as parameters you have an effect when it is first created
    +
    +-- One useful thing that you might want to set up before runtime is a serializer, this will convert non string keys into strings
    +-- This serializer will allow use to pass a player object and still have it serialized to the players name
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:set_serializer(function(rawKey)
    +    return rawKey.name
    +end)
    +
    +-- If we want to get data from the datastore we can use get or get_all
    +local value = ExampleData:get(player, defaultValue)
    +local values = ExampleData:get_all()
    +
    +-- If we want to set data then we can use set, increment, update, or update_all
    +ExampleData:set(player, 10)
    +ExampleData:increment(player)
    +ExampleData:update(player, function(player_name, value)
    +    return value * 2
    +end)
    +ExampleData:update_all(function(player_name, value)
    +    return value * 2
    +end)
    +
    +-- If we want to remove data then we use remove
    +ExampleData:remove(player)
    +
    +-- We can also listen for updates to a value done by any of the above methods with on_update
    +ExampleData:on_update(function(player_name, value)
    +    game.print(player_name..' has had their example data updated to '..tostring(value))
    +end)
    +
    -- Using Datastore Externally
    +-- If save_to_disk is used then this opens up the option for persistent data which you can request, save, and remove
    +-- All of the local methods are still usable put now there is the option for extra events
    +-- In order for this to work there must be an external script to read datastore.pipe and inject with Datastore.ingest
    +
    +-- To request data you would use request and the on_load event, this event can be used to modify data before it is used
    +ExampleData:request(player)
    +ExampleData:on_load(function(player_name, value)
    +    game.print('Loaded example data for '..player_name)
    +    -- A value can be returned here to overwrite the received value
    +end)
    +
    +-- To save data you would use save and the on_save event, this event can be used to modify data before it is saved
    +ExampleData:save(player)
    +ExampleData:on_save(function(player_name, value)
    +    game.print('Saved example data for '..player_name)
    +    -- A value can be returned here to overwrite the value which is saved
    +end)
    +
    +-- To remove data locally but not externally, like if a player logs off, you would use unload and on_unload
    +ExampleData:unload(player)
    +ExampleData:on_unload(function(player_name, value)
    +    game.print('Unloaded example data for '..player_name)
    +    -- Any return is ignored, this is event is for cleaning up other data
    +end)
    +
    -- Using Datastore Messaging
    +-- The message action can be used regardless of save_to_disk being set as no data is saved, but an external script is still required
    +-- These messages can be used to send data to other servers which doesnt need to be saved such as shouts or commands
    +-- Using messages is quite simple only using message and on_message
    +ExampleData:message(key, message)
    +ExampleData:on_message(function(key, message)
    +    game.print('Received message '..message)
    +end)
    +
    -- Combined Datastores
    +-- A combined datastore is a datastore which stores its data inside of another datastore
    +-- This means that the data is stored more efficiently in the external database and less requests need to be made
    +-- To understand how combined datastores work think of each key in the parent as a table where the sub datastore is a key in that table
    +-- Player data is the most used version of the combined datastore, below is how the player data module is setup
    +local PlayerData = Datastore.connect('PlayerData', true) -- saveToDisk
    +PlayerData:set_serializer(Datastore.name_serializer) -- use player name as key
    +PlayerData:combine('Statistics')
    +PlayerData:combine('Settings')
    +PlayerData:combine('Required')
    +
    +-- You can then further combine datastores to any depth, below we add some possible settings and statistics that we might use
    +-- Although we dont in this example, each of these functions returns the datastore object which you should use as a local value
    +PlayerData.Settings:combine('Color')
    +PlayerData.Settings:combine('Quickbar')
    +PlayerData.Settings:combine('JoinMessage')
    +PlayerData.Statistics:combine('Playtime')
    +PlayerData.Statistics:combine('JoinCount')
    +
    +-- Because sub datastore work just like a normal datastore you dont need any special code, using get and set will still return as if it wasnt a sub datastore
    +-- Things like the serializer and the datastore settings are always the same as the parent so you dont need to worry about setting up the serializer each time
    +-- And because save, request, and unload methods all point to the root datastore you are able to request and save your data as normal
    +
    +-- If you used get_all on PlayerData this is what you would get:
    +{
    +    Cooldude2606 = {
    +        Settings = {
    +            Color = 'ColorValue',
    +            Quickbar = 'QuickbarValue',
    +            JoinMessage = 'JoinMessageValue'
    +        },
    +        Statistics = {
    +            Playtime = 'PlaytimeValue',
    +            JoinCount = 'JoinCountValue'
    +        }
    +    }
    +}
    +
    +-- If you used get_all on PlayerData.Settings this is what you would get:
    +{
    +    Cooldude2606 = {
    +        Color = 'ColorValue',
    +        Quickbar = 'QuickbarValue',
    +        JoinMessage = 'JoinMessageValue'
    +    }
    +}
    +
    +-- If you used get_all on PlayerData.Settings.Color this is what you would get:
    +{
    +    Cooldude2606 = 'ColorValue'
    +}
    + + + + + +

    + +

    Dependencies

    + +
    + + + + + +
    utils.event
    + + +

    Fields

    + + + + + + + + +
    global.datastoresSave datastores in the global table
    + + +

    Datastore Manager

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    metatableMetatable used on datastores
    connect(datastoreName[, saveToDisk=false][, autoSave=false][, propagateChanges=false])Make a new datastore connection, if a connection already exists then it is returned
    combine(datastoreName, subDatastoreName)Make a new datastore that stores its data inside of another one
    ingest(action, datastoreName, key, valueJson)Ingest the result from a request, this is used through a rcon interface to sync data
    debug([datastoreName])Debug, Use to get all datastores, or return debug info on a datastore
    name_serializer(rawKey)Commonly used serializer, returns the name of the object
    + + +

    Datastore Internal

    + + + + + + + + + + + + + + + + + + + + + + + + +
    debug()Debug, Get the debug info for this datastore
    raw_get(key[, fromChild=false])Internal, Get data following combine logic
    raw_set(key, value)Internal, Set data following combine logic
    serialize(rawKey)Internal, Return the serialized key
    write_action(action, key, value)Internal, Writes an event to the output file to be saved and/or propagated
    + + +

    Datastore Local

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    combine(subDatastoreName)Create a new datastore which is stores its data inside of this datastore
    set_serializer(callback)Set a callback that will be used to serialize keys which aren't strings
    set_default(value, allowSet)Set a default value to be returned by get if no other default is given, using will mean get will never return nil, set using the default will set to nil to save space
    set_metadata(tags)Set metadata tags on this datastore which can be accessed by other scripts
    get(key[, default])Get a value from local storage, option to have a default value, do not edit the data returned as changes may not save, use update if you want to make changes
    set(key, value)Set a value in local storage, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save
    increment(key[, delta=1])Increment the value in local storage, only works for number values, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save
    update(key, callback)Use a function to update the value locally, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save
    remove(key)Remove a value locally and on the external source, works regardless of propagateChanges, requires save_to_disk for external changes
    get_all([callback])Get all keys in this datastore, optional filter callback
    update_all(callback)Update all keys in this datastore using the same update function
    + + +

    Datastore External

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    request(key)Request a value from an external source, will trigger on_load when data is received
    save(key)Save a value to an external source, will trigger on_save before data is saved, save_to_disk must be set to true
    unload(key)Save a value to an external source and remove locally, will trigger on_unload then on_save, save_to_disk is not required for on_unload
    message(key, message)Use to send a message over the connection, works regardless of saveToDisk and propagateChanges
    save_all([callback])Save all the keys in the datastore, optional filter callback
    unload_all([callback])Unload all the keys in the datastore, optional filter callback
    + + +

    Events

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    raise_event(event_name, key[, value][, old_value][, source])Internal, Raise an event on this datastore
    on_loadRegister a callback that triggers when data is loaded from an external source, returned value is saved locally
    on_saveRegister a callback that triggers before data is saved, returned value is saved externally
    on_unloadRegister a callback that triggers before data is unloaded, returned value is ignored
    on_messageRegister a callback that triggers when a message is received, returned value is ignored
    on_updateRegister a callback that triggers any time a value is changed, returned value is ignored
    + + +
    + + +

    Dependencies

    +
    +
    +
    +
    + # + utils.event +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +

    Fields

    +
    +
    +
    +
    + # + global.datastores +
    +
    +
    +
    + +

    Save datastores in the global table

    +

    + + + + + + + + + + + + + + +
    +
    +

    Datastore Manager

    +
    +
    +
    +
    + # + metatable +
    +
    +
    +
    + +

    Metatable used on datastores

    +

    + + + Fields: + +
      + + + + + +
    • + + __index + + + + + +
    • + + + + + +
    • + + __newidnex + + + + + +
    • + + + + + +
    • + + __call + + + + + +
    • + + +
    + + + + + + + + + + + + + +
    +
    +
    +
    + # + connect(datastoreName[, saveToDisk=false][, autoSave=false][, propagateChanges=false]) +
    +
    +
    +
    + +

    Make a new datastore connection, if a connection already exists then it is returned

    +

    + + + Parameters: + +
      + + + + + +
    • + + datastoreName + + : + + (string) + + The name that you want the new datastore to have, this can not have any whitespace + +
    • + + + + + +
    • + + saveToDisk + + : + + (boolean) + + When set to true, using the save method with write the data to datastore.pipe + + (default: false) +
    • + + + + + +
    • + + autoSave + + : + + (boolean) + + When set to true, using any method which modifies data will cause the data to be saved + + (default: false) +
    • + + + + + +
    • + + propagateChanges + + : + + (boolean) + + When set to true, using the save method will send the data to all other connected servers + + (default: false) +
    • + + +
    + + + + + Returns: +
      +
    • + (table) + The new datastore connection that can be used to access and modify data in the datastore +
    • +
    + + + + + + + + Usage: +
    -- Connecting to the test datastore which will allow saving to disk
    +local ExampleData = Datastore.connect('ExampleData', true) -- saveToDisk
    +
    + + +
    +
    +
    +
    + # + combine(datastoreName, subDatastoreName) +
    +
    +
    +
    + +

    Make a new datastore that stores its data inside of another one

    +

    + + + Parameters: + +
      + + + + + +
    • + + datastoreName + + : + + (string) + + The name of the datastore that will contain the data for the new datastore + +
    • + + + + + +
    • + + subDatastoreName + + : + + (string) + + The name of the new datastore, this name will also be used as the key inside the parent datastore + +
    • + + +
    + + + + + Returns: +
      +
    • + (table) + The new datastore connection that can be used to access and modify data in the datastore +
    • +
    + + + + + + + + Usage: +
    -- Setting up a datastore which stores its data inside of another datastore
    +local BarData = Datastore.combine('ExampleData', 'Bar')
    + + +
    +
    +
    +
    + # + ingest(action, datastoreName, key, valueJson) +
    +
    +
    +
    + +

    Ingest the result from a request, this is used through a rcon interface to sync data

    +

    + + + Parameters: + +
      + + + + + +
    • + + action + + : + + (string) + + The action that should be done, can be: remove, message, propagate, or request + +
    • + + + + + +
    • + + datastoreName + + : + + (string) + + The name of the datastore that should have the action done to it + +
    • + + + + + +
    • + + key + + : + + (string) + + The key of that datastore that is having the action done to it + +
    • + + + + + +
    • + + valueJson + + : + + (string) + + The json string for the value being ingested, remove does not require a value + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Replying to a data request
    +Datastore.ingest('request', 'ExampleData', 'TestKey', 'Foo')
    + + +
    +
    +
    +
    + # + debug([datastoreName]) +
    +
    +
    +
    + +

    Debug, Use to get all datastores, or return debug info on a datastore

    +

    + + + Parameters: + +
      + + + + + +
    • + + datastoreName + + : + + (string) + + The name of the datastore to get the debug info of + + (optional) +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Get all the datastores
    +local datastores = Datastore.debug()
    +
    -- Getting the debug info for a datastore
    +local debug_info = Datastore.debug('ExampleData')
    + + +
    +
    +
    +
    + # + name_serializer(rawKey) +
    +
    +
    +
    + +

    Commonly used serializer, returns the name of the object

    +

    + + + Parameters: + +
      + + + + + +
    • + + rawKey + + : + + (any) + + The raw key that will be serialized, this can be things like player, force, surface, etc + +
    • + + +
    + + + + + Returns: +
      +
    • + (string) + The name of the object that was passed +
    • +
    + + + + + + + + Usage: +
    -- Using the name serializer for your datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:set_serializer(Datastore.name_serializer)
    + + +
    +
    +

    Datastore Internal

    +
    +
    +
    +
    + # + debug() +
    +
    +
    +
    + +

    Debug, Get the debug info for this datastore

    +

    + + + + + + Returns: +
      +
    • + (table) + The debug info for this datastore, contains stuff like parent, settings, children, etc +
    • +
    + + + + + + + + Usage: +
    -- Get the debug info for a datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +local debug_info = ExampleData:debug()
    + + +
    +
    +
    +
    + # + raw_get(key[, fromChild=false]) +
    +
    +
    +
    + +

    Internal, Get data following combine logic

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (string) + + The key to get the value of from this datastore + +
    • + + + + + +
    • + + fromChild + + : + + (boolean) + + If the get request came from a child of this datastore + + (default: false) +
    • + + +
    + + + + + Returns: +
      +
    • + (any) + The value that was stored at this key in this datastore +
    • +
    + + + + + + + + Usage: +
    -- Internal, Get the data from a datastore
    +local value = self:raw_get('TestKey')
    + + +
    +
    +
    +
    + # + raw_set(key, value) +
    +
    +
    +
    + +

    Internal, Set data following combine logic

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (string) + + The key to set the value of in this datastore + +
    • + + + + + +
    • + + value + + : + + (any) + + The value that will be set at this key + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Internal, Set the value in a datastore
    +self:raw_set('TestKey', 'Foo')
    + + +
    +
    +
    +
    + # + serialize(rawKey) +
    +
    +
    +
    + +

    Internal, Return the serialized key

    +

    + + + Parameters: + +
      + + + + + +
    • + + rawKey + + : + + (any) + + The key that needs to be serialized, if it is already a string then it is returned + +
    • + + +
    + + + + + Returns: +
      +
    • + (string) + The key after it has been serialized +
    • +
    + + + + + + + + Usage: +
    -- Internal, Ensure that the key is a string
    +key = self:serialize(key)
    + + +
    +
    +
    +
    + # + write_action(action, key, value) +
    +
    +
    +
    + +

    Internal, Writes an event to the output file to be saved and/or propagated

    +

    + + + Parameters: + +
      + + + + + +
    • + + action + + : + + (string) + + The action that should be wrote to datastore.pipe, can be request, remove, message, save, propagate + +
    • + + + + + +
    • + + key + + : + + (string) + + The key that the action is being preformed on + +
    • + + + + + +
    • + + value + + : + + (any) + + The value that should be used with the action + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Write a data request to datastore.pipe
    +self:write_action('request', 'TestKey')
    +
    -- Write a data save to datastore.pipe
    +self:write_action('save', 'TestKey', 'Foo')
    + + +
    +
    +

    Datastore Local

    +
    +
    +
    +
    + # + combine(subDatastoreName) +
    +
    +
    +
    + +

    Create a new datastore which is stores its data inside of this datastore

    +

    + + + Parameters: + +
      + + + + + +
    • + + subDatastoreName + + : + + (string) + + The name of the datastore that will have its data stored in this datastore + +
    • + + +
    + + + + + Returns: +
      +
    • + (table) + The new datastore that was created inside of this datastore +
    • +
    + + + + + + + + Usage: +
    -- Add a new sub datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +local BarData = ExampleData:combine('Bar')
    + + +
    +
    +
    +
    + # + set_serializer(callback) +
    +
    +
    +
    + +

    Set a callback that will be used to serialize keys which aren't strings

    +

    + + + Parameters: + +
      + + + + + +
    • + + callback + + : + + (function) + + The function that will be used to serialize non string keys passed as an argument + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Set a custom serializer, this would be the same as Datastore.name_serializer
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:set_serializer(function(rawKey)
    +    return rawKey.name
    +end)
    + + +
    +
    +
    +
    + # + set_default(value, allowSet) +
    +
    +
    +
    + +

    Set a default value to be returned by get if no other default is given, using will mean get will never return nil, set using the default will set to nil to save space

    +

    + + + Parameters: + +
      + + + + + +
    • + + value + + : + + (any) + + The value that will be deep copied by get if the value is nil and no other default is given + +
    • + + + + + +
    • + + allowSet + + : + + (boolean) + + When true if the default is passed as the value for set it will be set rather than setting nil + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Set a default value to be returned by get
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:set_default('Foo')
    + + +
    +
    +
    +
    + # + set_metadata(tags) +
    +
    +
    +
    + +

    Set metadata tags on this datastore which can be accessed by other scripts

    +

    + + + Parameters: + +
      + + + + + +
    • + + tags + + : + + (table) + + A table of tags that you want to set in the metadata for this datastore + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Adding metadata that could be used by a gui to help understand the stored data
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:set_metadata{
    +    caption = 'Test Data',
    +    tooltip = 'Data used for testing datastores',
    +    type = 'table'
    +}
    + + +
    +
    +
    +
    + # + get(key[, default]) +
    +
    +
    +
    + +

    Get a value from local storage, option to have a default value, do not edit the data returned as changes may not save, use update if you want to make changes

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to get the value of, must be a string unless a serializer is set + +
    • + + + + + +
    • + + default + + : + + (any) + + The default value that will be returned if no value is found in the datastore + + (optional) +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Get a key from the datastore, the default will be deep copied if no value exists in the datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +local value = ExampleData:get('TestKey')
    + + +
    +
    +
    +
    + # + set(key, value) +
    +
    +
    +
    + +

    Set a value in local storage, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to set the value of, must be a string unless a serializer is set + +
    • + + + + + +
    • + + value + + : + + (any) + + The value that you want to set for this key + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Set a value in the datastore, this will trigger on_update, if auto_save is true then will trigger save
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:set('TestKey', 'Foo')
    + + +
    +
    +
    +
    + # + increment(key[, delta=1]) +
    +
    +
    +
    + +

    Increment the value in local storage, only works for number values, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to increment the value of, must be a string unless a serializer is set + +
    • + + + + + +
    • + + delta + + : + + (number) + + The amount that you want to increment the value by, can be negative or a decimal + + (default: 1) +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Increment a value in a datastore, the value must be a number or nil, if nil 0 is used as the start value
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:increment('TestNumber')
    + + +
    +
    +
    +
    + # + update(key, callback) +
    +
    +
    +
    + +

    Use a function to update the value locally, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to apply the update to, must be a string unless a serializer is set + +
    • + + + + + +
    • + + callback + + : + + (function) + + The function that will be used to update the value at this key + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Using a function to update a value, if a value is returned then this will be the new value
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:increment('TestKey', function(key, value)
    +    return value..value
    +end)
    + + +
    +
    +
    +
    + # + remove(key) +
    +
    +
    +
    + +

    Remove a value locally and on the external source, works regardless of propagateChanges, requires save_to_disk for external changes

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to remove locally and externally, must be a string unless a serializer is set + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Remove a key locally and externally
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:remove('TestKey')
    + + +
    +
    +
    +
    + # + get_all([callback]) +
    +
    +
    +
    + +

    Get all keys in this datastore, optional filter callback

    +

    + + + Parameters: + +
      + + + + + +
    • + + callback + + : + + (function) + + The filter function that can be used to filter the results returned + + (optional) +
    • + + +
    + + + + + Returns: +
      +
    • + (table) + All the data that is in this datastore, filtered if a filter was provided +
    • +
    + + + + + + + + Usage: +
    -- Get all the data in this datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +local data = ExampleData:get_all()
    +
    -- Get all the data in this datastore, with a filter
    +local ExampleData = Datastore.connect('ExampleData')
    +local data = ExampleData:get_all(function(key, value)
    +    return type(value) == 'string'
    +end)
    + + +
    +
    +
    +
    + # + update_all(callback) +
    +
    +
    +
    + +

    Update all keys in this datastore using the same update function

    +

    + + + Parameters: + +
      + + + + + +
    • + + callback + + : + + (function) + + The update function that will be applied to each key + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Get all the data in this datastore, with a filter
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:update_all(function(key, value)
    +    return value..value
    +end)
    + + +
    +
    +

    Datastore External

    +
    +
    +
    +
    + # + request(key) +
    +
    +
    +
    + +

    Request a value from an external source, will trigger on_load when data is received

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to request from an external source, must be a string unless a serializer is set + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Request a key from an external source, on_load is triggered when data is received
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:request('TestKey')
    + + +
    +
    +
    +
    + # + save(key) +
    +
    +
    +
    + +

    Save a value to an external source, will trigger on_save before data is saved, save_to_disk must be set to true

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to save to an external source, must be a string unless a serializer is set + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Save a key to an external source, save_to_disk must be set to true for there to be any effect
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:save('TestKey')
    + + +
    +
    +
    +
    + # + unload(key) +
    +
    +
    +
    + +

    Save a value to an external source and remove locally, will trigger on_unload then on_save, save_to_disk is not required for on_unload

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to unload from the datastore, must be a string unless a serializer is set + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Unload a key from the datastore, get will now return nil and value will be saved externally if save_to_disk is set to true
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:unload('TestKey')
    + + +
    +
    +
    +
    + # + message(key, message) +
    +
    +
    +
    + +

    Use to send a message over the connection, works regardless of saveToDisk and propagateChanges

    +

    + + + Parameters: + +
      + + + + + +
    • + + key + + : + + (any) + + The key that you want to send a message over, must be a string unless a serializer is set + +
    • + + + + + +
    • + + message + + : + + (any) + + The message that you want to send to other connected servers, or external source + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Send a message to other servers on this key, can listen for messages with on_message
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:message('TestKey', 'Foo')
    + + +
    +
    +
    +
    + # + save_all([callback]) +
    +
    +
    +
    + +

    Save all the keys in the datastore, optional filter callback

    +

    + + + Parameters: + +
      + + + + + +
    • + + callback + + : + + (function) + + The filter function that can be used to filter the keys saved + + (optional) +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Save all the data in this datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +local data = ExampleData:save_all()
    +
    -- Save all the data in this datastore, with a filter
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:save_all(function(key, value)
    +    return type(value) == 'string'
    +end)
    + + +
    +
    +
    +
    + # + unload_all([callback]) +
    +
    +
    +
    + +

    Unload all the keys in the datastore, optional filter callback

    +

    + + + Parameters: + +
      + + + + + +
    • + + callback + + : + + (function) + + The filter function that can be used to filter the keys unloaded + + (optional) +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Unload all the data in this datastore
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:unload_all()
    +
    -- Unload all the data in this datastore, with a filter
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:unload_all(function(key, value)
    +    return type(value) == 'string'
    +end)
    + + +
    +
    +

    Events

    +
    +
    +
    +
    + # + raise_event(event_name, key[, value][, old_value][, source]) +
    +
    +
    +
    + +

    Internal, Raise an event on this datastore

    +

    + + + Parameters: + +
      + + + + + +
    • + + event_name + + : + + (string) + + The name of the event to raise for this datastore + +
    • + + + + + +
    • + + key + + : + + (string) + + The key that this event is being raised for + +
    • + + + + + +
    • + + value + + : + + (any) + + The current value that this key has, might be a deep copy of the value + + (optional) +
    • + + + + + +
    • + + old_value + + : + + (any) + + The previous value that this key has, might be a deep copy of the value + + (optional) +
    • + + + + + +
    • + + source + + : + + (string) + + Where this call came from, used to do event recursion so can be parent or child + + (optional) +
    • + + +
    + + + + + Returns: +
      +
    • + (any) + The value that is left after being passed through all the event handlers +
    • +
    + + + + + + + + Usage: +
    -- Internal, Getting the value that should be saved
    +value = self:raise_event('on_save', key, value)
    + + +
    +
    +
    +
    + # + on_load +
    +
    +
    +
    + +

    Register a callback that triggers when data is loaded from an external source, returned value is saved locally

    +

    + + + +
      + + + + + +
    • + + callback + + : + + (function) + + The handler that will be registered to the on_load event + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Adding a handler to on_load, returned value will be saved locally, can be used to deserialize the value beyond a normal json
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:on_load(function(key, value)
    +    game.print('Test data loaded for: '..key)
    +end)
    + + +
    +
    +
    +
    + # + on_save +
    +
    +
    +
    + +

    Register a callback that triggers before data is saved, returned value is saved externally

    +

    + + + +
      + + + + + +
    • + + callback + + : + + (function) + + The handler that will be registered to the on_load event + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Adding a handler to on_save, returned value will be saved externally, can be used to serialize the value beyond a normal json
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:on_save(function(key, value)
    +    game.print('Test data saved for: '..key)
    +end)
    + + +
    +
    +
    +
    + # + on_unload +
    +
    +
    +
    + +

    Register a callback that triggers before data is unloaded, returned value is ignored

    +

    + + + +
      + + + + + +
    • + + callback + + : + + (function) + + The handler that will be registered to the on_load event + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Adding a handler to on_unload, returned value is ignored, can be used to clean up guis or local values related to this data
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:on_load(function(key, value)
    +    game.print('Test data unloaded for: '..key)
    +end)
    + + +
    +
    +
    +
    + # + on_message +
    +
    +
    +
    + +

    Register a callback that triggers when a message is received, returned value is ignored

    +

    + + + +
      + + + + + +
    • + + callback + + : + + (function) + + The handler that will be registered to the on_load event + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Adding a handler to on_message, returned value is ignored, can be used to receive messages from other connected servers without saving data
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:on_message(function(key, value)
    +    game.print('Test data message for: '..key)
    +end)
    + + +
    +
    +
    +
    + # + on_update +
    +
    +
    +
    + +

    Register a callback that triggers any time a value is changed, returned value is ignored

    +

    + + + +
      + + + + + +
    • + + callback + + : + + (function) + + The handler that will be registered to the on_load event + +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Adding a handler to on_update, returned value is ignored, can be used to update guis or send messages when data is changed
    +local ExampleData = Datastore.connect('ExampleData')
    +ExampleData:on_update(function(key, value)
    +    game.print('Test data updated for: '..key)
    +end)
    + + +
    +
    + + + +

    +

    + + + + + diff --git a/docs/core/External.html b/docs/core/External.html new file mode 100644 index 0000000000..5618848dce --- /dev/null +++ b/docs/core/External.html @@ -0,0 +1,756 @@ + + + + + + + + External core + + + + + + + +
    +
    + + + + + + + +
    + + + + + + + + +

    External core

    +

    Core Module - External +- A module used to make accessing externally set data easier.

    +

    + + + + + + +

    Usage

    +
    -- Printing all server to chat
    +local External = require 'expcore.external' --- @dep expcore.external
    +
    +local message = 'id: %s name: %s version: %s status: %s'
    +for server_id, server in pairs(External.get_servers()) do
    +    local status = External.get_server_status(server_id)
    +    game.print(message:format(server_id, server.name, server.version, status))
    +end
    + + + + + + + +

    Functions

    + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    valid()Checks that local links are valid, will try to add the links if invalid
    get_servers()Gets a table of all the servers, key is the server id, value is the server details
    get_servers_filtered(search)Gets a table of all the servers filtered by name, key is the server id, value is the server details
    get_current_server()Gets the details of the current server
    get_server_details(server_id)Gets the details of the given server
    get_server_status(server_id, raw)Gets the status of the given server
    get_server_ups()Gets the ups of the current server
    request_connection(player, server_id[, self_requested=false])Connect a player to the given server
    + + +
    + + +

    Functions

    +
    +
    +
    +
    + # + valid() +
    +
    +
    +
    + +

    Checks that local links are valid, will try to add the links if invalid

    +

    + + + + + + Returns: +
      +
    • + (boolean) + If the external data is valid, if false you should not call any other methods from External +
    • +
    + + + + + + + + Usage: +
    -- Check that external data is valid
    +if not External.valid() then
    +    -- error code here
    +end
    + + +
    +
    +
    +
    + # + get_servers() +
    +
    +
    +
    + +

    Gets a table of all the servers, key is the server id, value is the server details

    +

    + + + + + + Returns: +
      +
    • + (table) + A table containing all the servers, key is the server id, value is the server details +
    • +
    + + + + + + + + Usage: +
    -- Get all servers
    +local servers = External.get_servers()
    + + +
    +
    +
    +
    + # + get_servers_filtered(search) +
    +
    +
    +
    + +

    Gets a table of all the servers filtered by name, key is the server id, value is the server details

    +

    + + + Parameters: + +
      + + + + + +
    • + + search + + : + + (string) + + The string to search for, names, short_names and ids are checked for this string. + +
    • + + +
    + + + + + Returns: +
      +
    • + (table) + A table containing all the servers filtered by name, key is the server id, value is the server details +
    • +
    + + + + + + + + Usage: +
    -- Get all servers with public in the name
    +local servers = External.get_servers_filtered(public)
    + + +
    +
    +
    +
    + # + get_current_server() +
    +
    +
    +
    + +

    Gets the details of the current server

    +

    + + + + + + Returns: +
      +
    • + (table) + The details of the current server +
    • +
    + + + + + + + + Usage: +
    -- Get the details of the current server
    +local server = External.get_current_server()
    + + +
    +
    +
    +
    + # + get_server_details(server_id) +
    +
    +
    +
    + +

    Gets the details of the given server

    +

    + + + Parameters: + +
      + + + + + +
    • + + server_id + + : + + (string) + + The internal server if for the server you want the details of + +
    • + + +
    + + + + + Returns: +
      +
    • + (table) + The details of the given server +
    • +
    + + + + + + + + Usage: +
    -- Get the details of the given server
    +local server = External.get_server_details('eu-01')
    + + +
    +
    +
    +
    + # + get_server_status(server_id, raw) +
    +
    +
    +
    + +

    Gets the status of the given server

    +

    + + + Parameters: + +
      + + + + + +
    • + + server_id + + : + + (string) + + The internal server if for the server you want the status of + +
    • + + + + + +
    • + + raw + + : + + (boolean) + + When true Current will not be returned as status but rather the raw status for the server + +
    • + + +
    + + + + + Returns: +
      +
    • + (string) + The status of the given server, one of: Online, Modded, Protected, Current, Offline +
    • +
    + + + + + + + + Usage: +
    -- Get the status of the given server
    +local status = External.get_server_status('eu-01')
    + + +
    +
    +
    +
    + # + get_server_ups() +
    +
    +
    +
    + +

    Gets the ups of the current server

    +

    + + + + + + + + + + + + + Usage: +
    -- Get the ups of the current server
    +local server_ups = External.get_server_ups()
    + + +
    +
    +
    +
    + # + request_connection(player, server_id[, self_requested=false]) +
    +
    +
    +
    + +

    Connect a player to the given server

    +

    + + + Parameters: + +
      + + + + + +
    • + + player + + : + + (LuaPlayer) + + The player that you want to request to join a different server + +
    • + + + + + +
    • + + server_id + + : + + (string) + + The internal id of the server to connect to, can also be any address but this will show Unknown Server + +
    • + + + + + +
    • + + self_requested + + : + + (boolean) + + If the player requested the join them selfs, this will hide the message about being asked to switch + + (default: false) +
    • + + +
    + + + + + + + + + + + + Usage: +
    -- Request that a player joins a different server
    +External.request_connection(player, 'eu-01')
    +
    -- Request that a player joins a different server, by own request
    +External.request_connection(player, 'eu-01', true)
    + + +
    +
    + + + +
    +
    +
    + + + + diff --git a/docs/core/Groups.html b/docs/core/Groups.html index fcf6fcc9f5..7493f83da0 100644 --- a/docs/core/Groups.html +++ b/docs/core/Groups.html @@ -56,10 +56,12 @@

    Core

    + + + - @@ -88,9 +90,8 @@

    Addons

    - + - @@ -113,12 +114,25 @@

    Guis

    + @@ -190,8 +206,8 @@

    Modules

    @@ -1427,7 +1443,7 @@

    Players generated by LDoc diff --git a/docs/core/Gui.html b/docs/core/Gui.html index e9480d3ced..323744e8ea 100644 --- a/docs/core/Gui.html +++ b/docs/core/Gui.html @@ -61,10 +61,12 @@

    Core

    + + + - @@ -93,9 +95,8 @@

    Addons

    - + - @@ -118,12 +119,25 @@

    Guis

    + @@ -195,8 +211,8 @@

    Modules

    @@ -261,7 +277,7 @@

    Usage

    -- Making a factory function for a button which is contained within a flow
     -- This method is for when you still want to register event handlers but cant use the table method
     local example_flow_with_button =
    -Gui.element(function(event_trigger,parent,...)
    +Gui.element(function(event_trigger, parent, ...)
         -- ... shows that all other arguments from the factory call are passed to this function
         -- Here we are adding a flow which we will then later add a button to
         local flow =
    @@ -301,7 +317,7 @@ 

    Usage

    caption = 'Example Button', style = 'forward_button' -- factorio styles can be applied here } -:style(function(style,element,...) +:style(function(style, element, ...) -- style is the current style object for the elemenent -- element is the element that is being changed -- ... shows that all other arguments from the factory call are passed to this function @@ -316,7 +332,7 @@

    Usage

    type = 'button', caption = 'Example Button' } -:on_click(function(player,element,event) +:on_click(function(player, element, event) -- player is the player who interacted with the element to cause the event -- element is a refrence to the element which caused the event -- event is a raw refrence to the event data if player and element are not enough @@ -337,20 +353,20 @@

    Usage

    width = 18, height = 20 } -:on_click(function(player,_,_) +:on_click(function(player, _,_) Gui.hide_left_flow(player) end)
    -- Eample from defines, Gui.alignment, called like: Gui.alignment(parent, name, horizontal_align, vertical_align)
     -- Notice how _ are used to blank arguments that are not needed in that context and how they line up with above
     Gui.alignment =
    -Gui.element(function(_,parent,name,_,_)
    +Gui.element(function(_, parent, name, _,_)
         return parent.add{
             name = name or 'alignment',
             type = 'flow',
         }
     end)
    -:style(function(style,_,_,horizontal_align,vertical_align)
    -    style.padding = {1,2}
    +:style(function(style, _,_, horizontal_align, vertical_align)
    +    style.padding = {1, 2}
         style.vertical_align = vertical_align or 'center'
         style.horizontal_align = horizontal_align or 'right'
         style.vertically_stretchable  = style.vertical_align ~= 'center'
    @@ -1170,9 +1186,9 @@ 

    Defines Usage:
    -- Adding a right align flow
    -local alignment = Gui.alignment(element,'example_right_alignment')
    +
    local alignment = Gui.alignment(element, 'example_right_alignment')

    -- Adding a horizontal center and top align flow
    -local alignment = Gui.alignment(element,'example_center_top_alignment','center','top')
    +
    local alignment = Gui.alignment(element, 'example_center_top_alignment', 'center', 'top')

    @@ -1274,7 +1290,7 @@

    Defines Usage:
    -- Adding a scroll table with max height of 200 and column count of 3
    -local scroll_table = Gui.scroll_table(element,200,3)
    +
    local scroll_table = Gui.scroll_table(element, 200, 3)

    @@ -1607,7 +1623,7 @@

    Defines Usage:
    -- Adding a container as a base
    -local container = Gui.container(parent,'my_container',200)
    +
    local container = Gui.container(parent, 'my_container', 200)

    @@ -2921,7 +2937,7 @@

    El
    -- Using element defines with a custom factory function
     -- This method can be used if you still want to be able register event handlers but it is too complex to be compatible with LuaGuiElement.add
     local example_flow_with_button =
    -Gui.element(function(event_trigger,parent,...)
    +Gui.element(function(event_trigger, parent, ...)
         -- ... shows that all other arguments from the factory call are passed to this function
         -- parent is the element which was passed to the factory function where you should add your new element
         -- here we are adding a flow which we will then later add a button to
    @@ -3021,7 +3037,7 @@ 

    El caption = 'Example Button', style = 'forward_button' -- factorio styles can be applied here } -:style(function(style,element,...) +:style(function(style, element, ...) -- style is the current style object for the elemenent -- element is the element that is being changed -- ... shows that all other arguments from the factory call are passed to this function @@ -4150,7 +4166,7 @@

    Top Flow <
    -- Toggle your flow
     Gui.toggle_top_flow(game.player)
    -- Open your top flow
    -Gui.toggle_top_flow(game.player,true)
    +Gui.toggle_top_flow(game.player, true)

    @@ -4405,7 +4421,7 @@

    Top Flow < generated by LDoc diff --git a/docs/core/PlayerData.html b/docs/core/PlayerData.html new file mode 100644 index 0000000000..e911c5ce78 --- /dev/null +++ b/docs/core/PlayerData.html @@ -0,0 +1,539 @@ + + + + + + + + PlayerData core + + + + + + + +
    +
    + + + + + + + +
    + + + + + + + + +

    PlayerData core

    +

    Core Module - PlayerData +- A module used to store player data in a central datastore to minimize data requests and saves.

    +

    + + + + + + +

    Usage

    +
    -- Adding a colour setting for players
    +local PlayerData = require 'expcore.player_data'
    +local PlayerColors = PlayerData.Settings:combine('Color')
    +
    +-- Set the players color when their data is loaded
    +PlayerColors:on_load(function(player_name, color)
    +    local player = game.players[player_name]
    +    player.color = color
    +end)
    +
    +-- Overwrite the saved color with the players current color
    +PlayerColors:on_save(function(player_name, _)
    +    local player = game.players[player_name]
    +    return player.color -- overwrite existing data with the current color
    +end)
    +
    -- Add a playtime statistic for players
    +local Event = require 'utils.event'
    +local PlayerData = require 'expcore.player_data'
    +local Playtime = PlayerData.Statistics:combine('Playtime')
    +
    +-- When playtime reaches an hour interval tell the player and say thanks
    +Playtime:on_update(function(player_name, playtime)
    +    if playtime % 60 == 0 then
    +        local hours = playtime / 60
    +        local player = game.players[player_name]
    +        player.print('Thanks for playing on our servers, you have played for '..hours..' hours!')
    +    end
    +end)
    +
    +-- Update playtime for players, data is only loaded for online players so update_all can be used
    +Event.add_on_nth_tick(3600, function()
    +    Playtime:update_all(function(player_name, playtime)
    +        return playtime + 1
    +    end)
    +end)
    + + + + + + + +

    Dependencies

    + + + + + + + + + + + + + + + + + + + +
    utils.event
    expcore.async
    expcore.datastore
    expcore.commands
    config.expcore.command_general_parse
    + + +

    Commands

    + + + + + + + + + + + + +
    set-data-preferenceSets your data saving preference
    data-preferenceGets your data saving preference
    + + +
    + + +

    Dependencies

    +
    +
    +
    +
    + # + utils.event +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + expcore.async +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + expcore.datastore +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + expcore.commands +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + config.expcore.command_general_parse +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +

    Commands

    +
    +
    +
    +
    + # + set-data-preference +
    +
    +
    +
    + +

    Sets your data saving preference

    +

    + + + + + + + + + + + + + + +
    +
    +
    +
    + # + data-preference +
    +
    +
    +
    + +

    Gets your data saving preference

    +

    + + + + + + + + + + + + + + +
    +
    + + + +
    +
    +
    + + + + diff --git a/docs/core/Roles.html b/docs/core/Roles.html index 5a2def193f..09bd9cb7e3 100644 --- a/docs/core/Roles.html +++ b/docs/core/Roles.html @@ -43,9 +43,9 @@

    Sections

    @@ -92,9 +94,8 @@

    Addons

    - + - @@ -117,12 +118,25 @@

    Guis

    + @@ -194,8 +210,8 @@

    Modules

    @@ -210,9 +226,9 @@

    Jump to Section

    @@ -99,9 +101,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Addons

    + @@ -187,8 +203,8 @@

    Modules

    @@ -249,10 +265,7 @@

    Dependencies

    expcore.roles - expcore.store - - - utils.game + expcore.datastore utils.event @@ -364,33 +377,8 @@

    Depend
    - # - expcore.store -
    -
    -
    -
    - - - - - - - - - - - - - - - -
    -
    -
    -
    - # - utils.game + # + expcore.datastore
    @@ -718,7 +706,7 @@

    Elementsgenerated by LDoc diff --git a/docs/guis/Readme.html b/docs/guis/Readme.html index beecc8d108..b01eee7f15 100644 --- a/docs/guis/Readme.html +++ b/docs/guis/Readme.html @@ -43,6 +43,8 @@

    Sections

    @@ -67,10 +69,12 @@

    Core

    + + + - @@ -99,9 +103,8 @@

    Addons

    - + - @@ -110,12 +113,25 @@

    Addons

    + @@ -187,8 +205,8 @@

    Modules

    @@ -203,6 +221,8 @@

    Jump to Section

    @@ -243,6 +263,9 @@

    Dependencies

    + utils.event + + expcore.gui @@ -252,10 +275,16 @@

    Dependencies

    expcore.commands - utils.event + expcore.player_data + + + expcore.external - utils.game + expcore.common + + + util @@ -278,6 +307,10 @@

    Elements

    Scroll to be used with Gui.title_label tables + join_server + Used to connect to servers in server list + + welcome_content Content area for the welcome tab @@ -298,6 +331,10 @@

    Elements

    Content area for the servers tab + commands_content + Content area for the player data tab + + readme Main readme container for the center flow @@ -307,6 +344,30 @@

    Elements

    + + +

    Tables

    + + + + + + + + +
    tooltipnetwork panel black, warning black, download black
    + + +

    Fields

    + + + + + + + + +
    hovered_spritenetwork panel white, warning white, download white

    @@ -317,6 +378,31 @@

    Depend
    + # + utils.event +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    # expcore.gui
    @@ -392,8 +478,33 @@

    Depend
    - # - utils.event + # + expcore.player_data +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + expcore.external
    @@ -417,8 +528,33 @@

    Depend
    - # - utils.game + # + expcore.common +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + util
    @@ -516,6 +652,33 @@

    Elements + + + + + + +

    +
    +
    +
    + # + join_server +
    +
    +
    +
    + +

    Used to connect to servers in server list

    +

    + + + + + + + + @@ -651,6 +814,33 @@

    Elements + + + + + + +

    +
    +
    +
    + # + commands_content +
    +
    +
    +
    + +

    Content area for the player data tab

    +

    + + + + + + + + @@ -705,6 +895,87 @@

    Elements + + + + + + +

    + +

    Tables

    +
    +
    +
    +
    + # + tooltip +
    +
    +
    +
    + +

    network panel black, warning black, download black

    +

    + + + Fields: + +
      + + + + + +
    • + + wrong_version + + + + + +
    • + + +
    + + + + + + + + + + + + + +
    +
    +

    Fields

    +
    +
    +
    +
    + # + hovered_sprite +
    +
    +
    +
    + +

    network panel white, warning white, download white

    +

    + + + + + + + + @@ -727,7 +998,7 @@

    Elementsgenerated by LDoc

    diff --git a/docs/guis/Rocket-Info.html b/docs/guis/Rocket-Info.html index b112fb6ae6..772e09cfad 100644 --- a/docs/guis/Rocket-Info.html +++ b/docs/guis/Rocket-Info.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Addons

    + @@ -187,8 +203,8 @@

    Modules

    @@ -690,7 +706,7 @@

    Elementsgenerated by LDoc diff --git a/docs/guis/Science-Info.html b/docs/guis/Science-Info.html index 3b409eb27c..23f47c993e 100644 --- a/docs/guis/Science-Info.html +++ b/docs/guis/Science-Info.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Addons

    + @@ -187,8 +203,8 @@

    Modules

    @@ -569,7 +585,7 @@

    Elementsgenerated by LDoc diff --git a/docs/guis/Task-List.html b/docs/guis/Task-List.html index c9d42c2669..2ec7904b29 100644 --- a/docs/guis/Task-List.html +++ b/docs/guis/Task-List.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Addons

    + @@ -187,8 +203,8 @@

    Modules

    @@ -755,7 +771,7 @@

    Elementsgenerated by LDoc diff --git a/docs/guis/Warps-List.html b/docs/guis/Warps-List.html index 0eaf78086d..453645fdf1 100644 --- a/docs/guis/Warps-List.html +++ b/docs/guis/Warps-List.html @@ -43,6 +43,7 @@

    Sections

    @@ -67,10 +68,12 @@

    Core

    + + + - @@ -99,9 +102,8 @@

    Addons

    - + - @@ -110,12 +112,25 @@

    Addons

    + @@ -187,8 +204,8 @@

    Modules

    @@ -203,6 +220,7 @@

    Jump to Section

    @@ -246,7 +264,7 @@

    Dependencies

    expcore.gui - expcore.store + expcore.datastore utils.global @@ -255,9 +273,6 @@

    Dependencies

    utils.event - utils.game - - expcore.roles @@ -306,7 +321,7 @@

    Elements

    warp_editing - Editing state for a warp, contrins a text field and the two edit buttons + Editing state for a warp, contains a text field and the two edit buttons warp_label @@ -334,6 +349,18 @@

    Elements

    + + +

    Functions

    + + + + + + + + +
    update_wrap_buttons(player, timer, in_range)Update the warp buttons for a player

    @@ -369,8 +396,8 @@

    Depend
    - # - expcore.store + # + expcore.datastore
    @@ -434,31 +461,6 @@

    Depend - - - - - - -

    -
    -
    -
    - # - utils.game -
    -
    -
    -
    - - - - - - - - - @@ -766,7 +768,7 @@

    Elements
    -

    Editing state for a warp, contrins a text field and the two edit buttons

    +

    Editing state for a warp, contains a text field and the two edit buttons

    @@ -938,6 +940,86 @@

    Elements + + + + + + +

    +

    +

    Functions

    +
    +
    +
    +
    + # + update_wrap_buttons(player, timer, in_range) +
    +
    +
    +
    + +

    Update the warp buttons for a player

    +

    + + + Parameters: + +
      + + + + + +
    • + + player + + + + + +
    • + + + + + +
    • + + timer + + + + + +
    • + + + + + +
    • + + in_range + + : + + + Get the warp table + +
    • + + +
    + + + + + + + @@ -960,7 +1042,7 @@

    Elementsgenerated by LDoc

    diff --git a/docs/guis/server-ups.html b/docs/guis/server-ups.html index 3acdff7b3f..5f7167be3c 100644 --- a/docs/guis/server-ups.html +++ b/docs/guis/server-ups.html @@ -68,10 +68,12 @@

    Core

    + + + - @@ -100,9 +102,8 @@

    Addons

    - + - @@ -111,12 +112,25 @@

    Addons

    + @@ -188,8 +204,8 @@

    Modules

    @@ -253,6 +269,12 @@

    Dependencies

    expcore.commands + + expcore.external + + + expcore.player_data + @@ -354,6 +376,56 @@

    Depend + + + + + + + +
    +
    +
    + # + expcore.external +
    +
    +
    +
    + + + + + + + + + + + + + + + +
    +
    +
    +
    + # + expcore.player_data +
    +
    +
    +
    + + + + + + + + + @@ -436,7 +508,7 @@

    Commandsgenerated by LDoc

    diff --git a/docs/index.html b/docs/index.html index 266d509e8e..0271146012 100644 --- a/docs/index.html +++ b/docs/index.html @@ -58,6 +58,16 @@

    Core

    + + + + + + + + @@ -68,16 +78,16 @@

    Core

    + + + + - - - -
    Common Core Module - Common - Adds some commonly used functions used in many modules
    DatastoreCore Module - Datastore +- A module used to store data in the global table with the option to have it sync to an external source.
    ExternalCore Module - External +- A module used to make accessing externally set data easier.
    Gui Groups Core Module - Permission Groups - Permission group making for factorio so you never have to make one by hand again
    PlayerDataCore Module - PlayerData +- A module used to store player data in a central datastore to minimize data requests and saves.
    Roles Core Module - Roles - Factorio role system to manage custom permissions.
    StoreCore Module - Store -- Used to store and watch for updates for values in the global table

    Control

    @@ -131,7 +141,7 @@

    Addons

    Chat-Reply - Adds auto replies to chat messages; aswell as chat commands + Adds auto replies to chat messages; as well as chat commands Compilatron @@ -151,18 +161,14 @@

    Addons

    Sends alert messages to our discord server when certain events are triggered - greetings - Greets players on join + Inventory-Clear + Will move players items to spawn when they are banned or kicked, option to clear on leave Pollution-Grading Makes polution look much nice of the map, ie not one big red mess - Player-Colours - Gives players random colours when they join, also applies preset colours to those who have them - - Scorched-Earth When a player walks around the tiles under them will degrade over time, the same is true when entites are built @@ -213,19 +219,44 @@

    Guis

    - Adds a warp list gui which allows players to add and remove warp points -

    Commands

    +

    Data

    - - + + - + + + + + + + + + + + + + + + + +
    Admin-ChatCommands Module - Admin Chat - - Adds a command that allows admins to talk in a private chatAlt-ViewStores if you use alt mode or not and auto applies it
    BonusBonus Commands Module - Bonus - Adds a command that allows players to have increased stats
    GreetingsGreets players on join
    Player-ColoursGives players random colours when they join, also applies preset colours to those who have them
    QuickbarCommands Module - Quickbar + - Adds a command that allows players to load Quickbar presets
    TagCommands Module - Tag + - Adds a command that allows players to have a custom tag after their name
    +

    Commands

    + + + + + + @@ -236,6 +267,11 @@

    Commands

    - Adds a command that allows admins to clear people's inventorys + + + + @@ -301,11 +337,6 @@

    Commands

    - Adds a command that allows players to teleport to their spawn point - - - - @@ -353,7 +384,7 @@

    Configs

    - @@ -366,7 +397,7 @@

    Configs

    @@ -414,6 +445,10 @@

    Configs

    + + + + @@ -426,6 +461,10 @@

    Configs

    + + + + @@ -438,6 +477,10 @@

    Configs

    + + + + @@ -484,10 +527,10 @@

    Modules

    Topics

    Admin-ChatCommands Module - Admin Chat + - Adds a command that allows admins to talk in a private chat
    Cheat-Mode Commands Module - Cheat Mode - Adds a command that allows players to enter cheat mode
    ConnectCommands Module - Connect + - Adds a commands that allows you to request a player move to another server
    Debug Commands Module - Debug - Adds a command that opens the debug frame
    TagCommands Module - Tag - - Adds a command that allows players to have a custom tag after their name
    Teleport Commands Module - Teleport - Adds a command that allows players to teleport to other players
    Commands-Auth-AdminThis is a very simple config file which adds a admin only auth functio; + This is a very simple config file which adds a admin only auth function; not much to change here its more so it can be enabled and disabled from ./config/file_loader.lua; either way you can change the requirements to be "admin" if you wanted to
    This file contains some common command param parse functions; this file is less of a config and more of a requirement but you may wish to change how some behave; as such you need to be confident with lua but you edit this config file; -use Commands.add_parse('name',function(input,player,reject) end) to add a parse; +use Commands.add_parse('name',function(input, player, reject) end) to add a parse; see ./expcore/commands.lua for more details
    This file contains all the different settings for the warp system and gui
    inventory_clearConfig to control when players items are removed, this is a list of event names that will trigger inventory clear
    Pollution-Grading This controls how pollution is viewed on the map
    Preset colours that players get when they join the server, if not in the list then will be given a random colour (which isnt disallowed)
    Preset-Player-QuickbarPreset quickbar items that players can load
    Repair Config file for the repair command
    Used to config the spawn generation settings yes there is alot here i know just ignore the long tables at the end (they were generated with a command)
    StatisticsA list of all tracked statistics and the events which trigger them
    Warnings Config file for the warning system, this is very similar to reports but is for the use of moderators rather than normal users.
    - + - +
    readme.mdREADME.md
    licenseLICENSE
    @@ -507,7 +550,7 @@

    Topics

    generated by LDoc diff --git a/docs/modules/control.html b/docs/modules/control.html index 3542b8316b..7609ff8914 100644 --- a/docs/modules/control.html +++ b/docs/modules/control.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -124,12 +125,25 @@

    Guis

    + @@ -186,8 +202,8 @@

    Configs

    @@ -294,7 +310,7 @@

    Depend generated by LDoc diff --git a/docs/modules/modules.addons.station-auto-name.html b/docs/modules/modules.addons.station-auto-name.html index e5d0e142e4..2393a0674f 100644 --- a/docs/modules/modules.addons.station-auto-name.html +++ b/docs/modules/modules.addons.station-auto-name.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -124,12 +125,25 @@

    Guis

    + @@ -186,8 +202,8 @@

    Configs

    @@ -292,7 +308,7 @@

    Depend generated by LDoc diff --git a/docs/modules/overrides.debug.html b/docs/modules/overrides.debug.html index 3e5221fc83..e01332f32d 100644 --- a/docs/modules/overrides.debug.html +++ b/docs/modules/overrides.debug.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -124,12 +125,25 @@

    Guis

    + @@ -186,8 +202,8 @@

    Configs

    @@ -653,7 +669,7 @@

    Functionsgenerated by LDoc diff --git a/docs/modules/overrides.math.html b/docs/modules/overrides.math.html index f1734c974f..d841d36a18 100644 --- a/docs/modules/overrides.math.html +++ b/docs/modules/overrides.math.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -124,12 +125,25 @@

    Guis

    + @@ -186,8 +202,8 @@

    Configs

    @@ -352,7 +368,7 @@

    Functionsgenerated by LDoc diff --git a/docs/modules/overrides.table.html b/docs/modules/overrides.table.html index 20f2ea6897..cfe9d61319 100644 --- a/docs/modules/overrides.table.html +++ b/docs/modules/overrides.table.html @@ -69,10 +69,12 @@

    Core

    + + + - @@ -101,9 +103,8 @@

    Addons

    - + - @@ -126,12 +127,25 @@

    Guis

    + @@ -188,8 +204,8 @@

    Configs

    @@ -615,8 +631,8 @@

    Functions-- Adding 1000 values into the middle of the array local tbl = {} local values = {} -for i = 1,1000 do tbl[i] = i values[i] = i end -table.array_insert(tbl,500,values) -- around 0.4ms +for i = 1, 1000 do tbl[i] = i values[i] = i end +table.array_insert(tbl, 500, values) -- around 0.4ms

    @@ -711,8 +727,8 @@

    Functions-- Merging two tables local tbl = {} local tbl2 = {} -for i = 1,100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end -table.table_insert(tbl,50,tbl2) +for i = 1, 100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end +table.table_insert(tbl, 50, tbl2)

    @@ -1066,7 +1082,7 @@

    Functions Usage: -
    local key_three, key_one = extract({key_one='foo',key_two='bar',key_three=true},'key_three','key_one')
    +
    local key_three, key_one = extract({key_one='foo', key_two='bar', key_three=true}, 'key_three', 'key_one')

    @@ -2007,7 +2023,7 @@

    Fields< generated by LDoc diff --git a/docs/modules/utils.event.html b/docs/modules/utils.event.html index beaa2b207a..31375b50a8 100644 --- a/docs/modules/utils.event.html +++ b/docs/modules/utils.event.html @@ -68,10 +68,12 @@

    Core

    + + + - @@ -100,9 +102,8 @@

    Addons

    - + - @@ -125,12 +126,25 @@

    Guis

    + @@ -187,8 +203,8 @@

    Configs

    @@ -1291,7 +1307,7 @@

    Functionsgenerated by LDoc diff --git a/docs/modules/utils.event_core.html b/docs/modules/utils.event_core.html index c270c6ce59..58fbb75695 100644 --- a/docs/modules/utils.event_core.html +++ b/docs/modules/utils.event_core.html @@ -67,10 +67,12 @@

    Core

    + + + - @@ -99,9 +101,8 @@

    Addons

    - + - @@ -124,12 +125,25 @@

    Guis

    + @@ -186,8 +202,8 @@

    Configs

    @@ -433,7 +449,7 @@

    Functionsgenerated by LDoc diff --git a/docs/modules/utils.task.html b/docs/modules/utils.task.html index 43b62a102b..4911d74133 100644 --- a/docs/modules/utils.task.html +++ b/docs/modules/utils.task.html @@ -68,10 +68,12 @@

    Core

    + + + - @@ -100,9 +102,8 @@

    Addons

    - + - @@ -125,12 +126,25 @@

    Guis

    + @@ -187,8 +203,8 @@

    Configs

    @@ -650,7 +666,7 @@

    Functionsgenerated by LDoc diff --git a/docs/topics/license.html b/docs/topics/LICENSE.html similarity index 95% rename from docs/topics/license.html rename to docs/topics/LICENSE.html index 293edf6cc6..6caaa821c9 100644 --- a/docs/topics/license.html +++ b/docs/topics/LICENSE.html @@ -5,7 +5,7 @@ - license topic + LICENSE topic @@ -41,8 +41,8 @@ @@ -53,10 +53,12 @@

    Core

    + + + - @@ -85,9 +87,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Guis

    + @@ -199,7 +215,7 @@

    Modules

    -

    license topic

    +

    LICENSE topic

    @@ -788,7 +804,7 @@

    license topi generated by LDoc diff --git a/docs/topics/readme.md.html b/docs/topics/README.md.html similarity index 89% rename from docs/topics/readme.md.html rename to docs/topics/README.md.html index d9e08d04e7..dea000463f 100644 --- a/docs/topics/readme.md.html +++ b/docs/topics/README.md.html @@ -5,7 +5,7 @@ - readme.md topic + README.md topic @@ -41,8 +41,8 @@ @@ -53,10 +53,12 @@

    Core

    + + + - @@ -85,9 +87,8 @@

    Addons

    - + - @@ -110,12 +111,25 @@

    Guis

    + @@ -199,7 +215,7 @@

    Modules

    -

    readme.md topic

    +

    README.md topic

    @@ -249,6 +265,8 @@

    ExpGaming Scenario Repository

    ## Releases

    | Scenario Version* | Version Name | Factorio Version** | |---|---|---| +| [v6.1][s6.1] | External Data Overhaul | [v1.0.0][f1.0.0] | +| [v6.0][s6.0] | Gui / 0.18 Overhaul | [v0.18.17][f0.18.17] | | [v5.10][s5.10] | Data Store Rewrite | [v0.17.71][f0.17.71] | | [v5.9][s5.9] | Control Modules and Documentation | [v0.17.63][f0.17.63] | | [v5.8][s5.8] | Home and Chat Bot | [v0.17.47][f0.17.49] | @@ -267,7 +285,9 @@

    ExpGaming Scenario Repository

    | [v0.1][s0.1] | First Tracked Version | [v0.14][f0.14] |

    \* Scenario patch versions have been omitted.

    \*\* Factorio versions show the version they were made for, often the minimum requirement. -

    [s5.10]: https://github.com/explosivegaming/scenario/releases/tag/5.10.0 +

    [s6.1]: https://github.com/explosivegaming/scenario/releases/tag/6.1.0 +[s6.0]: https://github.com/explosivegaming/scenario/releases/tag/6.0.0 +[s5.10]: https://github.com/explosivegaming/scenario/releases/tag/5.10.0 [s5.9]: https://github.com/explosivegaming/scenario/releases/tag/5.9.0 [s5.8]: https://github.com/explosivegaming/scenario/releases/tag/5.8.0 [s5.7]: https://github.com/explosivegaming/scenario/releases/tag/5.7.0 @@ -283,7 +303,9 @@

    ExpGaming Scenario Repository

    [s2.0]: https://github.com/explosivegaming/scenario/releases/tag/v2.0 [s1.0]: https://github.com/explosivegaming/scenario/releases/tag/v1.0 [s0.1]: https://github.com/explosivegaming/scenario/releases/tag/v0.1 -

    [f0.17.71]: https://wiki.factorio.com/Version_history/0.17.0#0.17.71 +

    [f1.0.0]: https://wiki.factorio.com/Version_history/1.0.0#1.0.0 +[f0.18.17]: https://wiki.factorio.com/Version_history/0.18.0#0.18.17 +[f0.17.71]: https://wiki.factorio.com/Version_history/0.17.0#0.17.71 [f0.17.63]: https://wiki.factorio.com/Version_history/0.17.0#0.17.63 [f0.17.49]: https://wiki.factorio.com/Version_history/0.17.0#0.17.49 [f0.17.47]: https://wiki.factorio.com/Version_history/0.17.0#0.17.47 @@ -337,7 +359,7 @@

    ExpGaming Scenario Repository

    generated by LDoc diff --git a/expcore/async.lua b/expcore/async.lua index 473580aeb4..edfb3a45c6 100644 --- a/expcore/async.lua +++ b/expcore/async.lua @@ -16,11 +16,11 @@ Async.register(function(player) end) -- This will allow us to bypass the error by running one tick later outside of any player scope -Async(promote_player,game.player) +Async(promote_player, game.player) -- Here we make an sync function that we want to have a delay, note the delay is not defined here local print_message = -Async.register(function(player,message) +Async.register(function(player, message) player.print(message) end) @@ -71,7 +71,7 @@ Async.register = Token.register Async.run(set_admin, player, true) ]] -function Async.run(token,...) +function Async.run(token, ...) Task.queue_task(internal_run, { token = token, params = {...} @@ -87,15 +87,15 @@ end Async.wait(300, print_to_player, 'Hello, World!') ]] -function Async.wait(ticks,token,...) +function Async.wait(ticks, token, ...) Task.set_timeout_in_ticks(ticks, internal_run, { token = token, params = {...} }) end -return setmetatable(Async,{ - __call = function(self,...) +return setmetatable(Async, { + __call = function(self, ...) self.run(...) end }) \ No newline at end of file diff --git a/expcore/commands.lua b/expcore/commands.lua index a249ee939f..548fddddbe 100644 --- a/expcore/commands.lua +++ b/expcore/commands.lua @@ -3,19 +3,17 @@ @core Commands @alias Commands -@usage--- Full code example, see below for explaination +@usage--- Full code example, see below for explanation Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.') -:add_param('repeat-count', false, 'number-range-int', 1, 5) -- required int in range 1 to 5 inclusive +:add_param('repeat-count', 'number-range-int', 1, 5) -- required int in range 1 to 5 inclusive :add_param('smiley', true, function(input, player, reject) -- optional boolean default false if not input then return end - if input:lower() == 'true' or input:lower() == 'yes' then - return true - else - return false - end + input = input:lower() + if input == 'true' or input == 'yes' then return true end + return false end) -:set_defaults{ smiley=false } -:set_flag('admin_only', true) -- command is admin only +:set_defaults{ smiley = false } +:set_flag('admin_only') -- command is admin only :add_alias('name', 'rname') -- allow alias: name and rname :register(function(player, repeat_count, smiley, raw) game.print(player.name..' used a command with input: '..raw) @@ -25,94 +23,90 @@ end) msg = ':'..msg end - for 1 = 1,repeat_count do + for 1 = 1, repeat_count do Command.print(1..msg) end end) -@usage--- Example Command: --- How for the fun part making the commands, the commands can be set up with any number of params and flags that you want, --- you can add aliases for the commands and set default values for optional params and of course register your command callback --- in our example we will just have a command that will repeat the users name in chat X amount of times and only allow admins to use it. +@usage--- Example Command Explanation: +-- Making commands basics, the commands can be set up with any number of params and flags that you want, +-- you can add aliases for the commands and set default values for optional params and of course register your command callback. +-- In our example we will have a command that will repeat the users name in chat X amount of times and only allow admins to use it. --- First we create the new command, nb this will not register the command to the game this is done at the end, we will call --- the command "repeat-name" and set the help message as follows: +-- First we create the new command, note this will not register the command to the game this is done at the end. +-- We will call the command "repeat-name" and set the help message as follows: Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.') --- Now for our first param we will call "repeat-count" and it will be a required value between 1 and 5 inclusive: -:add_param('repeat-count', false, 'number-range-int', 1, 5) +-- Now for our first param, we have named it "repeat-count" and it will be a required value, between 1 and 5 inclusive: +-- By using "number-range-int" we are saying to use this parser to convert our input text, common ones exist in config.expcore.command_general_parse +:add_param('repeat-count', 'number-range-int', 1, 5) --- Our second param we need a custom parse for but we have not defined it, this is an option for when it is unlikely for --- any other command to use the same input type; however in our case it will just be a boolean which should be noted as being --- included in the general command parse config. As for the param its self it will be called "smiley" and will be optional with --- a default value of false: +-- Our second param needs a custom parser, meaning it isnt defined with add_parser, this is an option for when it is unlikely for +-- any other command to use the same input type. In the example it is a boolean type and we are just showing it here as part of the example. +-- As for the param its self it will be called "smiley" and will be optional with a default value of false: :add_param('smiley', true, function(input, player, reject) - -- since it is optional the input can be nil, in which case we just return + -- Since it is optional the input can be nil, in which case we just return if not input then return end - -- if it is not nil then we check for a truthy value - if input:lower() == 'true' or input:lower() == 'yes' then - return true - else - -- note that because we did not return nil or reject then false will be passed to command callback, see example parse - return false - end + -- If it is not nil then we check for a truthy value + if input == 'true' or input == 'yes' then return true end + -- Note that because we did not return nil or reject then false will be passed to command callback, see example parse + return false end) --- Once all params are defined you can now define some default values if you have optional params, the default value will be used only --- when no value is given as input, if an invalid value is given then the command will still fail and this value will not be used, the --- default can also be a function which is passed the player using the command and returns a value. Here we set the default for "smiley" to false: +-- Once all params are defined you can add some default values for your optional params, the default value will be used only +-- when no value is given as input, if an invalid value is given then the command will fail and the default will not be used, the +-- default can also be a function which is passed the player as an argument and should return a value to be the default. +-- Here we set the default for "smiley" to false: :set_defaults{smiley=false} -- Another example of defaults if we have: item, amount[opt], player[opt] :set_defaults{ - amount = 50, -- more than one value can be set at a time - player = function(player) - return player -- default is the player using the command - end + amount = 50, -- More than one value can be set at a time + player = function(player) return player end -- Default is the player using the command } --- Now the params are set up we can alter how the command works, we can set auth flags, add aliases to this command or enable "auto concat" --- which is when you want all extra words to be concatenated onto the end of the last param, useful for reason or messages: -:set_flag('admin_only', true) -- in our case we want "admin_only" to be set to true so only admins can use the command -:add_alias('name', 'rname') -- we also add two aliases here: "name" and "rname" which point to this command --- :enable_auto_concat() we do not use this in our case but this can also be used to enable the "auto concat" feature +-- Now the params are set up we can alter how the command works, we can set auth flags, add aliases, or enable "auto concat": +:set_flag('admin_only') -- In our case we want "admin_only" to be set to true so only admins can use the command +:add_alias('name', 'rname') -- We also add two aliases here: "name" and "rname" which point to this command +-- :enable_auto_concat() -- We do not use this in our case but this can also be used to enable the "auto concat" feature -- And finally we want to register a callback to this command, the callback is what defines what the command does, can be as complex as you --- want it to be to as simple as our example; the command receives two params plus all that you have defines: +-- want it to be, or as simple as our example; the command receives two params plus all param you have defined: -- 1) the player who used the command -- 2) in our case repeat_count which will be a number -- 3) in our case smiley which will be a boolean -- 4) the raw input; this param is always last as is always present as a catch all :register(function(player, repeat_count, smiley, raw) - -- this is to show the value for raw as this is an example command, the log file will also show this + -- This is to show the value for raw as this is an example command, the log file will also show this game.print(player.name..' used a command with input: '..raw) local msg = ') '..player.name + if smiley then - -- this is where that smiley param is used msg = ':'..msg end - for 1 = 1,repeat_count do + + for 1 = 1, repeat_count do -- this print function will return ANY value to the user in a desync safe manor, this includes if the command was used through rcon Command.print(1..msg) end - -- see below for what else can be used here + -- See below for what can be used here end) --- Other values that can be returned from register -Commands.print(any,colour[opt]) -- this will return any value value to the user including if it is ran through rcon console -Commands.error(message[opt]) -- this returns a warning to the user, aka an error that does not prevent execution of the command -return Commands.error(message[opt]) -- this returns an error to the user, and will halt the command execution, ie no success message is returned -Commands.success(message[opt]) -- used to return a success message however don't use this method see below -return Commands.success(message[opt]) -- will return the success message to the user and your given message, halts execution -return -- if any value is returned then it will be returned to the player via a Commands.success call +-- Values that can be returned from register callback +Commands.print(any, colour[opt]) -- This will return any value value to the user including if it is ran through rcon console +Commands.error(message[opt]) -- This returns a warning to the user, aka an error that does not prevent execution of the command +return Commands.error(message[opt]) -- This returns an error to the user, and will halt the command execution, ie no success message is returned +Commands.success(message[opt]) -- Used to return a success message however don't use this method, see below +return Commands.success(message[opt]) -- Will return the success message to the user and your given message, halts execution +return -- If any value is returned then it will be returned to the player via a Commands.success call @usage--- Example Authenticator: -- The command system is best used when you can control who uses commands; --- to do this would would need to define an authenticator which is ran every time a command is run; +-- to do this you need to define an authenticator which is ran every time a command is run; -- in this example I will show a simple one that requires certain commands to require the user to be a game admin. -- For our admin only example we will set a flag to true when we want it to be admin only; --- when we define the command will will use :set_flag('admin_only', true); +-- when we define the command will will use :set_flag('admin_only'); -- then inside the authenticator we will test if the flag is present using: if flags.admin_only then -- When the authenticator is called by the command handler it will be passed 4 arguments: @@ -126,11 +120,11 @@ return -- if any value is returned then it will be returned to the player -- 1) when the "admin_only" flag is not set, which we take assume that any one can use it -- 2) when the "admin_only" flag is set, and the player is admin --- When want to prevent exicution of the command we must reject it, listed is how that can be done: +-- When want to prevent execution of the command we must reject it, listed is how that can be done: -- 1) return false -- this is the most basic rejection and should only be used while testing -- 2) return reject -- returning the reject function is as a fail safe in case you forget to call it, same as returning false --- 3) reject() -- this will block execution without to allowing further code to be ran in your authenticator --- 4) reject('This command is for admins only!') -- Using reject as a function allows a error message to be returned +-- 3) reject() -- this will block execution while allowing further code to be ran in your authenticator +-- 4) reject('This command is for admins only!') -- using reject as a function allows a error message to be returned -- 5) return reject() -- using return on either case above is best practice as you should execute all your code before rejecting -- Example Code: @@ -145,15 +139,15 @@ Commands.add_authenticator(function(player, command, flags, reject) end end) -@usage--- Example Parse: +@usage--- Example Parser: -- Before you make a command it is important to understand the most powerful feature of this command handler; -- when you define a command you are able to type the params and have then be parsed and validated before your command is executed; --- This module should is paired with a general command parse but you may want to create your own. +-- This module should be paired with a general command parse but you may want to create your own. -- For our example we will create a parse to accept only integer numbers in a given range: -- 1) we will give it the name "number-range-int" this is the "type" that the input is expected to be -- 2) when we define the type we will also define the min and max of the range so we can use the function more than once -:add_param('repeat_count', false, 'number-range-int', 5, 10) -- "repeat_count" is required "number-range-int" in a range 5 to 10 inclusive +:add_param('repeat_count', 'number-range-int', 5, 10) -- "repeat_count" is a required "number-range-int" in a range 5 to 10 inclusive -- The command parse will be passed 3 arguments plus any other which you define, in our case: -- 1) input - the input that has been given by the user for this param, the role of this function is to transform this value @@ -178,7 +172,7 @@ input = Commands.parse('number-int', input, player, reject) if not input then return end -- nil check -- Example Code: -Commands.add_parse('number-range-int',function(input, player, reject, range_min, range_max) +Commands.add_parse('number-range-int', function(input, player, reject, range_min, range_max) local rtn = tonumber(input) and math.floor(tonumber(input)) or nil -- converts input to number if not rtn or rtn < range_min or rtn > range_max then -- the input is either not a number or is outside the range @@ -192,134 +186,194 @@ end) ]] local Game = require 'utils.game' --- @dep utils.game -local player_return,write_json = _C.player_return, _C.write_json --- @dep expcore.common +local player_return, write_json = _C.player_return, _C.write_json --- @dep expcore.common +local trace = debug.traceback local Commands = { - --- Values returned by the signal functions to cause the command system to react + --- Constant values used by the command system defines = { - error='CommandError', - unauthorized='CommandErrorUnauthorized', - success='CommandSuccess' + error = 'CommandError', + unauthorized = 'CommandErrorUnauthorized', + success = 'CommandSuccess' }, - --- Custom command data will be stored here - commands={}, - --- Set true to have authorize fail if a callback fails to run, more secure - authorization_fail_on_error=false, - --- Custom function are stored here which control who can use what commands - authorization={}, + --- An array of all custom commands that are registered + commands = {}, + --- When true any authenticator error will result in authorization failure, more secure + authorization_failure_on_error = false, + --- An array of all custom authenticators that are registered + authenticators = {}, --- Used to store default functions which are common parse function such as player or number in range - parse_functions={}, - -- Sends a value to the player, different to success as this does not signal the end of your command - print=player_return, - --- Used to store functions which gets added to new custom commands - _prototype={}, + parsers = {}, + --- Returns a value to the player, different to success as this does not signal the end of your command + print = player_return, + --- The command prototype which stores all command defining functions + _prototype = {}, } ---- Authenication. +--- Authentication. -- Functions that control who can use commands -- @section auth ---[[-- Adds an authorization callback, function used to check if a player if allowed to use a command -@tparam function callback the callback you want to register as an authenticator -@treturn number the index it was inserted at use to remove the callback, if anon function used +--[[-- Adds an authorization function, function used to check if a player if allowed to use a command +@tparam function authenticator The function you want to register as an authenticator +@treturn number The index it was inserted at, used to remove the authenticator -@usage-- Test if a command is admin only and if the player is admin +@usage-- If the admin_only flag is set, then make sure the player is an admin local admin_authenticator = Commands.add_authenticator(function(player, command, flags, reject) - if flags.admin_only then - return player.admin or reject('This command is for admins only!') + if flags.admin_only and not player.admin then + return reject('This command is for admins only!') else return true end end) ]] -function Commands.add_authenticator(callback) - table.insert(Commands.authorization,callback) - return #Commands.authorization +function Commands.add_authenticator(authenticator) + local next_index = #Commands.authenticators + 1 + Commands.authenticators[next_index] = authenticator + return next_index end ---[[-- Removes an authorization callback -@tparam function|number callback the callback to remove, an index returned by add_authenticator can be passed -@treturn boolean if the callback found and removed successfuly +--[[-- Removes an authorization function, can use the index or the function value +@tparam function|number authenticator The authenticator to remove, either the index return from add_authenticator or the function used +@treturn boolean If the authenticator was found and removed successfully -@usage-- Removing the admin authenticator, can not be done dueing runtime +@usage-- Removing the admin authenticator, can not be done during runtime Commands.remove_authenticator(admin_authenticator) ]] -function Commands.remove_authenticator(callback) - if type(callback) == 'number' then - -- if a number is passed then it is assumed to be the index - if Commands.authorization[callback] then - table.remove(Commands.authorization,callback) +function Commands.remove_authenticator(authenticator) + if type(authenticator) == 'number' then + -- If a number is passed then it is assumed to be the index + if Commands.authenticators[authenticator] then + Commands.authenticators[authenticator] = nil return true end else -- will search the array and remove the key - local index - for key,value in pairs(Commands.authorization) do - if value == callback then - index = key - break + for index, value in pairs(Commands.authenticators) do + if value == authenticator then + Commands.authenticators[index] = nil + return true end end - -- if the function was found it is removed - if index then - table.remove(Commands.authorization,index) - return true - end end return false end ---[[-- Mostly used internally, calls all authorization callbacks, returns if the player is authorized -@tparam LuaPlayer player the player that is using the command, passed to callbacks -@tparam string command_name the command that is being used, passed to callbacks -@treturn[1] boolean true player is authorized -@treturn[1] string commands const for success -@treturn[2] boolean false player is unauthorized -@treturn[2] string|locale_string the reason given by the authenticator +--[[-- Mostly used internally, calls all authenticators, returns if the player is authorized +@tparam LuaPlayer player The player who is using the command, passed to authenticators +@tparam string command_name The name of the command being used, passed to authenticators +@treturn[1] boolean true Player is authorized +@treturn[1] string commands Define value for success +@treturn[2] boolean false Player is unauthorized +@treturn[2] string|locale_string The reason given by the failed authenticator @usage-- Test if a player can use "repeat-name" local authorized, status = Commands.authorize(game.player, 'repeat-name') ]] -function Commands.authorize(player,command_name) - local failed - if not player then return true end +function Commands.authorize(player, command_name) local command_data = Commands.commands[command_name] if not command_data then return false end + if not player then return true end - -- function passed to authorization callback to make it simpler to use - local auth_fail = function(error_message) - failed = error_message or {'expcore-commands.unauthorized'} + -- This is the reject function given to authenticators + local failure_message + local function reject(message) + failure_message = message or {'expcore-commands.unauthorized'} return Commands.defines.unauthorized end - -- loops over each authorization callback if any return false or unauthorized command will fail - for _,callback in pairs(Commands.authorization) do - -- callback(player: LuaPlayer, command: string, flags: table, reject: function(error_message?: string)) - local success, rtn = pcall(callback,player,command_name,command_data.flags,auth_fail) - -- error handler - if not success then - -- the callback failed to run - log('[ERROR] Authorization failed: '..rtn) - if Commands.authorization_fail_on_error then - failed = 'Internal Error' - end - elseif rtn == false or rtn == Commands.defines.unauthorized or rtn == auth_fail or failed then - -- the callback returned unauthorized, failed be now be set if no value returned - failed = failed or {'expcore-commands.unauthorized'} - break + -- This is the internal error function used when an authenticator errors + local function authenticator_error(err) + log('[ERROR] Authorization failed: '..trace(err)) + if Commands.authorization_failure_on_error then + return reject('Internal Error') + end + end + + -- Loops over each authenticator, if any return false then then command will not be ran + for _, authenticator in pairs(Commands.authenticators) do + -- player: LuaPlayer, command: string, flags: table, reject: function(error_message: string) + local _, rtn = xpcall(authenticator, authenticator_error, player, command_name, command_data.flags, reject) + if rtn == false or rtn == Commands.defines.unauthorized or rtn == reject or failure_message ~= nil then + if failure_message == nil then failure_message = {'expcore-commands.unauthorized'} end + return false, failure_message end end - -- checks if the authorization failed - if failed then - return false, failed + return true, Commands.defines.success +end + +--- Parse. +-- Functions that help with parsing +-- @section parse + +--[[-- Adds a parse function which can be called by name (used in add_param) +nb: this is not required as you can use the callback directly this just allows it to be called by name +@tparam string name The name of the parse, should describe a type of input such as number or player, must be unique +@tparam function parser The function that is ran to parse the input string +@treturn boolean Was the parse added, will be false if the name is already used + +@usage-- Adding a parse to validate integers in a given range +Commands.add_parse('number-range-int', function(input, player, reject, range_min, range_max) + local rtn = tonumber(input) and math.floor(tonumber(input)) or nil -- converts input to number + if not rtn or rtn < range_min or rtn > range_max then + -- The input is either not a number or is outside the range + return reject('Number entered is not in range: '..range_min..', '..range_max) else - return true, Commands.defines.success + -- Returns the input as a number rather than a string, thus the param is now the correct type + return rtn end +end) + +]] +function Commands.add_parse(name, parser) + if Commands.parsers[name] then return false end + Commands.parsers[name] = parser + return true +end + +--[[-- Removes a parse function, see add_parse for adding them, cant be done during runtime +@tparam string name The name of the parse to remove + +@usage-- Removing a parse +Commands.remove_parse('number-range-int') + +]] +function Commands.remove_parse(name) + Commands.parsers[name] = nil +end + +--[[-- Intended to be used within other parse functions, runs a parse and returns success and new value +@tparam string name The name of the parse to call, must be a registered parser +@tparam string input The input to pass to the parse, must be a string but not necessarily the original input +@tparam LuaPlayer player The player that is using the command, pass directly from your arguments +@tparam function reject The reject function, pass directly from your arguments +@treturn any The new value for the input, if nil is return then either there was an error or the input was nil + +@usage-- Parsing an int after first checking it is a number +Commands.add_parse('number', function(input, player, reject) + local number = tonumber(input) + if number then return number end + return reject('Input must be a number value') +end) + +Commands.add_parse('number-int', function(input, player, reject) + local number = Commands.parse('number', input, player, reject) + if not number then return end + return math.floor(number) +end) + +]] +function Commands.parse(name, input, player, reject, ...) + if not Commands.parsers[name] then return end + local success, rtn = pcall(Commands.parsers[name], input, player, reject, ...) + if not success then error(rtn, 2) return end + if not rtn or rtn == Commands.defines.error then return end + return rtn end --- Getters. @@ -327,10 +381,10 @@ end -- @section getters --[[-- Gets all commands that a player is allowed to use, game commands are not included -@tparam[opt] LuaPlayer player the player that you want to get commands of, nil will return all commands -@treturn table all commands that that player is allowed to use, or all commands +@tparam[opt] LuaPlayer player The player that you want to get commands of, nil will return all commands +@treturn table All commands that that player is allowed to use, or all commands -@usage-- Get the command you are allowed to use +@usage-- Get the commands you are allowed to use local commands = Commands.get(game.player) @usage-- Get all commands that are registered @@ -341,18 +395,18 @@ function Commands.get(player) player = Game.get_player_from_any(player) if not player then return Commands.commands end local allowed = {} - for name,command_data in pairs(Commands.commands) do - if Commands.authorize(player,name) then - allowed[name]=command_data + for name, command_data in pairs(Commands.commands) do + if Commands.authorize(player, name) then + allowed[name] = command_data end end return allowed end --[[-- Searches command names and help messages to find possible commands, game commands are included -@tparam string keyword the word which you are trying to find in your search -@tparam[opt] LuaPlayer player the player to get allowed commands of, if nil all commands are searched -@treturn table all commands that contain the key word, and allowed by player if player given +@tparam string keyword The word which you are trying to find in your search +@tparam[opt] LuaPlayer player The player to get allowed commands of, if nil all commands are searched +@treturn table All commands that contain the key word, and allowed by the player if a player was given @usage-- Get all commands which "repeat" local commands = Commands.search('repeat') @@ -361,168 +415,106 @@ local commands = Commands.search('repeat') local commands = Commands.search('repeat', game.player) ]] -function Commands.search(keyword,player) +function Commands.search(keyword, player) local custom_commands = Commands.get(player) local matches = {} keyword = keyword:lower() - -- loops over custom commands - for name,command_data in pairs(custom_commands) do + -- Loops over custom commands + for name, command_data in pairs(custom_commands) do -- combines name help and aliases into one message to be searched - local search = string.format('%s %s %s',name,command_data.help,table.concat(command_data.aliases,' ')) + local search = string.format('%s %s %s', name, command_data.help, table.concat(command_data.aliases, ' ')) if search:lower():match(keyword) then matches[name] = command_data end end - -- loops over the names of game commands - for name,description in pairs(commands.game_commands) do + -- Loops over the names of game commands + for name, description in pairs(commands.game_commands) do if name:lower():match(keyword) then - -- because game commands lack some stuff that the custom ones have they are formated + -- because game commands lack some stuff that the custom ones have they are formatted matches[name] = { - name=name, - help=description, - description='', - aliases={} + name = name, + help = description, + description = '', + aliases = {} } end end return matches end ---- Parse. --- Functions that help with parsing --- @section parse - ---[[-- Adds a parse function which can be called by name (used in add_param) -nb: this is not required as you can use the callback directly this just allows it to be called by name -@tparam string name the name of the parse, should be the type like player or player_alive, must be unique -@tparam function callback the callback that is ran to parse the input -@treturn boolean was the parse added will be false if the name is already used - -@usage-- Adding a parse to validate ints in a given range -Commands.add_parse('number-range-int', function(input, player, reject, range_min, range_max) - local rtn = tonumber(input) and math.floor(tonumber(input)) or nil -- converts input to number - if not rtn or rtn < range_min or rtn > range_max then - -- the input is either not a number or is outside the range - return reject('Number entered is not in range: '..range_min..', '..range_max) - else - -- returns the input as a number rather than a string, thus the param is now the correct type - return rtn - end -end) - -]] -function Commands.add_parse(name,callback) - if Commands.parse_functions[name] then - return false - else - Commands.parse_functions[name] = callback - return true - end -end - ---[[-- Removes a parse function, see add_parse for adding them -@tparam string name the name of the parse to remove - -@usage-- Removing a parse -Commands.remove_parse('number-range-int') - -]] -function Commands.remove_parse(name) - Commands.parse_functions[name] = nil -end - ---[[-- Intended to be used within other parse functions, runs a parse and returns success and new value -@tparam string name the name of the parse to call, must be registered parse -@tparam string input string the input to pass to the parse, must be a string but not necessarily the original input -@tparam LuaPlayer player the player that is using the command -@tparam function reject the reject function that was passed by the command hander -@treturn any the new value for the input, may be nil, if nil then either there was an error or input was nil - -@usage-- Parsing a int in a given range -local parsed_input = Commands.parse('number-range-int', '7', player, reject, 1, 10) -- valid range 1 to 10 - -]] -function Commands.parse(name,input,player,reject,...) - if not Commands.parse_functions[name] then return end - local success,rtn = pcall(Commands.parse_functions[name],input,player,reject,...) - if not success then error(rtn,2) return end - if not rtn then return end - if rtn == Commands.defines.error then return end - return rtn -end - --- Creation. -- Functions that create a new command -- @section creation ---[[-- Creates a new command object to added details to, note this does not register the command to the game api -@tparam string name the name of the command to be created -@tparam string help the help message for the command -@treturn Commands._prototype this will be used with other functions to generate the command functions +--[[-- Creates a new command object to added details to, this does not register the command to the game api +@tparam string name The name of the command to be created +@tparam string help The help message for the command +@treturn table This will be used with other functions to define the new command @usage-- Define a new command -local command = Commands.new_command('repeat-name', 'Will repeat you name a number of times in chat.') ]] -function Commands.new_command(name,help) +function Commands.new_command(name, help) local command = setmetatable({ - name=name, - help=help, - callback=function() Commands.internal_error(false,name,'No callback registered') end, - auto_concat=false, - min_param_count=0, - max_param_count=0, - flags={}, -- stores flags that can be used by auth - aliases={}, -- n = name: string - params={}, -- [param_name] = {optional: boolean, default: any, parse: function, parse_args: table} + name = name, + help = help, + callback = function() Commands.internal_error(false, name, 'No callback registered') end, + auto_concat = false, + min_param_count = 0, + max_param_count = 0, + flags = {}, -- stores flags that can be used by auth + aliases = {}, -- stores aliases to this command + params = {}, -- [param_name] = {optional: boolean, default: any, parse: function, parse_args: table} }, { - __index= Commands._prototype + __index = Commands._prototype }) Commands.commands[name] = command return command end --[[-- Adds a new param to the command this will be displayed in the help and used to parse the input -@tparam string name the name of the new param that is being added to the command -@tparam[opt=false] boolean optional is this param required for this command, these must be after all required params -@tparam[opt=pass function through] ?string|function parse this function will take the input and return a new (or same) value -@param[opt] ... extra args you want to pass to the parse function; for example if the parse is general use -@treturn Commands._prototype pass through to allow more functions to be called +@tparam string name The name of the new param that is being added to the command +@tparam[opt=false] boolean optional Is this param optional, these must be added after all required params +@tparam[opt] ?string|function parse This function will take the input and return a new value, if not given no parse is done +@tparam[opt] any ... Extra args you want to pass to the parse function; for example if the parse is general use +@treturn table Pass through to allow more functions to be called -@usage-- Adding a param which has an parse defined -command:add_param('repeat-count', false, 'number-range-int', 1, 5) +@usage-- Adding a required param which has a parser pre-defined +command:add_param('repeat-count', 'number-range-int', 1, 5) -@usage-- Adding a param which has a custom parse, see Commands.add_parse for details +@usage-- Adding an optional param which has a custom parse, see Commands.add_parse for details command:add_param('smiley', true, function(input, player, reject) if not input then return end return input:lower() == 'true' or input:lower() == 'yes' or false end) ]] -function Commands._prototype:add_param(name,optional,parse,...) +function Commands._prototype:add_param(name, optional, parse, ...) local parse_args = {...} if type(optional) ~= 'boolean' then - parse_args = {parse,...} + parse_args = {parse, ...} parse = optional optional = false end - parse = parse or function(string) return string end + self.params[name] = { - optional=optional, - parse=parse, - parse_args=parse_args + optional = optional, + parse = parse or function(string) return string end, + parse_args = parse_args } - self.max_param_count = self.max_param_count+1 + + self.max_param_count = self.max_param_count + 1 if not optional then - self.min_param_count = self.min_param_count+1 + self.min_param_count = self.min_param_count + 1 end + return self end ---[[-- Add default values to params, only as an effect if the param is optional, if default value is a function it is called with acting player -@tparam table defaults table which is keyed by the name of the param and the value is the default value -@treturn Commands._prototype pass through to allow more functions to be called +--[[-- Add default values to params, only as an effect if the param is optional, if default value is a function it is called with the acting player +@tparam table defaults A table which is keyed by the name of the param and the value is the default value for that param +@treturn table Pass through to allow more functions to be called @usage-- Adding default values command:set_defaults{ @@ -535,7 +527,7 @@ command:set_defaults{ ]] function Commands._prototype:set_defaults(defaults) - for name,value in pairs(defaults) do + for name, value in pairs(defaults) do if self.params[name] then self.params[name].default = value end @@ -543,10 +535,10 @@ function Commands._prototype:set_defaults(defaults) return self end ---[[-- Adds a tag to the command which is passed via the flags param to the authenticators, can be used to assign command roles or type -@tparam string name the name of the tag to be added, set to true if no value is given -@tparam[opt=true] any value the tag that you want can be anything that the authenticators are expecting -@treturn Commands._prototype pass through to allow more functions to be called +--[[-- Adds a flag to the command which is passed via the flags param to the authenticators, can be used to assign command roles or usage type +@tparam string name The name of the flag to be added, set to true if no value is given +@tparam[opt=true] any value The value for the flag, can be anything that the authenticators are expecting +@treturn table Pass through to allow more functions to be called @usage-- Setting a custom flag command:set_flag('admin_only', true) @@ -555,32 +547,30 @@ command:set_flag('admin_only', true) command:set_flag('admin_only') ]] -function Commands._prototype:set_flag(name,value) - value = value or true - self.flags[name] = value +function Commands._prototype:set_flag(name, value) + self.flags[name] = value or true return self end ---[[-- Adds an alias, or multiple, that will also be registered with the same callback, eg /teleport can be used as /tp -@tparam string any ... amount of aliases that you want this command to be callable with -@treturn Commands._prototype pass through to allow more functions to be called +--[[-- Adds an alias, or multiple, that will be registered to this command, eg /teleport can be used as /tp +@tparam string ... Any amount of aliases that you want this command to be callable with +@treturn table Pass through to allow more functions to be called @usage-- Added multiple aliases to a command command:add_alias('name', 'rname') ]] function Commands._prototype:add_alias(...) - for _,alias in pairs({...}) do - table.insert(self.aliases,alias) - --Commands.alias_map[alias] = self.name + local start_index = #self.aliases + for index, alias in ipairs{...} do + self.aliases[start_index+index] = alias end return self end ---[[-- Enables auto concatenation of any params on the end so quotes are not needed for last param +--[[-- Enables auto concatenation for this command, all params after the last are added to the last param, useful for reasons or other long text input nb: this will disable max param checking as they will be concatenated onto the end of that last param -this can be useful for reasons or longs text, can only have one per command -@treturn Commands._prototype pass through to allow more functions to be called +@treturn table Pass through to allow more functions to be called @usage-- Enable auto concat for a command command:enable_auto_concat() @@ -591,46 +581,54 @@ function Commands._prototype:enable_auto_concat() return self end ---[[-- Adds the callback to the command and registers all aliases, params and help message with the game api +--[[-- Adds the callback to the command and registers: aliases, params and help message with the base game api nb: this must be the last function ran on the command and must be done for the command to work -@tparam function callback the callback for the command, will receive the player running command, and params added with add_param +@tparam function callback The callback for the command, will receive the player running command, and any params added with add_param -@usage-- Registering your command to the game api -command:register(function(player, repeat_count, smiley, _) +@usage-- Registering your command to the base game api +command:register(function(player, repeat_count, smiley, raw) local msg = ') '..player.name if smiley then msg = ':'..msg end - for 1 = 1,repeat_count do + for 1 = 1, repeat_count do Command.print(1..msg) end end) ]] function Commands._prototype:register(callback) - -- generates a description to be used self.callback = callback + + -- Generates a description to be used local description = '' - for param_name,param_details in pairs(self.params) do + for param_name, param_details in pairs(self.params) do if param_details.optional then - description = string.format('%s [%s]',description,param_name) + description = string.format('%s [%s]', description, param_name) else - description = string.format('%s <%s>',description,param_name) + description = string.format('%s <%s>', description, param_name) end end self.description = description - -- registers the command under its own name - commands.add_command(self.name,{'expcore-commands.command-help',description,self.help},function(command_event) - local success, err = pcall(Commands.run_command,command_event) - if not success then log('[ERROR] command/'..self.name..' :: '..err) end - end) - -- adds any aliases that it has - for _,alias in pairs(self.aliases) do + + -- Last resort error handler for commands + local function command_error(err) + Commands.internal_error(false, self.name, trace(err)) + end + + -- Callback that the game will call + local function command_callback(event) + event.name = self.name + xpcall(Commands.run_command, command_error, event) + end + + -- Registers the command under its own name + local help = {'expcore-commands.command-help', description, self.help} + commands.add_command(self.name, help, command_callback) + + -- Adds any aliases that it has + for _, alias in pairs(self.aliases) do if not commands.commands[alias] and not commands.game_commands[alias] then - commands.add_command(alias,{'expcore-commands.command-help',description,self.help},function(command_event) - command_event.name = self.name - local success, err = pcall(Commands.run_command,command_event) - Commands.internal_error(success,self.name,err) - end) + commands.add_command(alias, help, command_callback) end end end @@ -639,19 +637,46 @@ end -- Functions that indicate status -- @section status ---[[-- Sends an error message to the player and when returned will stop exicution of the command +--[[-- Sends a value to the player, followed by a command complete message, returning a value will trigger this automatically +@tparam[opt] any value The value to return to the player, if nil then only the success message is returned +@treturn Commands.defines.success Return this to the command handler to prevent two success messages + +@usage-- Print a custom success message +return Commands.success('Your message has been printed') + +@usage-- Returning the value has the same result +return 'Your message has been printed' + +]] +function Commands.success(value) + if value ~= nil then player_return(value) end + player_return({'expcore-commands.command-ran'}, 'cyan') + return Commands.defines.success +end + +--[[-- Sends a value to the player, different to success as this does not signal the end of your command +@function print +@tparam any value The value that you want to return to the player +@tparam table colour The colour of the message that the player sees + +@usage-- Output a message to the player +Commands.print('Your command is in progress') + +]] + +--[[-- Sends an error message to the player and when returned will stop execution of the command nb: this is for non fatal errors meaning there is no log of this event, use during register callback -@tparam[opt=''] string error_message an optional error message that can be sent to the user -@tparam[opt=utility/wire_pickup] string play_sound the sound to play for the error -@treturn Commands.defines.error return this to command handler to exit execution +@tparam[opt=''] string error_message An optional error message that can be sent to the user +@tparam[opt=utility/wire_pickup] string play_sound The sound to play for the error +@treturn Commands.defines.error Return this to command handler to terminate execution @usage-- Send an error message to the player, and stops further code running return Commands.error('The player you selected is offline') ]] -function Commands.error(error_message,play_sound) +function Commands.error(error_message, play_sound) error_message = error_message or '' - player_return({'expcore-commands.command-fail',error_message},'orange_red') + player_return({'expcore-commands.command-fail', error_message}, 'orange_red') if play_sound ~= false then play_sound = play_sound or 'utility/wire_pickup' if game.player then game.player.play_sound{path=play_sound} end @@ -659,12 +684,12 @@ function Commands.error(error_message,play_sound) return Commands.defines.error end ---[[-- Sends an error to the player and logs the error, used with pcall within command handler please avoid direct use -nb: use error(error_message) within your callback to trigger do not trigger directly as code exictuion may still continue -@tparam boolean success the success value returned from pcall, or just false to trigger error -@tparam string command_name the name of the command this is used within the log -@tparam string error_message the error returned by pcall or some other error, this is logged and not returned to player -@treturn boolean the opposite of success so true means to cancel execution, used internally +--[[-- Sends an error to the player and logs the error, used internally please avoid direct use +nb: use error(error_message) within your callback to trigger do not trigger directly as code execution may still continue +@tparam boolean success The success value returned from pcall, or just false to trigger error +@tparam string command_name The name of the command this is used within the log +@tparam string error_message The error returned by pcall or some other error, this is logged and not returned to player +@treturn boolean The opposite of success so true means to cancel execution, used internally @usage-- Used in the command system to log handler errors local success, err = pcall(command_data.callback, player, unpack(params)) @@ -673,202 +698,173 @@ if Commands.internal_error(success, command_data.name, err) then end ]] -function Commands.internal_error(success,command_name,error_message) +function Commands.internal_error(success, command_name, error_message) if not success then - Commands.error('Internal Error, Please contact an admin','utility/cannot_build') - log{'expcore-commands.command-error-log-format',command_name,error_message} + Commands.error('Internal Error, Please contact an admin', 'utility/cannot_build') + log{'expcore-commands.command-error-log-format', command_name, error_message} end return not success end ---[[-- Sends a value to the player, followed by a command complete message -nb: returning any value from your callback will trigger this function, return this function to prevent duplicate messages -@tparam[opt] any value the value to return to the player, if nil then only success message returned -@treturn Commands.defines.success return this to the command handler to prevent two success messages - -@usage-- Print a custom success message -return Commands.success('Your message has been printed') - -@usage-- Returning the value has the same result -return 'Your message has been printed' - -]] -function Commands.success(value) - if value ~= nil then player_return(value) end - player_return({'expcore-commands.command-ran'},'cyan') - return Commands.defines.success -end - ---[[-- Sends a value to the player, different to success as this does not signal the end of your command -@function print -@tparam any value the value that you want to return to the player -@tparam table colour the colour of the message that the player sees - -@usage-- Output a message to the player -Commands.print('Your command is in progress') - -]] - --- logs command usage to file -local function command_log(player,command,comment,params,raw,details) +--- Logs command usage to file +local function command_log(player, command, comment, params, raw, details) local player_name = player and player.name or '' - write_json('log/commands.log',{ - player_name=player_name, - command_name=command.name, - comment=comment, - details=details, - params=params, - raw=raw + write_json('log/commands.log', { + player_name = player_name, + command_name = command.name, + comment = comment, + details = details, + params = params, + raw = raw }) end --- Main event function that is ran for all commands, used internally please avoid direct use --- @tparam table command_event passed directly from command event from the add_command function +-- @tparam table command_event Passed directly from the add_command function -- @usage Commands.run_command(event) function Commands.run_command(command_event) local command_data = Commands.commands[command_event.name] - -- player can be nil when it is the server + -- Player can be nil when it is the server local player if command_event.player_index and command_event.player_index > 0 then - player = Game.get_player_by_index(command_event.player_index) + player = game.players[command_event.player_index] end - -- checks if player is allowed to use the command - local authorized, auth_fail = Commands.authorize(player,command_data.name) + -- Check if the player is allowed to use the command + local authorized, auth_fail = Commands.authorize(player, command_data.name) if not authorized then - command_log(player,command_data,'Failed Auth',{},command_event.parameter) - Commands.error(auth_fail,'utility/cannot_build') + command_log(player, command_data, 'Failed Auth', {}, command_event.parameter) + Commands.error(auth_fail, 'utility/cannot_build') return end - -- null param check + -- Check for parameter being nil if command_data.min_param_count > 0 and not command_event.parameter then - command_log(player,command_data,'No Params Given',{},command_event.parameter) - Commands.error({'expcore-commands.invalid-inputs',command_data.name,command_data.description}) + command_log(player, command_data, 'No Params Given', {}, command_event.parameter) + Commands.error{'expcore-commands.invalid-inputs', command_data.name, command_data.description} return end - -- splits the arguments - local input_string = command_event.parameter or '' - local quote_params = {} -- stores any " " params - input_string = input_string:gsub(' "[^"]-"',function(w) - -- finds all " " params are removes spaces for the next part - local no_spaces = w:gsub('%s','_') - local no_quotes = w:sub(2,-2) - quote_params[no_spaces]=no_quotes - if command_data.auto_concat then - -- if auto concat then don't remove quotes as it should be included later - quote_params[no_spaces]=w - end - return no_spaces + -- Extract quoted arguments + local raw_input = command_event.parameter or '' + local quote_params = {} + local input_string = raw_input:gsub('"[^"]-"', function(word) + local no_spaces = word:gsub('%s', '%%s') + quote_params[no_spaces] = word:sub(2, -2) + return ' '..no_spaces..' ' end) - local raw_params = {} -- stores all params - local param_number = 0 + -- Extract unquoted arguments + local raw_params = {} local last_index = 0 + local param_number = 0 for word in input_string:gmatch('%S+') do param_number = param_number + 1 if param_number > command_data.max_param_count then -- there are too many params given to the command if not command_data.auto_concat then -- error as they should not be more - command_log(player,command_data,'Invalid Input: Too Many Params',raw_params,input_string) - Commands.error({'expcore-commands.invalid-inputs',command_data.name,command_data.description}) + command_log(player, command_data, 'Invalid Input: Too Many Params', raw_params, raw_input) + Commands.error{'expcore-commands.invalid-inputs', command_data.name, command_data.description} return else -- concat to the last param if quote_params[word] then - -- if it was a " " param then the spaces are re added now - raw_params[last_index]=raw_params[last_index]..' '..quote_params[word] + raw_params[last_index] = raw_params[last_index]..' "'..quote_params[word]..'"' else - raw_params[last_index]=raw_params[last_index]..' '..word + raw_params[last_index] = raw_params[last_index]..' '..word end end else -- new param that needs to be added - -- all words are added to an array if quote_params[word] then - -- if it was a " " param then the spaces are re added now - table.insert(raw_params,quote_params[word]) last_index = last_index + 1 + raw_params[last_index] = quote_params[word] else - table.insert(raw_params,word) last_index = last_index + 1 + raw_params[last_index] = word end end end - -- checks param count + -- Check the param count local param_count = #raw_params if param_count < command_data.min_param_count then - command_log(player,command_data,'Invalid Input: Not Enough Params',raw_params,input_string) - Commands.error({'expcore-commands.invalid-inputs',command_data.name,command_data.description}) + command_log(player, command_data, 'Invalid Input: Not Enough Params', raw_params, raw_input) + Commands.error{'expcore-commands.invalid-inputs', command_data.name, command_data.description} return end - -- parses the arguments + -- Parse the arguments local index = 1 local params = {} for param_name, param_data in pairs(command_data.params) do local parse_callback = param_data.parse + -- If its a string this get it from the parser table if type(parse_callback) == 'string' then - -- if its a string this allows it to be pulled from the common store - parse_callback = Commands.parse_functions[parse_callback] + parse_callback = Commands.parsers[parse_callback] end + + -- If its not a function throw and error if not type(parse_callback) == 'function' then - -- if its not a function throw and error - Commands.internal_error(false,command_data.name,'Invalid param parse '..tostring(param_data.parse)) - command_log(player,command_data,'Internal Error: Invalid Param Parse',params,command_event.parameter,tostring(param_data.parse)) + Commands.internal_error(false, command_data.name, 'Invalid param parse '..tostring(param_data.parse)) + command_log(player, command_data, 'Internal Error: Invalid Param Parse', params, raw_input, tostring(param_data.parse)) return end - -- used below as the reject function - local parse_fail = function(error_message) + + -- This is the reject function given to parse callbacks + local function reject(error_message) error_message = error_message or '' - command_log(player,command_data,'Invalid Param Given',raw_params,input_string) - return Commands.error{'expcore-commands.invalid-param',param_name,error_message} + command_log(player, command_data, 'Invalid Param Given', raw_params, input_string) + return Commands.error{'expcore-commands.invalid-param', param_name, error_message} end + -- input: string, player: LuaPlayer, reject: function, ... extra args - local success,param_parsed = pcall(parse_callback,raw_params[index],player,parse_fail,unpack(param_data.parse_args)) - if Commands.internal_error(success,command_data.name,param_parsed) then - return command_log(player,command_data,'Internal Error: Param Parse Fail',params,command_event.parameter,param_parsed) + local success, param_parsed = pcall(parse_callback, raw_params[index], player, reject, unpack(param_data.parse_args)) + if Commands.internal_error(success, command_data.name, param_parsed) then + return command_log(player, command_data, 'Internal Error: Param Parse Fail', params, raw_input, param_parsed) end + if param_data.optional == true and raw_params[index] == nil then - -- if it is optional and param is nil then it is set to default + -- If the param is optional and nil then it is set to default param_parsed = param_data.default if type(param_parsed) == 'function' then - -- player: LuaPlayer - success,param_parsed = pcall(param_parsed,player) - if Commands.internal_error(success,command_data.name,param_parsed) then - return command_log(player,command_data,'Internal Error: Default Value Fail',params,command_event.parameter,param_parsed) + success, param_parsed = pcall(param_parsed, player) + if Commands.internal_error(success, command_data.name, param_parsed) then + return command_log(player, command_data, 'Internal Error: Default Value Fail', params, raw_input, param_parsed) end end - elseif param_parsed == nil or param_parsed == Commands.defines.error or param_parsed == parse_fail then - -- no value was returned or error was returned, if nil then give generic error + + elseif param_parsed == nil or param_parsed == Commands.defines.error or param_parsed == reject then + -- No value was returned or error was returned, if nil then give generic error if not param_parsed == Commands.defines.error then - command_log(player,command_data,'Invalid Param Given',raw_params,input_string,param_name) - Commands.error{'expcore-commands.command-error-param-format',param_name,'please make sure it is the correct type'} + command_log(player, command_data, 'Invalid Param Given', raw_params, raw_input, param_name) + Commands.error{'expcore-commands.command-error-param-format', param_name, 'please make sure it is the correct type'} end return + end - -- adds the param to the table to be passed to the command callback - table.insert(params,param_parsed) - index=index+1 + + -- Add the param to the table to be passed to the command callback + params[index] = param_parsed + index = index + 1 end - -- runs the command + -- Run the command -- player: LuaPlayer, ... command params, raw: string - table.insert(params,command_data.max_param_count+1,input_string) - local success, err = pcall(command_data.callback,player,unpack(params)) - if Commands.internal_error(success,command_data.name,err) then - return command_log(player,command_data,'Internal Error: Command Callback Fail',raw_params,command_event.parameter,err) - end - if err == Commands.defines.error or err == Commands.error then - return command_log(player,command_data,'Custom Error',raw_params,input_string) - elseif err ~= Commands.defines.success and err ~= Commands.success then - -- in this case the user has not received any output - Commands.success(err) - end - command_log(player,command_data,'Success',raw_params,input_string) + params[command_data.max_param_count+1] = raw_input + local success, rtn = pcall(command_data.callback, player, unpack(params)) + if Commands.internal_error(success, command_data.name, rtn) then + return command_log(player, command_data, 'Internal Error: Command Callback Fail', raw_params, command_event.parameter, rtn) + end + + -- Give output to the player + if rtn == Commands.defines.error or rtn == Commands.error then + return command_log(player, command_data, 'Custom Error', raw_params, raw_input) + elseif rtn ~= Commands.defines.success and rtn ~= Commands.success then + Commands.success(rtn) + end + command_log(player, command_data, 'Success', raw_params, raw_input) end return Commands \ No newline at end of file diff --git a/expcore/common.lua b/expcore/common.lua index e51b3edb95..6488631677 100644 --- a/expcore/common.lua +++ b/expcore/common.lua @@ -42,7 +42,7 @@ type_error(value, 'number', 'Value must be a number') ]] function Common.type_error(value, test_type, error_message, level) level = level and level+1 or 2 - return Common.type_check(value,test_type) or error(error_message,level) + return Common.type_check(value, test_type) or error(error_message, level) end --[[-- Asserts the argument is one of type test_types @@ -51,7 +51,7 @@ end @treturn boolean true if value is one of test_types @usage-- Check for a string or table -local is_string_or_table = multi_type_check(value, {'string','table'}) +local is_string_or_table = multi_type_check(value, {'string', 'table'}) ]] function Common.multi_type_check(value, test_types) @@ -72,12 +72,12 @@ end @treturn boolean true if no error was called @usage-- Raise error if value is not a string or table -multi_type_error('foo', {'string','table'}, 'Value must be a string or table') +multi_type_error('foo', {'string', 'table'}, 'Value must be a string or table') ]] function Common.multi_type_error(value, test_types, error_message, level) level = level and level+1 or 2 - return Common.mult_type_check(value, test_types) or error(error_message,level) + return Common.mult_type_check(value, test_types) or error(error_message, level) end --[[-- Raises an error when the value is the incorrect type, uses a consistent error message format @@ -95,15 +95,15 @@ validate_argument_type(value, 'number', 2, 'repeat_count') ]] function Common.validate_argument_type(value, test_type, param_number, param_name) - if not Common.test_type(value,test_type) then - local function_name = debug.getinfo(2,'n').name or '' + if not Common.test_type(value, test_type) then + local function_name = debug.getinfo(2, 'n').name or '' local error_message if param_name then error_message = string.format('Bad argument #%d to %q; %q is of type %s expected %s', param_number, function_name, param_name, type(value), test_type) else error_message = string.format('Bad argument #%d to %q; argument is of type %s expected %s', param_number, function_name, type(value), test_type) end - return error(error_message,3) + return error(error_message, 3) end return true end @@ -116,22 +116,22 @@ end @treturn boolean true if no error was raised @usage-- Output: "Bad argument #2 to ""; argument is of type number expected string or table" -validate_argument_type(value, {'string','table'}, 2) +validate_argument_type(value, {'string', 'table'}, 2) @usage-- Output: "Bad argument #2 to ""; "player" is of type number expected string or table" -validate_argument_type(value, {'string','table'}, 2, 'player') +validate_argument_type(value, {'string', 'table'}, 2, 'player') ]] function Common.validate_argument_multi_type(value, test_types, param_number, param_name) - if not Common.multi_type_check(value,test_types) then - local function_name = debug.getinfo(2,'n').name or '' + if not Common.multi_type_check(value, test_types) then + local function_name = debug.getinfo(2, 'n').name or '' local error_message if param_name then - error_message = string.format('Bad argument #%2d to %q; %q is of type %s expected %s', param_number, function_name, param_name, type(value), table.concat(test_types,' or ')) + error_message = string.format('Bad argument #%2d to %q; %q is of type %s expected %s', param_number, function_name, param_name, type(value), table.concat(test_types, ' or ')) else - error_message = string.format('Bad argument #%2d to %q; argument is of type %s expected %s', param_number, function_name, type(value), table.concat(test_types,' or ')) + error_message = string.format('Bad argument #%2d to %q; argument is of type %s expected %s', param_number, function_name, type(value), table.concat(test_types, ' or ')) end - return error(error_message,3) + return error(error_message, 3) end return true end @@ -140,8 +140,8 @@ end -- @usage error_if_runtime() function Common.error_if_runtime() if _LIFECYCLE == 8 then - local function_name = debug.getinfo(2,'n').name or '' - error(function_name..' can not be called during runtime',3) + local function_name = debug.getinfo(2, 'n').name or '' + error(function_name..' can not be called during runtime', 3) end end @@ -149,8 +149,8 @@ end -- @usage error_if_runetime_closure(func) function Common.error_if_runetime_closure(func) if _LIFECYCLE == 8 and Debug.is_closure(func) then - local function_name = debug.getinfo(2,'n').name or '' - error(function_name..' can not be called during runtime with a closure',3) + local function_name = debug.getinfo(2, 'n').name or '' + error(function_name..' can not be called during runtime with a closure', 3) end end @@ -180,7 +180,7 @@ end local value = Common.resolve_value(self.defaut_value, self) ]] -function Common.resolve_value(value,...) +function Common.resolve_value(value, ...) return value and type(value) == 'function' and value(...) or value end @@ -201,7 +201,7 @@ end -- @usage comma_value(input_number) function Common.comma_value(n) -- credit http://richard.warburton.it local left, num, right = string.match(n, '^([^%d]*%d)(%d*)(.-)$') - return left .. (num:reverse():gsub('(%d%d%d)', '%1,'):reverse()) .. right + return left .. (num:reverse():gsub('(%d%d%d)', '%1, '):reverse()) .. right end --[[-- Sets a table element to value while also returning value. @@ -227,8 +227,8 @@ end write_json('dump', tbl) ]] -function Common.write_json(path,tbl) - game.write_file(path,game.table_to_json(tbl)..'\n',true,0) +function Common.write_json(path, tbl) + game.write_file(path, game.table_to_json(tbl)..'\n', true, 0) end --[[-- Calls a require that will not error if the file is not found @@ -241,9 +241,9 @@ local Module = opt_require 'expcore.common' ]] function Common.opt_require(path) - local success, rtn = pcall(require,path) + local success, rtn = pcall(require, path) if success then return rtn - else return nil,rtn end + else return nil, rtn end end --[[-- Returns a desync safe file path for the current file @@ -273,17 +273,17 @@ local colors = enum{ ]] function Common.enum(tbl) local rtn = {} - for k,v in pairs(tbl) do + for k, v in pairs(tbl) do if type(k) ~= 'number' then rtn[v]=k end end - for k,v in pairs(tbl) do + for k, v in pairs(tbl) do if type(k) == 'number' then - table.insert(rtn,v) + table.insert(rtn, v) end end - for k,v in pairs(rtn) do + for k, v in pairs(rtn) do rtn[v]=k end return rtn @@ -306,20 +306,19 @@ local value = auto_complete(tbl, "foo", true) local key = auto_complete(tbl, "foo", true, true) ]] -function Common.auto_complete(options,input,use_key,rtn_key) - local rtn = {} +function Common.auto_complete(options, input, use_key, rtn_key) if type(input) ~= 'string' then return end input = input:lower() - for key,value in pairs(options) do + for key, value in pairs(options) do local check = use_key and key or value - if Common.string_contains(string.lower(check),input) then + if Common.string_contains(string.lower(check), input) then return rtn_key and key or value end end end ---- Formating. --- @section formating +--- Formatting. +-- @section formatting --[[-- Returns a valid string with the name of the actor of a command. @tparam string player_name the name of the player to use rather than server, used only if game.player is nil @@ -335,32 +334,32 @@ end --[[-- Returns a message with valid chat tags to change its colour @tparam string message the message that will be in the output -@tparam table color a color which contains r,g,b as its keys +@tparam table color a color which contains r, g, b as its keys @treturn string the message with the color tags included @usage-- Use factorio tags to color a chat message local message = format_chat_colour('Hello, World!', { r=355, g=100, b=100 }) ]] -function Common.format_chat_colour(message,color) +function Common.format_chat_colour(message, color) color = color or Colours.white - local color_tag = '[color='..math.round(color.r,3)..','..math.round(color.g,3)..','..math.round(color.b,3)..']' - return string.format('%s%s[/color]',color_tag,message) + local color_tag = '[color='..math.round(color.r, 3)..', '..math.round(color.g, 3)..', '..math.round(color.b, 3)..']' + return string.format('%s%s[/color]', color_tag, message) end --[[-- Returns a message with valid chat tags to change its colour, using localization @tparam ?string|table message the message that will be in the output -@tparam table color a color which contains r,g,b as its keys +@tparam table color a color which contains r, g, b as its keys @treturn table the message with the color tags included @usage-- Use factorio tags and locale strings to color a chat message local message = format_chat_colour_localized('Hello, World!', { r=355, g=100, b=100 }) ]] -function Common.format_chat_colour_localized(message,color) +function Common.format_chat_colour_localized(message, color) color = color or Colours.white - color = math.round(color.r,3)..','..math.round(color.g,3)..','..math.round(color.b,3) - return {'color-tag',color,message} + color = math.round(color.r, 3)..', '..math.round(color.g, 3)..', '..math.round(color.b, 3) + return {'color-tag', color, message} end --[[-- Returns the players name in the players color @@ -372,14 +371,14 @@ end local message = format_chat_player_name(game.player, true) ]] -function Common.format_chat_player_name(player,raw_string) +function Common.format_chat_player_name(player, raw_string) player = Game.get_player_from_any(player) local player_name = player and player.name or '' local player_chat_colour = player and player.chat_color or Colours.white if raw_string then - return Common.format_chat_colour(player_name,player_chat_colour) + return Common.format_chat_colour(player_name, player_chat_colour) else - return Common.format_chat_colour_localized(player_name,player_chat_colour) + return Common.format_chat_colour_localized(player_name, player_chat_colour) end end @@ -398,16 +397,16 @@ player_return('Hello, World!', 'green') player_return('Hello, World!', nil, player) ]] -function Common.player_return(value,colour,player) - colour = Common.type_check(colour,'table') and colour or Colours[colour] ~= Colours.white and Colours[colour] or Colours.white +function Common.player_return(value, colour, player) + colour = Common.type_check(colour, 'table') and colour or Colours[colour] ~= Colours.white and Colours[colour] or Colours.white player = player or game.player -- converts the value to a string local returnAsString - if Common.type_check(value,'table') or type(value) == 'userdata' then - if Common.type_check(value.__self,'userdata') or type(value) == 'userdata' then + if Common.type_check(value, 'table') or type(value) == 'userdata' then + if Common.type_check(value.__self, 'userdata') or type(value) == 'userdata' then -- value is userdata returnAsString = 'Cant Display Userdata' - elseif Common.type_check(value[1],'string') and string.find(value[1],'.+[.].+') and not string.find(value[1],'%s') then + elseif Common.type_check(value[1], 'string') and string.find(value[1], '.+[.].+') and not string.find(value[1], '%s') then -- value is a locale string returnAsString = value elseif getmetatable(value) ~= nil and not tostring(value):find('table: 0x') then @@ -415,9 +414,9 @@ function Common.player_return(value,colour,player) returnAsString = tostring(value) else -- value is a table - returnAsString = table.inspect(value,{depth=5,indent=' ',newline='\n'}) + returnAsString = table.inspect(value, {depth=5, indent=' ', newline='\n'}) end - elseif Common.type_check(value,'function') then + elseif Common.type_check(value, 'function') then -- value is a function returnAsString = 'Cant Display Functions' else returnAsString = tostring(value) end @@ -425,10 +424,10 @@ function Common.player_return(value,colour,player) if player then -- allows any valid player identifier to be used player = Game.get_player_from_any(player) - if not player then error('Invalid Player given to player_return',2) end + if not player then error('Invalid Player given to player_return', 2) end -- plays a nice sound that is different to normal message sound player.play_sound{path='utility/scenario_message'} - player.print(returnAsString,colour) + player.print(returnAsString, colour) else rcon.print(returnAsString) end end @@ -452,7 +451,7 @@ local time = format_time(18000, { hours=true, minutes=true, seconds=true, string local time = format_time(18000, { hours=true, minutes=true, seconds=true, string=true, null=true }) ]] -function Common.format_time(ticks,options) +function Common.format_time(ticks, options) -- Sets up the options options = options or { days=false, @@ -508,31 +507,31 @@ function Common.format_time(ticks,options) rtn_minutes = long and rtn_minutes..' minutes' or rtn_minutes..'m' rtn_seconds = long and rtn_seconds..' seconds' or rtn_seconds..'s' else - rtn_days = {suffix..'days'..suffix_2,rtn_days} - rtn_hours = {suffix..'hours'..suffix_2,rtn_hours} - rtn_minutes = {suffix..'minutes'..suffix_2,rtn_minutes} - rtn_seconds = {suffix..'seconds'..suffix_2,rtn_seconds} + rtn_days = {suffix..'days'..suffix_2, rtn_days} + rtn_hours = {suffix..'hours'..suffix_2, rtn_hours} + rtn_minutes = {suffix..'minutes'..suffix_2, rtn_minutes} + rtn_seconds = {suffix..'seconds'..suffix_2, rtn_seconds} end elseif not options.null then -- weather string or not it has same format - rtn_days = string.format('%02d',rtn_days) - rtn_hours = string.format('%02d',rtn_hours) - rtn_minutes = string.format('%02d',rtn_minutes) - rtn_seconds = string.format('%02d',rtn_seconds) + rtn_days = string.format('%02d', rtn_days) + rtn_hours = string.format('%02d', rtn_hours) + rtn_minutes = string.format('%02d', rtn_minutes) + rtn_seconds = string.format('%02d', rtn_seconds) end -- The final return is construed local rtn - local append = function(dom,value) + local append = function(dom, value) if dom and options.string then rtn = rtn and rtn..div..value or value elseif dom then - rtn = rtn and {div,rtn,value} or value + rtn = rtn and {div, rtn, value} or value end end - append(options.days,rtn_days) - append(options.hours,rtn_hours) - append(options.minutes,rtn_minutes) - append(options.seconds,rtn_seconds) + append(options.days, rtn_days) + append(options.hours, rtn_hours) + append(options.minutes, rtn_minutes) + append(options.seconds, rtn_seconds) return rtn end @@ -542,31 +541,31 @@ end --[[-- Moves items to the position and stores them in the closest entity of the type given @tparam table items items which are to be added to the chests, ['name']=count @tparam[opt=navies] LuaSurface surface the surface that the items will be moved to -@tparam[opt={0,0}] table position the position that the items will be moved to {x=100,y=100} +@tparam[opt={0, 0}] table position the position that the items will be moved to {x=100, y=100} @tparam[opt=32] number radius the radius in which the items are allowed to be placed @tparam[opt=iron-chest] string chest_type the chest type that the items should be moved into @treturn LuaEntity the last chest that had items inserted into it -@usage-- Copy all the items in a players inventory and place them in chests at {0,0} +@usage-- Copy all the items in a players inventory and place them in chests at {0, 0} move_items(game.player.get_main_inventory().get_contents()) ]] -function Common.move_items(items,surface,position,radius,chest_type) +function Common.move_items(items, surface, position, radius, chest_type) chest_type = chest_type or 'iron-chest' surface = surface or game.surfaces[1] if position and type(position) ~= 'table' then return end if type(items) ~= 'table' then return end -- Finds all entities of the given type - local p = position or {x=0,y=0} + local p = position or {x=0, y=0} local r = radius or 32 - local entities = surface.find_entities_filtered{area={{p.x-r,p.y-r},{p.x+r,p.y+r}},name=chest_type} or {} + local entities = surface.find_entities_filtered{area={{p.x-r, p.y-r}, {p.x+r, p.y+r}}, name=chest_type} or {} local count = #entities local current = 1 -- Makes a new empty chest when it is needed local function make_new_chest() - local pos = surface.find_non_colliding_position(chest_type,position,32,1) - local chest = surface.create_entity{name=chest_type,position=pos,force='neutral'} - table.insert(entities,chest) + local pos = surface.find_non_colliding_position(chest_type, position, 32, 1) + local chest = surface.create_entity{name=chest_type, position=pos, force='neutral'} + table.insert(entities, chest) count = count + 1 return chest end @@ -581,16 +580,16 @@ function Common.move_items(items,surface,position,radius,chest_type) return chest else -- Other wise it is removed from the list - table.remove(entities,current) + table.remove(entities, current) count = count - 1 end end -- Inserts the items into the chests local last_chest - for item_name,item_count in pairs(items) do - local chest = next_chest{name=item_name,count=item_count} - if not chest then return error(string.format('Cant move item %s to %s{%s, %s} no valid chest in radius',item.name,surface.name,p.x,p.y)) end - Util.insert_safe(chest,{[item_name]=item_count}) + for item_name, item_count in pairs(items) do + local chest = next_chest{name=item_name, count=item_count} + if not chest then return error(string.format('Cant move item %s to %s{%s, %s} no valid chest in radius', item_name, surface.name, p.x, p.y)) end + Util.insert_safe(chest, {[item_name]=item_count}) last_chest = chest end return last_chest @@ -606,7 +605,7 @@ https://github.com/Refactorio/RedMew/blob/9184b2940f311d8c9c891e83429fc57ec7e0c4 @tparam[opt=0] number offset the offset in the +x +y direction @tparam[opt=false] boolean immutable if immutable, only set, never do a surface lookup, values never change -@usage-- Place a 0 at {0,0} +@usage-- Place a 0 at {0, 0} print_grid_value(0, game.player.surface, { x=0, y=0 }) ]] @@ -664,7 +663,7 @@ clear_flying_text(game.player.surface) ]] function Common.clear_flying_text(surface) local entities = surface.find_entities_filtered{name ='flying-text'} - for _,entity in pairs(entities) do + for _, entity in pairs(entities) do if entity and entity.valid then entity.destroy() end diff --git a/expcore/datastore.lua b/expcore/datastore.lua new file mode 100644 index 0000000000..3fb930171b --- /dev/null +++ b/expcore/datastore.lua @@ -0,0 +1,859 @@ +--[[-- Core Module - Datastore +- A module used to store data in the global table with the option to have it sync to an external source. +@core Datastore +@alias DatastoreManager + +@usage-- Types of Datastore +-- This datastore will not save data externally and can be used to watch for updates on values within it +-- A common use might be to store data for a gui and only update the gui when a value changes +local LocalDatastore = Datastore.connect('LocalDatastore') + +-- This datastore will allow you to use the save and request method, this allows you to have persistent data +-- Should be used over auto save as it creates less save requests, but this means you need to tell the data to be saved +-- We use this type for player data as we know the data only needs to be saved when the player leaves +local PersistentDatastore = Datastore.connect('PersistentDatastore', true) -- save_to_disk + +-- This datastore is the same as above but the save method will be called automatically when ever you change a value +-- An auto save datastore should be used if the data does not change often, this can be global settings and things of that sort +-- If it is at all possible to setup events to unload and/or save the data then this is preferable +local AutosaveDatastore = Datastore.connect('AutosaveDatastore', true, true) -- save_to_disk, auto_save + +-- Finally you can have a datastore that propagates its changes to all other connected servers, this means request does not need to be used +-- This should be used when you might have data conflicts while saving, this is done by pushing the saved value to all active servers +-- The request method has little use after server start as any external changes to the value will be pushed automatically +-- Auto save can also be used with this type and you should follow the same guidelines above for when this should be avoided +local PropagateDatastore = Datastore.connect('PropagateDatastore', true, false, true) -- save_to_disk, propagate_changes + +@usage-- Using Datastores Locally +-- Once you have your datastore connection setup, any further requests with connect will return the same datastore +-- This is important to know because the settings passed as parameters you have an effect when it is first created + +-- One useful thing that you might want to set up before runtime is a serializer, this will convert non string keys into strings +-- This serializer will allow use to pass a player object and still have it serialized to the players name +local ExampleData = Datastore.connect('ExampleData') +ExampleData:set_serializer(function(rawKey) + return rawKey.name +end) + +-- If we want to get data from the datastore we can use get or get_all +local value = ExampleData:get(player, defaultValue) +local values = ExampleData:get_all() + +-- If we want to set data then we can use set, increment, update, or update_all +ExampleData:set(player, 10) +ExampleData:increment(player) +ExampleData:update(player, function(player_name, value) + return value * 2 +end) +ExampleData:update_all(function(player_name, value) + return value * 2 +end) + +-- If we want to remove data then we use remove +ExampleData:remove(player) + +-- We can also listen for updates to a value done by any of the above methods with on_update +ExampleData:on_update(function(player_name, value) + game.print(player_name..' has had their example data updated to '..tostring(value)) +end) + +@usage-- Using Datastore Externally +-- If save_to_disk is used then this opens up the option for persistent data which you can request, save, and remove +-- All of the local methods are still usable put now there is the option for extra events +-- In order for this to work there must be an external script to read datastore.pipe and inject with Datastore.ingest + +-- To request data you would use request and the on_load event, this event can be used to modify data before it is used +ExampleData:request(player) +ExampleData:on_load(function(player_name, value) + game.print('Loaded example data for '..player_name) + -- A value can be returned here to overwrite the received value +end) + +-- To save data you would use save and the on_save event, this event can be used to modify data before it is saved +ExampleData:save(player) +ExampleData:on_save(function(player_name, value) + game.print('Saved example data for '..player_name) + -- A value can be returned here to overwrite the value which is saved +end) + +-- To remove data locally but not externally, like if a player logs off, you would use unload and on_unload +ExampleData:unload(player) +ExampleData:on_unload(function(player_name, value) + game.print('Unloaded example data for '..player_name) + -- Any return is ignored, this is event is for cleaning up other data +end) + +@usage-- Using Datastore Messaging +-- The message action can be used regardless of save_to_disk being set as no data is saved, but an external script is still required +-- These messages can be used to send data to other servers which doesnt need to be saved such as shouts or commands +-- Using messages is quite simple only using message and on_message +ExampleData:message(key, message) +ExampleData:on_message(function(key, message) + game.print('Received message '..message) +end) + +@usage-- Combined Datastores +-- A combined datastore is a datastore which stores its data inside of another datastore +-- This means that the data is stored more efficiently in the external database and less requests need to be made +-- To understand how combined datastores work think of each key in the parent as a table where the sub datastore is a key in that table +-- Player data is the most used version of the combined datastore, below is how the player data module is setup +local PlayerData = Datastore.connect('PlayerData', true) -- saveToDisk +PlayerData:set_serializer(Datastore.name_serializer) -- use player name as key +PlayerData:combine('Statistics') +PlayerData:combine('Settings') +PlayerData:combine('Required') + +-- You can then further combine datastores to any depth, below we add some possible settings and statistics that we might use +-- Although we dont in this example, each of these functions returns the datastore object which you should use as a local value +PlayerData.Settings:combine('Color') +PlayerData.Settings:combine('Quickbar') +PlayerData.Settings:combine('JoinMessage') +PlayerData.Statistics:combine('Playtime') +PlayerData.Statistics:combine('JoinCount') + +-- Because sub datastore work just like a normal datastore you dont need any special code, using get and set will still return as if it wasnt a sub datastore +-- Things like the serializer and the datastore settings are always the same as the parent so you dont need to worry about setting up the serializer each time +-- And because save, request, and unload methods all point to the root datastore you are able to request and save your data as normal + +-- If you used get_all on PlayerData this is what you would get: +{ + Cooldude2606 = { + Settings = { + Color = 'ColorValue', + Quickbar = 'QuickbarValue', + JoinMessage = 'JoinMessageValue' + }, + Statistics = { + Playtime = 'PlaytimeValue', + JoinCount = 'JoinCountValue' + } + } +} + +-- If you used get_all on PlayerData.Settings this is what you would get: +{ + Cooldude2606 = { + Color = 'ColorValue', + Quickbar = 'QuickbarValue', + JoinMessage = 'JoinMessageValue' + } +} + +-- If you used get_all on PlayerData.Settings.Color this is what you would get: +{ + Cooldude2606 = 'ColorValue' +} + +]] + +local Event = require 'utils.event' --- @dep utils.event + +local DatastoreManager = {} +local Datastores = {} +local Datastore = {} +local Data = {} +local copy = table.deep_copy +local trace = debug.traceback + +--- Save datastores in the global table +global.datastores = Data +Event.on_load(function() + Data = global.datastores + for datastoreName, datastore in pairs(Datastores) do + datastore.data = Data[datastoreName] + end +end) + +----- Datastore Manager +-- @section datastoreManager + +--- Metatable used on datastores +DatastoreManager.metatable = { + __index = function(self, key) return rawget(self.children, key) or rawget(Datastore, key) end, + __newidnex = function(_, _, _) error('Datastore can not be modified', 2) end, + __call = function(self, ...) return self:get(...) end +} + +--[[-- Make a new datastore connection, if a connection already exists then it is returned +@tparam string datastoreName The name that you want the new datastore to have, this can not have any whitespace +@tparam[opt=false] boolean saveToDisk When set to true, using the save method with write the data to datastore.pipe +@tparam[opt=false] boolean autoSave When set to true, using any method which modifies data will cause the data to be saved +@tparam[opt=false] boolean propagateChanges When set to true, using the save method will send the data to all other connected servers +@treturn table The new datastore connection that can be used to access and modify data in the datastore + +@usage-- Connecting to the test datastore which will allow saving to disk +local ExampleData = Datastore.connect('ExampleData', true) -- saveToDisk + +]] +function DatastoreManager.connect(datastoreName, saveToDisk, autoSave, propagateChanges) + if Datastores[datastoreName] then return Datastores[datastoreName] end + if _LIFECYCLE ~= _STAGE.control then + -- Only allow this function to be called during the control stage + error('New datastore connection can not be created during runtime', 2) + end + + local new_datastore = { + name = datastoreName, + value_name = datastoreName, + auto_save = autoSave or false, + save_to_disk = saveToDisk or false, + propagate_changes = propagateChanges or false, + serializer = false, + parent = false, + children = {}, + metadata = {}, + events = {}, + data = {} + } + + Data[datastoreName] = new_datastore.data + Datastores[datastoreName] = new_datastore + return setmetatable(new_datastore, DatastoreManager.metatable) +end + +--[[-- Make a new datastore that stores its data inside of another one +@tparam string datastoreName The name of the datastore that will contain the data for the new datastore +@tparam string subDatastoreName The name of the new datastore, this name will also be used as the key inside the parent datastore +@treturn table The new datastore connection that can be used to access and modify data in the datastore + +@usage-- Setting up a datastore which stores its data inside of another datastore +local BarData = Datastore.combine('ExampleData', 'Bar') + +]] +function DatastoreManager.combine(datastoreName, subDatastoreName) + local datastore = assert(Datastores[datastoreName], 'Datastore not found '..tostring(datastoreName)) + return datastore:combine(subDatastoreName) +end + +--[[-- Ingest the result from a request, this is used through a rcon interface to sync data +@tparam string action The action that should be done, can be: remove, message, propagate, or request +@tparam string datastoreName The name of the datastore that should have the action done to it +@tparam string key The key of that datastore that is having the action done to it +@tparam string valueJson The json string for the value being ingested, remove does not require a value + +@usage-- Replying to a data request +Datastore.ingest('request', 'ExampleData', 'TestKey', 'Foo') + +]] +function DatastoreManager.ingest(action, datastoreName, key, valueJson) + local datastore = assert(Datastores[datastoreName], 'Datastore ingest error, Datastore not found '..tostring(datastoreName)) + assert(type(action) == 'string', 'Datastore ingest error, Action is not a string got: '..type(action)) + assert(type(key) == 'string', 'Datastore ingest error, Key is not a string got: '..type(key)) + + if action == 'remove' then + datastore:raw_set(key) + + elseif action == 'message' then + local success, value = pcall(game.json_to_table, valueJson) + if not success or value == nil then value = tonumber(valueJson) or valueJson end + datastore:raise_event('on_message', key, value) + + elseif action == 'propagate' or action == 'request' then + local success, value = pcall(game.json_to_table, valueJson) + if not success or value == nil then value = tonumber(valueJson) or valueJson end + local old_value = datastore:raw_get(key) + value = datastore:raise_event('on_load', key, value, old_value) + datastore:set(key, value) + + end + +end + +--[[-- Debug, Use to get all datastores, or return debug info on a datastore +@tparam[opt] string datastoreName The name of the datastore to get the debug info of + +@usage-- Get all the datastores +local datastores = Datastore.debug() + +@usage-- Getting the debug info for a datastore +local debug_info = Datastore.debug('ExampleData') + +]] +function DatastoreManager.debug(datastoreName) + if not datastoreName then return Datastores end + local datastore = assert(Datastores[datastoreName], 'Datastore not found '..tostring(datastoreName)) + return datastore:debug() +end + +--[[-- Commonly used serializer, returns the name of the object +@tparam any rawKey The raw key that will be serialized, this can be things like player, force, surface, etc +@treturn string The name of the object that was passed + +@usage-- Using the name serializer for your datastore +local ExampleData = Datastore.connect('ExampleData') +ExampleData:set_serializer(Datastore.name_serializer) + +]] +function DatastoreManager.name_serializer(rawKey) + return rawKey.name +end + +----- Datastore Internal +-- @section datastore-internal + +--[[-- Debug, Get the debug info for this datastore +@treturn table The debug info for this datastore, contains stuff like parent, settings, children, etc + +@usage-- Get the debug info for a datastore +local ExampleData = Datastore.connect('ExampleData') +local debug_info = ExampleData:debug() + +]] +function Datastore:debug() + local debug_info = {} + + if self.parent then + debug_info.parent = self.parent.name + else + debug_info.settings = { auto_save = self.auto_save, save_to_disk = self.save_to_disk, propagate_changes = self.propagate_changes, serializer = not not self.serializer } + end + + local children = {} + for name in pairs(self.children) do children[#children+1] = name end + if #children > 0 then debug_info.children = children end + + local events = {} + for name, handlers in pairs(self.events) do events[name] = #handlers end + if next(events) then debug_info.events = events end + + if next(self.metadata) then debug_info.metadata = self.metadata end + debug_info.data = self:get_all() + + return debug_info +end + +--[[-- Internal, Get data following combine logic +@tparam string key The key to get the value of from this datastore +@tparam[opt=false] boolean fromChild If the get request came from a child of this datastore +@treturn any The value that was stored at this key in this datastore + +@usage-- Internal, Get the data from a datastore +local value = self:raw_get('TestKey') + +]] +function Datastore:raw_get(key, fromChild) + local data = self.data + if self.parent then + data = self.parent:raw_get(key, true) + key = self.value_name + end + local value = data[key] + if value ~= nil then return value end + if fromChild then value = {} end + data[key] = value + return value +end + +--[[-- Internal, Set data following combine logic +@tparam string key The key to set the value of in this datastore +@tparam any value The value that will be set at this key + +@usage-- Internal, Set the value in a datastore +self:raw_set('TestKey', 'Foo') + +]] +function Datastore:raw_set(key, value) + if self.parent then + local data = self.parent:raw_get(key, true) + data[self.value_name] = value + else + self.data[key] = value + end +end + +local function serialize_error(err) error('An error ocurred in a datastore serializer: '..trace(err)) end +--[[-- Internal, Return the serialized key +@tparam any rawKey The key that needs to be serialized, if it is already a string then it is returned +@treturn string The key after it has been serialized + +@usage-- Internal, Ensure that the key is a string +key = self:serialize(key) + +]] +function Datastore:serialize(rawKey) + if type(rawKey) == 'string' then return rawKey end + assert(self.serializer, 'Datastore does not have a serializer and received non string key') + local success, key = xpcall(self.serializer, serialize_error, rawKey) + return success and key or nil +end + +--[[-- Internal, Writes an event to the output file to be saved and/or propagated +@tparam string action The action that should be wrote to datastore.pipe, can be request, remove, message, save, propagate +@tparam string key The key that the action is being preformed on +@tparam any value The value that should be used with the action + +@usage-- Write a data request to datastore.pipe +self:write_action('request', 'TestKey') + +@usage-- Write a data save to datastore.pipe +self:write_action('save', 'TestKey', 'Foo') + +]] +function Datastore:write_action(action, key, value) + local data = {action, self.name, key} + if value ~= nil then + data[4] = type(value) == 'table' and game.table_to_json(value) or value + end + game.write_file('ext/datastore.out', table.concat(data, ' ')..'\n', true, 0) +end + +----- Datastore Local +-- @section datastore-local + +--[[-- Create a new datastore which is stores its data inside of this datastore +@tparam string subDatastoreName The name of the datastore that will have its data stored in this datastore +@treturn table The new datastore that was created inside of this datastore + +@usage-- Add a new sub datastore +local ExampleData = Datastore.connect('ExampleData') +local BarData = ExampleData:combine('Bar') + +]] +function Datastore:combine(subDatastoreName) + local new_datastore = DatastoreManager.connect(self.name..'.'..subDatastoreName) + self.children[subDatastoreName] = new_datastore + new_datastore.value_name = subDatastoreName + new_datastore.serializer = self.serializer + new_datastore.auto_save = self.auto_save + new_datastore.parent = self + Data[new_datastore.name] = nil + new_datastore.data = nil + return new_datastore +end + +--[[-- Set a callback that will be used to serialize keys which aren't strings +@tparam function callback The function that will be used to serialize non string keys passed as an argument + +@usage-- Set a custom serializer, this would be the same as Datastore.name_serializer +local ExampleData = Datastore.connect('ExampleData') +ExampleData:set_serializer(function(rawKey) + return rawKey.name +end) + +]] +function Datastore:set_serializer(callback) + assert(type(callback) == 'function', 'Callback must be a function') + self.serializer = callback +end + +--[[-- Set a default value to be returned by get if no other default is given, using will mean get will never return nil, set using the default will set to nil to save space +@tparam any value The value that will be deep copied by get if the value is nil and no other default is given +@tparam boolean allowSet When true if the default is passed as the value for set it will be set rather than setting nil + +@usage-- Set a default value to be returned by get +local ExampleData = Datastore.connect('ExampleData') +ExampleData:set_default('Foo') + +]] +function Datastore:set_default(value, allowSet) + self.default = value + self.allow_set_to_default = allowSet +end + +--[[-- Set metadata tags on this datastore which can be accessed by other scripts +@tparam table tags A table of tags that you want to set in the metadata for this datastore + +@usage-- Adding metadata that could be used by a gui to help understand the stored data +local ExampleData = Datastore.connect('ExampleData') +ExampleData:set_metadata{ + caption = 'Test Data', + tooltip = 'Data used for testing datastores', + type = 'table' +} + +]] +function Datastore:set_metadata(tags) + local metadata = self.metadata + for key, value in pairs(tags) do + metadata[key] = value + end +end + +--[[-- Get a value from local storage, option to have a default value, do not edit the data returned as changes may not save, use update if you want to make changes +@tparam any key The key that you want to get the value of, must be a string unless a serializer is set +@tparam[opt] any default The default value that will be returned if no value is found in the datastore + +@usage-- Get a key from the datastore, the default will be deep copied if no value exists in the datastore +local ExampleData = Datastore.connect('ExampleData') +local value = ExampleData:get('TestKey') + +]] +function Datastore:get(key, default) + key = self:serialize(key) + local value = self:raw_get(key) + if value ~= nil then return value end + return copy(default or self.default) +end + +--[[-- Set a value in local storage, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save +@tparam any key The key that you want to set the value of, must be a string unless a serializer is set +@tparam any value The value that you want to set for this key + +@usage-- Set a value in the datastore, this will trigger on_update, if auto_save is true then will trigger save +local ExampleData = Datastore.connect('ExampleData') +ExampleData:set('TestKey', 'Foo') + +]] +function Datastore:set(key, value) + key = self:serialize(key) + local old_value = self:raw_get(key) + if value == self.default and not self.allow_set_to_default then + self:raw_set(key) + else + self:raw_set(key, value) + end + self:raise_event('on_update', key, value, old_value) + if self.auto_save then self:save(key) end + return value +end + +--[[-- Increment the value in local storage, only works for number values, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save +@tparam any key The key that you want to increment the value of, must be a string unless a serializer is set +@tparam[opt=1] number delta The amount that you want to increment the value by, can be negative or a decimal + +@usage-- Increment a value in a datastore, the value must be a number or nil, if nil 0 is used as the start value +local ExampleData = Datastore.connect('ExampleData') +ExampleData:increment('TestNumber') + +]] +function Datastore:increment(key, delta) + key = self:serialize(key) + local value = self:raw_get(key) or 0 + return self:set(key, value + (delta or 1)) +end + +local function update_error(err) error('An error ocurred in datastore update: '..trace(err), 2) end +--[[-- Use a function to update the value locally, will trigger on_update then on_save, save_to_disk and auto_save is required for on_save +@tparam any key The key that you want to apply the update to, must be a string unless a serializer is set +@tparam function callback The function that will be used to update the value at this key + +@usage-- Using a function to update a value, if a value is returned then this will be the new value +local ExampleData = Datastore.connect('ExampleData') +ExampleData:increment('TestKey', function(key, value) + return value..value +end) + +]] +function Datastore:update(key, callback) + key = self:serialize(key) + local value = self:raw_get(key) + local old_value = copy(self:raw_get(key)) + local success, new_value = xpcall(callback, update_error, key, value) + if success and new_value ~= nil then + self:set(key, new_value) + else + self:raise_event('on_update', key, value, old_value) + if self.auto_save then self:save(key) end + end +end + +--[[-- Remove a value locally and on the external source, works regardless of propagateChanges, requires save_to_disk for external changes +@tparam any key The key that you want to remove locally and externally, must be a string unless a serializer is set + +@usage-- Remove a key locally and externally +local ExampleData = Datastore.connect('ExampleData') +ExampleData:remove('TestKey') + +]] +function Datastore:remove(key) + key = self:serialize(key) + local old_value = self:raw_get(key) + self:raw_set(key) + self:raise_event('on_update', key, nil, old_value) + if self.save_to_disk then self:write_action('remove', key) end + if self.parent and self.parent.auto_save then return self.parent:save(key) end +end + +local function filter_error(err) log('An error ocurred in a datastore filter:'..trace(err)) end +--[[-- Internal, Used to filter elements from a table +@tparam table tbl The table that will have the filter applied to it +@tparam[opt] function callback The function that will be used as a filter, if none giving then the provided table is returned +@treturn table The table which has only the key values pairs which passed the filter + +@usage-- Internal, Filter a table by the values it contains, return true to keep the key value pair +local filtered_table = filter({5,3,4,1,2}, function(key, value) + return value > 2 +end) + +]] +local function filter(tbl, callback) + if not callback then return tbl end + local rtn = {} + for key, value in pairs(tbl) do + local success, add = xpcall(callback, filter_error, key, value) + if success and add then rtn[key] = value end + end + return rtn +end + +--[[-- Get all keys in this datastore, optional filter callback +@tparam[opt] function callback The filter function that can be used to filter the results returned +@treturn table All the data that is in this datastore, filtered if a filter was provided + +@usage-- Get all the data in this datastore +local ExampleData = Datastore.connect('ExampleData') +local data = ExampleData:get_all() + +@usage-- Get all the data in this datastore, with a filter +local ExampleData = Datastore.connect('ExampleData') +local data = ExampleData:get_all(function(key, value) + return type(value) == 'string' +end) + +]] +function Datastore:get_all(callback) + if not self.parent then + return filter(self.data, callback) + else + local data, value_name = {}, self.value_name + for key, value in pairs(self.parent:get_all()) do + data[key] = value[value_name] + end + return filter(data, callback) + end +end + +--[[-- Update all keys in this datastore using the same update function +@tparam function callback The update function that will be applied to each key + +@usage-- Get all the data in this datastore, with a filter +local ExampleData = Datastore.connect('ExampleData') +ExampleData:update_all(function(key, value) + return value..value +end) + +]] +function Datastore:update_all(callback) + local data = self:get_all() + for key, value in pairs(data) do + local old_value = copy(value) + local success, new_value = xpcall(callback, update_error, key, value) + if success and new_value ~= nil then + self:set(key, new_value) + else + self:raise_event('on_update', key, value, old_value) + if self.auto_save then self:save(key) end + end + end +end + +----- Datastore External +-- @section datastore-external + +--[[-- Request a value from an external source, will trigger on_load when data is received +@tparam any key The key that you want to request from an external source, must be a string unless a serializer is set + +@usage-- Request a key from an external source, on_load is triggered when data is received +local ExampleData = Datastore.connect('ExampleData') +ExampleData:request('TestKey') + +]] +function Datastore:request(key) + if self.parent then return self.parent:request(key) end + key = self:serialize(key) + self:write_action('request', key) +end + +--[[-- Save a value to an external source, will trigger on_save before data is saved, save_to_disk must be set to true +@tparam any key The key that you want to save to an external source, must be a string unless a serializer is set + +@usage-- Save a key to an external source, save_to_disk must be set to true for there to be any effect +local ExampleData = Datastore.connect('ExampleData') +ExampleData:save('TestKey') + +]] +function Datastore:save(key) + if self.parent then self.parent:save(key) end + if not self.save_to_disk then return end + key = self:serialize(key) + local value = self:raise_event('on_save', key, copy(self:raw_get(key))) + local action = self.propagate_changes and 'propagate' or 'save' + self:write_action(action, key, value) +end + +--[[-- Save a value to an external source and remove locally, will trigger on_unload then on_save, save_to_disk is not required for on_unload +@tparam any key The key that you want to unload from the datastore, must be a string unless a serializer is set + +@usage-- Unload a key from the datastore, get will now return nil and value will be saved externally if save_to_disk is set to true +local ExampleData = Datastore.connect('ExampleData') +ExampleData:unload('TestKey') + +]] +function Datastore:unload(key) + if self.parent then return self.parent:unload(key) end + key = self:serialize(key) + self:raise_event('on_unload', key, copy(self:raw_get(key))) + self:save(key) + self:raw_set(key) +end + +--[[-- Use to send a message over the connection, works regardless of saveToDisk and propagateChanges +@tparam any key The key that you want to send a message over, must be a string unless a serializer is set +@tparam any message The message that you want to send to other connected servers, or external source + +@usage-- Send a message to other servers on this key, can listen for messages with on_message +local ExampleData = Datastore.connect('ExampleData') +ExampleData:message('TestKey', 'Foo') + +]] +function Datastore:message(key, message) + key = self:serialize(key) + self:write_action('message', key, message) +end + +--[[-- Save all the keys in the datastore, optional filter callback +@tparam[opt] function callback The filter function that can be used to filter the keys saved + +@usage-- Save all the data in this datastore +local ExampleData = Datastore.connect('ExampleData') +local data = ExampleData:save_all() + +@usage-- Save all the data in this datastore, with a filter +local ExampleData = Datastore.connect('ExampleData') +ExampleData:save_all(function(key, value) + return type(value) == 'string' +end) + +]] +function Datastore:save_all(callback) + local data = self:get_all(callback) + for key in pairs(data) do self:save(key) end +end + +--[[-- Unload all the keys in the datastore, optional filter callback +@tparam[opt] function callback The filter function that can be used to filter the keys unloaded + +@usage-- Unload all the data in this datastore +local ExampleData = Datastore.connect('ExampleData') +ExampleData:unload_all() + +@usage-- Unload all the data in this datastore, with a filter +local ExampleData = Datastore.connect('ExampleData') +ExampleData:unload_all(function(key, value) + return type(value) == 'string' +end) + +]] +function Datastore:unload_all(callback) + local data = self:get_all(callback) + for key in pairs(data) do self:unload(key) end +end + +----- Events +-- @section events + +local function event_error(err) log('An error ocurred in a datastore event handler: '..trace(err)) end +--[[-- Internal, Raise an event on this datastore +@tparam string event_name The name of the event to raise for this datastore +@tparam string key The key that this event is being raised for +@tparam[opt] any value The current value that this key has, might be a deep copy of the value +@tparam[opt] any old_value The previous value that this key has, might be a deep copy of the value +@tparam[opt] string source Where this call came from, used to do event recursion so can be parent or child +@treturn any The value that is left after being passed through all the event handlers + +@usage-- Internal, Getting the value that should be saved +value = self:raise_event('on_save', key, value) + +]] +function Datastore:raise_event(event_name, key, value, old_value, source) + -- Raise the event for the children of this datastore + if source ~= 'child' and next(self.children) then + if type(value) ~= 'table' then value = {} end + for value_name, child in pairs(self.children) do + local old_child_value = old_value and old_value[value_name] or nil + value[value_name] = child:raise_event(event_name, key, value[value_name], old_child_value, 'parent') + end + end + + -- Raise the event for this datastore + local handlers = self.events[event_name] + if handlers then + for _, handler in ipairs(handlers) do + local success, new_value = xpcall(handler, event_error, key, value, old_value) + if success and new_value ~= nil then value = new_value end + end + end + + -- Raise the event for the parent of this datastore + if source ~= 'parent' and self.parent then + local parent_value = self.parent:raw_get(key, true) + self.parent:raise_event(event_name, key, parent_value, parent_value, 'child') + end + + -- If this is the save event and the table is empty then return nil + if event_name == 'on_save' and next(self.children) and not next(value) then return end + return value +end + +--[[-- Internal, Returns a function which will add a callback to an event +@tparam string event_name The name of the event that this should create a handler adder for +@treturn function The function that can be used to add handlers to this event + +@usage-- Internal, Get the function to add handlers to on_load +Datastore.on_load = event_factory('on_load') + +]] +local function event_factory(event_name) + return function(self, callback) + assert(type(callback) == 'function', 'Handler must be a function') + local handlers = self.events[event_name] + if not handlers then + self.events[event_name] = { callback } + else + handlers[#handlers+1] = callback + end + end +end + +--[[-- Register a callback that triggers when data is loaded from an external source, returned value is saved locally +@tparam function callback The handler that will be registered to the on_load event +@usage-- Adding a handler to on_load, returned value will be saved locally, can be used to deserialize the value beyond a normal json +local ExampleData = Datastore.connect('ExampleData') +ExampleData:on_load(function(key, value) + game.print('Test data loaded for: '..key) +end) +]] +Datastore.on_load = event_factory('on_load') + +--[[-- Register a callback that triggers before data is saved, returned value is saved externally +@tparam function callback The handler that will be registered to the on_load event +@usage-- Adding a handler to on_save, returned value will be saved externally, can be used to serialize the value beyond a normal json +local ExampleData = Datastore.connect('ExampleData') +ExampleData:on_save(function(key, value) + game.print('Test data saved for: '..key) +end) +]] +Datastore.on_save = event_factory('on_save') + +--[[-- Register a callback that triggers before data is unloaded, returned value is ignored +@tparam function callback The handler that will be registered to the on_load event +@usage-- Adding a handler to on_unload, returned value is ignored, can be used to clean up guis or local values related to this data +local ExampleData = Datastore.connect('ExampleData') +ExampleData:on_load(function(key, value) + game.print('Test data unloaded for: '..key) +end) +]] +Datastore.on_unload = event_factory('on_unload') + +--[[-- Register a callback that triggers when a message is received, returned value is ignored +@tparam function callback The handler that will be registered to the on_load event +@usage-- Adding a handler to on_message, returned value is ignored, can be used to receive messages from other connected servers without saving data +local ExampleData = Datastore.connect('ExampleData') +ExampleData:on_message(function(key, value) + game.print('Test data message for: '..key) +end) +]] +Datastore.on_message = event_factory('on_message') + +--[[-- Register a callback that triggers any time a value is changed, returned value is ignored +@tparam function callback The handler that will be registered to the on_load event +@usage-- Adding a handler to on_update, returned value is ignored, can be used to update guis or send messages when data is changed +local ExampleData = Datastore.connect('ExampleData') +ExampleData:on_update(function(key, value) + game.print('Test data updated for: '..key) +end) +]] +Datastore.on_update = event_factory('on_update') + +----- Module Return +return DatastoreManager diff --git a/expcore/external.lua b/expcore/external.lua new file mode 100644 index 0000000000..314901ade2 --- /dev/null +++ b/expcore/external.lua @@ -0,0 +1,153 @@ +--[[-- Core Module - External +- A module used to make accessing externally set data easier. +@core External +@alias External + +@usage-- Printing all server to chat +local External = require 'expcore.external' --- @dep expcore.external + +local message = 'id: %s name: %s version: %s status: %s' +for server_id, server in pairs(External.get_servers()) do + local status = External.get_server_status(server_id) + game.print(message:format(server_id, server.name, server.version, status)) +end + +]] + +local ext, var +local concat = table.concat + +local External = {} + +--[[-- Checks that local links are valid, will try to add the links if invalid +@treturn boolean If the external data is valid, if false you should not call any other methods from External + +@usage-- Check that external data is valid +if not External.valid() then + -- error code here +end + +]] +function External.valid() + if global.ext == nil then return false end + if ext == global.ext and var == ext.var then + return var ~= nil + else + ext = global.ext + var = ext.var + return var ~= nil + end +end + +--[[-- Gets a table of all the servers, key is the server id, value is the server details +@treturn table A table containing all the servers, key is the server id, value is the server details + +@usage-- Get all servers +local servers = External.get_servers() + +]] +function External.get_servers() + assert(ext, 'No external data was found, use External.valid() to ensure external data exists.') + return assert(ext.servers, 'No server list was found, please ensure that the external service is running') +end + +--[[-- Gets a table of all the servers filtered by name, key is the server id, value is the server details +@tparam string search The string to search for, names, short_names and ids are checked for this string. +@treturn table A table containing all the servers filtered by name, key is the server id, value is the server details + +@usage-- Get all servers with public in the name +local servers = External.get_servers_filtered(public) + +]] +function External.get_servers_filtered(search) + assert(ext, 'No external data was found, use External.valid() to ensure external data exists.') + local servers = assert(ext.servers, 'No server list was found, please ensure that the external service is running') + local found_servers = {} + search = search:lower() + for server_id, server in pairs(servers) do + local str = concat{server.name, server.short_name, server.id} + if str:lower():find(search, 1, true) then found_servers[server_id] = server end + end + return found_servers +end + +--[[-- Gets the details of the current server +@treturn table The details of the current server + +@usage-- Get the details of the current server +local server = External.get_current_server() + +]] +function External.get_current_server() + assert(ext, 'No external data was found, use External.valid() to ensure external data exists.') + local servers = assert(ext.servers, 'No server list was found, please ensure that the external service is running') + local server_id = assert(ext.current, 'No current id was found, please ensure that the external service is running') + return servers[server_id] +end + +--[[-- Gets the details of the given server +@tparam string server_id The internal server if for the server you want the details of +@treturn table The details of the given server + +@usage-- Get the details of the given server +local server = External.get_server_details('eu-01') + +]] +function External.get_server_details(server_id) + assert(ext, 'No external data was found, use External.valid() to ensure external data exists.') + local servers = assert(ext.servers, 'No server list was found, please ensure that the external service is running') + return servers[server_id] +end + +--[[-- Gets the status of the given server +@tparam string server_id The internal server if for the server you want the status of +@tparam boolean raw When true Current will not be returned as status but rather the raw status for the server +@treturn string The status of the given server, one of: Online, Modded, Protected, Current, Offline + +@usage-- Get the status of the given server +local status = External.get_server_status('eu-01') + +]] +function External.get_server_status(server_id, raw) + assert(var, 'No external data was found, use External.valid() to ensure external data exists.') + local servers = assert(var.status, 'No server status was found, please ensure that the external service is running') + local current = assert(ext.current, 'No current id was found, please ensure that the external service is running') + return not raw and server_id == current and 'Current' or servers[server_id] +end + +--[[-- Gets the ups of the current server +@usage-- Get the ups of the current server +local server_ups = External.get_server_ups() + +]] +function External.get_server_ups() + assert(var, 'No external data was found, use External.valid() to ensure external data exists.') + return assert(var.server_ups, 'No server ups was found, please ensure that the external service is running') +end + +--[[-- Connect a player to the given server +@tparam LuaPlayer player The player that you want to request to join a different server +@tparam string server_id The internal id of the server to connect to, can also be any address but this will show Unknown Server +@tparam[opt=false] boolean self_requested If the player requested the join them selfs, this will hide the message about being asked to switch + +@usage-- Request that a player joins a different server +External.request_connection(player, 'eu-01') + +@usage-- Request that a player joins a different server, by own request +External.request_connection(player, 'eu-01', true) + +]] +function External.request_connection(player, server_id, self_requested) + local server = { address = server_id, name = 'Unknown Server', description = 'This server is not ran by us, please check the address of the server.' } + if ext and ext.servers and ext.servers[server_id] then server = ext.servers[server_id] end + local message = 'Please press the connect button below to join.' + if not self_requested then message = 'You have been asked to switch to a different server.\n'..message end + player.connect_to_server{ + address = server.address, + name = '\n[color=orange][font=heading-1]'..server.name..'[/font][/color]\n', + description = server.description..'\n'..message + } +end + +--- Module return +return External \ No newline at end of file diff --git a/expcore/gui/_require.lua b/expcore/gui/_require.lua index 306c354d45..51fc0a1482 100644 --- a/expcore/gui/_require.lua +++ b/expcore/gui/_require.lua @@ -18,7 +18,7 @@ Gui.element{ @usage-- Making a factory function for a button which is contained within a flow -- This method is for when you still want to register event handlers but cant use the table method local example_flow_with_button = -Gui.element(function(event_trigger,parent,...) +Gui.element(function(event_trigger, parent, ...) -- ... shows that all other arguments from the factory call are passed to this function -- Here we are adding a flow which we will then later add a button to local flow = @@ -60,7 +60,7 @@ Gui.element{ caption = 'Example Button', style = 'forward_button' -- factorio styles can be applied here } -:style(function(style,element,...) +:style(function(style, element, ...) -- style is the current style object for the elemenent -- element is the element that is being changed -- ... shows that all other arguments from the factory call are passed to this function @@ -76,7 +76,7 @@ Gui.element{ type = 'button', caption = 'Example Button' } -:on_click(function(player,element,event) +:on_click(function(player, element, event) -- player is the player who interacted with the element to cause the event -- element is a refrence to the element which caused the event -- event is a raw refrence to the event data if player and element are not enough @@ -98,21 +98,21 @@ Gui.element{ width = 18, height = 20 } -:on_click(function(player,_,_) +:on_click(function(player, _,_) Gui.hide_left_flow(player) end) @usage-- Eample from defines, Gui.alignment, called like: Gui.alignment(parent, name, horizontal_align, vertical_align) -- Notice how _ are used to blank arguments that are not needed in that context and how they line up with above Gui.alignment = -Gui.element(function(_,parent,name,_,_) +Gui.element(function(_, parent, name, _,_) return parent.add{ name = name or 'alignment', type = 'flow', } end) -:style(function(style,_,_,horizontal_align,vertical_align) - style.padding = {1,2} +:style(function(style, _,_, horizontal_align, vertical_align) + style.padding = {1, 2} style.vertical_align = vertical_align or 'center' style.horizontal_align = horizontal_align or 'right' style.vertically_stretchable = style.vertical_align ~= 'center' diff --git a/expcore/gui/core_defines.lua b/expcore/gui/core_defines.lua index 0a545a34cc..50e3ec09e2 100644 --- a/expcore/gui/core_defines.lua +++ b/expcore/gui/core_defines.lua @@ -23,7 +23,7 @@ Gui.element{ width = 18, height = 36 } -:on_click(function(player,_,_) +:on_click(function(player, _,_) Gui.toggle_top_flow(player) end) Gui.core_defines.hide_top_flow = hide_top_flow @@ -42,7 +42,7 @@ Gui.element{ width = 18, height = 20 } -:on_click(function(player,_,_) +:on_click(function(player, _,_) Gui.toggle_top_flow(player) end) Gui.core_defines.show_top_flow = show_top_flow @@ -61,13 +61,13 @@ Gui.element{ width = 18, height = 20 } -:on_click(function(player,_,_) +:on_click(function(player, _,_) Gui.hide_left_flow(player) end) Gui.core_defines.hide_left_flow = hide_left_flow --- Draw the core elements when a player joins the game -Event.add(defines.events.on_player_created,function(event) +Event.add(defines.events.on_player_created, function(event) local player = game.players[event.player_index] -- Draw the top flow diff --git a/expcore/gui/defines.lua b/expcore/gui/defines.lua index c322d1b226..9945318183 100644 --- a/expcore/gui/defines.lua +++ b/expcore/gui/defines.lua @@ -17,21 +17,21 @@ local Gui = require 'expcore.gui.prototype' @treturn LuaGuiElement the alignment flow that was created @usage-- Adding a right align flow -local alignment = Gui.alignment(element,'example_right_alignment') +local alignment = Gui.alignment(element, 'example_right_alignment') @usage-- Adding a horizontal center and top align flow -local alignment = Gui.alignment(element,'example_center_top_alignment','center','top') +local alignment = Gui.alignment(element, 'example_center_top_alignment', 'center', 'top') ]] Gui.alignment = -Gui.element(function(_,parent,name,_,_) +Gui.element(function(_, parent, name, _,_) return parent.add{ name = name or 'alignment', type = 'flow', } end) -:style(function(style,_,_,horizontal_align,vertical_align) - style.padding = {1,2} +:style(function(style, _,_, horizontal_align, vertical_align) + style.padding = {1, 2} style.vertical_align = vertical_align or 'center' style.horizontal_align = horizontal_align or 'right' style.vertically_stretchable = style.vertical_align ~= 'center' @@ -47,11 +47,11 @@ end) @treturn LuaGuiElement the table that was created @usage-- Adding a scroll table with max height of 200 and column count of 3 -local scroll_table = Gui.scroll_table(element,200,3) +local scroll_table = Gui.scroll_table(element, 200, 3) ]] Gui.scroll_table = -Gui.element(function(_,parent,height,column_count,name) +Gui.element(function(_, parent, height, column_count, name) -- Draw the scroll local scroll_pane = parent.add{ @@ -65,7 +65,7 @@ Gui.element(function(_,parent,height,column_count,name) -- Set the style of the scroll pane local scroll_style = scroll_pane.style - scroll_style.padding = {1,3} + scroll_style.padding = {1, 3} scroll_style.maximal_height = height scroll_style.horizontally_stretchable = true @@ -105,7 +105,7 @@ local header = Gui.header( ]] Gui.header = -Gui.element(function(_,parent,caption,tooltip,add_alignment,name,label_name) +Gui.element(function(_, parent, caption, tooltip, add_alignment, name, label_name) -- Draw the header local header = parent.add{ @@ -116,7 +116,7 @@ Gui.element(function(_,parent,caption,tooltip,add_alignment,name,label_name) -- Change the style of the header local style = header.style - style.padding = {2,4} + style.padding = {2, 4} style.use_header_filler = false style.horizontally_stretchable = true @@ -153,7 +153,7 @@ local footer = Gui.footer( ]] Gui.footer = -Gui.element(function(_,parent,caption,tooltip,add_alignment,name) +Gui.element(function(_, parent, caption, tooltip, add_alignment, name) -- Draw the header local footer = parent.add{ @@ -164,7 +164,7 @@ Gui.element(function(_,parent,caption,tooltip,add_alignment,name) -- Change the style of the footer local style = footer.style - style.padding = {2,4} + style.padding = {2, 4} style.use_header_filler = false style.horizontally_stretchable = true @@ -190,11 +190,11 @@ end) @tparam number width the minimal width that the frame will have @usage-- Adding a container as a base -local container = Gui.container(parent,'my_container',200) +local container = Gui.container(parent, 'my_container', 200) ]] Gui.container = -Gui.element(function(_,parent,name,_) +Gui.element(function(_, parent, name, _) -- Draw the external container local frame = parent.add{ @@ -210,7 +210,7 @@ Gui.element(function(_,parent,name,_) style = 'window_content_frame_packed' } end) -:style(function(style,element,_,width) +:style(function(style, element, _,width) style.vertically_stretchable = false local frame_style = element.parent.style frame_style.padding = 2 @@ -227,16 +227,16 @@ local bar = Gui.bar(parent, 100) ]] Gui.bar = -Gui.element(function(_,parent) +Gui.element(function(_, parent) return parent.add{ type = 'progressbar', size = 1, value = 1 } end) -:style(function(style,_,width) +:style(function(style, _,width) style.height = 3 - style.color = {r=255,g=255,b=255} + style.color = {r=255, g=255, b=255} if width then style.width = width else style.horizontally_stretchable = true end end) @@ -253,7 +253,7 @@ local label = Gui.centered_label(parent, 100, 'This is centered') ]] Gui.centered_label = -Gui.element(function(_,parent,width,caption,tooltip) +Gui.element(function(_, parent, width, caption, tooltip) local label = parent.add{ type = 'label', caption = caption, @@ -281,11 +281,11 @@ local label = Gui.centered_label(parent, 100, 'This is centered') ]] Gui.title_label = -Gui.element(function(_,parent,width,caption,tooltip) +Gui.element(function(_, parent, width, caption, tooltip) local title_flow = parent.add{ type='flow' } title_flow.style.vertical_align = 'center' - Gui.bar(title_flow,width) + Gui.bar(title_flow, width) local title_label = title_flow.add{ type = 'label', caption = caption, diff --git a/expcore/gui/helper_functions.lua b/expcore/gui/helper_functions.lua index c303fb1528..5346c593ae 100644 --- a/expcore/gui/helper_functions.lua +++ b/expcore/gui/helper_functions.lua @@ -30,7 +30,7 @@ end local new_enabled_state = Gui.toggle_enabled_state(element) ]] -function Gui.toggle_enabled_state(element,state) +function Gui.toggle_enabled_state(element, state) if not element or not element.valid then return end if state == nil then state = not element.enabled end element.enabled = state @@ -46,7 +46,7 @@ end local new_visible_state = Gui.toggle_visible_state(element) ]] -function Gui.toggle_visible_state(element,state) +function Gui.toggle_visible_state(element, state) if not element or not element.valid then return end if state == nil then state = not element.visible end element.visible = state @@ -82,7 +82,7 @@ Gui.element{ :style(Gui.sprite_style(20)) ]] -function Gui.sprite_style(size,padding,style) +function Gui.sprite_style(size, padding, style) style = style or {} style.padding = padding or -2 style.height = size diff --git a/expcore/gui/left_flow.lua b/expcore/gui/left_flow.lua index 4befce31d1..42f0265537 100644 --- a/expcore/gui/left_flow.lua +++ b/expcore/gui/left_flow.lua @@ -55,11 +55,11 @@ Gui.left_toolbar_button('entity/inserter', 'Nothing to see here', example_flow_w end) ]] -function Gui.left_toolbar_button(sprite,tooltip,element_define,authenticator) - local button = Gui.toolbar_button(sprite,tooltip,authenticator) +function Gui.left_toolbar_button(sprite, tooltip, element_define, authenticator) + local button = Gui.toolbar_button(sprite, tooltip, authenticator) -- Add on_click handler to handle click events comming from the player - button:on_click(function(player,_,_) + button:on_click(function(player, _,_) local top_flow = Gui.get_top_flow(player) local element = top_flow[button.name] local visibility_state = Gui.toggle_left_element(player, element_define) @@ -169,7 +169,7 @@ function Gui.hide_left_flow(player) -- Set the visible state of all elements in the flow hide_button.visible = false - for name,_ in pairs(Gui.left_elements) do + for name, _ in pairs(Gui.left_elements) do left_flow[name].visible = false -- Check if the the element has a toobar button attached @@ -202,7 +202,7 @@ end local frame = Gui.get_left_element(game.player, example_flow_with_button) ]] -function Gui.get_left_element(player,element_define) +function Gui.get_left_element(player, element_define) local left_flow = Gui.get_left_flow(player) return left_flow[element_define.name] end @@ -220,7 +220,7 @@ Gui.toggle_top_flow(game.player, example_flow_with_button) Gui.toggle_top_flow(game.player, example_flow_with_button, true) ]] -function Gui.toggle_left_element(player,element_define,state) +function Gui.toggle_left_element(player, element_define, state) local left_flow = Gui.get_left_flow(player) local top_flow = Gui.get_top_flow(player) diff --git a/expcore/gui/prototype.lua b/expcore/gui/prototype.lua index f780360208..8bd7a64430 100644 --- a/expcore/gui/prototype.lua +++ b/expcore/gui/prototype.lua @@ -22,9 +22,9 @@ local Gui = { _prototype_element = {}, --- The prototype metatable applied to new element defines _mt_element = { - __call = function(self,parent,...) - local element = self._draw(self.name,parent,...) - if self._style then self._style(element.style,element,...) end + __call = function(self, parent, ...) + local element = self._draw(self.name, parent, ...) + if self._style then self._style(element.style, element, ...) end return element end } @@ -50,7 +50,7 @@ Gui.element{ @usage-- Using element defines with a custom factory function -- This method can be used if you still want to be able register event handlers but it is too complex to be compatible with LuaGuiElement.add local example_flow_with_button = -Gui.element(function(event_trigger,parent,...) +Gui.element(function(event_trigger, parent, ...) -- ... shows that all other arguments from the factory call are passed to this function -- parent is the element which was passed to the factory function where you should add your new element -- here we are adding a flow which we will then later add a button to @@ -90,7 +90,7 @@ function Gui.element(element_define) if type(element_define) == 'table' then Gui.debug_info[name].draw = element_define element_define.name = name - element._draw = function(_,parent) + element._draw = function(_, parent) return parent.add(element_define) end else @@ -131,7 +131,7 @@ Gui.element{ caption = 'Example Button', style = 'forward_button' -- factorio styles can be applied here } -:style(function(style,element,...) +:style(function(style, element, ...) -- style is the current style object for the elemenent -- element is the element that is being changed -- ... shows that all other arguments from the factory call are passed to this function @@ -147,7 +147,7 @@ function Gui._prototype_element:style(style_define) if type(style_define) == 'table' then Gui.debug_info[self.name].style = style_define self._style = function(style) - for key,value in pairs(style_define) do + for key, value in pairs(style_define) do style[key] = value end end @@ -171,8 +171,8 @@ element_deinfe:on_custom_event('my_custom_event', function(event) end) ]] -function Gui._prototype_element:on_custom_event(event_name,handler) - table.insert(Gui.debug_info[self.name].events,event_name) +function Gui._prototype_element:on_custom_event(event_name, handler) + table.insert(Gui.debug_info[self.name].events, event_name) Gui.events[event_name] = event_name self[event_name] = handler return self @@ -210,7 +210,7 @@ function Gui._prototype_element:raise_custom_event(event) end event.player = player - local success, err = pcall(handler,player,element,event) + local success, err = pcall(handler, player, element, event) if not success then error('There as been an error with an event handler for a gui element:\n\t'..err) end @@ -227,8 +227,8 @@ local function event_handler_factory(event_name) element_define:raise_custom_event(event) end) - return function(self,handler) - table.insert(Gui.debug_info[self.name].events,debug.getinfo(1, "n").name) + return function(self, handler) + table.insert(Gui.debug_info[self.name].events, debug.getinfo(1, "n").name) self[event_name] = handler return self end diff --git a/expcore/gui/top_flow.lua b/expcore/gui/top_flow.lua index 1f50fc47f9..e2cb38c19b 100644 --- a/expcore/gui/top_flow.lua +++ b/expcore/gui/top_flow.lua @@ -73,7 +73,8 @@ function Gui.update_top_flow(player) end -- Set the visible state - element.visible = is_visible and authenticator(player) or false + local allowed = type(authenticator) == 'function' and authenticator(player) or authenticator + element.visible = is_visible and allowed or false end end @@ -86,10 +87,10 @@ end Gui.toggle_top_flow(game.player) @usage-- Open your top flow -Gui.toggle_top_flow(game.player,true) +Gui.toggle_top_flow(game.player, true) ]] -function Gui.toggle_top_flow(player,state) +function Gui.toggle_top_flow(player, state) -- Get the top flow and hide button local top_flow = Gui.get_top_flow(player) if state == nil then state = not top_flow.visible end @@ -129,7 +130,7 @@ Gui.left_toolbar_button('entity/inserter', 'Nothing to see here', function(playe end) ]] -function Gui.toolbar_button(sprite,tooltip,authenticator) +function Gui.toolbar_button(sprite, tooltip, authenticator) return Gui.element{ type = 'sprite-button', sprite = sprite, diff --git a/expcore/permission_groups.lua b/expcore/permission_groups.lua index 5b88331fe7..30ac6039a8 100644 --- a/expcore/permission_groups.lua +++ b/expcore/permission_groups.lua @@ -35,14 +35,14 @@ local Permissions_Groups = { -- Async function to add players to permission groups local add_to_permission_group = -Async.register(function(permission_group,player) +Async.register(function(permission_group, player) permission_group.add_player(player) end) Permissions_Groups.async_token_add_to_permission_group = add_to_permission_group -- Async function to remove players from permission groups local remove_from_permission_group = -Async.register(function(permission_group,player) +Async.register(function(permission_group, player) permission_group.remove_player(player) end) Permissions_Groups.async_token_remove_from_permission_group = remove_from_permission_group @@ -64,7 +64,7 @@ function Permissions_Groups.new_group(name) name=name, actions={}, allow_all_actions=true - },{ + }, { __index= Permissions_Groups._prototype }) Permissions_Groups.groups[name] = group @@ -111,7 +111,7 @@ Groups.reload_permissions() ]] function Permissions_Groups.reload_permissions() - for _,group in pairs(Permissions_Groups.groups) do + for _, group in pairs(Permissions_Groups.groups) do group:create() end end @@ -125,7 +125,7 @@ end Groups.set_player_group(game.player, 'Admin') ]] -function Permissions_Groups.set_player_group(player,group) +function Permissions_Groups.set_player_group(player, group) player = Game.get_player_from_any(player) group = Permissions_Groups.get_group_by_name(group) if not group or not player then return false end @@ -146,7 +146,7 @@ end group:set_action('toggle_map_editor', false) ]] -function Permissions_Groups._prototype:set_action(action,state) +function Permissions_Groups._prototype:set_action(action, state) if type(action) == 'string' then action = defines.input_action[action] end @@ -168,8 +168,8 @@ function Permissions_Groups._prototype:allow(actions) if type(actions) ~= 'table' then actions = {actions} end - for _,action in pairs(actions) do - self:set_action(action,true) + for _, action in pairs(actions) do + self:set_action(action, true) end return self end @@ -192,8 +192,8 @@ function Permissions_Groups._prototype:disallow(actions) if type(actions) ~= 'table' then actions = {actions} end - for _,action in pairs(actions) do - self:set_action(action,false) + for _, action in pairs(actions) do + self:set_action(action, false) end return self end @@ -257,8 +257,8 @@ function Permissions_Groups._prototype:create() if not group then group = game.permissions.create_group(self.name) end - for _,action in pairs(defines.input_action) do - group.set_allows_action(action,self:is_allowed(action)) + for _, action in pairs(defines.input_action) do + group.set_allows_action(action, self:is_allowed(action)) end return group end @@ -324,9 +324,9 @@ function Permissions_Groups._prototype:get_players(online) if online == nil then return group.players else - for _,player in pairs(group.players) do + for _, player in pairs(group.players) do if player.connected == online then - table.insert(player,player) + table.insert(player, player) end end end @@ -344,7 +344,7 @@ group:print('Hello, World!') ]] function Permissions_Groups._prototype:print(message) local players = self:get_players(true) - for _,player in pairs(players) do + for _, player in pairs(players) do player.print(message) end return #players diff --git a/expcore/player_data.lua b/expcore/player_data.lua new file mode 100644 index 0000000000..2eba29f5b8 --- /dev/null +++ b/expcore/player_data.lua @@ -0,0 +1,152 @@ +--[[-- Core Module - PlayerData +- A module used to store player data in a central datastore to minimize data requests and saves. +@core PlayerData + +@usage-- Adding a colour setting for players +local PlayerData = require 'expcore.player_data' +local PlayerColors = PlayerData.Settings:combine('Color') + +-- Set the players color when their data is loaded +PlayerColors:on_load(function(player_name, color) + local player = game.players[player_name] + player.color = color +end) + +-- Overwrite the saved color with the players current color +PlayerColors:on_save(function(player_name, _) + local player = game.players[player_name] + return player.color -- overwrite existing data with the current color +end) + +@usage-- Add a playtime statistic for players +local Event = require 'utils.event' +local PlayerData = require 'expcore.player_data' +local Playtime = PlayerData.Statistics:combine('Playtime') + +-- When playtime reaches an hour interval tell the player and say thanks +Playtime:on_update(function(player_name, playtime) + if playtime % 60 == 0 then + local hours = playtime / 60 + local player = game.players[player_name] + player.print('Thanks for playing on our servers, you have played for '..hours..' hours!') + end +end) + +-- Update playtime for players, data is only loaded for online players so update_all can be used +Event.add_on_nth_tick(3600, function() + Playtime:update_all(function(player_name, playtime) + return playtime + 1 + end) +end) + +]] + +local Event = require 'utils.event' --- @dep utils.event +local Async = require 'expcore.async' --- @dep expcore.async +local Datastore = require 'expcore.datastore' --- @dep expcore.datastore +local Commands = require 'expcore.commands' --- @dep expcore.commands +require 'config.expcore.command_general_parse' --- @dep config.expcore.command_general_parse + +--- Common player data that acts as the root store for player data +local PlayerData = Datastore.connect('PlayerData', true) -- saveToDisk +PlayerData:set_serializer(Datastore.name_serializer) -- use player name + +--- Store and enum for the data saving preference +local DataSavingPreference = PlayerData:combine('DataSavingPreference') +local PreferenceEnum = { 'All', 'Statistics', 'Settings', 'Required' } +for k,v in ipairs(PreferenceEnum) do PreferenceEnum[v] = k end +DataSavingPreference:set_default('All') +DataSavingPreference:set_metadata{ + name = {'expcore-data.preference'}, + tooltip = {'expcore-data.preference-tooltip'}, + value_tooltip ={'expcore-data.preference-value-tooltip'} +} + +--- Sets your data saving preference +-- @command set-data-preference +Commands.new_command('set-preference', 'Allows you to set your data saving preference') +:add_param('option', false, 'string-options', PreferenceEnum) +:register(function(player, option) + DataSavingPreference:set(player, option) + return {'expcore-data.set-preference', option} +end) + +--- Gets your data saving preference +-- @command data-preference +Commands.new_command('preference', 'Shows you what your current data saving preference is') +:register(function(player) + return {'expcore-data.get-preference', DataSavingPreference:get(player)} +end) + +--- Gets your data and writes it to a file +Commands.new_command('save-data', 'Writes all your player data to a file on your computer') +:register(function(player) + player.print{'expcore-data.get-data'} + game.write_file('expgaming_player_data.json', game.table_to_json(PlayerData:get(player, {})), false, player.index) +end) + +--- Async function called after 5 seconds with no player data loaded +local check_data_loaded = Async.register(function(player) + local player_data = PlayerData:get(player) + if not player_data or not player_data.valid then + player.print{'expcore-data.data-failed'} + Datastore.ingest('request', 'PlayerData', player.name, '{"valid":false}') + end +end) + +--- When player data loads tell the player if the load had failed previously +PlayerData:on_load(function(player_name, player_data, existing_data) + if not player_data or player_data.valid == false then return end + if existing_data and existing_data.valid == false then + game.players[player_name].print{'expcore-data.data-restore'} + end + player_data.valid = true +end) + +--- Remove data that the player doesnt want to have stored +PlayerData:on_save(function(player_name, player_data) + local dataPreference = DataSavingPreference:get(player_name) + dataPreference = PreferenceEnum[dataPreference] + if dataPreference == PreferenceEnum.All then + player_data.valid = nil + return player_data + end + + local saved_player_data = { PlayerRequired = player_data.PlayerRequired, DataSavingPreference = PreferenceEnum[dataPreference] } + if dataPreference <= PreferenceEnum.Settings then saved_player_data.PlayerSettings = player_data.PlayerSettings end + if dataPreference <= PreferenceEnum.Statistics then saved_player_data.PlayerStatistics = player_data.PlayerStatistics end + + return saved_player_data +end) + +--- Display your data preference when your data loads +DataSavingPreference:on_load(function(player_name, dataPreference) + game.players[player_name].print{'expcore-data.get-preference', dataPreference or DataSavingPreference.default} +end) + +--- Load player data when they join +Event.add(defines.events.on_player_joined_game, function(event) + local player = game.players[event.player_index] + Async.wait(300, check_data_loaded, player) + PlayerData:raw_set(player.name) + PlayerData:request(player) +end) + +--- Unload player data when they leave +Event.add(defines.events.on_player_left_game, function(event) + local player = game.players[event.player_index] + local player_data = PlayerData:get(player) + if player_data and player_data.valid == true then + PlayerData:unload(player) + else PlayerData:raw_set(player.name) end +end) + +----- Module Return ----- +return { + All = PlayerData, -- Root for all of a players data + Statistics = PlayerData:combine('Statistics'), -- Common place for stats + Settings = PlayerData:combine('Settings'), -- Common place for settings + Required = PlayerData:combine('Required'), -- Common place for required data + DataSavingPreference = DataSavingPreference, -- Stores what data groups will be saved + PreferenceEnum = PreferenceEnum -- Enum for the allowed options for data saving preference +} \ No newline at end of file diff --git a/expcore/roles.lua b/expcore/roles.lua index 05eb3cbf60..f97771a7ff 100644 --- a/expcore/roles.lua +++ b/expcore/roles.lua @@ -6,13 +6,13 @@ @usage--- Using Role System (assignment): --When a map first starts you will want to define on mass all the players you expect to join and the roles to give them: Roles.override_player_roles{ - Cooldude2606 = {'Owner','Admin','Member'}, + Cooldude2606 = {'Owner', 'Admin', 'Member'}, NotCooldude2606 = {'Member'} } --Once the game is running you still want to be able to give role and remove them which is when you would use: -Roles.assign_player(player,'Admin',by_player_name) -- this will give the "Admin" role to the player -Roles.unassign_player(player,{'Admin','Moderator'},by_player_name) -- this will remove "Admin" and "Moderator" role in one go +Roles.assign_player(player, 'Admin', by_player_name) -- this will give the "Admin" role to the player +Roles.unassign_player(player, {'Admin', 'Moderator'}, by_player_name) -- this will remove "Admin" and "Moderator" role in one go @usage--- Using Role System (role testing): --To comparer two players you can comparer the index of they highest roles, can be used when you want to allow a "write" down type system: @@ -22,9 +22,9 @@ Roles.get_player_highest_role(playerOne).index < Roles.get_player_highest_role(p Roles.get_player_roles(player) -- the return is an array that can be looped over however this is not in particular order --Finally you may want to test if a player has a certain role, flag or action allowed which is when you would use: -Roles.player_has_role(player,'Admin') -- you can provide a role name if you only want a name based system -Roles.player_has_flag(player,'is_donator') -- your roles can be grouped together with flags such as is_donator -Roles.player_allowed(player,'game modifiers') -- or you can have an action based system where each action is something the player can do +Roles.player_has_role(player, 'Admin') -- you can provide a role name if you only want a name based system +Roles.player_has_flag(player, 'is_donator') -- your roles can be grouped together with flags such as is_donator +Roles.player_allowed(player, 'game modifiers') -- or you can have an action based system where each action is something the player can do @usage--- Example Flag Define: --Flags can be used to group multiple roles and actions under one catch all, for example if you want a piece of code to only @@ -32,7 +32,7 @@ Roles.player_allowed(player,'game modifiers') -- or you can have an action based --a player has that tag present: -- give you donators a speed boost when they join; these functions aren't required but can be useful -Roles.define_flag_trigger('is_donator',function(player,state) +Roles.define_flag_trigger('is_donator', function(player, state) if state then player.character_running_speed_modifier = 1.5 else @@ -45,30 +45,30 @@ Roles.new_role('Donator') :set_flag('is_donator') -- and in your code you would test for -if Roles.player_has_flag(player,'is_donator') then +if Roles.player_has_flag(player, 'is_donator') then -- some donator only code end @usage--- Example Role Define: --You can't use a role system without any roles so first you must define your roles; each role has a minimum of a name with --the option for a shorthand: -Roles.new_role('Administrator','Admin') +Roles.new_role('Administrator', 'Admin') --Next you will want to add any extras you want to have, such as a tag, colour, permission group or any custom flags: -Roles.new_role('Administrator','Admin') +Roles.new_role('Administrator', 'Admin') :set_custom_tag('[Admin]') -:set_custom_color('red') -- this can be {r=0,g=0,b=0} or a predefined value +:set_custom_color('red') -- this can be {r=0, g=0, b=0} or a predefined value :set_permission_group('Staff') -- a second argument can be added if you have not used the custom permission group config :set_flag('is_admin') --You will then want to decide if you want to allow all actions, this should of course be used sparely: -Roles.new_role('Administrator','Admin') +Roles.new_role('Administrator', 'Admin') ...extras... :set_allow_all() --If you don't do this want this as i would advise you do then you will want to define what the role can do; this comes with --an optional inheritance system if you like those sort of things in which case disallow may also be of some use to you: -Roles.new_role('Administrator','Admin') +Roles.new_role('Administrator', 'Admin') ...extras... :set_parent('Moderator') -- the admin can do anything that a moderator can do :allow{ -- these actions can be anything just try to keep them without conflicts @@ -77,7 +77,7 @@ Roles.new_role('Administrator','Admin') } --Here is what the finished admin role would look like: -Roles.new_role('Administrator','Admin') +Roles.new_role('Administrator', 'Admin') :set_custom_tag('[Admin]') :set_custom_color('red') :set_permission_group('Staff') @@ -119,15 +119,15 @@ local write_json = _C.write_json --- @dep expcore.common local Roles = { _prototype={}, config={ - order={}, -- Contains the order of the roles, lower index is better - roles={}, -- Contains the raw info for the roles, indexed by role name - flags={}, -- Contains functions that run when a flag is added/removed from a player - internal={}, -- Contains all internally accessed roles, such as root, default - players={} -- Contains the roles that players have + order = {}, -- Contains the order of the roles, lower index is better + roles = {}, -- Contains the raw info for the roles, indexed by role name + flags = {}, -- Contains functions that run when a flag is added/removed from a player + internal = {}, -- Contains all internally accessed roles, such as root, default + players = {} -- Contains the roles that players have }, events = { - on_role_assigned=script.generate_event_name(), - on_role_unassigned=script.generate_event_name(), + on_role_assigned = script.generate_event_name(), + on_role_unassigned = script.generate_event_name(), } } @@ -143,9 +143,9 @@ end) --- Internal function used to trigger a few different things when roles are changed -- this is the raw internal trigger as the other function is called at other times -- there is a second half called role_update which triggers after the event call, it also is called when a player joins -local function emit_player_roles_updated(player,type,roles,by_player_name,skip_game_print) +local function emit_player_roles_updated(player, type, roles, by_player_name, skip_game_print) by_player_name = game.player and game.player.name or by_player_name or '' - local by_player = Game.get_player_from_any(by_player_name) + local by_player = game.players[by_player_name] local by_player_index = by_player and by_player.index or 0 -- get the event id from the type of emit local event = Roles.events.on_role_assigned @@ -153,31 +153,31 @@ local function emit_player_roles_updated(player,type,roles,by_player_name,skip_g event = Roles.events.on_role_unassigned end -- convert the roles to objects and get the names of the roles - local role_names = {} - for index,role in pairs(roles) do + local index, role_names = 0, {} + for _, role in ipairs(roles) do role = Roles.get_role_from_any(role) if role then - roles[index] = role - table.insert(role_names,role.name) + index = index + 1 + role_names[index] = role.name end end -- output to all the different locations: game print, player sound, event trigger and role log if not skip_game_print then - game.print({'expcore-roles.game-message-'..type,player.name,table.concat(role_names,', '),by_player_name},Colours.cyan) + game.print({'expcore-roles.game-message-'..type, player.name, table.concat(role_names, ', '), by_player_name}, Colours.cyan) end if type == 'assign' then player.play_sound{path='utility/achievement_unlocked'} else player.play_sound{path='utility/game_lost'} end - script.raise_event(event,{ + script.raise_event(event, { name=event, tick=game.tick, player_index=player.index, by_player_index=by_player_index, - roles=roles + roles=role_names }) - write_json('log/roles.log',{ + write_json('log/roles.log', { player_name=player.name, by_player_name=by_player_name, type=type, @@ -194,11 +194,11 @@ game.player.print(Roles.debug()) ]] function Roles.debug() local output = '' - for index,role_name in pairs(Roles.config.order) do + for index, role_name in ipairs(Roles.config.order) do local role = Roles.config.roles[role_name] local color = role.custom_color or Colours.white - color = string.format('[color=%d,%d,%d]',color.r,color.g,color.b) - output = output..string.format('\n%s %s) %s[/color]',color,index,serpent.line(role)) + color = string.format('[color=%d, %d, %d]', color.r, color.g, color.b) + output = output..string.format('\n%s %s) %s[/color]', color, index, serpent.line(role)) end return output end @@ -208,11 +208,11 @@ end @tparam string message the message to send to the players @usage-- Print a message to the given roles -Roles.print_to_roles({'Administrator','Moderator'}, 'Hello, World!') +Roles.print_to_roles({'Administrator', 'Moderator'}, 'Hello, World!') ]] -function Roles.print_to_roles(roles,message) - for _,role in pairs(roles) do +function Roles.print_to_roles(roles, message) + for _, role in ipairs(roles) do role = Roles.get_role_from_any(role) if role then role:print(message) end end @@ -226,16 +226,16 @@ end Roles.print_to_roles_higher('Moderator', 'Hello, World!') ]] -function Roles.print_to_roles_higher(role,message) +function Roles.print_to_roles_higher(role, message) role = Roles.get_role_from_any(role) if not role then return end local roles = {} - for index,role_name in pairs(Roles.config.order) do + for index, role_name in ipairs(Roles.config.order) do if index <= role.index and role_name ~= Roles.config.internal.default then - table.insert(roles,role_name) + roles[#roles+1] = role_name end end - Roles.print_to_roles(roles,message) + Roles.print_to_roles(roles, message) end --[[-- Prints a message to all players who have the given role or one which is lower (excluding default) @@ -246,16 +246,16 @@ end Roles.print_to_roles_higher('Moderator', 'Hello, World!') ]] -function Roles.print_to_roles_lower(role,message) +function Roles.print_to_roles_lower(role, message) role = Roles.get_role_from_any(role) if not role then return end local roles = {} - for index,role_name in pairs(Roles.config.order) do + for index, role_name in ipairs(Roles.config.order) do if index >= role.index and role_name ~= Roles.config.internal.default then - table.insert(roles,role_name) + roles[#roles+1] = role_name end end - Roles.print_to_roles(roles,message) + Roles.print_to_roles(roles, message) end --[[-- Get a role for the given name @@ -283,7 +283,7 @@ function Roles.get_role_by_order(index) return Roles.config.roles[name] end ---[[-- Gets a role from a name,index or role object (where it is just returned) +--[[-- Gets a role from a name, index or role object (where it is just returned) nb: this function is used for the input for most outward facing functions @tparam ?number|string|table any the value used to find the role @treturn Roles._prototype the role that was found or nil see above @@ -318,8 +318,8 @@ function Roles.get_player_roles(player) local roles = Roles.config.players[player.name] or {} local default = Roles.config.roles[Roles.config.internal.default] local rtn = {default} - for _,role_name in pairs(roles) do - table.insert(rtn,Roles.config.roles[role_name]) + for index, role_name in ipairs(roles) do + rtn[index+1] = Roles.config.roles[role_name] end return rtn end @@ -336,7 +336,7 @@ function Roles.get_player_highest_role(player) local roles = Roles.get_player_roles(player) if not roles then return end local highest - for _,role in pairs(roles) do + for _, role in ipairs(roles) do if not highest or role.index < highest.index then highest = role end @@ -344,9 +344,9 @@ function Roles.get_player_highest_role(player) return highest end ---- Assinment. +--- Assignment. -- Functions for changing player's roles --- @section assinment +-- @section assignment --[[-- Gives a player the given role(s) with an option to pass a by player name used in the log @tparam LuaPlayer player the player that will be assigned the roles @@ -362,13 +362,14 @@ Roles.assign_player(game.player, 'Moderator') Roles.assign_player('Cooldude2606', 'Moderator', nil, true) ]] -function Roles.assign_player(player,roles,by_player_name,skip_checks,silent) +function Roles.assign_player(player, roles, by_player_name, skip_checks, silent) local valid_player = Game.get_player_from_any(player) if not skip_checks and not valid_player then return end + if not player then return end if type(roles) ~= 'table' or roles.name then roles = {roles} end - for _,role in pairs(roles) do + for _, role in ipairs(roles) do role = Roles.get_role_from_any(role) if role then role:add_player(valid_player or player, valid_player == nil, true) @@ -393,14 +394,14 @@ Roles.unassign_player(game.player, 'Moderator') Roles.unassign_player('Cooldude2606', 'Moderator', nil, true) ]] -function Roles.unassign_player(player,roles,by_player_name,skip_checks,silent) +function Roles.unassign_player(player, roles, by_player_name, skip_checks, silent) local valid_player = Game.get_player_from_any(player) if not skip_checks and not valid_player then return end if not player then return end if type(roles) ~= 'table' or roles.name then roles = {roles} end - for _,role in pairs(roles) do + for _, role in ipairs(roles) do role = Roles.get_role_from_any(role) if role then role:remove_player(valid_player or player, valid_player == nil, true) @@ -420,8 +421,8 @@ Roles.override_player_roles('Cooldude2606', {'Moderator'}) @usage-- Override all existing roles, effects all users not just ones listed Roles.override_player_roles{ - ['Cooldude2606'] = {'Administrator','Moderator'}, - ['arty714'] = {'Administrator','Moderator'}, + ['Cooldude2606'] = {'Administrator', 'Moderator'}, + ['arty714'] = {'Administrator', 'Moderator'}, } ]] @@ -448,12 +449,12 @@ end local has_role = Roles.player_has_role(game.player, 'Moderator') ]] -function Roles.player_has_role(player,search_role) +function Roles.player_has_role(player, search_role) local roles = Roles.get_player_roles(player) if not roles then return end search_role = Roles.get_role_from_any(search_role) if not search_role then return end - for _,role in pairs(roles) do + for _, role in ipairs(roles) do if role.name == search_role.name then return true end end return false @@ -468,10 +469,10 @@ end local has_flag = Roles.player_has_flag(game.player, 'is_donator') ]] -function Roles.player_has_flag(player,flag_name) +function Roles.player_has_flag(player, flag_name) local roles = Roles.get_player_roles(player) if not roles then return end - for _,role in pairs(roles) do + for _, role in ipairs(roles) do if role:has_flag(flag_name) then return true end @@ -488,10 +489,10 @@ end local has_flag = Roles.player_has_flag(game.player, 'is_donator') ]] -function Roles.player_allowed(player,action) +function Roles.player_allowed(player, action) local roles = Roles.get_player_roles(player) if not roles then return end - for _,role in pairs(roles) do + for _, role in ipairs(roles) do if role:is_allowed(action) then return true end @@ -499,7 +500,7 @@ function Roles.player_allowed(player,action) return false end ---- Definations. +--- Definitions. -- Functions which are used to define roles -- @section checks @@ -522,31 +523,31 @@ function Roles.define_role_order(order) _C.error_if_runtime() Roles.config.order = {} local done = {} - for _,role in ipairs(order) do + for index, role in ipairs(order) do if type(role) == 'table' and role.name then done[role.name] = true - table.insert(Roles.config.order,role.name) + Roles.config.order[index] = role.name else done[role] = true - table.insert(Roles.config.order,role) + Roles.config.order[index] = role end end -- Check no roles were missed - for role_name,_ in pairs(Roles.config.roles) do + for role_name in pairs(Roles.config.roles) do if not done[role_name] then - error('Role missing '..role_name..' from role order, all defined roles must be included.',2) + error('Role missing '..role_name..' from role order, all defined roles must be included.', 2) end end -- Re-links roles to they parents as this is called at the end of the config - for index,role_name in pairs(Roles.config.order) do + for index, role_name in pairs(Roles.config.order) do local role = Roles.config.roles[role_name] if not role then - error('Role with name '..role_name..' has not beed defined, either define it or remove it from the order list.',2) + error('Role with name '..role_name..' has not beed defined, either define it or remove it from the order list.', 2) end role.index = index local parent = Roles.config.roles[role.parent] if parent then - setmetatable(role.allowed_actions,{__index=parent.allowed_actions}) + setmetatable(role.allowed_actions, {__index=parent.allowed_actions}) end end end @@ -555,13 +556,13 @@ end @tparam string name the name of the flag which the roles will have @tparam function callback the function that is called when roles are assigned -@usage-- Defineing a flag trigger +@usage-- Defining a flag trigger Roles.define_flag_trigger('is_donator', function(player, state) player.character_running_speed_modifier = state and 1.5 or 1 end) ]] -function Roles.define_flag_trigger(name,callback) +function Roles.define_flag_trigger(name, callback) _C.error_if_runtime() Roles.config.flags[name] = Async.register(callback) end @@ -598,11 +599,11 @@ end @tparam[opt=name] string short_hand the shortened version of the name @treturn Roles._prototype the start of the config chain for this role -@usage-- Defineing a new role +@usage-- Defining a new role local role = Roles.new_role('Moderator', 'Mod') ]] -function Roles.new_role(name,short_hand) +function Roles.new_role(name, short_hand) _C.error_if_runtime() if Roles.config.roles[name] then return error('Role name is non unique') end local role = setmetatable({ @@ -611,7 +612,7 @@ function Roles.new_role(name,short_hand) allowed_actions={}, allow_all_actions=false, flags={} - },{__index=Roles._prototype}) + }, {__index=Roles._prototype}) Roles.config.roles[name] = role return role end @@ -649,7 +650,7 @@ function Roles._prototype:allow(actions) if type(actions) ~= 'table' then actions = {actions} end - for _,action in pairs(actions) do + for _, action in ipairs(actions) do self.allowed_actions[action]=true end return self @@ -659,7 +660,7 @@ end @tparam table actions indexed with numbers and is an array of action names, order has no effect @treturn Roles._prototype allows chaining -@usage-- Disalow an action for a role, useful if inherit an action from a parent +@usage-- Disallow an action for a role, useful if inherit an action from a parent role:disallow{ 'command/kill', 'gui/game settings' @@ -670,7 +671,7 @@ function Roles._prototype:disallow(actions) if type(actions) ~= 'table' then actions = {actions} end - for _,action in pairs(actions) do + for _, action in ipairs(actions) do self.allowed_actions[action]=false end return self @@ -702,13 +703,13 @@ end role:set_flag('is_admin') ]] -function Roles._prototype:set_flag(name,value) +function Roles._prototype:set_flag(name, value) if value == nil then value = true end self.flags[name] = not not value -- not not forces a boolean value return self end ---[[-- Clears all flags from this role, individual flags can be removed with set_flag(name,false) +--[[-- Clears all flags from this role, individual flags can be removed with set_flag(name, false) @treturn Roles._prototype allows chaining @usage-- Remove all flags from a role @@ -733,7 +734,7 @@ function Roles._prototype:has_flag(name) end --- Role Properties. --- Functions for chaning other proerties +-- Functions for changing other properties -- @section properties --[[-- Sets a custom player tag for the role, can be accessed by other code @@ -774,10 +775,10 @@ end role:set_permission_group('Admin') ]] -function Roles._prototype:set_permission_group(name,use_factorio_api) +function Roles._prototype:set_permission_group(name, use_factorio_api) _C.error_if_runtime() if use_factorio_api then - self.permission_group = {true,name} + self.permission_group = {true, name} else local group = Groups.get_group_by_name(name) if not group then return end @@ -849,31 +850,32 @@ end role:add_player(game.player) ]] -function Roles._prototype:add_player(player,skip_check,skip_event) - player = Game.get_player_from_any(player) +function Roles._prototype:add_player(player, skip_check, skip_event) + local valid_player = Game.get_player_from_any(player) -- Default role cant have players added or removed if self.name == Roles.config.internal.default then return end -- Check the player is valid, can be skipped but a name must be given - if not player then - if skip_check then - player = {name=player} - else - return false - end + local player_name + if valid_player then + player_name = valid_player.name + elseif skip_check then + player_name = player + else + return false end -- Add the role name to the player's roles - local player_roles = Roles.config.players[player.name] + local player_roles = Roles.config.players[player_name] if player_roles then - for _,role_name in pairs(player_roles) do + for _, role_name in ipairs(player_roles) do if role_name == self.name then return false end end - table.insert(player_roles,self.name) + player_roles[#player_roles+1] = self.name else - Roles.config.players[player.name] = {self.name} + Roles.config.players[player_name] = {self.name} end -- Emits event if required - if not skip_event then - emit_player_roles_updated(player,'assign',{self}) + if valid_player and not skip_event then + emit_player_roles_updated(valid_player, 'assign', {self}) end return true end @@ -888,38 +890,40 @@ end role:remove_player(game.player) ]] -function Roles._prototype:remove_player(player,skip_check,skip_event) - player = Game.get_player_from_any(player) +function Roles._prototype:remove_player(player, skip_check, skip_event) + local valid_player = Game.get_player_from_any(player) -- Default role cant have players added or removed if self.name == Roles.config.internal.default then return end -- Check the player is valid, can be skipped but a name must be given - if not player then - if skip_check then - player = {name=player} - else - return false - end + local player_name + if valid_player then + player_name = valid_player.name + elseif skip_check then + player_name = player + else + return false end -- Remove the role from the players roles - local player_roles = Roles.config.players[player.name] - local rtn = false + local player_roles = Roles.config.players[player_name] + local found = false if player_roles then - for index,role_name in pairs(player_roles) do + for index, role_name in ipairs(player_roles) do if role_name == self.name then - table.remove(player_roles,index) - rtn = true + player_roles[index] = player_roles[#player_roles] + player_roles[#player_roles] = nil + found = true break end end if #player_roles == 0 then - Roles.config.players[player.name] = nil + Roles.config.players[player_name] = nil end end -- Emits event if required - if not skip_event then - emit_player_roles_updated(player,'unassign',{self}) + if valid_player and not skip_event then + emit_player_roles_updated(valid_player, 'unassign', {self}) end - return rtn + return found end --[[-- Returns an array of all the players who have this role, can be filtered by online status @@ -935,30 +939,20 @@ local players = role:get_players(true) ]] function Roles._prototype:get_players(online) local players = {} - -- Gets all players that have this role - for player_name,player_roles in pairs(Roles.config.players) do - for _,role_name in pairs(player_roles) do + -- Search all players to check if they have this role + for player_name, player_roles in pairs(Roles.config.players) do + for _, role_name in ipairs(player_roles) do if role_name == self.name then - table.insert(players,player_name) - end - end - end - -- Convert the player names to LuaPlayer - for index,player_name in pairs(players) do - players[index] = Game.get_player_from_any(player_name) - end - -- Filter by online if param is defined - if online == nil then - return players - else - local filtered = {} - for _,player in pairs(players) do - if player.connected == online then - table.insert(filtered,player) + local player = game.players[player_name] + -- Filter by online state if required + if player and (online == nil or player.connected == online) then + players[#players+1] = player + end + break end end - return filtered end + return players end --[[-- Will print a message to all players with this role @@ -971,7 +965,7 @@ role:print('Hello, World!') ]] function Roles._prototype:print(message) local players = self:get_players(true) - for _,player in pairs(players) do + for _, player in ipairs(players) do player.print(message) end return #players @@ -979,10 +973,10 @@ end --- Used internally to be the first trigger on an event change, would be messy to include this in 4 different places local function role_update(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] -- Updates flags given to the player for flag, async_token in pairs(Roles.config.flags) do - local state = Roles.player_has_flag(player,flag) + local state = Roles.player_has_flag(player, flag) Async(async_token, player, state) end -- Updates the players permission group @@ -1000,22 +994,22 @@ local function role_update(event) end --- When a player joined or has a role change then the update is triggered -Event.add(Roles.events.on_role_assigned,role_update) -Event.add(Roles.events.on_role_unassigned,role_update) -Event.add(defines.events.on_player_joined_game,role_update) +Event.add(Roles.events.on_role_assigned, role_update) +Event.add(Roles.events.on_role_unassigned, role_update) +Event.add(defines.events.on_player_joined_game, role_update) -- Every 60 seconds the auto promote check is preformed -Event.on_nth_tick(3600,function() +Event.on_nth_tick(3600, function() local promotes = {} - for _,player in pairs(game.connected_players) do - for _,role in pairs(Roles.config.roles) do + for _, player in pairs(game.connected_players) do + for _, role in ipairs(Roles.config.roles) do if role.auto_promote_condition then - local success,err = pcall(role.auto_promote_condition,player) + local success, err = pcall(role.auto_promote_condition, player) if not success then - log{'expcore-roles.error-log-format-promote',role.name,err} + log{'expcore-roles.error-log-format-promote', role.name, err} else - if err == true and not Roles.player_has_role(player,role) then + if err == true and not Roles.player_has_role(player, role) then if promotes[player.name] then - table.insert(promotes[player.name],role.name) + table.insert(promotes[player.name], role.name) else promotes[player.name] = {role.name} end @@ -1024,8 +1018,8 @@ Event.on_nth_tick(3600,function() end end end - for player_name,roles in pairs(promotes) do - Roles.assign_player(player_name,roles) + for player_name, roles in pairs(promotes) do + Roles.assign_player(player_name, roles) end end) diff --git a/expcore/store.lua b/expcore/store.lua deleted file mode 100644 index ffb2afa836..0000000000 --- a/expcore/store.lua +++ /dev/null @@ -1,523 +0,0 @@ ---[[-- Core Module - Store -- Used to store and watch for updates for values in the global table -@core Store -@alias Store - -@usage-- Require the module and add a store with no keys --- Store with no keys does not need a serializer -local Store = require 'expcore.store' --- @dep expcore.store -local scenario_diffculty = Store.register() - --- When the store is changed this function will trigger -Store.watch(scenario_diffculty,function(value) - game.print('The scenario diffculty has been set to '..value) -end) - -Store.set(scenario_diffculty,'hard') -- Set the value stored to 'hard' -Store.get(scenario_diffculty) -- Returns 'hard' -Store.update(scenario_diffculty,function(value) -- Will set value to 'normal' if no value is present - return not value and 'normal' -end) - -@usage-- Require the module and add a store with keys --- Store with keys does not require a serializer but it can be helpful -local Store = require 'expcore.store' --- @dep expcore.store -local player_scores = Store.register(function(player) -- Use player name as the key - return player.name -end) - --- When any key in the store is changed this function will trigger -Store.watch(player_scores,function(value,key,old_value) - game.print(key..' now has a score of '..value) -end) - -Store.set(player_scores,game.player,10) -- Set your score to 10 -Store.get(scenario_diffculty,game.player) -- Returns 10 -Store.update(scenario_diffculty,game.player,function(value) -- Add 1 to your score - return value + 1 -end) - -]] - -local Event = require 'utils.event' --- @dep utils.event - -local Store = { - --- The current highest uid that is being used, will not increase during runtime - -- @field uid - uid = 0, - --- An array of the serializers that stores are using, key is store uids - -- @table serializers - serializers = {}, - --- An array of watchers that stores will trigger, key is store uids - -- @table watchers - watchers = {}, - --- An index used for debuging to find the file where different stores where registered - -- @table file_paths - file_paths = {} -} - --- All data is stored in global.data_store and is accessed here with data_store -local data_store = {} -global.data_store = data_store -Event.on_load(function() - data_store = global.data_store -end) - ---- Store Setup. --- @section setup - ---[[-- An error checking and serializing function for checking store uids and keys, note key is not required -@tparam number store the uid of the store that you want to check is valid -@tparam[opt] ?string|any key the key that you want to serialize or check is a string -@tparam[opt=1] number error_stack the position in the stack relative to the current function (1) to raise this error on -@treturn string if key is given and a serializer is registered, or key was already a string, then the key is returned - -@usage-- Registering a new store and checking that it is valid --- New store will use player names as the keys -local player_scores = Store.register(function(player) - return player.name -end) - --- player_scores is a valid store and key will be your player name -local key = Store.validate(player_scores,game.player) - -]] -function Store.validate(store,key,error_stack) - error_stack = error_stack or 1 - - if type(store) ~= 'number' then - -- Store is not a number and so if not valid - error('Store uid given is not a number; recived type '..type(store),error_stack+1) - elseif store > Store.uid then - -- Store is a number but it is out of range, ie larger than the current highest uid - error('Store uid is out of range; recived '..tostring(store),error_stack+1) - elseif key ~= nil and type(key) ~= 'string' and Store.serializers[store] == nil then - -- Key is present but is not a string and there is no serializer registered - error('Store key is not a string and no serializer has been registered; recived '..type(key),error_stack+1) - elseif key ~= nil then - -- Key is present and so it is serialized and returned - local serializer = Store.serializers[store] - if type(key) ~= 'string' then - local success, serialized_key = pcall(serializer,key) - - if not success then - -- Serializer casued an error while serializing the key - error('Store watcher casued an error:\n\t'..key,error_stack+1) - elseif type(serialized_key) ~= 'string' then - -- Serializer was successful but failed to return a string value - error('Store key serializer did not return a string; recived type '..type(key),error_stack+1) - end - - return serialized_key - end - - return key - end - -end - ---[[-- Required to create new stores and register an serializer to a store, serializer not required -@tparam[opt] function serializer the function used to convert non string keys into strings to be used in the store -@treturn number the uid for the new store that you have created, use this as the first param to all other functions - -@usage-- Creating a store with no serializer -local scenario_diffculty = Store.register() - -@usage-- Creating a store which can take LuaPlayer -local player_scores = Store.register(function(player) - return player.name -end) - -]] -function Store.register(serializer) - if _LIFECYCLE ~= _STAGE.control then - -- Only allow this function to be called during the control stage - error('Store can not be registered durring runtime', 2) - end - - -- Increment the uid counter - local uid = Store.uid + 1 - Store.uid = uid - - -- Register the serializer if given - if serializer then - Store.serializers[uid] = serializer - end - - -- Add entry in the debug table - local file_path = debug.getinfo(2, 'S').source:match('^.+/currently%-playing/(.+)$'):sub(1, -5) - Store.file_paths[uid] = file_path - - -- Return the new uid - return uid -end - ---[[-- Register a watch function to a store that is called when the value in the store is changed, triggers for any key -@tparam number store the uid of the store that you want to watch for changes to -@tparam function watcher the function that will be called when there is a change to the store - -@usage-- Printing the changed value to all players, no keys --- Register the new store, we are not using keys so we dont need a serializer -local scenario_diffculty = Store.register() - --- Register the watcher so that when we change the value the message is printed -Store.watch(scenario_diffculty,function(value) - game.print('The scenario diffculty has been set to '..value) -end) - --- Set a new value for the diffculty and see that it has printed to the game -Store.set(scenario_diffculty,'hard') - -@usage-- Printing the changed value to all players, with keys --- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects -local player_scores = Store.register(function(player) - return player.name -end) - --- Register the watcher so that when we change the value the message is printed -Store.watch(player_scores,function(value,key,old_value) - game.print(key..' now has a score of '..value) -end) - --- Set a new value for your score and see that it has printed to the game -Store.set(player_scores,game.player,10) - -]] -function Store.watch(store,watcher) - if _LIFECYCLE ~= _STAGE.control then - -- Only allow this function to be called during the control stage - error('Store watcher can not be registered durring runtime', 2) - end - - Store.validate(store,nil,2) - - -- Add the watchers table if it does not exist - local watchers = Store.watchers[store] - if not watchers then - watchers = {} - Store.watchers[store] = watchers - end - - -- Append the new watcher function - watchers[#watchers+1] = watcher -end - ---- Store Data Management. --- @section data - ---[[-- Used to retrive the current data that is stored, key is optional depending on if you are using them -@tparam number store the uid of the store that you want to get the value from -@tparam[opt] ?string|any key the key that you want to get the value of, must be a string unless you have a serializer -@treturn any the data that is stored - -@usage-- Getting the value of a store with no keys --- Register the new store, we are not using keys so we dont need a serializer -local scenario_diffculty = Store.register() - --- Get the current diffculty for the scenario -local diffculty = Store.get(scenario_diffculty) - -@usage-- Getting the data from a store with keys --- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects -local player_scores = Store.register(function(player) - return player.name -end) - --- Get your current score -local my_score = Store.get(player_scores,game.player) - --- Get all scores -lcoal scores = Store.get(player_scores) - -]] -function Store.get(store,key) - key = Store.validate(store,key,2) - - -- Get the data from the data store - local data = data_store[store] - if key then - if type(data) ~= 'table' then - data_store[store] = {_value = data_store[store]} - return nil - else - return data[key] - end - end - - -- Return all data if there is no key - return data -end - ---[[-- Used to clear the data in a store, will trigger any watchers, key is optional depending on if you are using them -@tparam number store the uid of the store that you want to clear -@tparam[opt] ?string|any key the key that you want to clear, must be a string unless you have a serializer - -@usage-- Clear a store which does not use keys --- Register the new store, we are not using keys so we dont need a serializer -local scenario_diffculty = Store.register() - --- Clear the scenario diffculty -Store.clear(scenario_diffculty) - -@usage-- Clear data that is in a store with keys --- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects -local player_scores = Store.register(function(player) - return player.name -end) - --- Clear your score -Store.clear(player_scores,game.player) - --- Clear all scores -Store.clear(player_scores) - -]] -function Store.clear(store,key) - key = Store.validate(store,key,2) - local old_value - - -- Check if there is a key being used - if key then - if type(data_store[store]) == 'table' then - old_value = data_store[store][key] - data_store[store][key] = nil - end - else - old_value = data_store[store] - data_store[store] = nil - end - - -- Trigger any watch functions - Store.raw_trigger(store,key,nil,old_value) -end - ---[[-- Used to set the data in a store, will trigger any watchers, key is optional depending on if you are using them -@tparam number store the uid of the store that you want to set -@tparam[opt] ?string|any key the key that you want to set, must be a string unless you have a serializer -@tparam any value the value that you want to set - -@usage-- Setting a store which does not use keys --- Register the new store, we are not using keys so we dont need a serializer -local scenario_diffculty = Store.register() - --- Set the new scenario diffculty -Store.set(scenario_diffculty,'hard') - -@usage-- Set data in a store with keys --- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects -local player_scores = Store.register(function(player) - return player.name -end) - --- Set your current score -Store.set(player_scores,game.player,10) - --- Set all scores, note this might not have much use -Store.set(player_scores,{ - [game.player.name] = 10, - ['SomeOtherPlayer'] = 0 -}) - -]] -function Store.set(store,key,value) - -- Allow for key to be optional - if value == nil then - value = key - key = nil - end - - -- Check the store is valid - key = Store.validate(store,key,2) - local old_value - - -- If there is a key being used then the store must be a able - if key then - if type(data_store[store]) ~= 'table' then - data_store[store] = {_value = data_store[store]} - end - old_value = data_store[store][key] - data_store[store][key] = value - else - old_value = data_store[store] - data_store[store] = value - end - - -- Trigger any watchers - Store.raw_trigger(store,key,value,old_value) -end - ---[[-- Used to update the data in a store, use this with tables, will trigger any watchers, key is optional depending on if you are using them -@tparam number store the uid of the store that you want to update -@tparam[opt] ?string|any key the key that you want to update, must be a string unless you have a serializer -@tparam function updater the function which is called to make changes to the value, such as changing table keys, if a value is returned it will replace the current value in the store - -@usage-- Incrementing a global score --- Because we are only going to have one score so we will not need keys or a serializer -local game_score = Store.register() - --- Setting a default value -Store.set(game_score,0) - --- We now will update the game score by one, we return the value so that it is set as the new value in the store -Store.update(game_score,function(value) - return value + 1 -end) - -@usage-- Updating keys in a table of data --- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects -local player_data = Store.register(function(player) - return player.name -end) - --- Setting a default value for your player, used to show the table structure -Store.set(player_data,game.player,{ - group = 'Admin', - role = 'Owner', - show_group_config = false -}) - --- Updating the show_group_config key in your player data, note that it would be harder to call set every time --- We do not need to return anything in this case as we are not replacing all the data -Store.update(player_data,game.player,function(data) - data.show_group_config = not data.show_group_config -end) - -]] -function Store.update(store,key,updater) - -- Allow for key to be nil - if updater == nil then - updater = key - key = nil - end - - -- Check the store is valid - key = Store.validate(store,key,2) - local value, old_value - - -- If a key is used then the store must be a table - if key then - if type(data_store[store]) ~= 'table' then - data_store[store] = {_value = data_store[store]} - end - - -- Call the updater and if it returns a value then set this value - local rtn = updater(data_store[store][key]) - if rtn then - old_value = data_store[store][key] - data_store[store][key] = rtn - end - value = data_store[store][key] - - else - -- Call the updater and if it returns a value then set this value - local rtn = updater(data_store[store]) - if rtn then - old_value = data_store[store][key] - data_store[store] = rtn - end - value = data_store[store] - - end - - -- Trigger any watchers - Store.raw_trigger(store,key,value,old_value) -end - ---[[-- Used to update all values that are in a store, similar to Store.update but acts on all keys at once, will trigger watchers for every key present -@tparam number store the uid of the store that you want to map -@tparam function updater the function that is called on every key in this store - -@usage-- Updating keys in a table of data --- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects -local player_data = Store.register(function(player) - return player.name -end) - --- Setting a default value for your player, used to show the table structure -Store.set(player_data,game.player,{ - group = 'Admin', - role = 'Owner', - show_group_config = false -}) - --- Updating the show_group_config key for all players, note that it would be harder to call set every time --- We do not need to return anything in this case as we are not replacing all the data --- We also have access to the current key being updated if needed -Store.map(player_data,function(data,key) - data.show_group_config = not data.show_group_config -end) - -]] -function Store.map(store,updater) - Store.validate(store,nil,2) - - -- Get all that data in the store and check its a table - local data = data_store[store] - if type(data) ~= 'table' then - return - end - - -- Loop over all the keys and call the updater, setting value if returned, and calling watcher functions - for key,value in pairs(data) do - local rtn = updater(value,key) - if rtn then - data[key] = rtn - end - Store.raw_trigger(store,key,data[key],value) - end -end - ---[[-- Used to trigger watcher functions, this may be used to trigger them if you did not use Store.update or Store.set -@tparam number store the uid of the store that you want to trigger -@tparam[opt] ?string|any key the key that you want to trigger, must be a string unless you have a serializer -@usage-- Faking the update to a store --- The type of store we use does not really matter for this as long as you pass it what you watchers are expecting -local scenario_diffculty = Store.register() - --- Trigger the watchers with a fake change of diffculty -Store.trigger(scenario_diffculty) - -]] -function Store.trigger(store,key) - key = Store.validate(store,key,2) - - -- Get the data from the data store - local data = data_store[store] - if key then - data = data[key] - Store.raw_trigger(store,key,data,data) - else - Store.raw_trigger(store,key,data,data) - end -end - ---[[-- Used to trigger watcher functions, the value and key are passed directly to the watchers regardless if the value is correct -@tparam number store the uid of the store that you want to trigger -@tparam[opt] ?string|any key the key that you want to trigger, must be a string unless you have a serializer -@tparam[opt] any value the new value that is at this key or store, passed directly to the watcher -@tparam[opt] any old_value the old value that was at this key or store often the same if value is a table, passed directly to the watcher - -@usage-- Triggering a manule call of the watchers --- The type of store we use does not really matter for this as long as you pass it what you watchers are expecting -local scenario_diffculty = Store.register() - --- Trigger the watchers with a fake change of diffculty --- This is mostly used internally but it can be useful in other cases -Store.raw_trigger(scenario_diffculty,nil,'normal','normal') - -]] -function Store.raw_trigger(store,key,value,old_value) - key = Store.validate(store,key,2) - - -- Get the watchers and then loop over them - local watchers = Store.watchers[store] or {} - for _,watcher in pairs(watchers) do - local success, err = pcall(watcher,value,key,old_value) - if not success then - error('Store watcher casued an error:\n\t'..err) - end - end -end - --- Module return -return Store \ No newline at end of file diff --git a/locale/en/addons.cfg b/locale/en/addons.cfg index 4cb4c8373b..ed0d9123f5 100644 --- a/locale/en/addons.cfg +++ b/locale/en/addons.cfg @@ -77,7 +77,4 @@ get-mead-1= Filling the drinking horn get-mead-2= Skål! get-beer-1= 🍺 Pouring A Glass 🍺 get-beer-2= 🍻 Chears Mate 🍻 -verify=Please return to our discord and type r!verify __1__ - -[greetings] -greet=[color=0,1,0] Welcome to explosive gaming community server! If you like the server join our discord: __1__ [/color] \ No newline at end of file +verify=Please return to our discord and type r!verify __1__ \ No newline at end of file diff --git a/locale/en/commands.cfg b/locale/en/commands.cfg index 081b8f3654..6c9fb44faa 100644 --- a/locale/en/commands.cfg +++ b/locale/en/commands.cfg @@ -45,9 +45,10 @@ removed=__1__ has one or more reports removed by __2__. [expcom-warnings] received=__1__ received a warning from __2__ for __3__. player=__1__ has __2__ warnings and __3__/__4__ script warnings. -list-tilte=The following player have this many warnings (and this many script warnings): +player-detail=__1__ gave warning for: __2__ +list-title=The following players have this many warnings (and this many script warnings): list=__1__: __2__ (__3__/__4__) -cleared=__1__ had all they warnings cleared by __2__. +cleared=__1__ had all their warnings cleared by __2__. [expcom-spawn] unavailable=They was a problem getting you to spawn, please try again later. @@ -75,4 +76,11 @@ return-set=Your return point has been set to x: __1__ y: __2__ home-get=Your home point is at x: __1__ y: __2__ [expcom-server-ups] -no-ext=No external source was found, cannot display server ups. \ No newline at end of file +no-ext=No external source was found, cannot display server ups. + +[expcom-connect] +too-many-matching=Multiple server were found with the given name: __1__ +wrong-version=Servers were found but are on a different version: __1__ +same-server=You are already connected to the server: __1__ +offline=You cannot connect as the server is currently offline: __1__ +none-matching=No servers were found with that name, if you used an address please append true to the end of your command. \ No newline at end of file diff --git a/locale/en/data.cfg b/locale/en/data.cfg new file mode 100644 index 0000000000..5c52ed155d --- /dev/null +++ b/locale/en/data.cfg @@ -0,0 +1,83 @@ +[join-message] +greet=[color=0,1,0] Welcome to explosive gaming community server! If you like the server join our discord: __1__ [/color] +message-set=Your join message has been updated. + +[quickbar] +saved=Your quickbar filters have been saved. + +[exp-required] +Warnings=Warnings +Warnings-tooltip=The total number of warnings you have received from staff +Warnings-value-tooltip=The total number of warnings you have received from staff +[exp-settings] +Colour=Colour +Colour-tooltip=Your player colour +Colour-value-tooltip=Change by using /color +JoinMessage=Join Message +JoinMessage-tooltip=The message displayed when you join +JoinMessage-value-tooltip=Change by using /join-message +QuickbarFilters=Quickbar Filters +QuickbarFilters-tooltip=The filters on your quickbar +QuickbarFilters-value-tooltip=Change by using /save-quickbar +UsesAlt=Alt View +UsesAlt-tooltip=Whether you use alt view when you play +UsesAlt-value-tooltip=Change by pressing __CONTROL__show-info__ +UsesServerUps=Server UPS +UsesServerUps-tooltip=Whether the current server UPS is shown +UsesServerUps-value-tooltip=Change by using /server-ups +Tag=Player Tag +Tag-tooltip=The tag shown after your name +Tag-value-tooltip=Change by using /tag +Bonus=Player Bonus +Bonus-tooltip=The bonus given to your character +Bonus-value-tooltip=Change by using /bonus + +[exp-statistics] +MapsPlayed=Maps Played +MapsPlayed-tooltip=The number of unique maps you have played on +JoinCount=Join Count +JoinCount-tooltip=The number of times you have joined our servers +Playtime=Playtime +Playtime-tooltip=The amount of time you have spent on our servers +AfkTime=AFK Time +AfkTime-tooltip=The amount of time you have been AFK on our servers +ChatMessages=Messages +ChatMessages-tooltip=The number of messages you have sent in chat +CommandsUsed=Commands +CommandsUsed-tooltip=The number of commands you have used +RocketsLaunched=Rockets Launched +RocketsLaunched-tooltip=The number of rockets launched while you were online +ResearchCompleted=Research Completed +ResearchCompleted-tooltip=The number of research projects completed while you were online +MachinesBuilt=Machines Built +MachinesBuilt-tooltip=The number of machines you have built +MachinesRemoved=Machines Removed +MachinesRemoved-tooltip=The number of machines you have removed +TilesBuilt=Tiles Placed +TilesBuilt-tooltip=The number of tiles you have placed +TilesRemoved=Tiles Removed +TilesRemoved-tooltip=The number of tiles you have removed +TreesDestroyed=Trees Destroyed +TreesDestroyed-tooltip=The number of trees you have destroyed +OreMined=Ore Mined +OreMined-tooltip=The amount of ore you have mined +ItemsCrafted=Items Crafted +ItemsCrafted-tooltip=The number of items you have crafted +ItemsPickedUp=Items Picked Up +ItemsPickedUp-tooltip=The number of items you have picked up +Kills=Kills +Kills-tooltip=The number of biters and biter bases you have squished +Deaths=Deaths +Deaths-tooltip=The number of times you have died +DamageDealt=Damage Dealt +DamageDealt-tooltip=The amount of damage you have dealt to other forces +DistanceTravelled=Distance Travelled +DistanceTravelled-tooltip=The total distance in tiles that you have travelled +CapsulesUsed=Capsules Used +CapsulesUsed-tooltip=The number of capsules you have used +EntityRepaired=Machines Repaired +EntityRepaired-tooltip=The number of machines which you have repaired +DeconstructionPlannerUsed=Decon Planner Used +DeconstructionPlannerUsed-tooltip=The number of times you have used the deconstruction planner +MapTagsMade=Map Tags Created +MapTagsMade-tooltip=The number of map tags you have created \ No newline at end of file diff --git a/locale/en/expcore.cfg b/locale/en/expcore.cfg index ce4d3d459d..e5fc44df3f 100644 --- a/locale/en/expcore.cfg +++ b/locale/en/expcore.cfg @@ -36,3 +36,17 @@ button_tooltip=Shows/hides the toolbar. [expcore-gui] left-button-tooltip=Hide all open windows. + +[expcore-data] +set-preference=You data saving preference has been set to __1__. Existing data will not be effected until you rejoin. +get-preference=You data saving preference is __1__. Use /set-preference to change this. Use /save-data to get a local copy of your data. +get-data=Your player data has been writen to file, location: factorio/script_output/expgaming_player_data.json +data-failed=Your player data has failed to load. Any changes to your data will not be saved. +data-restore=Your player data has been restored and changes will now save when you leave. +preference=Saving Preference +preference-tooltip=Which categories will be saved when you leave the game +preference-value-tooltip=Change by using /set-preference +preference-All=All data will be saved +preference-Statistics=Only statistics, settings, and required data will be saved +preference-Settings=Only settings and required data will be saved +preference-Required=Only required data will be saved \ No newline at end of file diff --git a/locale/en/gui.cfg b/locale/en/gui.cfg index fca7827fc6..aaec09be95 100644 --- a/locale/en/gui.cfg +++ b/locale/en/gui.cfg @@ -146,6 +146,12 @@ servers-7=S7 Event servers-d7=This is our event server, we try to run events at least once per week. servers-8=S8 T̷-̶s̶-̴:̷ servers-d8=N̵o̴ ̶o̷-̶e̵ ̴k̸n̷-̶w̵s̸ ̴w̷h̷a̶-̶ ̷h̴a̴p̷p̴e̷n̷s̸ ̷o̶n̴ ̷t̶h̴-̶s̶ ̷s̷e̶r̸v̸e̴r̷,̶ ̸i̸t̴ ̷m̶-̸g̴h̶t̷ ̸n̸-̶t̵ ̷e̴v̸e̸n̶t̷ ̵-̷x̴i̵s̶t̸.̸ +servers-connect-Offline=Server is currently offline +servers-connect-Current=This is your current server +servers-connect-Version=Server is on a different version: __1__ +servers-connect-Password=Server requires a password +servers-connect-Modded=Server requires mods to be downloaded +servers-connect-Online=Server is online servers-external=External Links servers-open-in-browser=Open in your browser backers-tab=Backers @@ -155,4 +161,12 @@ backers-management=Administrators backers-board=Board Members and Senior Backers backers-staff=Staff Members backers-backers=Sponsors and Supporters -backers-active=Active Players \ No newline at end of file +backers-active=Active Players +data-tab=Data +data-tooltip=All of your stored player data +data-general=Our servers will save your player data so that we can sync it between servers. All of your data can be found below, if you wish to save a copy locally then use /save-data. If you want to change what data is saved then use /set-preference. +data-settings=Settings +data-statistics=Statistics +data-required=Required +data-misc=Miscellaneous +data-format=__1____2__ \ No newline at end of file diff --git a/modules/addons/advanced-start.lua b/modules/addons/advanced-start.lua index 3e93c853ea..dad7802bba 100644 --- a/modules/addons/advanced-start.lua +++ b/modules/addons/advanced-start.lua @@ -2,12 +2,11 @@ -- @addon Advanced-Start local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local config = require 'config.advanced_start' --- @dep config.advanced_start local items = config.items Event.add(defines.events.on_player_created, function(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] -- game init settings if event.player_index == 1 then player.force.friendly_fire = config.friendly_fire @@ -17,31 +16,31 @@ Event.add(defines.events.on_player_created, function(event) player.force.chart(player.surface, {{p.x-r, p.y-r}, {p.x+r, p.y+r}}) end -- spawn items - for item,callback in pairs(items) do + for item, callback in pairs(items) do if type(callback) == 'function' then local stats = player.force.item_production_statistics local made = stats.get_input_count(item) - local success,count = pcall(callback,made,stats.get_input_count,player) + local success, count = pcall(callback, made, stats.get_input_count, player) count = math.floor(count) if success and count > 0 then - player.insert{name=item,count=count} + player.insert{name=item, count=count} end end end end) Event.on_init(function() - remote.call('freeplay','set_created_items',{}) - remote.call('freeplay','set_chart_distance',0) - remote.call('freeplay','set_skip_intro',config.skip_intro) + remote.call('freeplay', 'set_created_items', {}) + remote.call('freeplay', 'set_chart_distance', 0) + remote.call('freeplay', 'set_skip_intro', config.skip_intro) if config.research_queue_from_start then - for _,force in pairs(game.forces) do + for _, force in pairs(game.forces) do force.research_queue_enabled = true end end if not config.disable_base_game_silo_script then if config.skip_victory then - remote.call('silo_script','set_no_victory',true) + remote.call('silo_script', 'set_no_victory', true) end end end) \ No newline at end of file diff --git a/modules/addons/chat-popups.lua b/modules/addons/chat-popups.lua index d27672a643..8bc187019d 100644 --- a/modules/addons/chat-popups.lua +++ b/modules/addons/chat-popups.lua @@ -8,9 +8,9 @@ local config = require 'config.popup_messages' --- @dep config.popup_messages local send_text = Game.print_player_floating_text -- (player_index, text, color) -Event.add(defines.events.on_console_chat,function(event) +Event.add(defines.events.on_console_chat, function(event) if not event.player_index or event.player_index < 1 then return end - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] -- Some basic sanity checks if not player then return end @@ -18,7 +18,7 @@ Event.add(defines.events.on_console_chat,function(event) -- Sends the message as text above them if config.show_player_messages then - send_text(player.index,{'chat-popup.message',player.name,event.message},player.chat_color) + send_text(player.index, {'chat-popup.message', player.name, event.message}, player.chat_color) end if not config.show_player_mentions then return end @@ -27,10 +27,10 @@ Event.add(defines.events.on_console_chat,function(event) local search_string = event.message:lower():gsub("%s+", "") -- Loops over online players to see if they name is included - for _,mentioned_player in pairs(game.connected_players) do + for _, mentioned_player in pairs(game.connected_players) do if mentioned_player.index ~= player.index then - if search_string:match(mentioned_player.name:lower(), 1, true) then - send_text(mentioned_player.index,{'chat-popup.ping',player.name},player.chat_color) + if search_string:find(mentioned_player.name:lower(), 1, true) then + send_text(mentioned_player.index, {'chat-popup.ping', player.name}, player.chat_color) end end end diff --git a/modules/addons/chat-reply.lua b/modules/addons/chat-reply.lua index a4685ef39d..e0fc661c3f 100644 --- a/modules/addons/chat-reply.lua +++ b/modules/addons/chat-reply.lua @@ -1,52 +1,50 @@ ---- Adds auto replies to chat messages; aswell as chat commands +--- Adds auto replies to chat messages; as well as chat commands -- @addon Chat-Reply local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local Roles = require 'expcore.roles' --- @dep expcore.roles local config = require 'config.chat_reply' --- @dep config.chat_reply -Event.add(defines.events.on_console_chat,function(event) +Event.add(defines.events.on_console_chat, function(event) local player_index = event.player_index if not player_index or player_index < 1 then return end - local player = Game.get_player_by_index(player_index) + local player = game.players[player_index] local message = event.message:lower():gsub("%s+", "") local allowed = true if config.command_admin_only and not player.admin then allowed = false end - if config.command_permission and not Roles.player_allowed(player,config.command_permission) then allowed = false end + if config.command_permission and not Roles.player_allowed(player, config.command_permission) then allowed = false end local prefix = config.command_prefix - for key_word,reply in pairs(config.messages) do + for key_word, reply in pairs(config.messages) do if message:find(key_word) then + local is_command = message:find(prefix..key_word) if type(reply) == 'function' then - reply = reply(player) + reply = reply(player, is_command) end - if message:find(prefix..key_word) then - if allowed then - game.print{'chat-bot.reply',reply} - else - player.print{'chat-bot.disallow'} - end + if is_command and allowed then + game.print{'chat-bot.reply', reply} + elseif is_command then + player.print{'chat-bot.disallow'} elseif not allowed then - player.print{'chat-bot.reply',reply} + player.print{'chat-bot.reply', reply} end end end if not allowed then return end - for key_word,reply in pairs(config.commands) do + for key_word, reply in pairs(config.commands) do if message:find(prefix..key_word) then if type(reply) == 'function' then - reply = reply(player) + reply = reply(player, true) if reply then - game.print{'chat-bot.reply',reply} + game.print{'chat-bot.reply', reply} end else - game.print{'chat-bot.reply',reply} + game.print{'chat-bot.reply', reply} end end diff --git a/modules/addons/compilatron.lua b/modules/addons/compilatron.lua index 0fe347b90a..f2932ca7cd 100644 --- a/modules/addons/compilatron.lua +++ b/modules/addons/compilatron.lua @@ -3,7 +3,6 @@ local Event = require 'utils.event' --- @dep utils.event local Global = require 'utils.global' --- @dep utils.global -local Game = require 'utils.game' --- @dep utils.game local Task = require 'utils.task' --- @dep utils.task local Token = require 'utils.token' --- @dep utils.token local config = require 'config.compilatron' --- @dep config.compilatron @@ -18,7 +17,7 @@ local Public = { Global.register({ compilatrons = Public.compilatrons, current_messages = Public.current_messages -},function(tbl) +}, function(tbl) Public.compilatrons = tbl.compilatrons Public.current_messages = tbl.current_messages end) @@ -42,7 +41,7 @@ local callback = local function circle_messages() for name, ent in pairs(Public.compilatrons) do if not ent.valid then - Public.spawn_compilatron(game.players[1].surface,name) + Public.spawn_compilatron(game.players[1].surface, name) end local current_message = Public.current_messages[name] local msg_number @@ -66,7 +65,7 @@ Event.on_nth_tick(config.message_cycle, circle_messages) --- This will add a compilatron to the global and start his message cycle -- @tparam LuaEntity entity the compilatron entity that moves around --- @tparam string name the name of the location that the complitron is at +-- @tparam string name the name of the location that the compilatron is at function Public.add_compilatron(entity, name) if not entity and not entity.valid then return @@ -85,19 +84,19 @@ end --- This spawns a new compilatron on a surface with the given location tag (not a position) -- @tparam LuaSurface surface the surface to spawn the compilatron on -- @tparam string location the location tag that is in the config file -function Public.spawn_compilatron(surface,location) +function Public.spawn_compilatron(surface, location) local position = locations[location] local pos = surface.find_non_colliding_position('compilatron', position, 1.5, 0.5) - local compi = surface.create_entity {name='compilatron',position=pos,force=game.forces.neutral} - Public.add_compilatron(compi,location) + local compi = surface.create_entity {name='compilatron', position=pos, force=game.forces.neutral} + Public.add_compilatron(compi, location) end -- When the first player is created this will create all compilatrons that are resisted in the config -Event.add(defines.events.on_player_created,function(event) +Event.add(defines.events.on_player_created, function(event) if event.player_index ~= 1 then return end - local player = Game.get_player_by_index(event.player_index) - for location,pos in pairs(locations) do - Public.spawn_compilatron(player.surface,location) + local player = game.players[event.player_index] + for location in pairs(locations) do + Public.spawn_compilatron(player.surface, location) end end) diff --git a/modules/addons/damage-popups.lua b/modules/addons/damage-popups.lua index 1701697759..b6cb1662f7 100644 --- a/modules/addons/damage-popups.lua +++ b/modules/addons/damage-popups.lua @@ -12,21 +12,21 @@ Event.add(defines.events.on_entity_damaged, function(event) local damage = math.floor(event.original_damage_amount) local health = math.floor(entity.health) local health_percentage = entity.get_health_ratio() - local text_colour = {r=1-health_percentage,g=health_percentage,b=0} + local text_colour = {r=1-health_percentage, g=health_percentage, b=0} -- Gets the location of the text local size = entity.get_radius() if size < 1 then size = 1 end local r = (math.random()-0.5)*size*config.damage_location_variance local p = entity.position - local position = {x=p.x+r,y=p.y-size} + local position = {x=p.x+r, y=p.y-size} -- Sets the message local message if entity.name == 'character' and config.show_player_health then - message = {'damage-popup.player-health',health} + message = {'damage-popup.player-health', health} elseif entity.name ~= 'character' and cause and cause.name == 'character' and config.show_player_damage then - message = {'damage-popup.player-damage',damage} + message = {'damage-popup.player-damage', damage} end -- Outputs the message as floating text diff --git a/modules/addons/death-logger.lua b/modules/addons/death-logger.lua index 2e6d90d0e7..a046fa3578 100644 --- a/modules/addons/death-logger.lua +++ b/modules/addons/death-logger.lua @@ -2,28 +2,27 @@ -- @addon Death-Logger local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local Global = require 'utils.global' --- @dep utils.global local config = require 'config.death_logger' --- @dep config.death_logger -local format_time,move_items = _C.format_time, _C.move_items --- @dep expcore.common +local format_time, move_items = _C.format_time, _C.move_items --- @dep expcore.common local deaths = { archive={} -- deaths moved here after body is gone - --{player_name='Cooldude2606',time_of_death='15H 15M',position={x=0,y=0},corpse=LuaEntity,tag=LuaCustomChartTag} + --{player_name='Cooldude2606', time_of_death='15H 15M', position={x=0, y=0}, corpse=LuaEntity, tag=LuaCustomChartTag} } -Global.register(deaths,function(tbl) +Global.register(deaths, function(tbl) deaths = tbl end) --- Creates a new death marker and saves it to the given death local function create_map_tag(death) - local player = Game.get_player_from_any(death.player_name) + local player = game.players[death.player_name] local message = player.name..' died' if config.include_time_of_death then - local time = format_time(death.time_of_death,{hours=true,minutes=true,string=true}) + local time = format_time(death.time_of_death, {hours=true, minutes=true, string=true}) message = message..' at '..time end - death.tag = player.force.add_chart_tag(player.surface,{ + death.tag = player.force.add_chart_tag(player.surface, { position=death.position, icon=config.map_icon, text=message @@ -33,7 +32,7 @@ end --- Checks that all map tags are present and valid -- adds missing ones, deletes expired ones local function check_map_tags() - for index,death in ipairs(deaths) do + for index, death in ipairs(deaths) do local map_tag = death.tag local corpse = death.corpse -- Check the corpse is valid @@ -51,19 +50,19 @@ local function check_map_tags() -- Move the death to the archive death.corpse = nil death.tag = nil - table.insert(deaths.archive,death) - table.remove(deaths,index) + table.insert(deaths.archive, death) + table.remove(deaths, index) end end end -- when a player dies a new death is added to the records and a map marker is made -Event.add(defines.events.on_player_died,function(event) - local player = Game.get_player_by_index(event.player_index) - local corpse = player.surface.find_entity('character-corpse',player.position) +Event.add(defines.events.on_player_died, function(event) + local player = game.players[event.player_index] + local corpse = player.surface.find_entity('character-corpse', player.position) if config.use_chests_as_bodies then local items = corpse.get_inventory(defines.inventory.character_corpse).get_contents() - local chest = move_items(items,corpse.surface,corpse.position) + local chest = move_items(items, corpse.surface, corpse.position) chest.destructible = false corpse.destroy() corpse = chest @@ -77,22 +76,22 @@ Event.add(defines.events.on_player_died,function(event) if config.show_map_markers then create_map_tag(death) end - table.insert(deaths,death) + table.insert(deaths, death) end) -- every 5 min all bodies are checked for valid map tags if config.show_map_markers then local check_period = 60*60*5 -- five minutes - Event.on_nth_tick(check_period,function(event) + Event.on_nth_tick(check_period, function() check_map_tags() end) end if config.auto_collect_bodies then - Event.add(defines.events.on_character_corpse_expired,function(event) + Event.add(defines.events.on_character_corpse_expired, function(event) local corpse = event.corpse local items = corpse.get_inventory(defines.inventory.character_corpse).get_contents() - move_items(items,corpse.surface,{x=0,y=0}) + move_items(items, corpse.surface, {x=0, y=0}) end) end diff --git a/modules/addons/discord-alerts.lua b/modules/addons/discord-alerts.lua index ab124d843a..27b89ad91c 100644 --- a/modules/addons/discord-alerts.lua +++ b/modules/addons/discord-alerts.lua @@ -2,13 +2,12 @@ -- @addon Discord-Alerts local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local Colors = require 'utils.color_presets' --- @dep utils.color_presets -local write_json,format_time = _C.write_json, _C.format_time --- @dep expcore.common +local write_json, format_time = _C.write_json, _C.format_time --- @dep expcore.common local config = require 'config.discord_alerts' --- @dep config.discord_alerts local function get_player_name(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] return player.name, event.by_player_name end @@ -16,8 +15,8 @@ local function to_hex(color) local hex_digits = '0123456789ABCDEF' local function hex(bit) local major, minor = math.modf(bit/16) - major,minor = major+1,minor*16+1 - return hex_digits:sub(major,major)..hex_digits:sub(minor,minor) + major, minor = major+1, minor*16+1 + return hex_digits:sub(major, major)..hex_digits:sub(minor, minor) end return '0x'..hex(color.r)..hex(color.g)..hex(color.b) @@ -32,25 +31,25 @@ local function emit_event(args) color = to_hex(color) end - local tick = args.tick or 0 - local tick_formated = format_time(tick,{hours = true,minutes = true,string = true,long = true}) + local tick = args.tick or game.tick + local tick_formatted = format_time(tick, {days = true, hours = true, minutes = true, string = true, long = true}) local players_online = 0 local admins_online = 0 - for _,player in pairs(game.connected_players) do + for _, player in pairs(game.connected_players) do players_online = players_online+1 if player.admin then admins_online = admins_online + 1 end end - local done = {title=true,color=true,description=true} + local done = {title=true, color=true, description=true} local fields = {{ name='Server Details', - value=string.format('Server name: ${serverName} Players: %d Admins: %d Time: %s',players_online,admins_online,tick_formated) + value=string.format('Server: ${serverName} Time: %s\nTotal: %d Online: %d Admins: %d', tick_formatted, #game.players, players_online, admins_online) }} - for key,value in pairs(args) do + for key, value in pairs(args) do if not done[key] then done[key] = true local field = { @@ -59,13 +58,13 @@ local function emit_event(args) inline=false } - local new_value, inline = value:gsub('','',1) + local new_value, inline = value:gsub('', '', 1) if inline then field.value = new_value field.inline = true end - table.insert(fields,field) + table.insert(fields, field) end end @@ -80,25 +79,27 @@ end --- Reports added and removed if config.player_reports then local Reports = require 'modules.control.reports' --- @dep modules.control.reports - Event.add(Reports.events.on_player_reported,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Reports.events.on_player_reported, function(event) + local player_name, by_player_name = get_player_name(event) emit_event{ title='Report', description='A player was reported', color=Colors.yellow, - ['Player:']=''..player_name, - ['By:']=''..by_player_name, - ['Reason:']=event.reason + ['Player']=''..player_name, + ['By']=''..by_player_name, + ['Reason']=event.reason } end) - Event.add(Reports.events.on_report_removed,function(event) + Event.add(Reports.events.on_report_removed, function(event) + if event.batch ~= 1 then return end local player_name = get_player_name(event) emit_event{ - title='Report Removed', + title='Reports Removed', description='A player has a report removed', color=Colors.green, - ['Player:']=''..player_name, - ['By:']=''..event.removed_by_name + ['Player']=''..player_name, + ['By']=''..event.removed_by_name, + ['Amount']=''..event.batch_count } end) end @@ -106,25 +107,27 @@ end --- Warnings added and removed if config.player_warnings then local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings - Event.add(Warnings.events.on_warning_added,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Warnings.events.on_warning_added, function(event) + local player_name, by_player_name = get_player_name(event) emit_event{ title='Warning', description='A player has been given a warning', color=Colors.yellow, - ['Player:']=''..player_name, - ['By:']=''..by_player_name, - ['Reason:']=event.reason + ['Player']=''..player_name, + ['By']=''..by_player_name, + ['Reason']=event.reason } end) - Event.add(Warnings.events.on_warning_removed,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Warnings.events.on_warning_removed, function(event) + if event.batch ~= 1 then return end + local player_name = get_player_name(event) emit_event{ - title='Warning Removed', + title='Warnings Removed', description='A player has a warning removed', color=Colors.green, - ['Player:']=''..player_name, - ['By:']=''..by_player_name + ['Player']=''..player_name, + ['By']=''..event.removed_by_name, + ['Amount']=''..event.batch_count } end) end @@ -132,25 +135,25 @@ end --- When a player is jailed or unjailed if config.player_jail then local Jail = require 'modules.control.jail' - Event.add(Jail.events.on_player_jailed,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Jail.events.on_player_jailed, function(event) + local player_name, by_player_name = get_player_name(event) emit_event{ title='Jail', description='A player has been jailed', color=Colors.yellow, - ['Player:']=''..player_name, - ['By:']=''..by_player_name, - ['Reason:']=event.reason + ['Player']=''..player_name, + ['By']=''..by_player_name, + ['Reason']=event.reason } end) - Event.add(Jail.events.on_player_unjailed,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Jail.events.on_player_unjailed, function(event) + local player_name, by_player_name = get_player_name(event) emit_event{ title='Unjail', description='A player has been unjailed', color=Colors.green, - ['Player:']=''..player_name, - ['By:']=''..by_player_name + ['Player']=''..player_name, + ['By']=''..by_player_name } end) end @@ -158,53 +161,53 @@ end --- When a player is tempbanned if config.player_temp_ban then local Jail = require 'modules.control.jail' - Event.add(Jail.events.on_player_temp_banned,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Jail.events.on_player_temp_banned, function(event) + local player_name, by_player_name = get_player_name(event) emit_event{ title='Temp Ban', description='A player has been temp banned', color=Colors.red, - ['Player:']=''..player_name, - ['By:']=''..by_player_name, - ['Reason:']=event.reason + ['Player']=''..player_name, + ['By']=''..by_player_name, + ['Reason']=event.reason } end) - Event.add(Jail.events.on_player_untemp_banned,function(event) - local player_name,by_player_name = get_player_name(event) + Event.add(Jail.events.on_player_untemp_banned, function(event) + local player_name, by_player_name = get_player_name(event) emit_event{ title='Temp Ban Removed', description='A player has been untemp banned', color=Colors.green, - ['Player:']=''..player_name, - ['By:']=''..by_player_name + ['Player']=''..player_name, + ['By']=''..by_player_name } end) end --- Ban and unban if config.player_bans then - Event.add(defines.events.on_player_banned,function(event) + Event.add(defines.events.on_player_banned, function(event) if event.by_player then - local by_player = Game.get_player_by_index(event.by_player) + local by_player = game.players[event.by_player] emit_event{ title='Banned', description='A player has been banned', color=Colors.red, - ['Player:']=''..event.player_name, - ['By:']=''..by_player.name, - ['Reason:']=event.reason + ['Player']=''..event.player_name, + ['By']=''..by_player.name, + ['Reason']=event.reason } end end) - Event.add(defines.events.on_player_unbanned,function(event) + Event.add(defines.events.on_player_unbanned, function(event) if event.by_player then - local by_player = Game.get_player_by_index(event.by_player) + local by_player = game.players[event.by_player] emit_event{ title='Un-Banned', description='A player has been un-banned', color=Colors.green, - ['Player:']=''..event.player_name, - ['By:']=''..by_player.name + ['Player']=''..event.player_name, + ['By']=''..by_player.name } end end) @@ -212,39 +215,39 @@ end --- Mute and unmute if config.player_mutes then - Event.add(defines.events.on_player_muted,function(event) + Event.add(defines.events.on_player_muted, function(event) local player_name = get_player_name(event) emit_event{ title='Muted', description='A player has been muted', color=Colors.yellow, - ['Player:']=''..player_name + ['Player']=''..player_name } end) - Event.add(defines.events.on_player_unmuted,function(event) + Event.add(defines.events.on_player_unmuted, function(event) local player_name = get_player_name(event) emit_event{ title='Un-Muted', description='A player has been un-muted', color=Colors.green, - ['Player:']=''..player_name + ['Player']=''..player_name } end) end --- Kick if config.player_kicks then - Event.add(defines.events.on_player_kicked,function(event) + Event.add(defines.events.on_player_kicked, function(event) if event.by_player then local player_name = get_player_name(event) - local by_player = Game.get_player_by_index(event.by_player) + local by_player = game.players[event.by_player] emit_event{ title='Kick', description='A player has been kicked', color=Colors.orange, - ['Player:']=''..player_name, - ['By:']=''..by_player.name, - ['Reason:']=event.reason + ['Player']=''..player_name, + ['By']=''..by_player.name, + ['Reason']=event.reason } end end) @@ -252,37 +255,37 @@ end --- Promote and demote if config.player_promotes then - Event.add(defines.events.on_player_promoted,function(event) + Event.add(defines.events.on_player_promoted, function(event) local player_name = get_player_name(event) emit_event{ title='Promote', description='A player has been promoted', color=Colors.green, - ['Player:']=''..player_name + ['Player']=''..player_name } end) - Event.add(defines.events.on_player_demoted,function(event) + Event.add(defines.events.on_player_demoted, function(event) local player_name = get_player_name(event) emit_event{ title='Demote', description='A player has been demoted', color=Colors.yellow, - ['Player:']=''..player_name + ['Player']=''..player_name } end) end --- Other commands -Event.add(defines.events.on_console_command,function(event) +Event.add(defines.events.on_console_command, function(event) if event.player_index then local player_name = get_player_name(event) if config[event.command] then emit_event{ - title=event.command:gsub('^%l',string.upper), + title=event.command:gsub('^%l', string.upper), description='/'..event.command..' was used', color=Colors.grey, - ['By:']=''..player_name, - ['Details:'] = event.parameters ~= '' and event.parameters or nil + ['By']=''..player_name, + ['Details'] = event.parameters ~= '' and event.parameters or nil } end end diff --git a/modules/addons/greetings.lua b/modules/addons/greetings.lua deleted file mode 100644 index 4541f42ed4..0000000000 --- a/modules/addons/greetings.lua +++ /dev/null @@ -1,26 +0,0 @@ ---- Greets players on join --- @addon greetings - -local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.event -local config = require 'config.join_messages' --- @dep config.join_messages -local Global = require 'utils.global' --- @dep utils.global -require 'overrides.table' - -Global.register(config,function(tbl) - config = tbl -end) - -local greet = -function(event) - local player = Game.get_player_by_index(event.player_index) - local custom_message = config[player.name] - if custom_message then - game.print(custom_message,player.color) - else - player.print{'greetings.greet',{'links.discord'}} - end - -end - -Event.add(defines.events.on_player_joined_game, greet) \ No newline at end of file diff --git a/modules/addons/pollution-grading.lua b/modules/addons/pollution-grading.lua index dd4b091494..872cd758b7 100644 --- a/modules/addons/pollution-grading.lua +++ b/modules/addons/pollution-grading.lua @@ -5,7 +5,7 @@ local Event = require 'utils.event' --- @dep utils.event local config = require 'config.pollution_grading' --- @dep config.pollution_grading local delay = config.update_delay * 3600 -- convert from minutes to ticks -Event.on_nth_tick(delay,function() +Event.on_nth_tick(delay, function() local surface = game.surfaces[1] local true_max = surface.get_pollution(config.reference_point) local max = true_max*config.max_scalar diff --git a/modules/addons/random-player-colours.lua b/modules/addons/random-player-colours.lua deleted file mode 100644 index 30526f202f..0000000000 --- a/modules/addons/random-player-colours.lua +++ /dev/null @@ -1,29 +0,0 @@ ---- Gives players random colours when they join, also applies preset colours to those who have them --- @addon Player-Colours - -local Colours = require 'utils.color_presets' --- @dep utils.color_presets -local Game = require 'utils.game' --- @dep utils.game -local Event = require 'utils.event' --- @dep utils.event -local config = require 'config.preset_player_colours' --- @dep config.preset_player_colours -local Global = require 'utils.global' --- @dep utils.global -require 'overrides.table' - -Global.register(config,function(tbl) - config = tbl -end) - -Event.add(defines.events.on_player_created,function(event) - local player = Game.get_player_by_index(event.player_index) - local color = 'white' - if config.players[player.name] then - color = config.players[player.name] - else - while config.disallow[color] do - color = table.get_random_dictionary_entry(Colours,true) - end - color = Colours[color] - end - color = {r=color.r/255,g=color.g/255,b=color.b/255,a=0.5} - player.color = color - player.chat_color = color -end) \ No newline at end of file diff --git a/modules/addons/scorched-earth.lua b/modules/addons/scorched-earth.lua index c6c822c57c..1af6b59b95 100644 --- a/modules/addons/scorched-earth.lua +++ b/modules/addons/scorched-earth.lua @@ -2,14 +2,13 @@ -- @addon Scorched-Earth local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local Global = require 'utils.global' --- @dep utils.global local print_grid_value, clear_flying_text = _C.print_grid_value, _C.clear_flying_text --- @dep expcore.common local config = require 'config.scorched_earth' --- @dep config.scorched_earth -- Loops over the config and finds the wile which has the highest value for strength local max_strength = 0 -for _,strength in pairs(config.strengths) do +for _, strength in pairs(config.strengths) do if strength > max_strength then max_strength = strength end @@ -22,12 +21,12 @@ Global.register(debug_players, function(tbl) end) -- Will degrade a tile down to the next tile when called -local function degrade(surface,position) +local function degrade(surface, position) local tile = surface.get_tile(position) local tile_name = tile.name local degrade_tile_name = config.degrade_order[tile_name] if not degrade_tile_name then return end - surface.set_tiles{{name=degrade_tile_name,position=position}} + surface.set_tiles{{name=degrade_tile_name, position=position}} end -- Same as degrade but will degrade all tiles that are under an entity @@ -42,12 +41,12 @@ local function degrade_entity(entity) for x = lt.x, rb.x do -- x loop local px = position.x+x for y = lt.y, rb.y do -- y loop - local p = {x=px,y=position.y+y} + local p = {x=px, y=position.y+y} local tile = surface.get_tile(p) local tile_name = tile.name local degrade_tile_name = config.degrade_order[tile_name] if not degrade_tile_name then return end - table.insert(tiles,{name=degrade_tile_name,position=p}) + table.insert(tiles, {name=degrade_tile_name, position=p}) end end surface.set_tiles(tiles) @@ -62,15 +61,15 @@ local function get_probability(strength) end -- Gets the mean of the strengths around a tile to give the strength at that position -local function get_tile_strength(surface,position) +local function get_tile_strength(surface, position) local tile = surface.get_tile(position) local tile_name = tile.name local strength = config.strengths[tile_name] if not strength then return end - for x = -1,1 do -- x loop + for x = -1, 1 do -- x loop local px = position.x + x - for y = -1,1 do -- y loop - local check_tile = surface.get_tile{x=px,y=position.y+y} + for y = -1, 1 do -- y loop + local check_tile = surface.get_tile{x=px, y=position.y+y} local check_tile_name = check_tile.name local check_strength = config.strengths[check_tile_name] or 0 strength = strength + check_strength @@ -80,12 +79,12 @@ local function get_tile_strength(surface,position) end -- Same as get_tile_strength but returns to a in game text rather than as a value -local function debug_get_tile_strength(surface,position) - for x = -3,3 do -- x loop +local function debug_get_tile_strength(surface, position) + for x = -3, 3 do -- x loop local px = position.x+x - for y = -3,3 do -- y loop - local p = {x=px,y=position.y+y} - local strength = get_tile_strength(surface,p) or 0 + for y = -3, 3 do -- y loop + local p = {x=px, y=position.y+y} + local strength = get_tile_strength(surface, p) or 0 local tile = surface.get_tile(p) print_grid_value(get_probability(strength)*config.weakness_value, surface, tile.position) end @@ -94,16 +93,16 @@ end -- When the player changes position the tile will have a chance to downgrade, debug check is here Event.add(defines.events.on_player_changed_position, function(event) - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] local surface = player.surface local position = player.position - local strength = get_tile_strength(surface,position) + local strength = get_tile_strength(surface, position) if not strength then return end if get_probability(strength) > math.random() then - degrade(surface,position) + degrade(surface, position) end if debug_players[player.name] then - debug_get_tile_strength(surface,position) + debug_get_tile_strength(surface, position) end end) @@ -112,7 +111,7 @@ Event.add(defines.events.on_built_entity, function(event) local entity = event.created_entity local surface = entity.surface local position = entity.position - local strength = get_tile_strength(surface,position) + local strength = get_tile_strength(surface, position) if not strength then return end if get_probability(strength)*config.weakness_value > math.random() then degrade_entity(entity) @@ -124,7 +123,7 @@ Event.add(defines.events.on_robot_built_entity, function(event) local entity = event.created_entity local surface = entity.surface local position = entity.position - local strength = get_tile_strength(surface,position) + local strength = get_tile_strength(surface, position) if not strength then return end if get_probability(strength)*config.weakness_value > math.random() then degrade_entity(entity) @@ -132,8 +131,8 @@ Event.add(defines.events.on_robot_built_entity, function(event) end) -- Used as a way to access the global table -return function(player_name,state) - local player = Game.get_player_from_any(player_name) +return function(player_name, state) + local player = game.players[player_name] clear_flying_text(player.surface) debug_players[player_name] = state end \ No newline at end of file diff --git a/modules/addons/spawn-area.lua b/modules/addons/spawn-area.lua index dcdbb5f022..4b9daf3ba5 100644 --- a/modules/addons/spawn-area.lua +++ b/modules/addons/spawn-area.lua @@ -3,14 +3,13 @@ local Global = require 'utils.global' --- @dep utils.global local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local config = require 'config.spawn_area' --- @dep config.spawn_area local tiles = config.tiles local entities = config.entities local belts = config.afk_belts.locations local turrets = config.infinite_ammo_turrets.locations -Global.register(turrets,function(tbl) +Global.register(turrets, function(tbl) turrets = tbl end) @@ -19,13 +18,13 @@ local function get_spawn_force() local force = game.forces['Spawn'] if force and force.valid then return force end force = game.create_force('Spawn') - force.set_cease_fire('player',true) - game.forces['player'].set_cease_fire('Spawn',true) + force.set_cease_fire('player', true) + game.forces['player'].set_cease_fire('Spawn', true) return force end -- protects and entity so players cant do anything to it -local function protect_entity(entity,set_force) +local function protect_entity(entity, set_force) if entity and entity.valid then entity.destructible = false entity.minable = false @@ -39,40 +38,40 @@ end -- handles the infinite ammo turrets local function spawn_turrets() if config.infinite_ammo_turrets.enabled then - for _,turret_pos in pairs(turrets) do + for _, turret_pos in pairs(turrets) do local surface = game.surfaces[turret_pos.surface] local pos = turret_pos.position - local turret = surface.find_entity('gun-turret',pos) + local turret = surface.find_entity('gun-turret', pos) -- Makes a new turret if it is not found if not turret or not turret.valid then - turret = surface.create_entity{name='gun-turret',position=pos,force='Spawn'} - protect_entity(turret,true) + turret = surface.create_entity{name='gun-turret', position=pos, force='Spawn'} + protect_entity(turret, true) end -- adds ammo to the turret local inv = turret.get_inventory(defines.inventory.turret_ammo) - if inv.can_insert{name=config.infinite_ammo_turrets.ammo_type,count=10} then - inv.insert{name=config.infinite_ammo_turrets.ammo_type,count=10} + if inv.can_insert{name=config.infinite_ammo_turrets.ammo_type, count=10} then + inv.insert{name=config.infinite_ammo_turrets.ammo_type, count=10} end end end end -- makes a 2x2 afk belt where set in config -local function spawn_belts(surface,position) - local belt_details = {{-0.5,-0.5,2},{0.5,-0.5,4},{-0.5,0.5,0},{0.5,0.5,6}} -- x,y,dir - for _,belt_set in pairs(belts) do +local function spawn_belts(surface, position) + local belt_details = {{-0.5, -0.5, 2}, {0.5, -0.5, 4}, {-0.5, 0.5, 0}, {0.5, 0.5, 6}} -- x, y,dir + for _, belt_set in pairs(belts) do local o = position local p = belt_set - for _,belt in pairs(belt_details) do - local pos = {x=o.x+p.x+belt[1],y=o.y+p.y+belt[2]} - local belt_entity = surface.create_entity{name='transport-belt',position=pos,force='neutral',direction=belt[3]} + for _, belt in pairs(belt_details) do + local pos = {x=o.x+p.x+belt[1], y=o.y+p.y+belt[2]} + local belt_entity = surface.create_entity{name='transport-belt', position=pos, force='neutral', direction=belt[3]} protect_entity(belt_entity) end end end -- generates an area with no water and removes entities in the decon area -local function spawn_base(surface,position) +local function spawn_base(surface, position) local dr = config.corrections.deconstruction_radius local dr2 = dr^2 local dtile = config.corrections.deconstruction_tile @@ -86,17 +85,17 @@ local function spawn_base(surface,position) for y = -pr, pr do -- loop over y local y2 = y^2 local prod = x2+y2 - local p = {x=position.x+x,y=position.y+y} + local p = {x=position.x+x, y=position.y+y} if prod < dr2 then -- if it is inside the decon radius - table.insert(tiles_to_make,{name=dtile,position=p}) - local entities_to_remove = surface.find_entities_filtered{area={{p.x-1,p.y-1},{p.x,p.y}}} - for _,entity in pairs(entities_to_remove) do + table.insert(tiles_to_make, {name=dtile, position=p}) + local entities_to_remove = surface.find_entities_filtered{area={{p.x-1, p.y-1}, {p.x, p.y}}} + for _, entity in pairs(entities_to_remove) do if entity.name ~= 'character' then entity.destroy() end end elseif prod < pr2 then -- if it is inside the pattern radius - table.insert(tiles_to_make,{name=ptile,position=p}) + table.insert(tiles_to_make, {name=ptile, position=p}) end end end @@ -104,46 +103,46 @@ local function spawn_base(surface,position) end -- generates the pattern that is in the config -local function spawn_pattern(surface,position) +local function spawn_pattern(surface, position) local tiles_to_make = {} local ptile = config.corrections.pattern_tile local o = config.corrections.offset - local p = {x=position.x+o.x,y=position.y+o.y} - for _,tile in pairs(tiles) do - table.insert(tiles_to_make,{name=ptile,position={tile[1]+p.x,tile[2]+p.y}}) + local p = {x=position.x+o.x, y=position.y+o.y} + for _, tile in pairs(tiles) do + table.insert(tiles_to_make, {name=ptile, position={tile[1]+p.x, tile[2]+p.y}}) end surface.set_tiles(tiles_to_make) end -- generates the entities that are in the config -local function spawn_entities(surface,position) +local function spawn_entities(surface, position) local o = config.corrections.offset - local p = {x=position.x+o.x,y=position.y+o.y} - for _,entity in pairs(entities) do - entity = surface.create_entity{name=entity[1],position={entity[2]+p.x,entity[3]+p.y},force='neutral'} + local p = {x=position.x+o.x, y=position.y+o.y} + for _, entity in pairs(entities) do + entity = surface.create_entity{name=entity[1], position={entity[2]+p.x, entity[3]+p.y}, force='neutral'} protect_entity(entity) entity.operable = true end end local refill_time = 60*60*5 -- 5 minutes -Event.on_nth_tick(refill_time,function() +Event.on_nth_tick(refill_time, function() if game.tick < 10 then return end spawn_turrets() end) Event.add(defines.events.on_player_created, function(event) if event.player_index ~= 1 then return end - local player = Game.get_player_by_index(event.player_index) - local p = {x=0,y=0} + local player = game.players[event.player_index] + local p = {x=0, y=0} local s = player.surface - spawn_base(s,p) - spawn_pattern(s,p) + spawn_base(s, p) + spawn_pattern(s, p) get_spawn_force() - spawn_entities(s,p) - spawn_belts(s,p) + spawn_entities(s, p) + spawn_belts(s, p) spawn_turrets() - player.teleport(p,s) + player.teleport(p, s) end) -- Way to access global table diff --git a/modules/addons/station-auto-name.lua b/modules/addons/station-auto-name.lua index 2710890ef4..15a9f21b8f 100644 --- a/modules/addons/station-auto-name.lua +++ b/modules/addons/station-auto-name.lua @@ -1,71 +1,86 @@ ---LuaPlayerBuiltEntityEventFilters ---Events.set_event_filter(defines.events.on_built_entity, {{filter = "name", name = "fast-inserter"}}) local Event = require 'utils.event' --- @dep utils.event -local station_name_changer = -function(event) - local enetety = event.created_entity - local name = enetety.name - if name == "train-stop" then --only do the event if its a trainstop - local boundingbox = enetety.bounding_box +--Credit to Cooldude2606 for using his lua magic to make this function. +local directions = { + ['W'] = -0.875, + ['NW'] = -0.625, + ['N'] = -0.375, + ['NE'] = -0.125, + ['E'] = 0.125, + ['SE'] = 0.375, + ['S'] = 0.625, + ['SW'] = 0.875 +} + +local function Angle(entity) + local angle = math.atan2(entity.position.y, entity.position.x)/math.pi + for direction, requiredAngle in pairs(directions) do + if angle < requiredAngle then + return direction + end + end + return 'W' +end + +local custom_string = ' *' +local custom_string_len = #custom_string + +local function station_name_changer(event) + local entity = event.created_entity + local name = entity.name + if name == "entity-ghost" then + if entity.ghost_name ~= "train-stop" then return end + local backername = entity.backer_name + if backername ~= '' then + entity.backer_name = backername..custom_string + end + + elseif name == "train-stop" then --only do the event if its a train stop + local backername = entity.backer_name + if backername:sub(-custom_string_len) == custom_string then + entity.backer_name = backername:sub(1, -custom_string_len) + return + end + + local boundingBox = entity.bounding_box -- expanded box for recourse search: - local bounding2 = { {boundingbox.left_top.x -100 ,boundingbox.left_top.y -100} , {boundingbox.right_bottom.x +100,boundingbox.right_bottom.y +100 } } - --gets all resources in bounding_box2: - local recoursec = game.surfaces[1].find_entities_filtered{area = bounding2, type = "resource"} - - if #recoursec > 0 then -- save cpu time if their are no recourses in bounding_box2 + local bounding2 = { {boundingBox.left_top.x -100 ,boundingBox.left_top.y -100} , {boundingBox.right_bottom.x +100, boundingBox.right_bottom.y +100 } } + -- gets all resources in bounding_box2: + local recourses = game.surfaces[1].find_entities_filtered{area = bounding2, type = "resource"} + + if #recourses > 0 then -- save cpu time if their are no recourses in bounding_box2 local closest_distance - local px,py = boundingbox.left_top.x,boundingbox.left_top.y + local px, py = boundingBox.left_top.x, boundingBox.left_top.y local recourse_closed - --Check which recource is closest - for i, item in ipairs(recoursec) do + --Check which recourse is closest + for i, item in ipairs(recourses) do local dx, dy = px - item.bounding_box.left_top.x, py - item.bounding_box.left_top.y local distance = (dx*dx)+(dy*dy) if not closest_distance or distance < closest_distance then recourse_closed = item closest_distance = distance end - + end - local item_name = recourse_closed.name if item_name then -- prevent errors if something went wrong - local item_name2 = item_name:gsub("^%l", string.upper):gsub('-',' ') -- removing the - and making first letter capital - + local item_name2 = item_name:gsub("^%l", string.upper):gsub('-', ' ') -- removing the - and making first letter capital + local Item_ore_fluid = "item" if item_name == "crude-oil" then Item_ore_fluid = "fluid" end --Final string: - enetety.backer_name = string.format("[L] [img=%s.%s] %s %s (%s)",Item_ore_fluid,item_name,item_name2,enetety.backer_name,Angle( enetety )) + entity.backer_name = string.format("[L] [img=%s.%s] %s %s (%s)", Item_ore_fluid, item_name, item_name2, entity.backer_name, Angle( entity )) end end end end ---add func to robot and player build entities -Event.add(defines.events.on_built_entity,station_name_changer) -Event.add(defines.events.on_robot_built_entity,station_name_changer) - ---Credit to Cooldude2606 for using his lua magic to make this function. -local directions = { - ['W'] = -0.875, - ['NW'] = -0.625, - ['N'] = -0.375, - ['NE'] = -0.125, - ['E'] = 0.125, - ['SE'] = 0.375, - ['S'] = 0.625, - ['SW'] = 0.875 -} -function Angle( enetety ) - local angle = math.atan2(enetety.position.y,enetety.position.x)/math.pi - for direction, requiredAngle in pairs(directions) do - if angle < requiredAngle then - return direction - end - end -end - \ No newline at end of file +-- Add handler to robot and player build entities +Event.add(defines.events.on_built_entity, station_name_changer) +Event.add(defines.events.on_robot_built_entity, station_name_changer) diff --git a/modules/addons/tree-decon.lua b/modules/addons/tree-decon.lua index 75f5738b1b..29e1370702 100644 --- a/modules/addons/tree-decon.lua +++ b/modules/addons/tree-decon.lua @@ -2,7 +2,6 @@ -- @addon Tree-Decon local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local Global = require 'utils.global' --- @dep utils.global local Roles = require 'expcore.roles' --- @dep expcore.roles @@ -18,8 +17,9 @@ end) Event.add(defines.events.on_marked_for_deconstruction, function(event) -- Check which type of decon a player is allowed local index = event.player_index + if not index then return end if chache[index] == nil then - local player = Game.get_player_by_index(index) + local player = game.players[index] if Roles.player_allowed(player, 'fast-tree-decon') then chache[index] = 'fast' elseif Roles.player_allowed(player, 'standard-decon') then chache[index] = 'standard' else chache[index] = player.force end @@ -57,7 +57,7 @@ Event.add(defines.events.on_tick, function() local max_remove = math.floor(head/100)+1 local remove_count = math.random(0, max_remove) while remove_count > 0 and head > 0 do - local remove_index = math.random(1,head) + local remove_index = math.random(1, head) local entity = tree_queue[remove_index] tree_queue[remove_index] = tree_queue[head] head = head - 1 @@ -71,7 +71,7 @@ end) -- Clear the chache Event.on_nth_tick(300, function() - for key,_ in pairs(chache) do + for key, _ in pairs(chache) do chache[key] = nil end end) \ No newline at end of file diff --git a/modules/commands/admin-chat.lua b/modules/commands/admin-chat.lua index 19aae6cb6a..f42f1e8b89 100644 --- a/modules/commands/admin-chat.lua +++ b/modules/commands/admin-chat.lua @@ -10,16 +10,16 @@ require 'config.expcore.command_general_parse' --- Sends a message in chat that only admins can see -- @command admin-chat -- @tparam string message the message to send in the admin chat -Commands.new_command('admin-chat','Sends a message in chat that only admins can see.') -:add_param('message',false) +Commands.new_command('admin-chat', 'Sends a message in chat that only admins can see.') +:add_param('message', false) :enable_auto_concat() :set_flag('admin_only') :add_alias('ac') -:register(function(player,message,raw) +:register(function(player, message) local player_name_colour = format_chat_player_name(player) - for _,return_player in pairs(game.connected_players) do + for _, return_player in pairs(game.connected_players) do if return_player.admin then - return_player.print{'expcom-admin-chat.format',player_name_colour,message} + return_player.print{'expcom-admin-chat.format', player_name_colour, message} end end return Commands.success -- prevents command complete message from showing diff --git a/modules/commands/bonus.lua b/modules/commands/bonus.lua deleted file mode 100644 index b39fc1f144..0000000000 --- a/modules/commands/bonus.lua +++ /dev/null @@ -1,72 +0,0 @@ ---[[-- Commands Module - Bonus - - Adds a command that allows players to have increased stats - @commands Bonus -]] - -local Commands = require 'expcore.commands' --- @dep expcore.commands -local Roles = require 'expcore.roles' --- @dep expcore.roles -local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game -local Store = require 'expcore.store' --- @dep expcore.store -local config = require 'config.bonuses' --- @dep config.bonuses -require 'config.expcore.command_general_parse' - --- Store bonus percentages keyed by player name -local bonus_store = Store.register(function(player) - return player.name -end) - --- Apply a bonus amount to a player -local function apply_bonus(player,amount) - if not amount then return end - for bonus,min_max in pairs(config) do - local increase = min_max[2]*amount - player[bonus] = min_max[1]+increase - end -end - ---- Changes the amount of bonus you receive --- @command bonus --- @tparam number amount range 0-50 the percent increase for your bonus -Commands.new_command('bonus','Changes the amount of bonus you receive') -:add_param('amount','integer-range',0,50) -:register(function(player,amount) - local percent = amount/100 - Store.set(bonus_store,player,percent) - Commands.print{'expcom-bonus.set',amount} - Commands.print({'expcom-bonus.wip'},'orange') -end) - --- When store is updated apply new bonus to the player -Store.watch(bonus_store,function(value,category) - local player = Game.get_player_from_any(category) - apply_bonus(player,value) -end) - --- When a player respawns re-apply bonus -Event.add(defines.events.on_player_respawned,function(event) - local player = Game.get_player_by_index(event.player_index) - local value = Store.get(bonus_store,player) - apply_bonus(player,value) -end) - --- When a player dies allow them to have instant respawn -Event.add(defines.events.on_player_died,function(event) - local player = Game.get_player_by_index(event.player_index) - if Roles.player_has_flag(player,'instance-respawn') then - player.ticks_to_respawn = 120 - end -end) - --- Remove bonus if a player no longer has access to the command -local function role_update(event) - local player = Game.get_player_by_index(event.player_index) - if not Roles.player_allowed(player,'command/bonus') then - Store.clear(bonus_store,player) - end -end - -Event.add(Roles.events.on_role_assigned,role_update) -Event.add(Roles.events.on_role_unassigned,role_update) - -return bonus_store \ No newline at end of file diff --git a/modules/commands/cheat-mode.lua b/modules/commands/cheat-mode.lua index c2eb462a57..b021457905 100644 --- a/modules/commands/cheat-mode.lua +++ b/modules/commands/cheat-mode.lua @@ -9,12 +9,12 @@ require 'config.expcore.command_general_parse' --- Toggles cheat mode for your player, or another player. -- @command toggle-cheat-mode -- @tparam[opt=self] LuaPlayer player player to toggle chest mode of, can be nil for self -Commands.new_command('toggle-cheat-mode','Toggles cheat mode for your player, or another player.') -:add_param('player',true,'player') +Commands.new_command('toggle-cheat-mode', 'Toggles cheat mode for your player, or another player.') +:add_param('player', true, 'player') :set_defaults{player=function(player) return player -- default is the user using the command end} :set_flag('admin_only') -:register(function(player,action_player,raw) - action_player.cheat_mode = not action_player.cheat_mode +:register(function(_, player) + player.cheat_mode = not player.cheat_mode end) \ No newline at end of file diff --git a/modules/commands/clear-inventory.lua b/modules/commands/clear-inventory.lua index e684fb5e60..041559787a 100644 --- a/modules/commands/clear-inventory.lua +++ b/modules/commands/clear-inventory.lua @@ -10,11 +10,14 @@ require 'config.expcore.command_role_parse' --- Clears a players inventory -- @command clear-inventory -- @tparam LuaPlayer player the player to clear the inventory of -Commands.new_command('clear-inventory','Clears a players inventory') -:add_param('player',false,'player-role-alive') -:add_alias('clear-inv','move-inventory','move-inv') -:register(function(player,action_player) - local inv = action_player.get_main_inventory() +Commands.new_command('clear-inventory', 'Clears a players inventory') +:add_param('player', false, 'player-role') +:add_alias('clear-inv', 'move-inventory', 'move-inv') +:register(function(_, player) + local inv = player.get_main_inventory() + if not inv then + return Commands.error{'expcore-commands.reject-player-alive'} + end move_items(inv.get_contents()) inv.clear() end) \ No newline at end of file diff --git a/modules/commands/connect.lua b/modules/commands/connect.lua new file mode 100644 index 0000000000..7951e628bc --- /dev/null +++ b/modules/commands/connect.lua @@ -0,0 +1,107 @@ +--[[-- Commands Module - Connect + - Adds a commands that allows you to request a player move to another server + @commands Connect +]] + +local Async = require 'expcore.async' --- @dep expcore.async +local External = require 'expcore.external' --- @dep expcore.external +local Commands = require 'expcore.commands' --- @dep expcore.commands +require 'config.expcore.command_role_parse' +local concat = table.concat + +local request_connection = Async.register(External.request_connection) + +local function get_server_id(server) + local current_server = External.get_current_server() + local current_version = current_server.version + local servers = External.get_servers_filtered(server) + + local server_names_before, server_names = {}, {} + local server_count_before, server_count = 0, 0 + for next_server_id, server_details in pairs(servers) do + server_count_before = server_count_before + 1 + server_names_before[server_count_before] = server_details.name + if server_details.version == current_version then + server_count = server_count + 1 + server_names[server_count] = server_details.name + else + servers[next_server_id] = nil + end + end + + if server_count > 1 then + return false, Commands.error{'expcom-connect.too-many-matching', concat(server_names, ', ')} + elseif server_count == 1 then + local server_id, server_details = next(servers) + local status = External.get_server_status(server_id) + if server_id == current_server.id then + return false, Commands.error{'expcom-connect.same-server', server_details.name} + elseif status == 'Offline' then + return false, Commands.error{'expcom-connect.offline', server_details.name} + end + return true, server_id + elseif server_count_before > 0 then + return false, Commands.error{'expcom-connect.wrong-version', concat(server_names_before, ', ')} + else + return false, Commands.error{'expcom-connect.none-matching'} + end +end + +--- Connect to a different server +-- @command connect +-- @tparam string server The address or name of the server to connect to +-- @tparam[opt=false] boolean is_address If an address was given for the server param +Commands.new_command('connect', 'Connect to another server') +:add_param('server') +:add_param('is_address', true, 'boolean') +:add_alias('join', 'server') +:register(function(player, server, is_address) + local server_id = server + if not is_address and External.valid() then + local success, new_server_id = get_server_id(server) + if not success then return new_server_id end + server_id = new_server_id + end + + Async(request_connection, player, server_id, true) +end) + +--- Connect a player to a different server +-- @command connect-player +-- @tparam string address The address or name of the server to connect to +-- @tparam LuaPlayer player The player to connect to a different server +-- @tparam[opt=false] boolean is_address If an address was given for the server param +Commands.new_command('connect-player', 'Send a player to a different server') +:add_param('player', 'player-role') +:add_param('server') +:add_param('is_address', true, 'boolean') +:register(function(_, player, server, is_address) + local server_id = server + if not is_address and External.valid() then + local success, new_server_id = get_server_id(server) + if not success then return new_server_id end + server_id = new_server_id + end + + External.request_connection(player, server_id) +end) + +--- Connect all players to a different server +-- @command connect-all +-- @tparam string address The address or name of the server to connect to +-- @tparam[opt=false] boolean is_address If an address was given for the server param +Commands.new_command('connect-all', 'Connect all players to another server') +:add_param('server') +:add_param('is_address', true, 'boolean') +:register(function(_, server, is_address) + local server_id = server + if not is_address and External.valid() then + local success, new_server_id = get_server_id(server) + if not success then return new_server_id end + server_id = new_server_id + end + + for _, player in pairs(game.connected_players) do + External.request_connection(player, server_id) + end +end) \ No newline at end of file diff --git a/modules/commands/debug.lua b/modules/commands/debug.lua index e29786a616..649bf6d514 100644 --- a/modules/commands/debug.lua +++ b/modules/commands/debug.lua @@ -8,7 +8,7 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands --- Opens the debug pannel for viewing tables. -- @command debug -Commands.new_command('debug','Opens the debug pannel for viewing tables.') +Commands.new_command('debug', 'Opens the debug pannel for viewing tables.') :register(function(player) DebugView.open_dubug(player) end) \ No newline at end of file diff --git a/modules/commands/find.lua b/modules/commands/find.lua index 58ab5530ff..13639fefc3 100644 --- a/modules/commands/find.lua +++ b/modules/commands/find.lua @@ -9,11 +9,11 @@ require 'config.expcore.command_general_parse' --- Find a player on your map. -- @command find-on-map -- @tparam LuaPlayer the player to find on the map -Commands.new_command('find-on-map','Find a player on your map.') -:add_param('player',false,'player-online') -:add_alias('find','zoom-to') -:register(function(player,action_player,raw) +Commands.new_command('find-on-map', 'Find a player on your map.') +:add_param('player', false, 'player-online') +:add_alias('find', 'zoom-to') +:register(function(player, action_player) local position = action_player.position - player.zoom_to_world(position,1.75) + player.zoom_to_world(position, 1.75) return Commands.success -- prevents command complete message from showing end) \ No newline at end of file diff --git a/modules/commands/help.lua b/modules/commands/help.lua index af43910dcd..6bb31c933f 100644 --- a/modules/commands/help.lua +++ b/modules/commands/help.lua @@ -10,7 +10,7 @@ require 'config.expcore.command_general_parse' local results_per_page = 5 local search_cache = {} -Global.register(search_cache,function(tbl) +Global.register(search_cache, function(tbl) search_cache = tbl end) @@ -18,12 +18,12 @@ end) -- @command chelp -- @tparam string keyword the keyword that will be looked for -- @tparam number page the page of help to view, must be in range of pages -Commands.new_command('search-help','Searches for a keyword in all commands you are allowed to use.') -:add_alias('chelp','shelp','commands') -:add_param('keyword',true) -:add_param('page',true,'integer') -:set_defaults{keyword='',page=1} -:register(function(player,keyword,page,raw) +Commands.new_command('search-help', 'Searches for a keyword in all commands you are allowed to use.') +:add_alias('chelp', 'shelp', 'commands') +:add_param('keyword', true) +:add_param('page', true, 'integer') +:set_defaults{keyword='', page=1} +:register(function(player, keyword, page) local player_index = player and player.index or 0 -- if keyword is a number then treat it as page number if tonumber(keyword) then @@ -40,20 +40,20 @@ Commands.new_command('search-help','Searches for a keyword in all commands you a pages = {{}} local current_page = 1 local page_count = 0 - local commands = Commands.search(keyword,player) + local commands = Commands.search(keyword, player) -- loops other all commands returned by search, includes game commands - for _,command_data in pairs(commands) do + for _, command_data in pairs(commands) do -- if the number of results if greater than the number already added then it moves onto a new page if page_count >= results_per_page then page_count = 0 current_page = current_page + 1 - table.insert(pages,{}) + table.insert(pages, {}) end -- adds the new command to the page page_count = page_count + 1 found = found + 1 - local alias_format = #command_data.aliases > 0 and {'expcom-chelp.alias',table.concat(command_data.aliases,', ')} or '' - table.insert(pages[current_page],{ + local alias_format = #command_data.aliases > 0 and {'expcom-chelp.alias', table.concat(command_data.aliases, ', ')} or '' + table.insert(pages[current_page], { 'expcom-chelp.format', command_data.name, command_data.description, @@ -70,15 +70,15 @@ Commands.new_command('search-help','Searches for a keyword in all commands you a end -- print the requested page keyword = keyword == '' and '' or keyword - Commands.print({'expcom-chelp.title',keyword},'cyan') + Commands.print({'expcom-chelp.title', keyword}, 'cyan') if pages[page] then - for _,command in pairs(pages[page]) do + for _, command in pairs(pages[page]) do Commands.print(command) end - Commands.print({'expcom-chelp.footer',found,page,#pages},'cyan') + Commands.print({'expcom-chelp.footer', found, page, #pages}, 'cyan') else - Commands.print({'expcom-chelp.footer',found,page,#pages},'cyan') - return Commands.error{'expcom-chelp.out-of-range',page} + Commands.print({'expcom-chelp.footer', found, page, #pages}, 'cyan') + return Commands.error{'expcom-chelp.out-of-range', page} end -- blocks command complete message return Commands.success diff --git a/modules/commands/home.lua b/modules/commands/home.lua index c6ce907807..851141d985 100644 --- a/modules/commands/home.lua +++ b/modules/commands/home.lua @@ -8,16 +8,16 @@ local Global = require 'utils.global' --- @dep utils.global require 'config.expcore.command_general_parse' local homes = {} -Global.register(homes,function(tbl) +Global.register(homes, function(tbl) homes = tbl end) -local function teleport(player,position) +local function teleport(player, position) local surface = player.surface - local pos = surface.find_non_colliding_position('character',position,32,1) + local pos = surface.find_non_colliding_position('character', position, 32, 1) if not position then return false end if player.driving then player.driving = false end -- kicks a player out a vehicle if in one - player.teleport(pos,surface) + player.teleport(pos, surface) return true end @@ -30,22 +30,22 @@ end --- Teleports you to your home location -- @command home -Commands.new_command('home','Teleports you to your home location') -:register(function(player,raw) +Commands.new_command('home', 'Teleports you to your home location') +:register(function(player) local home = homes[player.index] if not home or not home[1] then return Commands.error{'expcom-home.no-home'} end local rtn = floor_pos(player.position) - teleport(player,home[1]) + teleport(player, home[1]) home[2] = rtn - Commands.print{'expcom-home.return-set',rtn.x,rtn.y} + Commands.print{'expcom-home.return-set', rtn.x, rtn.y} end) --- Sets your home location to your current position -- @command home-set -Commands.new_command('home-set','Sets your home location to your current position') -:register(function(player,raw) +Commands.new_command('home-set', 'Sets your home location to your current position') +:register(function(player) local home = homes[player.index] if not home then home = {} @@ -53,31 +53,31 @@ Commands.new_command('home-set','Sets your home location to your current positio end local pos = floor_pos(player.position) home[1] = pos - Commands.print{'expcom-home.home-set',pos.x,pos.y} + Commands.print{'expcom-home.home-set', pos.x, pos.y} end) --- Returns your current home location -- @command home-get -Commands.new_command('home-get','Returns your current home location') -:register(function(player,raw) +Commands.new_command('home-get', 'Returns your current home location') +:register(function(player) local home = homes[player.index] if not home or not home[1] then return Commands.error{'expcom-home.no-home'} end local pos = home[1] - Commands.print{'expcom-home.home-get',pos.x,pos.y} + Commands.print{'expcom-home.home-get', pos.x, pos.y} end) --- Teleports you to previous location -- @command return -Commands.new_command('return','Teleports you to previous location') -:register(function(player,raw) +Commands.new_command('return', 'Teleports you to previous location') +:register(function(player) local home = homes[player.index] if not home or not home[2] then return Commands.error{'expcom-home.no-return'} end local rtn = floor_pos(player.position) - teleport(player,home[2]) + teleport(player, home[2]) home[2] = rtn - Commands.print{'expcom-home.return-set',rtn.x,rtn.y} + Commands.print{'expcom-home.return-set', rtn.x, rtn.y} end) \ No newline at end of file diff --git a/modules/commands/interface.lua b/modules/commands/interface.lua index a826d2860f..a95d66be54 100644 --- a/modules/commands/interface.lua +++ b/modules/commands/interface.lua @@ -5,105 +5,112 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands local Global = require 'utils.global' --- @dep utils.global -local Common = require 'expcore.common' --- @dep expcore.common -- modules that are loaded into the interface env to be accessed local interface_modules = { - ['Game']='utils.game', - ['_C']=Common, - ['Commands']=Commands, - ['output']=Common.player_return, - ['Group']='expcore.permission_groups', - ['Roles']='expcore.roles', - ['Store']='expcore.store', - ['Gui']='expcore.gui', - ['Async']='expcore.async' + ['Commands'] = Commands, + ['output'] = _C.player_return, + ['Group'] = 'expcore.permission_groups', + ['Roles'] = 'expcore.roles', + ['Gui'] = 'expcore.gui', + ['Async'] = 'expcore.async', + ['Datastore'] = 'expcore.datastore', + ['External'] = 'expcore.external' } -- loads all the modules given in the above table -for key,value in pairs(interface_modules) do +for key, value in pairs(interface_modules) do if type(value) == 'string' then - interface_modules[key] = Common.opt_require(value) + interface_modules[key] = _C.opt_require(value) end end local interface_env = {} -- used as a persistent sandbox for interface commands local interface_callbacks = {} -- saves callbacks which can load new values per use -Global.register(interface_env,function(tbl) +Global.register(interface_env, function(tbl) interface_env = tbl end) ---- Adds a callback function when the interface command is used --- nb: returned value is saved in the env that the interface uses --- @tparam string name the name that the value is loaded under, cant use upvalues --- @tparam function callback the function that will run whent he command is used +--- Adds a static module that can be accessed with the interface +-- @tparam string name The name that the value is assigned to +-- @tparam any value The value that will be accessible in the interface env -- callback param - player: LuaPlayer - the player who used the command -local function add_interface_callback(name,callback) +local function add_interface_module(name, value) + interface_modules[name] = value +end + +--- Adds a dynamic value that is calculated when the interface is used +-- @tparam string name The name that the value is assigned to +-- @tparam function callback The function that will be called to get the value +local function add_interface_callback(name, callback) if type(callback) == 'function' then interface_callbacks[name] = callback end end --- this is a meta function for __index when self[key] is nil -local function get_index(self,key) +--- Internal, this is a meta function for __index when self[key] is nil +local function get_index(_, key) if interface_env[key] then return interface_env[key] elseif interface_modules[key] then return interface_modules[key] + elseif _G[key] then + return _G[key] end end ---- Sends an innovation to be ran and returns the result. +--- Sends an invocation to be ran and returns the result. -- @command interface --- @tparam string innovation the command that will be run -Commands.new_command('interface','Sends an innovation to be ran and returns the result.') -:add_param('innovation',false) +-- @tparam string invocation the command that will be run +Commands.new_command('interface', 'Sends an invocation to be ran and returns the result.') +:add_param('invocation', false) :enable_auto_concat() :set_flag('admin_only') -:register(function(player,innovation,raw) - if not innovation:find('%s') and not innovation:find('return') then - -- if there are no spaces and return is not present then return is appended to the start - innovation='return '..innovation +:register(function(player, invocation) + -- If the invocation has no white space then prepend return to it + if not invocation:find('%s') and not invocation:find('return') then + invocation = 'return '..invocation end - -- temp_env will index to interface_env and interface_modules if value not found - local temp_env = setmetatable({},{__index=get_index}) - if player then -- player can be nil when it is the server - for name,callback in pairs(interface_callbacks) do - -- loops over callbacks and loads the values returned - local success, rtn = pcall(callback,player) - temp_env[name]=rtn + + -- _env will be the new _ENV that the invocation will run inside of + local _env = setmetatable({}, { + __index = get_index, + __newindex = interface_env + }) + + -- If the command is ran by a player then load the dynamic values + if player then + for name, callback in pairs(interface_callbacks) do + local _, rtn = pcall(callback, player) + rawset(_env, name, rtn) end end - -- sets the global metatable to prevent new values being made - -- global will index to temp_env and new indexs saved to interface_sandbox - local old_mt = getmetatable(_G) - setmetatable(_G,{__index=temp_env,__newindex=interface_env}) - -- runs the innovation and returns values to the player - innovation = loadstring(innovation) - local success, rtn = pcall(innovation) - setmetatable(_G,old_mt) + + -- Compile the invocation with the custom _env value + local invocation_func, compile_error = load(invocation, 'interface', nil, _env) + if compile_error then return Commands.error(compile_error) end + + -- Run the invocation + local success, rtn = pcall(invocation_func) if not success then - if type(rtn) == 'string' then - -- there may be stack trace that must be removed to avoid desyncs - rtn = rtn:gsub('%.%.%..-/temp/currently%-playing','') - end - return Commands.error(rtn) - else - return Commands.success(rtn) + local err = rtn:gsub('%.%.%..-/temp/currently%-playing', '') + return Commands.error(err) end + return Commands.success(rtn) end) --- adds some basic callbacks for the interface -add_interface_callback('player',function(player) return player end) -add_interface_callback('surface',function(player) return player.surface end) -add_interface_callback('force',function(player) return player.force end) -add_interface_callback('position',function(player) return player.position end) -add_interface_callback('entity',function(player) return player.selected end) -add_interface_callback('tile',function(player) return player.surface.get_tile(player.position) end) +-- Adds some basic callbacks for the interface +add_interface_callback('player', function(player) return player end) +add_interface_callback('surface', function(player) return player.surface end) +add_interface_callback('force', function(player) return player.force end) +add_interface_callback('position', function(player) return player.position end) +add_interface_callback('entity', function(player) return player.selected end) +add_interface_callback('tile', function(player) return player.surface.get_tile(player.position) end) +-- Module Return return { - add_interface_callback=add_interface_callback, - interface_env=interface_env, - interface_callbacks=interface_callbacks, - clean_stack_trace=function(str) return str:gsub('%.%.%..-/temp/currently%-playing','') end + add_interface_module = add_interface_module, + add_interface_callback = add_interface_callback, + interface_env = interface_env, + clean_stack_trace = function(str) return str:gsub('%.%.%..-/temp/currently%-playing', '') end } \ No newline at end of file diff --git a/modules/commands/jail.lua b/modules/commands/jail.lua index 59e125005b..98941616d3 100644 --- a/modules/commands/jail.lua +++ b/modules/commands/jail.lua @@ -12,37 +12,37 @@ require 'config.expcore.command_role_parse' -- @command jail -- @tparam LuaPlayer player the player that will be jailed -- @tparam[opt] string reason the reason why the player is being jailed -Commands.new_command('jail','Puts a player into jail and removes all other roles.') -:add_param('player',false,'player-role') -:add_param('reason',true) +Commands.new_command('jail', 'Puts a player into jail and removes all other roles.') +:add_param('player', false, 'player-role') +:add_param('reason', true) :enable_auto_concat() -:register(function(player,action_player,reason,raw) +:register(function(player, action_player, reason) reason = reason or 'Non Given.' local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) local player_name = player and player.name or '' if Jail.jail_player(action_player, player_name, reason) then - game.print{'expcom-jail.give',action_player_name_color,by_player_name_color,reason} + game.print{'expcom-jail.give', action_player_name_color, by_player_name_color, reason} else - return Commands.error{'expcom-jail.already-jailed',action_player_name_color} + return Commands.error{'expcom-jail.already-jailed', action_player_name_color} end end) --- Removes a player from jail. -- @command unjail -- @tparam LuaPlayer the player that will be unjailed -Commands.new_command('unjail','Removes a player from jail.') -:add_param('player',false,'player-role') -:add_alias('clear-jail','remove-jail') +Commands.new_command('unjail', 'Removes a player from jail.') +:add_param('player', false, 'player-role') +:add_alias('clear-jail', 'remove-jail') :enable_auto_concat() -:register(function(player,action_player,raw) +:register(function(player, action_player) local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) local player_name = player and player.name or '' if Jail.unjail_player(action_player, player_name) then - game.print{'expcom-jail.remove',action_player_name_color,by_player_name_color} + game.print{'expcom-jail.remove', action_player_name_color, by_player_name_color} else - return Commands.error{'expcom-jail.not-jailed',action_player_name_color} + return Commands.error{'expcom-jail.not-jailed', action_player_name_color} end end) @@ -50,33 +50,33 @@ end) -- @command temp-ban -- @tparam LuaPlayer player the player that will be temp banned -- @tparam string reason the reason that the player is being temp banned -Commands.new_command('temp-ban','Temp bans a player until the next reset; this requires a reason; this will clear the players inventory.') -:add_param('player',false,'player-role') -:add_param('reason',false) +Commands.new_command('temp-ban', 'Temp bans a player until the next reset; this requires a reason; this will clear the players inventory.') +:add_param('player', false, 'player-role') +:add_param('reason', false) :enable_auto_concat() -:register(function(player,action_player,reason,raw) +:register(function(player, action_player, reason) local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) - if Jail.temp_ban_player(action_player,player.name,reason) then - game.print{'expcom-jail.temp-ban',action_player_name_color,by_player_name_color,reason} + if Jail.temp_ban_player(action_player, player.name, reason) then + game.print{'expcom-jail.temp-ban', action_player_name_color, by_player_name_color, reason} else - return Commands.error{'expcom-jail.already-banned',action_player_name_color} + return Commands.error{'expcom-jail.already-banned', action_player_name_color} end end) --- Removes temp ban from a player; this will not restore their items. -- @command clear-temp-ban -- @tparam LuaPlayer player the player to revoke the temp ban from -Commands.new_command('clear-temp-ban','Removes temp ban from a player; this will not restore their items.') -:add_param('player',false,'player-role') -:add_alias('untemp-ban','remove-temp-ban') +Commands.new_command('clear-temp-ban', 'Removes temp ban from a player; this will not restore their items.') +:add_param('player', false, 'player-role') +:add_alias('untemp-ban', 'remove-temp-ban') :enable_auto_concat() -:register(function(player,action_player,raw) +:register(function(player, action_player) local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) - if Jail.untemp_ban_player(action_player,player.name) then - game.print{'expcom-jail.temp-ban-clear',action_player_name_color,by_player_name_color} + if Jail.untemp_ban_player(action_player, player.name) then + game.print{'expcom-jail.temp-ban-clear', action_player_name_color, by_player_name_color} else - return Commands.error{'expcom-jail.not-temp-banned',action_player_name_color} + return Commands.error{'expcom-jail.not-temp-banned', action_player_name_color} end end) diff --git a/modules/commands/kill.lua b/modules/commands/kill.lua index 3fea3e9a4d..dad370b1f6 100644 --- a/modules/commands/kill.lua +++ b/modules/commands/kill.lua @@ -11,22 +11,22 @@ require 'config.expcore.command_role_parse' --- Kills yourself or another player. -- @command kill -- @tparam[opt=self] LuaPlayer player the player to kill, must be alive to be valid -Commands.new_command('kill','Kills yourself or another player.') -:add_param('player',true,'player-role-alive') +Commands.new_command('kill', 'Kills yourself or another player.') +:add_param('player', true, 'player-role-alive') :set_defaults{player=function(player) -- default is the player unless they are dead if player.character and player.character.health > 0 then return player end end} -:register(function(player,action_player,raw) +:register(function(player, action_player) if not action_player then -- can only be nil if no player given and the user is dead return Commands.error{'expcom-kill.already-dead'} end if player == action_player then action_player.character.die() - elseif Roles.player_allowed(player,'command/kill/always') then + elseif Roles.player_allowed(player, 'command/kill/always') then action_player.character.die() else return Commands.error{'expcore-commands.unauthorized'} diff --git a/modules/commands/me.lua b/modules/commands/me.lua index 9e6364e820..d13a71c97e 100644 --- a/modules/commands/me.lua +++ b/modules/commands/me.lua @@ -8,10 +8,10 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands --- Sends an action message in the chat -- @command me -- @tparam string action the action that follows your name in chat -Commands.new_command('me','Sends an action message in the chat') -:add_param('action',false) +Commands.new_command('me', 'Sends an action message in the chat') +:add_param('action', false) :enable_auto_concat() -:register(function(player,action,raw) +:register(function(player, action) local player_name = player and player.name or '' - game.print(string.format('* %s %s *',player_name,action),player.chat_color) + game.print(string.format('* %s %s *', player_name, action), player.chat_color) end) \ No newline at end of file diff --git a/modules/commands/rainbow.lua b/modules/commands/rainbow.lua index 350e0ae6be..58fa883635 100644 --- a/modules/commands/rainbow.lua +++ b/modules/commands/rainbow.lua @@ -6,27 +6,27 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands local format_chat_colour = _C.format_chat_colour --- @dep expcore.common -local function step_component(c1,c2) +local function step_component(c1, c2) if c1 < 0 then - return 0,c2+c1 + return 0, c2+c1 elseif c1 > 1 then - return 1,c2-c1+1 + return 1, c2-c1+1 else - return c1,c2 + return c1, c2 end end local function step_color(color) - color.r,color.g = step_component(color.r,color.g) - color.g,color.b = step_component(color.g,color.b) - color.b,color.r = step_component(color.b,color.r) - color.r = step_component(color.r,0) + color.r, color.g = step_component(color.r, color.g) + color.g, color.b = step_component(color.g, color.b) + color.b, color.r = step_component(color.b, color.r) + color.r = step_component(color.r, 0) return color end -local function next_color(color,step) +local function next_color(color, step) step = step or 0.1 - local new_color = {r=0,g=0,b=0} + local new_color = {r=0, g=0, b=0} if color.b == 0 and color.r ~= 0 then new_color.r = color.r-step new_color.g = color.g+step @@ -43,19 +43,19 @@ end --- Sends an rainbow message in the chat -- @command rainbow -- @tparam string message the message that will be printed in chat -Commands.new_command('rainbow','Sends an rainbow message in the chat') -:add_param('message',false) +Commands.new_command('rainbow', 'Sends an rainbow message in the chat') +:add_param('message', false) :enable_auto_concat() -:register(function(player,message,raw) +:register(function(player, message) local player_name = player and player.name or '' local player_color = player and player.color or nil local color_step = 3/message:len() if color_step > 1 then color_step = 1 end - local current_color = {r=1,g=0,b=0} - local output = format_chat_colour(player_name..': ',player_color) - output = output..message:gsub('%S',function(letter) - local rtn = format_chat_colour(letter,current_color) - current_color = next_color(current_color,color_step) + local current_color = {r=1, g=0, b=0} + local output = format_chat_colour(player_name..': ', player_color) + output = output..message:gsub('%S', function(letter) + local rtn = format_chat_colour(letter, current_color) + current_color = next_color(current_color, color_step) return rtn end) game.print(output) diff --git a/modules/commands/ratio.lua b/modules/commands/ratio.lua index dcdcb1169a..51737d0ec9 100644 --- a/modules/commands/ratio.lua +++ b/modules/commands/ratio.lua @@ -2,33 +2,46 @@ local Commands = require 'expcore.commands' +local function Modules(moduleInventory) -- returns the multiplier of the modules + local effect1 = moduleInventory.get_item_count("productivity-module") -- type 1 + local effect2 = moduleInventory.get_item_count("productivity-module-2")-- type 2 + local effect3 = moduleInventory.get_item_count("productivity-module-3") -- type 3 -Commands.new_command('ratio','This command will give the input and ouput ratios of the selected machine. Use the parameter for calcualting the machines needed for that amount of items per second.') - :add_param('itemsPerSecond',true,'number') - :register(function(player,itemsPerSecond,raw) - + local multi = effect1*4+effect2*6+effect3*10 + return multi/100+1 +end + +local function AmountOfMachines(itemsPerSecond, output) + if(itemsPerSecond) then + return itemsPerSecond/output + end +end + +Commands.new_command('ratio', 'This command will give the input and output ratios of the selected machine. Use the parameter for calculating the machines needed for that amount of items per second.') + :add_param('itemsPerSecond', true, 'number') + :register(function(player, itemsPerSecond) local machine = player.selected -- selected machine if not machine then --nil check return Commands.error{'expcom-ratio.notSelecting'} end - + if machine.type ~= "assembling-machine" and machine.type ~= "furnace" then return Commands.error{'expcom-ratio.notSelecting'} end - local recpie = machine.get_recipe() -- recpie + local recipe = machine.get_recipe() -- recipe - if not recpie then --nil check + if not recipe then --nil check return Commands.error{'expcom-ratio.notSelecting'} end - local items = recpie.ingredients -- items in that recpie - local product = recpie.products -- output items + local items = recipe.ingredients -- items in that recipe + local products = recipe.products -- output items local amountOfMachines - local moduleInvetory = machine.get_module_inventory()--the module Invetory of the machine - local mult = Modules(moduleInvetory) --function for the productivety moduals + local moduleInventory = machine.get_module_inventory()--the module Inventory of the machine + local multi = Modules(moduleInventory) --function for the productively modals if itemsPerSecond then - amountOfMachines = math.ceil( AmountOfMachines(itemsPerSecond,1/recpie.energy*machine.crafting_speed*product[1].amount*mult)) -- amount of machines + amountOfMachines = math.ceil( AmountOfMachines(itemsPerSecond, 1/recipe.energy*machine.crafting_speed*products[1].amount*multi)) -- amount of machines end if not amountOfMachines then amountOfMachines = 1 --set to 1 to make it not nil @@ -42,14 +55,13 @@ Commands.new_command('ratio','This command will give the input and ouput ratios else sprite = 'expcom-ratio.fluid-in' end - - - local ips = item.amount/recpie.energy*machine.crafting_speed*amountOfMachines --math on the items/fluids per second - Commands.print {sprite,math.round(ips,3),item.name}-- full string + + local ips = item.amount/recipe.energy*machine.crafting_speed*amountOfMachines --math on the items/fluids per second + Commands.print {sprite, math.round(ips, 3), item.name}-- full string end ----------------------------products---------------------------- - - for i, product in ipairs(product) do + + for i, product in ipairs(products) do local sprite -- string to make the icon work either fluid ore item if product.type == "item" then @@ -58,28 +70,13 @@ Commands.new_command('ratio','This command will give the input and ouput ratios sprite = 'expcom-ratio.fluid-out' end - local output = 1/recpie.energy*machine.crafting_speed*product.amount*mult --math on the outputs per second - Commands.print {sprite,math.round(output*amountOfMachines,3),product.name} -- full string + local output = 1/recipe.energy*machine.crafting_speed*product.amount*multi --math on the outputs per second + Commands.print {sprite, math.round(output*amountOfMachines, 3), product.name} -- full string end if amountOfMachines ~= 1 then - Commands.print{'expcom-ratio.machines',amountOfMachines} + Commands.print{'expcom-ratio.machines', amountOfMachines} end - end) -function Modules(moduleInvetory) -- returns the multeplier of the modules - local effect1 = moduleInvetory.get_item_count("productivity-module") -- type 1 - local effect2 = moduleInvetory.get_item_count("productivity-module-2")-- type 2 - local effect3 = moduleInvetory.get_item_count("productivity-module-3") -- type 3 - - local mult = effect1*4+effect2*6+effect3*10 - return mult/100+1 -end - -function AmountOfMachines(itemsPerSecond,output) - if(itemsPerSecond) then - return itemsPerSecond/output - - end -end + end) \ No newline at end of file diff --git a/modules/commands/repair.lua b/modules/commands/repair.lua index f7ff434c09..c8814f3d8d 100644 --- a/modules/commands/repair.lua +++ b/modules/commands/repair.lua @@ -11,18 +11,18 @@ local max_time_to_live = 4294967295 -- unit32 max --- Repairs entities on your force around you -- @command repair -- @tparam number range the range to repair stuff in, there is a max limit to this -Commands.new_command('repair','Repairs entities on your force around you') -:add_param('range',false,'integer-range',1,config.max_range) -:register(function(player,range,raw) +Commands.new_command('repair', 'Repairs entities on your force around you') +:add_param('range', false, 'integer-range', 1,config.max_range) +:register(function(player, range) local revive_count = 0 local heal_count = 0 local range2 = range^2 local surface = player.surface local center = player.position - local area = {{x=center.x-range,y=center.y-range},{x=center.x+range,y=center.y+range}} + local area = {{x=center.x-range, y=center.y-range}, {x=center.x+range, y=center.y+range}} if config.allow_ghost_revive then - local ghosts = surface.find_entities_filtered({area=area,type='entity-ghost',force=player.force}) - for _,ghost in pairs(ghosts) do + local ghosts = surface.find_entities_filtered({area=area, type='entity-ghost', force=player.force}) + for _, ghost in pairs(ghosts) do if ghost.valid then local x = ghost.position.x-center.x local y = ghost.position.y-center.y @@ -36,8 +36,8 @@ Commands.new_command('repair','Repairs entities on your force around you') end end if config.allow_heal_entities then - local entities = surface.find_entities_filtered({area=area,force=player.force}) - for _,entity in pairs(entities) do + local entities = surface.find_entities_filtered({area=area, force=player.force}) + for _, entity in pairs(entities) do if entity.valid then local x = entity.position.x-center.x local y = entity.position.y-center.y @@ -48,5 +48,5 @@ Commands.new_command('repair','Repairs entities on your force around you') end end end - return Commands.success{'expcom-repair.result',revive_count,heal_count} + return Commands.success{'expcom-repair.result', revive_count, heal_count} end) \ No newline at end of file diff --git a/modules/commands/reports.lua b/modules/commands/reports.lua index 93ab600872..00aff1b291 100644 --- a/modules/commands/reports.lua +++ b/modules/commands/reports.lua @@ -13,25 +13,25 @@ require 'config.expcore.command_general_parse' -- @command report -- @tparam LuaPlayer player the player to report, some players are immune -- @tparam string reason the reason the player is being reported -Commands.new_command('report','Reports a player and notifies moderators') -:add_param('player',false,function(input,player,reject) - input = Commands.parse('player',input,player,reject) +Commands.new_command('report', 'Reports a player and notifies moderators') +:add_param('player', false, function(input, player, reject) + input = Commands.parse('player', input, player, reject) if not input then return end - if Roles.player_has_flag(input,'report-immune') then + if Roles.player_has_flag(input, 'report-immune') then return reject{'expcom-report.player-immune'} else return input end end) -:add_param('reason',false) +:add_param('reason', false) :add_alias('report-player') :enable_auto_concat() -:register(function(player,action_player,reason,raw) +:register(function(player, action_player, reason) local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) - if Reports.report_player(action_player,player.name,reason) then - game.print{'expcom-report.non-admin',action_player_name_color,reason} - Roles.print_to_roles_higher('Trainee',{'expcom-report.admin',action_player_name_color,by_player_name_color,reason}) + if Reports.report_player(action_player, player.name, reason) then + game.print{'expcom-report.non-admin', action_player_name_color, reason} + Roles.print_to_roles_higher('Trainee', {'expcom-report.admin', action_player_name_color, by_player_name_color, reason}) else return Commands.error{'expcom-report.already-reported'} end @@ -40,25 +40,25 @@ end) --- Gets a list of all reports that a player has on them. If no player then lists all players and the number of reports on them. -- @command get-reports -- @tparam LuaPlayer player the player to get the report for -Commands.new_command('get-reports','Gets a list of all reports that a player has on them. If no player then lists all players and the number of reports on them.') -:add_param('player',true,'player') -:add_alias('reports','list-reports') -:register(function(player,action_player,raw) - if action_player then - local reports = Reports.get_reports(action_player) - local action_player_name_color = format_chat_player_name(action_player) - Commands.print{'expcom-report.player-report-title',action_player_name_color} - for player_name,reason in pairs(reports) do +Commands.new_command('get-reports', 'Gets a list of all reports that a player has on them. If no player then lists all players and the number of reports on them.') +:add_param('player', true, 'player') +:add_alias('reports', 'list-reports') +:register(function(_, player) + if player then + local reports = Reports.get_reports(player) + local player_name_color = format_chat_player_name(player) + Commands.print{'expcom-report.player-report-title', player_name_color} + for player_name, reason in pairs(reports) do local by_player_name_color = format_chat_player_name(player_name) - Commands.print{'expcom-report.list',by_player_name_color,reason} + Commands.print{'expcom-report.list', by_player_name_color, reason} end else local user_reports = Reports.user_reports Commands.print{'expcom-report.player-count-title'} - for player_name,reports in pairs(user_reports) do + for player_name in pairs(user_reports) do local player_name_color = format_chat_player_name(player_name) local report_count = Reports.count_reports(player_name) - Commands.print{'expcom-report.list',player_name_color,report_count} + Commands.print{'expcom-report.list', player_name_color, report_count} end end end) @@ -67,20 +67,20 @@ end) -- @command clear-reports -- @tparam LuaPlayer player the player to clear the report(s) from -- @tparam[opt=all] LuaPlayer from-player remove only the report made by this player -Commands.new_command('clear-reports','Clears all reports from a player or just the report from one player.') -:add_param('player',false,'player') -:add_param('from-player',true,'player') -:register(function(player,action_player,from_player,raw) +Commands.new_command('clear-reports', 'Clears all reports from a player or just the report from one player.') +:add_param('player', false, 'player') +:add_param('from-player', true, 'player') +:register(function(player, action_player, from_player) if from_player then - if not Reports.remove_report(action_player,from_player.name,player.name) then + if not Reports.remove_report(action_player, from_player.name, player.name) then return Commands.error{'expcom-report.not-reported'} end else - if not Reports.remove_all(action_player,player.name) then + if not Reports.remove_all(action_player, player.name) then return Commands.error{'expcom-report.not-reported'} end end local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) - game.print{'expcom-report.removed',action_player_name_color,by_player_name_color} + game.print{'expcom-report.removed', action_player_name_color, by_player_name_color} end) \ No newline at end of file diff --git a/modules/commands/roles.lua b/modules/commands/roles.lua index 1005b322a9..20bd93d419 100644 --- a/modules/commands/roles.lua +++ b/modules/commands/roles.lua @@ -12,15 +12,15 @@ local format_chat_player_name, format_chat_colour_localized = _C.format_chat_pla -- @command assign-role -- @tparam LuaPlayer player the player to assign the role to -- @tparam string role the name of the role to assign to the player, supports auto complete after enter -Commands.new_command('assign-role','Assigns a role to a player') -:add_param('player',false,'player-role') -:add_param('role',false,'role') +Commands.new_command('assign-role', 'Assigns a role to a player') +:add_param('player', false, 'player-role') +:add_param('role', false, 'role') :set_flag('admin-only') -:add_alias('rpromote','assign','role','add-role') -:register(function(player,action_player,role,raw) +:add_alias('rpromote', 'assign', 'role', 'add-role') +:register(function(player, action_player, role) local player_highest = Roles.get_player_highest_role(player) if player_highest.index < role.index then - Roles.assign_player(action_player,role,player.name) + Roles.assign_player(action_player, role, player.name) else return Commands.error{'expcom-roles.higher-role'} end @@ -30,15 +30,15 @@ end) -- @command unassign-role -- @tparam LuaPlayer player the player to unassign the role from -- @tparam string role the name of the role to unassign from the player, supports auto complete after enter -Commands.new_command('unassign-role','Unassigns a role from a player') -:add_param('player',false,'player-role') -:add_param('role',false,'role') +Commands.new_command('unassign-role', 'Unassigns a role from a player') +:add_param('player', false, 'player-role') +:add_param('role', false, 'role') :set_flag('admin-only') -:add_alias('rdemote','unassign','rerole','remove-role') -:register(function(player,action_player,role,raw) +:add_alias('rdemote', 'unassign', 'rerole', 'remove-role') +:register(function(player, action_player, role) local player_highest = Roles.get_player_highest_role(player) if player_highest.index < role.index then - Roles.unassign_player(action_player,role,player.name) + Roles.unassign_player(action_player, role, player.name) else return Commands.error{'expcom-roles.higher-role'} end @@ -47,27 +47,27 @@ end) --- Lists all roles in they correct order -- @command list-roles -- @tparam[opt=all] LuaPlayer player list only the roles which this player has -Commands.new_command('list-roles','Lists all roles in they correct order') -:add_param('player',true,'player') -:add_alias('lsroles','roles') -:register(function(player,action_player,raw) +Commands.new_command('list-roles', 'Lists all roles in they correct order') +:add_param('player', true, 'player') +:add_alias('lsroles', 'roles') +:register(function(_, player) local roles = Roles.config.order local message = {'expcom-roles.list'} - if action_player then - roles = Roles.get_player_roles(action_player) + if player then + roles = Roles.get_player_roles(player) end - for index,role in pairs(roles) do + for index, role in pairs(roles) do role = Roles.get_role_from_any(role) local colour = role.custom_color or Colours.white - local role_name = format_chat_colour_localized(role.name,colour) + local role_name = format_chat_colour_localized(role.name, colour) if index == 1 then - message = {'expcom-roles.list',role_name} - if action_player then - local player_name_colour = format_chat_player_name(action_player) - message = {'expcom-roles.list-player',player_name_colour,role_name} + message = {'expcom-roles.list', role_name} + if player then + local player_name_colour = format_chat_player_name(player) + message = {'expcom-roles.list-player', player_name_colour, role_name} end else - message = {'expcom-roles.list-element',message,role_name} + message = {'expcom-roles.list-element', message, role_name} end end return Commands.success(message) diff --git a/modules/commands/spawn.lua b/modules/commands/spawn.lua index 0e8e7df7db..bc718ea366 100644 --- a/modules/commands/spawn.lua +++ b/modules/commands/spawn.lua @@ -9,18 +9,18 @@ local Roles = require 'expcore.roles' --- @dep expcore.roles local function teleport(player) local surface = player.surface local spawn = player.force.get_spawn_position(surface) - local position = surface.find_non_colliding_position('character',spawn,32,1) + local position = surface.find_non_colliding_position('character', spawn, 32, 1) if not position then return false end if player.driving then player.driving = false end -- kicks a player out a vehicle if in one - player.teleport(position,surface) + player.teleport(position, surface) return true end --- Teleport to spawn -- @command go-to-spawn -- @tparam[opt=self] LuaPlayer player the player to teleport to their spawn point -Commands.new_command('go-to-spawn','Teleport to spawn') -:add_param('player',true,'player-role-alive') +Commands.new_command('go-to-spawn', 'Teleport to spawn') +:add_param('player', true, 'player-role-alive') :set_defaults{ player=function(player) if player.connected and player.character and player.character.health > 0 then @@ -28,15 +28,15 @@ Commands.new_command('go-to-spawn','Teleport to spawn') end end } -:add_alias('spawn','tp-spawn') -:register(function(player,action_player) - if not action_player then +:add_alias('spawn', 'tp-spawn') +:register(function(player, action_player) + if not action_player then return Commands.error{'expcom-spawn.unavailable'} elseif action_player == player then if not teleport(player) then return Commands.error{'expcom-spawn.unavailable'} end - elseif Roles.player_allowed(player,'command/go-to-spawn/always') then + elseif Roles.player_allowed(player, 'command/go-to-spawn/always') then if not teleport(action_player) then return Commands.error{'expcom-spawn.unavailable'} end diff --git a/modules/commands/teleport.lua b/modules/commands/teleport.lua index 5e8ea3b4da..fb6fbb68c8 100644 --- a/modules/commands/teleport.lua +++ b/modules/commands/teleport.lua @@ -6,12 +6,12 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands require 'config.expcore.command_general_parse' -local function teleport(from_player,to_player) +local function teleport(from_player, to_player) local surface = to_player.surface - local position = surface.find_non_colliding_position('character',to_player.position,32,1) + local position = surface.find_non_colliding_position('character', to_player.position, 32, 1) if not position then return false end -- return false if no new position if from_player.driving then from_player.driving = false end -- kicks a player out a vehicle if in one - from_player.teleport(position,surface) + from_player.teleport(position, surface) return true end @@ -19,17 +19,17 @@ end -- @command teleport -- @tparam LuaPlayer from_player the player that will be teleported, must be alive -- @tparam LuaPlayer to_player the player to teleport to, must be online (if dead goes to where they died) -Commands.new_command('teleport','Teleports a player to another player.') -:add_param('from_player',false,'player-alive') -:add_param('to_player',false,'player-online') +Commands.new_command('teleport', 'Teleports a player to another player.') +:add_param('from_player', false, 'player-alive') +:add_param('to_player', false, 'player-online') :add_alias('tp') :set_flag('admin_only') -:register(function(player,from_player,to_player,raw) +:register(function(_, from_player, to_player) if from_player.index == to_player.index then -- return if attempting to teleport to self return Commands.error{'expcom-tp.to-self'} end - if not teleport(from_player,to_player) then + if not teleport(from_player, to_player) then -- return if the teleport failed return Commands.error{'expcom-tp.no-position-found'} end @@ -38,15 +38,15 @@ end) --- Teleports a player to you. -- @command bring -- @tparam LuaPlayer player the player that will be teleported, must be alive -Commands.new_command('bring','Teleports a player to you.') -:add_param('player',false,'player-alive') +Commands.new_command('bring', 'Teleports a player to you.') +:add_param('player', false, 'player-alive') :set_flag('admin_only') -:register(function(player,from_player,raw) +:register(function(player, from_player) if from_player.index == player.index then -- return if attempting to teleport to self return Commands.error{'expcom-tp.to-self'} end - if not teleport(from_player,player) then + if not teleport(from_player, player) then -- return if the teleport failed return Commands.error{'expcom-tp.no-position-found'} end @@ -55,16 +55,16 @@ end) --- Teleports you to a player. -- @command goto -- @tparam LuaPlayer player the player to teleport to, must be online (if dead goes to where they died) -Commands.new_command('goto','Teleports you to a player.') -:add_param('player',false,'player-online') -:add_alias('tp-me','tpme') +Commands.new_command('goto', 'Teleports you to a player.') +:add_param('player', false, 'player-online') +:add_alias('tp-me', 'tpme') :set_flag('admin_only') -:register(function(player,to_player,raw) +:register(function(player, to_player) if to_player.index == player.index then -- return if attempting to teleport to self return Commands.error{'expcom-tp.to-self'} end - if not teleport(player,to_player) then + if not teleport(player, to_player) then -- return if the teleport failed return Commands.error{'expcom-tp.no-position-found'} end diff --git a/modules/commands/warnings.lua b/modules/commands/warnings.lua index 42f7b8685a..ccd4d6a017 100644 --- a/modules/commands/warnings.lua +++ b/modules/commands/warnings.lua @@ -13,47 +13,49 @@ require 'config.expcore.command_role_parse' -- @command give-warning -- @tparam LuaPlayer player the player the will recive a warning -- @tparam string reason the reason the player is being given a warning -Commands.new_command('give-warning','Gives a warning to a player; may lead to automatic script action.') -:add_param('player',false,'player-role') -:add_param('reason',false) +Commands.new_command('give-warning', 'Gives a warning to a player; may lead to automatic script action.') +:add_param('player', false, 'player-role') +:add_param('reason', false) :add_alias('warn') :enable_auto_concat() -:register(function(player,action_player,reason,raw) - Warnings.add_warning(action_player,player.name,reason) +:register(function(player, action_player, reason) + Warnings.add_warning(action_player, player.name, reason) local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) - game.print{'expcom-warnings.received',action_player_name_color,by_player_name_color,reason} + game.print{'expcom-warnings.received', action_player_name_color, by_player_name_color, reason} end) --- Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have. -- @command get-warnings -- @tparam[opt=list] LuaPlayer player the player to get the warning for, if nil all players are listed -Commands.new_command('get-warnings','Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have.') -:add_param('player',true,'player') -:add_alias('warnings','list-warnings') -:register(function(player,action_player,raw) - if action_player then - local warnings = Warnings.get_warnings(action_player) - local script_warnings = Warnings.get_script_warnings(action_player) - local action_player_name_color = format_chat_player_name(action_player) - Commands.print{'expcom-warnings.player',action_player_name_color,warnings,script_warnings,config.temp_warning_limit} +Commands.new_command('get-warnings', 'Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have.') +:add_param('player', true, 'player') +:add_alias('warnings', 'list-warnings') +:register(function(_, player) + if player then + local warnings = Warnings.get_warnings(player) + local script_warnings = Warnings.get_script_warnings(player) + local player_name_color = format_chat_player_name(player) + Commands.print{'expcom-warnings.player', player_name_color, #warnings, #script_warnings, config.temp_warning_limit} + for _, warning in ipairs(warnings) do + Commands.print{'expcom-warnings.player-detail', format_chat_player_name(warning.by_player_name), warning.reason} + end else local rtn = {} - local user_warnings = Warnings.user_warnings local user_script_warnings = Warnings.user_script_warnings - for player_name,warnings in pairs(user_warnings) do - rtn[player_name] = {#warnings,0} + for player_name, warnings in pairs(Warnings.user_warnings:get_all()) do + rtn[player_name] = {#warnings, 0} end - for player_name,warnings in pairs(user_script_warnings) do + for player_name, warnings in pairs(user_script_warnings) do if not rtn[player_name] then - rtn[player_name] = {0,0} + rtn[player_name] = {0, 0} end rtn[player_name][2] = #warnings end - Commands.print{'expcom-warnings.list-tilte'} - for player_name,warnings in pairs(rtn) do + Commands.print{'expcom-warnings.list-title'} + for player_name, warnings in pairs(rtn) do local player_name_color = format_chat_player_name(player_name) - Commands.print{'expcom-warnings.list',player_name_color,warnings[1],warnings[2],config.temp_warning_limit} + Commands.print{'expcom-warnings.list', player_name_color, warnings[1], warnings[2], config.temp_warning_limit} end end end) @@ -61,12 +63,12 @@ end) --- Clears all warnings (and script warnings) from a player -- @command clear-warnings -- @tparam LuaPlayer player the player to clear the warnings from -Commands.new_command('clear-warnings','Clears all warnings (and script warnings) from a player') -:add_param('player',false,'player') -:register(function(player,action_player,raw) - Warnings.clear_warnings(action_player,player.name) - Warnings.clear_script_warnings(action_player,player.name) +Commands.new_command('clear-warnings', 'Clears all warnings (and script warnings) from a player') +:add_param('player', false, 'player') +:register(function(player, action_player) + Warnings.clear_warnings(action_player, player.name) + Warnings.clear_script_warnings(action_player, player.name) local action_player_name_color = format_chat_player_name(action_player) local by_player_name_color = format_chat_player_name(player) - game.print{'expcom-warnings.cleared',action_player_name_color,by_player_name_color} + game.print{'expcom-warnings.cleared', action_player_name_color, by_player_name_color} end) \ No newline at end of file diff --git a/modules/control/jail.lua b/modules/control/jail.lua index a188d9840f..df46f9ceac 100644 --- a/modules/control/jail.lua +++ b/modules/control/jail.lua @@ -9,15 +9,15 @@ -- This will move 'MrBiter' to the jail role and remove all other roles from them -- the player name and reason are only so they can be included in the event for user feedback - Jail.jail_player('MrBiter','Cooldude2606','Likes biters too much') + Jail.jail_player('MrBiter', 'Cooldude2606', 'Likes biters too much') -- This will give 'MrBiter' all his roles back and remove him from jail -- again as above the player name is only used in the event for user feedback - Jail.unjail_player('MrBiter','Cooldude2606') + Jail.unjail_player('MrBiter', 'Cooldude2606') -- Temp ban works the same as jail but will store the reason and move the players items to spawn -- this is meant to be used as a more permiment jail but not as strong as a ban - Jail.temp_ban_player('MrBiter','Cooldude2606','Likes biters too much') + Jail.temp_ban_player('MrBiter', 'Cooldude2606', 'Likes biters too much') ]] local Roles = require 'expcore.roles' --- @dep expcore.roles @@ -65,7 +65,7 @@ local temp_bans = Jail.temp_bans Global.register({ old_roles = old_roles, temp_bans = temp_bans -},function(tbl) +}, function(tbl) Jail.old_roles = tbl.old_roles Jail.temp_bans = tbl.temp_bans old_roles = Jail.old_roles @@ -77,8 +77,8 @@ end) -- @tparam LuaPlayer player the player who is being acted on -- @tparam string by_player_name the player who is doing the action -- @tparam string reason the reason for the action (jail and tempban only) -local function event_emit(event,player,by_player_name,reason) - script.raise_event(event,{ +local function event_emit(event, player, by_player_name, reason) + script.raise_event(event, { name=event, tick=game.tick, player_index=player.index, @@ -95,7 +95,7 @@ end -- @tparam LuaPlayer player the player to check if they are in jail -- @treturn boolean whether the player is currently in jail function Jail.is_jailed(player) - return has_role(player,'Jail') + return has_role(player, 'Jail') end --- Moves a player to jail and removes all other roles @@ -103,14 +103,14 @@ end -- @tparam string by_player_name the name of the player who is doing the jailing -- @tparam[opt='Non given.'] string reason the reason that the player is being jailed -- @treturn boolean wheather the user was jailed successfully -function Jail.jail_player(player,by_player_name,reason) +function Jail.jail_player(player, by_player_name, reason) player = valid_player(player) if not player then return end if not by_player_name then return end reason = reason or 'Non given.' - if has_role(player,'Jail') then return end + if has_role(player, 'Jail') then return end local roles = get_roles(player) old_roles[player.name] = roles @@ -126,12 +126,12 @@ end -- @tparam LuaPlayer player the player that will be unjailed -- @tparam string by_player_name the name of the player that is doing the unjail -- @treturn boolean whether the player was unjailed successfully -function Jail.unjail_player(player,by_player_name) +function Jail.unjail_player(player, by_player_name) player = valid_player(player) if not player then return end if not by_player_name then return end - if not has_role(player,'Jail') then return end + if not has_role(player, 'Jail') then return end local roles = old_roles[player.name] or {} assign_roles(player, roles, by_player_name, nil, true) @@ -160,7 +160,7 @@ end -- @tparam string by_player_name the name of the player who is doing the temp ban -- @tparam[opt='Non given.'] string reason the reason that the player is being temp banned -- @treturn boolean whether the player was successfully temp banned -function Jail.temp_ban_player(player,by_player_name,reason) +function Jail.temp_ban_player(player, by_player_name, reason) player = valid_player(player) if not player then return end if not by_player_name then return end @@ -168,9 +168,9 @@ function Jail.temp_ban_player(player,by_player_name,reason) reason = reason or 'Non given.' if temp_bans[player.name] then return end - temp_bans[player.name] = {reason,by_player_name} + temp_bans[player.name] = {reason, by_player_name} - if not has_role(player,'Jail') then + if not has_role(player, 'Jail') then local roles = get_roles(player) old_roles[player.name] = roles @@ -182,7 +182,7 @@ function Jail.temp_ban_player(player,by_player_name,reason) move_items(inv.get_contents()) inv.clear() - event_emit(Jail.events.on_player_temp_banned,player,by_player_name,reason) + event_emit(Jail.events.on_player_temp_banned, player, by_player_name, reason) return true end @@ -191,7 +191,7 @@ end -- @tparam LuaPlayer player the player who is being removed from temp ban -- @tparam string by_player_name the name of the player who is doing the untemp ban -- @treturn boolean whether the player was successfully removed -function Jail.untemp_ban_player(player,by_player_name) +function Jail.untemp_ban_player(player, by_player_name) player = valid_player(player) if not player then return end if not by_player_name then return end @@ -199,14 +199,14 @@ function Jail.untemp_ban_player(player,by_player_name) if not temp_bans[player.name] then return end temp_bans[player.name] = nil - if has_role(player,'Jail') then + if has_role(player, 'Jail') then local roles = old_roles[player.name] assign_roles(player, roles, by_player_name, nil, true) unassign_roles(player, 'Jail', by_player_name, nil, true) end - event_emit(Jail.events.on_player_untemp_banned,player,by_player_name) + event_emit(Jail.events.on_player_untemp_banned, player, by_player_name) return true end diff --git a/modules/control/production.lua b/modules/control/production.lua index 2c7fced8fa..e11bfd6b2f 100644 --- a/modules/control/production.lua +++ b/modules/control/production.lua @@ -14,21 +14,21 @@ -- The get production function is used to get production, consumion and net -- it may be used for any item and with any precision level, use total for total - Production.get_production(game.forces.player,'iron-plate',defines.flow_precision_index.one_minute) + Production.get_production(game.forces.player, 'iron-plate', defines.flow_precision_index.one_minute) -- The fluctuations works by compearing recent production with the average over time -- again any precision may be used, apart from one_thousand_hours as there would be no valid average - Production.get_fluctuations(game.forces.player,'iron-plate',defines.flow_precision_index.one_minute) + Production.get_fluctuations(game.forces.player, 'iron-plate', defines.flow_precision_index.one_minute) -- ETA is calculated based on what function you use but all share a similar method -- for production eta it will take current production average given by the precision -- and work out how many ticks it will require to make the required amount (1000 by default) - Production.get_production_eta(game.forces.player,'iron-plate',defines.flow_precision_index.one_minute,250000) + Production.get_production_eta(game.forces.player, 'iron-plate', defines.flow_precision_index.one_minute, 250000) -- Both get_color and format_number are helper functions to help format production stats - -- get_color will return green,orange,red,or grey based on the active_value - -- the passive_value is used when active_value is 0 and can only return orange,red,or grey - Production.get_color(clamp,active_value,passive_value) + -- get_color will return green, orange, red, or grey based on the active_value + -- the passive_value is used when active_value is 0 and can only return orange, red, or grey + Production.get_color(clamp, active_value, passive_value) ]] @@ -47,13 +47,13 @@ local Production = {} -- @treturn[1] defines.flow_precision_index the next precision value -- @treturn[1] number the multiplicive difference between the values function Production.precision_up(precision) - if precision == precision_index.one_second then return precision_index.one_minute,60 - elseif precision == precision_index.one_minute then return precision_index.ten_minutes,10 - elseif precision == precision_index.ten_minutes then return precision_index.one_hour,6 - elseif precision == precision_index.one_hour then return precision_index.ten_hours,10 - elseif precision == precision_index.ten_hours then return precision_index.fifty_hours,5 - elseif precision == precision_index.fifty_hours then return precision_index.two_hundred_fifty_hours,5 - elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.one_thousand_hours,4 + if precision == precision_index.one_second then return precision_index.one_minute, 60 + elseif precision == precision_index.one_minute then return precision_index.ten_minutes, 10 + elseif precision == precision_index.ten_minutes then return precision_index.one_hour, 6 + elseif precision == precision_index.one_hour then return precision_index.ten_hours, 10 + elseif precision == precision_index.ten_hours then return precision_index.fifty_hours, 5 + elseif precision == precision_index.fifty_hours then return precision_index.two_hundred_fifty_hours, 5 + elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.one_thousand_hours, 4 end end @@ -62,13 +62,13 @@ end -- @treturn[1] defines.flow_precision_index the next precision value -- @treturn[1] number the multiplicive difference between the values function Production.precision_down(precision) - if precision == precision_index.one_minute then return precision_index.one_second,60 - elseif precision == precision_index.ten_minutes then return precision_index.one_minute,10 - elseif precision == precision_index.one_hour then return precision_index.ten_minutes,6 - elseif precision == precision_index.ten_hours then return precision_index.one_hour,10 - elseif precision == precision_index.fifty_hours then return precision_index.ten_hours,5 - elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.fifty_hours,5 - elseif precision == precision_index.one_thousand_hours then return precision_index.two_hundred_fifty_hours,4 + if precision == precision_index.one_minute then return precision_index.one_second, 60 + elseif precision == precision_index.ten_minutes then return precision_index.one_minute, 10 + elseif precision == precision_index.one_hour then return precision_index.ten_minutes, 6 + elseif precision == precision_index.ten_hours then return precision_index.one_hour, 10 + elseif precision == precision_index.fifty_hours then return precision_index.ten_hours, 5 + elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.fifty_hours, 5 + elseif precision == precision_index.one_thousand_hours then return precision_index.two_hundred_fifty_hours, 4 end end @@ -95,7 +95,7 @@ end -- @tparam LuaForce force the force to get the data for -- @tparam string item_name the name of the item that you want the data about -- @treturn table contains total made, used and net -function Production.get_production_total(force,item_name) +function Production.get_production_total(force, item_name) local stats = force.item_production_statistics local made = stats.get_input_count(item_name) or 0 local used = stats.get_output_count(item_name) or 0 @@ -113,10 +113,10 @@ end -- @tparam string item_name the name of the item that you want the data about -- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @treturn table contains made, used and net -function Production.get_production(force,item_name,precision) +function Production.get_production(force, item_name, precision) local stats = force.item_production_statistics.get_flow_count - local made = stats{name=item_name,input=true,precision_index=precision} or 0 - local used = stats{name=item_name,input=false,precision_index=precision} or 0 + local made = stats{name=item_name, input=true, precision_index=precision} or 0 + local used = stats{name=item_name, input=false, precision_index=precision} or 0 return { made=made, @@ -131,10 +131,10 @@ end -- @tparam string item_name the name of the item that you want the data about -- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @treturn table contains made, used and net -function Production.get_fluctuations(force,item_name,precision) +function Production.get_fluctuations(force, item_name, precision) local percision_up = Production.precision_up(precision) - local current = Production.get_production(force,item_name,precision) - local previous = Production.get_production(force,item_name,percision_up) + local current = Production.get_production(force, item_name, precision) + local previous = Production.get_production(force, item_name, percision_up) return { made=(current.made/previous.made)-1, @@ -150,10 +150,10 @@ end -- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @tparam[opt=1000] number required the number of items that are required to be made -- @treturn number the number of ticks required to produce this ammount of items -function Production.get_production_eta(force,item_name,precision,required) +function Production.get_production_eta(force, item_name, precision, required) required = required or 1000 local ticks = Production.precision_ticks(precision) - local production = Production.get_production(force,item_name,precision) + local production = Production.get_production(force, item_name, precision) return production.made == 0 and -1 or ticks*required/production.made end @@ -163,10 +163,10 @@ end -- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @tparam[opt=1000] number required the number of items that are required to be consumed -- @treturn number the number of ticks required to consume this ammount of items -function Production.get_consumsion_eta(force,item_name,precision,required) +function Production.get_consumsion_eta(force, item_name, precision, required) required = required or 1000 local ticks = Production.precision_ticks(precision) - local production = Production.get_production(force,item_name,precision) + local production = Production.get_production(force, item_name, precision) return production.used == 0 and -1 or ticks*required/production.used end @@ -176,10 +176,10 @@ end -- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @tparam[opt=1000] number required the number of items that are required to be made but not used -- @treturn number the number of ticks required to produce, but not use, this ammount of items -function Production.get_net_eta(force,item_name,precision,required) +function Production.get_net_eta(force, item_name, precision, required) required = required or 1000 local ticks = Production.precision_ticks(precision) - local production = Production.get_production(force,item_name,precision) + local production = Production.get_production(force, item_name, precision) return production.net == 0 and -1 or ticks*required/production.net end @@ -213,19 +213,19 @@ end -- @treturn[1] string the sign for the number -- @treturn[1] string the surfix for any unit used function Production.format_number(value) - local rtn = format_number(math.round(value,1),true) + local rtn = format_number(math.round(value, 1), true) local surfix = rtn:sub(-1) if value > 0 then rtn = '+'..rtn - elseif value == 0 and rtn:sub(1,1) == '-' then + elseif value == 0 and rtn:sub(1, 1) == '-' then rtn = rtn:sub(2) end if not tonumber(surfix) then - return surfix,rtn:sub(1,-2) + return surfix, rtn:sub(1, -2) else - return '',rtn + return '', rtn end end diff --git a/modules/control/reports.lua b/modules/control/reports.lua index d5d5cf1b4a..ea2a710fbf 100644 --- a/modules/control/reports.lua +++ b/modules/control/reports.lua @@ -10,13 +10,13 @@ -- This will place a report on "MrBiter" (must be a valid player) the report will have been made -- by "Cooldude2606" (must be the player name) with the reason 'Liking biters too much' this can be -- seen by using Reports.get_report. - Reports.report_player('MrBiter','Cooldude2606','Liking biters too much') -- true + Reports.report_player('MrBiter', 'Cooldude2606', 'Liking biters too much') -- true -- The other get methods can be used to get all the reports on a player or to test if a player is reported. - Reports.get_report('MrBiter','Cooldude2606') -- 'Liking biters too much' + Reports.get_report('MrBiter', 'Cooldude2606') -- 'Liking biters too much' -- This will remove the warning on 'MrBiter' (must be a valid player) which was made by 'Cooldude2606'. - Reports.remove_report('MrBiter','Cooldude2606') -- true + Reports.remove_report('MrBiter', 'Cooldude2606') -- true -- This will remove all the report that have been made against 'MrBiter'. Note that the remove event will -- be triggered once per report issused. @@ -43,12 +43,14 @@ local Reports = { -- @tparam number player_index the player index of the player who has the report removed -- @tparam string reported_by_name the name of the player who made the removed report -- @tparam string removed_by_name the name of the player who removed the report + -- @tparam number batch_count the number of reports removed in this batch, always one when not a batch + -- @tparam number batch the index of this event in a batch, always one when not a batch on_report_removed = script.generate_event_name() } } local user_reports = Reports.user_reports -Global.register(user_reports,function(tbl) +Global.register(user_reports, function(tbl) Reports.user_reports = tbl user_reports = Reports.user_reports end) @@ -71,7 +73,7 @@ end -- @tparam LuaPlayer player the player to get the report for -- @tparam string by_player_name the name of the player who made the report -- @treturn ?string|nil string is the reason that the player was reported, if the player is not reported -function Reports.get_report(player,by_player_name) +function Reports.get_report(player, by_player_name) player = valid_player(player) if not player then return end if not by_player_name then return end @@ -84,7 +86,7 @@ end -- @tparam LuaPlayer player the player to check if reported -- @tparam[opt] string by_player_name when given will check if reported by this player -- @treturn boolean if the player has been reported -function Reports.is_reported(player,by_player_name) +function Reports.is_reported(player, by_player_name) player = valid_player(player) if not player then return end @@ -100,15 +102,15 @@ end -- @tparam LuaPlayer player the player to count the reports for -- @tparam[opt] function custom_count when given this function will be used to count the reports -- @treturn number the number of reports that the user has -function Reports.count_reports(player,custom_count) +function Reports.count_reports(player, custom_count) player = valid_player(player) if not player then return end local reports = user_reports[player.name] or {} if custom_count then local ctn = 0 - for by_player_name,reason in pairs(reports) do - ctn = ctn + custom_count(player,by_player_name,reason) + for by_player_name, reason in pairs(reports) do + ctn = ctn + custom_count(player, by_player_name, reason) end return ctn else @@ -125,7 +127,7 @@ end -- @tparam string by_player_name the name of the player that is making the report -- @tparam[opt='Non given.'] string reason the reason that the player is being reported -- @treturn boolean whether the report was added successfully -function Reports.report_player(player,by_player_name,reason) +function Reports.report_player(player, by_player_name, reason) player = valid_player(player) if not player then return end local player_name = player.name @@ -144,7 +146,7 @@ function Reports.report_player(player,by_player_name,reason) reports[by_player_name] = reason end - script.raise_event(Reports.events.on_player_reported,{ + script.raise_event(Reports.events.on_player_reported, { name = Reports.events.on_player_reported, tick = game.tick, player_index = player.index, @@ -159,13 +161,17 @@ end -- @tparam LuaPlayer player the player who is having the report removed from them -- @tparam string reported_by_name the player who had the report -- @tparam string removed_by_name the player who is clearing the report -local function report_removed_event(player,reported_by_name,removed_by_name) - script.raise_event(Reports.events.on_report_removed,{ +-- @tparam number batch the index of this event in a batch, always one when not a batch +-- @tparam number batch_count the number of reports removed in this batch, always one when not a batch +local function report_removed_event(player, reported_by_name, removed_by_name, batch, batch_count) + script.raise_event(Reports.events.on_report_removed, { name = Reports.events.on_report_removed, tick = game.tick, player_index = player.index, reported_by_name = reported_by_name, - removed_by_name = removed_by_name + removed_by_name = removed_by_name, + batch_count = batch_count or 1, + batch = batch or 1 }) end @@ -174,7 +180,7 @@ end -- @tparam string reported_by_name the name of the player that made the report -- @tparam string removed_by_name the name of the player who removed the report -- @treturn boolean whether the report was removed successfully -function Reports.remove_report(player,reported_by_name,removed_by_name) +function Reports.remove_report(player, reported_by_name, removed_by_name) player = valid_player(player) if not player then return end @@ -188,7 +194,7 @@ function Reports.remove_report(player,reported_by_name,removed_by_name) return false end - report_removed_event(player,reported_by_name,removed_by_name) + report_removed_event(player, reported_by_name, removed_by_name) reports[reported_by_name] = nil return true @@ -198,7 +204,7 @@ end -- @tparam LuaPlayer player the player to remove the reports from -- @tparam string removed_by_name the name of the player who removed the report -- @treturn boolean whether the reports were removed successfully -function Reports.remove_all(player,removed_by_name) +function Reports.remove_all(player, removed_by_name) player = valid_player(player) if not player then return end @@ -206,9 +212,10 @@ function Reports.remove_all(player,removed_by_name) if not reports then return false end - - for reported_by_name,_ in pairs(reports) do - report_removed_event(player,reported_by_name,removed_by_name) + local ctn, total = 0, #reports + for reported_by_name, _ in pairs(reports) do + ctn = ctn + 1 + report_removed_event(player, reported_by_name, removed_by_name, ctn, total) end user_reports[player.name] = nil diff --git a/modules/control/rockets.lua b/modules/control/rockets.lua index a09c74ce65..f830ebfadf 100644 --- a/modules/control/rockets.lua +++ b/modules/control/rockets.lua @@ -18,10 +18,10 @@ Rockets.get_silos('player') -- You can get the launch time for a rocket, meaning what game tick the 50th rocket was launched - Rockets.get_rocket_time('player',50) + Rockets.get_rocket_time('player', 50) -- The rolling average will work out the time to launch one rocket based on the last X rockets - Rockets.get_rolling_average('player',10) + Rockets.get_rolling_average('player', 10) ]] @@ -30,7 +30,7 @@ local Global = require 'utils.global' --- @dep utils.global local config = require 'config.gui.rockets' --- @dep config.rockets local largest_rolling_avg = 0 -for _,avg_over in pairs(config.stats.rolling_avg) do +for _, avg_over in pairs(config.stats.rolling_avg) do if avg_over > largest_rolling_avg then largest_rolling_avg = avg_over end @@ -49,7 +49,7 @@ Global.register({ rocket_times = rocket_times, rocket_stats = rocket_stats, rocket_silos = rocket_silos -},function(tbl) +}, function(tbl) Rockets.times = tbl.rocket_times Rockets.stats = tbl.rocket_stats Rockets.silos = tbl.rocket_silos @@ -94,9 +94,9 @@ end -- @treturn table an array of silo data that all belong to this force function Rockets.get_silos(force_name) local rtn = {} - for _,silo_data in pairs(rocket_silos) do + for _, silo_data in pairs(rocket_silos) do if silo_data.force == force_name then - table.insert(rtn,silo_data) + table.insert(rtn, silo_data) end end return rtn @@ -106,7 +106,7 @@ end -- @tparam string force_name the name of the force to get the count for -- @tparam number rocket_number the number of the rocket to get the launch time for -- @treturn number the game tick that the rocket was lanuched on -function Rockets.get_rocket_time(force_name,rocket_number) +function Rockets.get_rocket_time(force_name, rocket_number) return rocket_times[force_name] and rocket_times[force_name][rocket_number] or nil end @@ -122,7 +122,7 @@ end -- @treturn number the total number of rockets launched this game function Rockets.get_game_rocket_count() local rtn = 0 - for _,force in pairs(game.forces) do + for _, force in pairs(game.forces) do rtn = rtn + force.rockets_launched end return rtn @@ -132,7 +132,7 @@ end -- @tparam string force_name the name of the force to get the average for -- @tparam number count the distance to get the rolling average over -- @treturn number the number of ticks required to launch one rocket -function Rockets.get_rolling_average(force_name,count) +function Rockets.get_rolling_average(force_name, count) local force = game.forces[force_name] local rocket_count = force.rockets_launched if rocket_count == 0 then return 0 end @@ -146,7 +146,7 @@ function Rockets.get_rolling_average(force_name,count) end --- Event used to update the stats and the hui when a rocket is launched -Event.add(defines.events.on_rocket_launched,function(event) +Event.add(defines.events.on_rocket_launched, function(event) local entity = event.rocket_silo local silo_data = Rockets.get_silo_data(entity) local force = event.rocket_silo.force @@ -177,7 +177,7 @@ Event.add(defines.events.on_rocket_launched,function(event) rocket_times[force_name][rockets_launched] = event.tick local remove_rocket = rockets_launched-largest_rolling_avg - if remove_rocket > 0 and not table.contains(config.milestones,remove_rocket) then + if remove_rocket > 0 and not table.contains(config.milestones, remove_rocket) then rocket_times[force_name][remove_rocket] = nil end @@ -186,7 +186,7 @@ Event.add(defines.events.on_rocket_launched,function(event) end) --- When a launch is reiggered it will await reset -Event.add(defines.events.on_rocket_launch_ordered,function(event) +Event.add(defines.events.on_rocket_launch_ordered, function(event) local entity = event.rocket_silo local silo_data = Rockets.get_silo_data(entity) silo_data.awaiting_reset = true @@ -212,7 +212,7 @@ local function on_built(event) end end -Event.add(defines.events.on_built_entity,on_built) -Event.add(defines.events.on_robot_built_entity,on_built) +Event.add(defines.events.on_built_entity, on_built) +Event.add(defines.events.on_robot_built_entity, on_built) return Rockets \ No newline at end of file diff --git a/modules/control/tasks.lua b/modules/control/tasks.lua index 0806efde54..ec0f8c3815 100644 --- a/modules/control/tasks.lua +++ b/modules/control/tasks.lua @@ -4,28 +4,27 @@ @alias Tasks @usage-- Making and then editing a new task -local task_id = Tasks.add_task(game.player.force.name,nil,game.player.name) +local task_id = Tasks.add_task(game.player.force.name, nil, game.player.name) -Tasks.update_task(task_id,'We need more iron!',game.player.name) +Tasks.update_task(task_id, 'We need more iron!', game.player.name) ]] -local Store = require 'expcore.store' --- @dep expcore.store +local Datastore = require 'expcore.datastore' --- @dep expcore.datastore local Global = require 'utils.global' --- @dep utils.global -local Token = require 'utils.token' --- @dep utils.token + +--- Stores all data for the warp gui +local TaskData = Datastore.connect('TaskData') +TaskData:set_serializer(function(raw_key) return raw_key.task_id end) local Tasks = {} -- Global lookup table for force name to task ids -local force_tasks = {} -Global.register(force_tasks,function(tbl) +local force_tasks = {_uid=1} +Global.register(force_tasks, function(tbl) force_tasks = tbl end) --- Task store is keyed by task id, value is a table -local task_store = Store.register() -Tasks.store = task_store - --- Setters. -- functions used to created and alter tasks -- @section setters @@ -38,13 +37,14 @@ Tasks.store = task_store @treturn string the uid of the task which was created @usage-- Adding a new task for your force -local task_id = Tasks.add_task(game.player.force.name,nil,game.player.name) +local task_id = Tasks.add_task(game.player.force.name, nil, game.player.name) ]] -function Tasks.add_task(force_name,task_number,player_name,task_message) +function Tasks.add_task(force_name, task_number, player_name, task_message) -- Get a new task id - local task_id = tostring(Token.uid()) + local task_id = tostring(force_tasks._uid) task_message = task_message or 'New Task' + force_tasks._uid = force_tasks._uid + 1 -- Get the existing tasks for this force local tasks = force_tasks[force_name] @@ -55,9 +55,9 @@ function Tasks.add_task(force_name,task_number,player_name,task_message) -- Insert the task id into the forces tasks if task_number then - table.insert(tasks,task_number,task_id) + table.insert(tasks, task_number, task_id) else - table.insert(tasks,task_id) + table.insert(tasks, task_id) end -- Create the editing table @@ -67,13 +67,13 @@ function Tasks.add_task(force_name,task_number,player_name,task_message) end -- Add the new task to the store - Store.set(task_store,task_id,{ + TaskData:set(task_id, { task_id = task_id, force_name = force_name, message = task_message, last_edit_name = player_name or '', last_edit_time = game.tick, - curently_editing = editing + currently_editing = editing }) return task_id @@ -87,10 +87,10 @@ Tasks.remove_task(task_id) ]] function Tasks.remove_task(task_id) - local task = Store.get(task_store,task_id) + local task = TaskData:get(task_id) local force_name = task.force_name - table.remove_element(force_tasks[force_name],task_id) - Store.clear(task_store,task_id) + table.remove_element(force_tasks[force_name], task_id) + TaskData:remove(task_id) end --[[-- Update the message and last edited information for a task @@ -99,11 +99,11 @@ end @tparam[opt='server'] string player_name the name of the player who made the edit @usage-- Updating the message for on a task -Task.update_task(task_id,'We need more iron!',game.player.name) +Task.update_task(task_id, 'We need more iron!', game.player.name) ]] -function Tasks.update_task(task_id,new_message,player_name) - Store.update(task_store,task_id,function(task) +function Tasks.update_task(task_id, new_message, player_name) + TaskData:update(task_id, function(_, task) task.last_edit_name = player_name or '' task.last_edit_time = game.tick task.message = new_message @@ -116,12 +116,12 @@ end @tparam boolean state the new state to set editing to @usage-- Setting your editing state to true -Tasks.set_editing(task_id,game.player.name,true) +Tasks.set_editing(task_id, game.player.name, true) ]] -function Tasks.set_editing(task_id,player_name,state) - Store.update(task_store,task_id,function(task) - task.curently_editing[player_name] = state +function Tasks.set_editing(task_id, player_name, state) + TaskData:update(task_id, function(_, task) + task.currently_editing[player_name] = state end) end @@ -135,7 +135,7 @@ end) ]] function Tasks.on_update(handler) - Store.watch(task_store,handler) + TaskData:on_update(handler) end --- Getters. @@ -151,7 +151,7 @@ local task = Tasks.get_task(task_id) ]] function Tasks.get_task(task_id) - return Store.get(task_store,task_id) + return TaskData:get(task_id) end --[[-- Gets all the task ids that a force has @@ -172,12 +172,12 @@ end @treturn boolean weather the player is currently editing this task @usage-- Check if a player is editing a task or not -local editing = Tasks.get_editing(task_id,game.player.name) +local editing = Tasks.get_editing(task_id, game.player.name) ]] -function Tasks.get_editing(task_id,player_name) - local task = Store.get(task_store,task_id) - return task.curently_editing[player_name] +function Tasks.get_editing(task_id, player_name) + local task = TaskData:get(task_id) + return task.currently_editing[player_name] end -- Module Return diff --git a/modules/control/warnings.lua b/modules/control/warnings.lua index 2e6d057bc5..aca6f1ba84 100644 --- a/modules/control/warnings.lua +++ b/modules/control/warnings.lua @@ -8,17 +8,17 @@ local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings -- This will add a warning to the player - Warnings.add_warning('MrBiter','Cooldude2606','Killed too many biters') + Warnings.add_warning('MrBiter', 'Cooldude2606', 'Killed too many biters') -- This will remove a warning from a player, second name is just who is doing the action - Warnings.remove_warning('MrBiter','Cooldude2606') + Warnings.remove_warning('MrBiter', 'Cooldude2606') -- Script warning as similar to normal warning but are designed to have no effect for a short amount of time -- this is so it can be used for greifer protection without being too agressive - Warnings.add_script_warning('MrBiter','Killed too many biters') + Warnings.add_script_warning('MrBiter', 'Killed too many biters') -- Both normal and script warnings can also be cleared, this will remove all warnings - Warnings.clear_warnings('MrBiter','Cooldude2606') + Warnings.clear_warnings('MrBiter', 'Cooldude2606') ]] local Event = require 'utils.event' --- @dep utils.event @@ -28,8 +28,20 @@ local config = require 'config.warnings' --- @dep config.warnings local valid_player = Game.get_player_from_any +--- Stores the quickbar filters for a player +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local PlayerWarnings = PlayerData.Required:combine('Warnings') +PlayerWarnings:set_metadata{ + stringify = function(value) + if not value then return 'You have no warnings' end + local count = 0 + for _ in pairs(value) do count = count + 1 end + return 'You have '..count..' warnings' + end +} + local Warnings = { - user_warnings={}, + user_warnings=PlayerWarnings, user_script_warnings={}, events = { --- When a warning is added to a player @@ -45,6 +57,8 @@ local Warnings = { -- @tparam string warning_by_name the name of the player who gave the warning -- @tparam string removed_by_name the name of the player who is removing the warning -- @tparam number warning_count the new number of warnings that the player has + -- @tparam number batch_count the number of warnings removed in this batch, always one when not a batch + -- @tparam number batch the index of this event in a batch, always one when not a batch on_warning_removed = script.generate_event_name(), --- When a warning is added to a player, by the script -- @event on_script_warning_added @@ -52,7 +66,7 @@ local Warnings = { -- @tparam string reason the reason that the player was given a warning -- @tparam number warning_count the new number of warnings that the player has on_script_warning_added = script.generate_event_name(), - --- When a warning is remnoved from a player, by the script + --- When a warning is removed from a player, by the script -- @event on_script_warning_removed -- @tparam number player_index the index of the player who is having the warning removed -- @tparam number warning_count the new number of warnings that the player has @@ -60,30 +74,24 @@ local Warnings = { } } -local user_warnings = Warnings.user_warnings local user_script_warnings = Warnings.user_script_warnings -Global.register({ - user_warnings = user_warnings, - user_script_warnings = user_script_warnings -},function(tbl) - Warnings.user_warnings = tbl.user_warnings - Warnings.user_script_warnings = tbl.user_script_warnings - user_warnings = Warnings.user_warnings - user_script_warnings = Warnings.user_script_warnings +Global.register(user_script_warnings, function(tbl) + Warnings.user_script_warnings = tbl + user_script_warnings = tbl end) ---- Gets an array of warnings that the player has, always returns a list even if emtpy +--- Gets an array of warnings that the player has, always returns a list even if empty -- @tparam LuaPlayer player the player to get the warning for -- @treturn table an array of all the warnings on this player, contains tick, by_player_name and reason function Warnings.get_warnings(player) - return user_warnings[player.name] or {} + return PlayerWarnings:get(player.name, {}) end --- Gets the number of warnings that a player has on them -- @tparam LuaPlayer player the player to count the warnings for -- @treturn number the number of warnings that the player has function Warnings.count_warnings(player) - local warnings = user_warnings[player.name] or {} + local warnings = PlayerWarnings:get(player.name, {}) return #warnings end @@ -92,28 +100,30 @@ end -- @tparam string by_player_name the name of the player who is doing the action -- @tparam[opt='Non given.'] string reason the reason that the player is being warned -- @treturn number the number of warnings that the player has -function Warnings.add_warning(player,by_player_name,reason) +function Warnings.add_warning(player, by_player_name, reason) player = valid_player(player) if not player then return end if not by_player_name then return end - reason = reason or 'Non given.' - - local warnings = user_warnings[player.name] - if not warnings then - warnings = {} - user_warnings[player.name] = warnings - end - - table.insert(warnings,{ - tick = game.tick, - by_player_name = by_player_name, - reason = reason - }) - - local warning_count = #warnings + reason = reason or 'None given.' + + local warning_count + PlayerWarnings:update(player.name, function(_, warnings) + local warning = { + by_player_name = by_player_name, + reason = reason + } + + if not warnings then + warning_count = 1 + return {warning} + else + table.insert(warnings, warning) + warning_count = #warnings + end + end) - script.raise_event(Warnings.events.on_warning_added,{ + script.raise_event(Warnings.events.on_warning_added, { name = Warnings.events.on_warning_added, tick = game.tick, player_index = player.index, @@ -122,15 +132,15 @@ function Warnings.add_warning(player,by_player_name,reason) reason = reason }) - local action = config.actions[#warnings] + local action = config.actions[warning_count] if action then local _type = type(action) if _type == 'function' then - action(player,by_player_name,warning_count) + action(player, by_player_name, warning_count) elseif _type == 'table' then local current = table.deepcopy(action) - table.insert(current,2,by_player_name) - table.insert(current,3,warning_count) + table.insert(current, 2,by_player_name) + table.insert(current, 3,warning_count) player.print(current) elseif type(action) == 'string' then player.print(action) @@ -145,54 +155,61 @@ end -- @tparam string warning_by_name the name of the player who made the warning -- @tparam string removed_by_name the name of the player who is doing the action -- @tparam number warning_count the number of warnings that the player how has -local function warning_removed_event(player,warning_by_name,removed_by_name,warning_count) - script.raise_event(Warnings.events.on_warning_removed,{ +-- @tparam number batch the index of this event in a batch, always one when not a batch +-- @tparam number batch_count the number of reports removed in this batch, always one when not a batch +local function warning_removed_event(player, warning_by_name, removed_by_name, warning_count, batch, batch_count) + script.raise_event(Warnings.events.on_warning_removed, { name = Warnings.events.on_warning_removed, tick = game.tick, player_index = player.index, warning_count = warning_count, warning_by_name = warning_by_name, - removed_by_name = removed_by_name + removed_by_name = removed_by_name, + batch_count = batch_count or 1, + batch = batch or 1 }) end ---- Removes a warning from a player, always removes the earlyist warning, fifo +--- Removes a warning from a player, always removes the earliest warning, fifo -- @tparam LuaPlayer player the player to remove a warning from -- @tparam string by_player_name the name of the player who is doing the action -- @treturn number the number of warnings that the player has -function Warnings.remove_warning(player,by_player_name) +function Warnings.remove_warning(player, by_player_name) player = valid_player(player) if not player then return end if not by_player_name then return end - local warnings = user_warnings[player.name] - if not warnings then return end - - local warning = table.remove(warnings,1) + local warning, warning_count + PlayerWarnings:update(player.name, function(_, warnings) + if not warnings then return end + warning = table.remove(warnings, 1) + warning_count = #warnings + end) - warning_removed_event(player,warning.by_player_name,by_player_name,#warnings) + if not warning then return end + warning_removed_event(player, warning.by_player_name, by_player_name, warning_count) - return #warnings + return warning_count end --- Removes all warnings from a player, will trigger remove event for each warning -- @tparam LuaPlayer player the player to clear the warnings from -- @tparam string by_player_name the name of the player who is doing the action -- @treturn boolean true when warnings were cleared succesfully -function Warnings.clear_warnings(player,by_player_name) +function Warnings.clear_warnings(player, by_player_name) player = valid_player(player) if not player then return end if not by_player_name then return end - local warnings = user_warnings[player.name] + local warnings = PlayerWarnings:get(player) if not warnings then return end local warning_count = #warnings - for n,warning in pairs(warnings) do - warning_removed_event(player,warning.by_player_name,by_player_name,warning_count-n) + for n, warning in pairs(warnings) do + warning_removed_event(player, warning.by_player_name, by_player_name, warning_count-n, n, warning_count) end - user_warnings[player.name] = nil + PlayerWarnings:remove(player) return true end @@ -215,7 +232,7 @@ end -- @tparam LuaPlayer player the player to add a script warning to -- @tparam[opt='Non given.'] string reason the reason that the player is being warned -- @treturn number the number of script warnings that the player has -function Warnings.add_script_warning(player,reason) +function Warnings.add_script_warning(player, reason) player = valid_player(player) if not player then return end @@ -227,14 +244,14 @@ function Warnings.add_script_warning(player,reason) user_script_warnings[player.name] = warnings end - table.insert(warnings,{ + table.insert(warnings, { tick = game.tick, reason = reason }) local warning_count = #warnings - script.raise_event(Warnings.events.on_script_warning_added,{ + script.raise_event(Warnings.events.on_script_warning_added, { name = Warnings.events.on_script_warning_added, tick = game.tick, player_index = player.index, @@ -243,17 +260,17 @@ function Warnings.add_script_warning(player,reason) }) if warning_count > config.script_warning_limit then - Warnings.add_warning(player,'',reason) + Warnings.add_warning(player, '', reason) end return warning_count end ---- Script warning removed event tigger due to it being looped in clear script warnings +--- Script warning removed event trigger due to it being looped in clear script warnings -- @tparam LuaPlayer player the player who is having a script warning removed --- @tparam number warning_count the number of warning that the player has -local function script_warning_removed_event(player,warning_count) - script.raise_event(Warnings.events.on_script_warning_removed,{ +-- @tparam number warning_count the number of warnings that the player has +local function script_warning_removed_event(player, warning_count) + script.raise_event(Warnings.events.on_script_warning_removed, { name = Warnings.events.on_script_warning_removed, tick = game.tick, player_index = player.index, @@ -271,7 +288,7 @@ function Warnings.remove_script_warning(player) local warnings = user_script_warnings[player.name] if not warnings then return end - table.remove(warnings,1) + table.remove(warnings, 1) script_warning_removed_event(player) @@ -288,8 +305,8 @@ function Warnings.clear_script_warnings(player) if not warnings then return end local warning_count = #warnings - for n,_ in pairs(warnings) do - script_warning_removed_event(player,warning_count-n) + for n, _ in pairs(warnings) do + script_warning_removed_event(player, warning_count-n) end user_script_warnings[player.name] = nil @@ -298,11 +315,11 @@ end -- script warnings are removed after a certain amount of time to make them even more lienient local script_warning_cool_down = config.script_warning_cool_down*3600 -Event.on_nth_tick(script_warning_cool_down/4,function() +Event.on_nth_tick(script_warning_cool_down/4, function() local cutoff = game.tick - script_warning_cool_down - for player_name,script_warnings in pairs(user_script_warnings) do + for player_name, script_warnings in pairs(user_script_warnings) do if #script_warnings > 0 then - for _,warning in pairs(script_warnings) do + for _, warning in pairs(script_warnings) do if warning.tick < cutoff then Warnings.remove_script_warning(player_name) end diff --git a/modules/control/warps.lua b/modules/control/warps.lua index 897b2bc136..b846460a4d 100644 --- a/modules/control/warps.lua +++ b/modules/control/warps.lua @@ -6,7 +6,7 @@ @usage-- Making a new spawn warp local player = game.player local force = player.force -local spawn_id = Warps.add_warp(force.name,player.surface,player.position,player.name,'Spawn') +local spawn_id = Warps.add_warp(force.name, player.surface, player.position, player.name, 'Spawn') Warps.set_spawn_warp(spawn_id, force) Warps.make_warp_tag(spawn_id) @@ -14,32 +14,31 @@ Warps.make_warp_tag(spawn_id) @usage-- Making a new warp with a warp area local player = game.player local force = player.force -local warp_id = Warps.add_warp(force.name,player.surface,player.position,player.name) +local warp_id = Warps.add_warp(force.name, player.surface, player.position, player.name) Warps.make_warp_area(warp_id) Warps.make_warp_tag(warp_id) ]] -local Store = require 'expcore.store' --- @dep expcore.store +local Datastore = require 'expcore.datastore' --- @dep expcore.datastore local Global = require 'utils.global' --- @dep utils.global -local Token = require 'utils.token' --- @dep utils.token local config = require 'config.gui.warps' --- @dep config.warps +--- Stores all data for the warp system +local WrapData = Datastore.connect('WrapData') +WrapData:set_serializer(function(raw_key) return raw_key.warp_id end) + local Warps = {} -- Global lookup table for force name to task ids -local force_warps = {} -Global.register(force_warps,function(tbl) +local force_warps = {_uid=1} +Global.register(force_warps, function(tbl) force_warps = tbl end) --- Warp store is keyed by warp id, value is a table -local warp_store = Store.register() -Warps.store = warp_store - -- When a warp is updated change its chat tag and resort the warp order -Store.watch(warp_store,function(warp,warp_id) +WrapData:on_update(function(warp_id, warp, old_warp) if warp then -- Update the map chart tag if there is one if warp.tag then @@ -47,7 +46,7 @@ Store.watch(warp_store,function(warp,warp_id) end -- Check that the name of the warp has been changed - if warp.name == warp.old_name then return end + if not old_warp or warp.name == old_warp.name then return end -- Get the names of all the warp points for this force local force_name = warp.force_name @@ -55,8 +54,8 @@ Store.watch(warp_store,function(warp,warp_id) local spawn_id = warp_ids.spawn local warp_names = {} - for _,next_warp_id in pairs(warp_ids) do - local next_warp = Store.get(warp_store,next_warp_id) + for _, next_warp_id in pairs(warp_ids) do + local next_warp = WrapData:get(next_warp_id) if next_warp_id ~= spawn_id then warp_names[next_warp.name..next_warp_id] = next_warp_id end @@ -64,15 +63,15 @@ Store.watch(warp_store,function(warp,warp_id) -- Sort the warp names in alphabetical order local new_warp_ids = table.get_values(table.keysort(warp_names)) - table.insert(new_warp_ids,1,spawn_id) + table.insert(new_warp_ids, 1,spawn_id) new_warp_ids.spawn = spawn_id force_warps[force_name] = new_warp_ids end end) ---- Map Intergration. +--- Map Integration. -- functions used to create and alter warps with in the map --- @section mapIntergration +-- @section mapIntegration --[[-- Add or update the chat tag for this warp @tparam string warp_id the uid of the warp you want the chart tag for @@ -83,7 +82,7 @@ local tag_added = Warps.make_warp_tag(warp_id) ]] function Warps.make_warp_tag(warp_id) - local warp = Store.get(warp_store,warp_id) + local warp = WrapData:get(warp_id) local name = warp.name local icon = warp.icon @@ -91,7 +90,7 @@ function Warps.make_warp_tag(warp_id) local tag = warp.tag if tag and tag.valid then tag.text = 'Warp: '..name - tag.icon = {type='item',name=icon} + tag.icon = {type='item', name=icon} return false end @@ -100,10 +99,10 @@ function Warps.make_warp_tag(warp_id) local surface = warp.surface local position = warp.position - tag = force.add_chart_tag(surface,{ - position = {position.x+0.5,position.y+0.5}, + tag = force.add_chart_tag(surface, { + position = {position.x+0.5, position.y+0.5}, text = 'Warp: '..name, - icon = {type='item',name=icon} + icon = {type='item', name=icon} }) -- Add the tag to this warp, store.update not needed as we dont want it to trigger @@ -120,7 +119,7 @@ local removed = Warps.remove_warp_tag(warp_id) ]] function Warps.remove_warp_tag(warp_id) - local warp = Store.get(warp_store,warp_id) + local warp = WrapData:get(warp_id) -- Check there is a tag to remove local tag = warp.tag @@ -144,7 +143,7 @@ Warps.make_warp_area(warp_id) ]] function Warps.make_warp_area(warp_id) - local warp = Store.get(warp_store,warp_id) + local warp = WrapData:get(warp_id) local surface = warp.surface local position = warp.position local posx = position.x @@ -164,24 +163,24 @@ function Warps.make_warp_area(warp_id) for y = -radius, radius do local y2 = y^2 if x2+y2 < radius2 then - table.insert(base_tiles,{name=base_tile,position={x+posx,y+posy}}) + table.insert(base_tiles, {name=base_tile, position={x+posx, y+posy}}) end end end surface.set_tiles(base_tiles) - -- Add a tile patern ontop of the base + -- Add a tile pattern on top of the base local tiles = {} - for _,pos in pairs(config.tiles) do - table.insert(tiles,{name=base_tile,position={pos[1]+posx,pos[2]+posy}}) + for _, pos in pairs(config.tiles) do + table.insert(tiles, {name=base_tile, position={pos[1]+posx, pos[2]+posy}}) end surface.set_tiles(tiles) -- Add entities to the warp structure - for _,entity in pairs(config.entities) do + for _, entity in pairs(config.entities) do entity = surface.create_entity{ name=entity[1], - position={entity[2]+posx,entity[3]+posy}, + position={entity[2]+posx, entity[3]+posy}, force='neutral' } entity.destructible = false @@ -199,7 +198,7 @@ Warps.remove_warp_area(warp_id) ]] function Warps.remove_warp_area(warp_id) - local warp = Store.get(warp_store,warp_id) + local warp = WrapData:get(warp_id) local position = warp.position local surface = warp.surface local radius = config.standard_proximity_radius @@ -216,21 +215,21 @@ function Warps.remove_warp_area(warp_id) for y = -radius, radius do local y2 = y^2 if x2+y2 < radius2 then - table.insert(tiles,{name=base_tile,position={x+position.x,y+position.y}}) + table.insert(tiles, {name=base_tile, position={x+position.x, y+position.y}}) end end end surface.set_tiles(tiles) - -- Remove all the entites that are in the area + -- Remove all the entities that are in the area local entities = surface.find_entities_filtered{ force='neutral', area={ - {position.x-radius,position.y-radius}, - {position.x+radius,position.y+radius} + {position.x-radius, position.y-radius}, + {position.x+radius, position.y+radius} } } - for _,entity in pairs(entities) do if entity.name ~= 'player' then entity.destroy() end end + for _, entity in pairs(entities) do if entity and entity.valid and entity.name ~= 'player' then entity.destroy() end end end --[[-- Set a warp to be the spawn point for a force, force must own this warp @@ -238,12 +237,12 @@ end @tparam LuaForce force the force that you want to set the spawn for @usage-- Set your forces spawn to a warp -Warps.set_spawn_warp(warp_id,game.player.force) +Warps.set_spawn_warp(warp_id, game.player.force) ]] -function Warps.set_spawn_warp(warp_id,force) +function Warps.set_spawn_warp(warp_id, force) -- Check the force owns this warp - local warp = Store.get(warp_store,warp_id) + local warp = WrapData:get(warp_id) if warp.force_name ~= force.name then return end -- Set this warp as the spawn @@ -263,11 +262,11 @@ end @tparam LuaPlayer player the player to teleport to the warp @usage-- Teleport yourself to a warp point -Warps.teleport_player(warp_id,game.player) +Warps.teleport_player(warp_id, game.player) ]] -function Warps.teleport_player(warp_id,player) - local warp = Store.get(warp_store,warp_id) +function Warps.teleport_player(warp_id, player) + local warp = WrapData:get(warp_id) local surface = warp.surface local position = { x=warp.position.x+0.5, @@ -275,9 +274,9 @@ function Warps.teleport_player(warp_id,player) } -- Teleport the player - local goto_position = surface.find_non_colliding_position('character',position,32,1) + local goto_position = surface.find_non_colliding_position('character', position, 32, 1) if player.driving then player.driving = false end - player.teleport(goto_position,surface) + player.teleport(goto_position, surface) end --- Setters. @@ -294,12 +293,13 @@ end @usage-- Adding a new warp for your force at your position local player = game.player -local warp_id = Warps.add_warp(player.force.name,player.surface,player.position,player.name) +local warp_id = Warps.add_warp(player.force.name, player.surface, player.position, player.name) ]] -function Warps.add_warp(force_name,surface,position,player_name,warp_name) +function Warps.add_warp(force_name, surface, position, player_name, warp_name) -- Get new warp id - local warp_id = tostring(Token.uid()) + local warp_id = tostring(force_warps._uid) + force_warps._uid = force_warps._uid + 1 warp_name = warp_name or 'New warp' -- Get the existing warps for this force @@ -310,7 +310,7 @@ function Warps.add_warp(force_name,surface,position,player_name,warp_name) end -- Insert the warp id into the force warps - table.insert(warp_ids,warp_id) + table.insert(warp_ids, warp_id) -- Create the editing table local editing = {} @@ -319,7 +319,7 @@ function Warps.add_warp(force_name,surface,position,player_name,warp_name) end -- Add the new warp to the store - Store.set(warp_store,warp_id,{ + WrapData:set(warp_id, { warp_id = warp_id, force_name = force_name, name = warp_name, @@ -345,12 +345,12 @@ Warps.remove_warp(warp_id) ]] function Warps.remove_warp(warp_id) - local warp = Store.get(warp_store,warp_id) + local warp = WrapData:get(warp_id) local force_name = warp.force_name Warps.remove_warp_tag(warp_id) Warps.remove_warp_area(warp_id) - Store.clear(warp_store,warp_id) - table.remove_element(force_warps[force_name],warp_id) + WrapData:remove(warp_id) + table.remove_element(force_warps[force_name], warp_id) end --[[-- Update the name and icon for a warp @@ -360,14 +360,13 @@ end @tparam[opt='server'] string player_name the name of the player that made the edit @usage-- Changing the name and icon for a warp -Warps.update_warp(warp_id,'My Warp','iron-plate',game.player.name) +Warps.update_warp(warp_id, 'My Warp', 'iron-plate', game.player.name) ]] -function Warps.update_warp(warp_id,new_name,new_icon,player_name) - Store.update(warp_store,warp_id,function(warp) +function Warps.update_warp(warp_id, new_name, new_icon, player_name) + WrapData:update(warp_id, function(_, warp) warp.last_edit_name = player_name or '' warp.last_edit_time = game.tick - warp.old_name = warp.name warp.name = new_name or warp.name warp.icon = new_icon or warp.icon end) @@ -379,11 +378,11 @@ end @tparam boolean state the new state to set editing to @usage-- Setting your editing state to true -Warps.set_editing(warp_id,game.player.name,true) +Warps.set_editing(warp_id, game.player.name, true) ]] -function Warps.set_editing(warp_id,player_name,state) - Store.update(warp_store,warp_id,function(warp) +function Warps.set_editing(warp_id, player_name, state) + WrapData:update(warp_id, function(_, warp) warp.currently_editing[player_name] = state end) end @@ -398,7 +397,7 @@ end) ]] function Warps.on_update(handler) - Store.watch(warp_store,handler) + WrapData:on_update(handler) end --- Getters. @@ -414,7 +413,7 @@ local warp = Warps.get_warp(warp_id) ]] function Warps.get_warp(warp_id) - return Store.get(warp_store,warp_id) + return WrapData:get(warp_id) end --[[-- Gets all the warp ids that a force has @@ -448,11 +447,11 @@ end @treturn boolean weather the player is currently editing this warp @usage-- Check if a player is editing a warp or not -local editing = Warps.get_editing(warp_id,game.player.name) +local editing = Warps.get_editing(warp_id, game.player.name) ]] -function Warps.get_editing(warp_id,player_name) - local warp = Store.get(warp_store,warp_id) +function Warps.get_editing(warp_id, player_name) + local warp = WrapData:get(warp_id) return warp.currently_editing[player_name] end diff --git a/modules/data/alt-view.lua b/modules/data/alt-view.lua new file mode 100644 index 0000000000..609851ad0f --- /dev/null +++ b/modules/data/alt-view.lua @@ -0,0 +1,24 @@ +--- Stores if you use alt mode or not and auto applies it +-- @data Alt-View + +local Event = require 'utils.event' ---@dep utils.event + +--- Stores the visible state of alt mode +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local UsesAlt = PlayerData.Settings:combine('UsesAlt') +UsesAlt:set_default(false) +UsesAlt:set_metadata{ + stringify = function(value) return value and 'Visible' or 'Hidden' end +} + +--- When your data loads apply alt view if you have it enabled +UsesAlt:on_load(function(player_name, uses_alt) + local player = game.players[player_name] + player.game_view_settings.show_entity_info = uses_alt or false +end) + +--- When alt view is toggled update this +Event.add(defines.events.on_player_toggled_alt_mode, function(event) + local player = game.players[event.player_index] + UsesAlt:set(player, player.game_view_settings.show_entity_info) +end) \ No newline at end of file diff --git a/modules/data/bonus.lua b/modules/data/bonus.lua new file mode 100644 index 0000000000..cd87de7b91 --- /dev/null +++ b/modules/data/bonus.lua @@ -0,0 +1,73 @@ +--[[-- Commands Module - Bonus + - Adds a command that allows players to have increased stats + @data Bonus +]] + +local Roles = require 'expcore.roles' --- @dep expcore.roles +local Event = require 'utils.event' --- @dep utils.event +local config = require 'config.bonuses' --- @dep config.bonuses +local Commands = require 'expcore.commands' --- @dep expcore.commands +require 'config.expcore.command_general_parse' + +--- Stores the bonus for the player +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local PlayerBonus = PlayerData.Settings:combine('Bonus') +PlayerBonus:set_default(0) +PlayerBonus:set_metadata{ + permission = 'command/bonus', + stringify = function(value) + if not value or value == 0 then return 'None set' end + return (value*100)..'%' + end +} + +--- Apply a bonus amount to a player +local function apply_bonus(player, amount) + if not amount then return end + for bonus, min_max in pairs(config) do + local increase = min_max[2]*amount + player[bonus] = min_max[1]+increase + end +end + +--- When store is updated apply new bonus to the player +PlayerBonus:on_update(function(player_name, player_bonus) + apply_bonus(game.players[player_name], player_bonus or 0) +end) + +--- Changes the amount of bonus you receive +-- @command bonus +-- @tparam number amount range 0-50 the percent increase for your bonus +Commands.new_command('bonus', 'Changes the amount of bonus you receive') +:add_param('amount', 'integer-range', 0,50) +:register(function(player, amount) + local percent = amount/100 + PlayerBonus:set(player, percent) + Commands.print{'expcom-bonus.set', amount} + Commands.print({'expcom-bonus.wip'}, 'orange') +end) + +--- When a player respawns re-apply bonus +Event.add(defines.events.on_player_respawned, function(event) + local player = game.players[event.player_index] + apply_bonus(player, PlayerBonus:get(player)) +end) + +--- When a player dies allow them to have instant respawn +Event.add(defines.events.on_player_died, function(event) + local player = game.players[event.player_index] + if Roles.player_has_flag(player, 'instance-respawn') then + player.ticks_to_respawn = 120 + end +end) + +--- Remove bonus if a player no longer has access to the command +local function role_update(event) + local player = game.players[event.player_index] + if not Roles.player_allowed(player, 'command/bonus') then + PlayerBonus:remove(player) + end +end + +Event.add(Roles.events.on_role_assigned, role_update) +Event.add(Roles.events.on_role_unassigned, role_update) \ No newline at end of file diff --git a/modules/data/greetings.lua b/modules/data/greetings.lua new file mode 100644 index 0000000000..1c885eab85 --- /dev/null +++ b/modules/data/greetings.lua @@ -0,0 +1,36 @@ +--- Greets players on join +-- @data Greetings + +local config = require 'config.join_messages' --- @dep config.join_messages +local Commands = require 'expcore.commands' ---@dep expcore.commands +require 'config.expcore.command_general_parse' + +--- Stores the join message that the player have +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local CustomMessages = PlayerData.Settings:combine('JoinMessage') +CustomMessages:set_metadata{ + permission = 'command/join-message' +} + +--- When a players data loads show their message +CustomMessages:on_load(function(player_name, player_message) + local player = game.players[player_name] + local custom_message = player_message or config[player_name] + if custom_message then + game.print(custom_message, player.color) + else + player.print{'join-message.greet', {'links.discord'}} + end +end) + +--- Set your custom join message +-- @command join-message +-- @tparam string message The custom join message that will be used +Commands.new_command('join-message', 'Sets your custom join message') +:add_param('message', false, 'string-max-length', 255) +:enable_auto_concat() +:register(function(player, message) + if not player then return end + CustomMessages:set(player, message) + return {'join-message.message-set'} +end) \ No newline at end of file diff --git a/modules/data/player-colours.lua b/modules/data/player-colours.lua new file mode 100644 index 0000000000..f32aa7ffbe --- /dev/null +++ b/modules/data/player-colours.lua @@ -0,0 +1,62 @@ +--- Gives players random colours when they join, also applies preset colours to those who have them +-- @data Player-Colours + +local Event = require 'utils.event' --- @dep utils.event +local Colours = require 'utils.color_presets' --- @dep utils.color_presets +local config = require 'config.preset_player_colours' --- @dep config.preset_player_colours + +--- Stores the colour that the player wants +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local PlayerColours = PlayerData.Settings:combine('Colour') +PlayerColours:set_metadata{ + stringify = function(value) + if not value then return 'None set' end + local c = value[1] + return string.format('Red: %d Green: %d Blue: %d', c[1], c[2], c[3]) + end +} + +--- Used to compact player colours to take less space +local floor = math.floor +local function compact(colour) + return { + floor(colour.r * 255), + floor(colour.g * 255), + floor(colour.b * 255) + } +end + +--- Returns a colour that is a bit lighter than the one given +local function lighten(c) + return {r = 255 - (255 - c.r) * 0.5, g = 255 - (255 - c.g) * 0.5, b = 255 - (255 - c.b) * 0.5, a = 255} +end + +--- When your data loads apply the players colour, or a random on if none is saved +PlayerColours:on_load(function(player_name, player_colour) + if not player_colour then + local preset = config.players[player_name] + if preset then + player_colour = {preset, lighten(preset)} + else + local colour_name = 'white' + while config.disallow[colour_name] do + colour_name = table.get_random_dictionary_entry(Colours, true) + end + player_colour = {Colours[colour_name], lighten(Colours[colour_name])} + end + end + + local player = game.players[player_name] + player.color = player_colour[1] + player.chat_color = player_colour[2] +end) + +--- Save the players color when they use the color command +Event.add(defines.events.on_console_command, function(event) + if event.command ~= 'color' then return end + if event.parameters == '' then return end + if not event.player_index then return end + local player = game.players[event.player_index] + if not player or not player.valid then return end + PlayerColours:set(player, {compact(player.color), compact(player.chat_color)}) +end) \ No newline at end of file diff --git a/modules/data/quickbar.lua b/modules/data/quickbar.lua new file mode 100644 index 0000000000..e368eef886 --- /dev/null +++ b/modules/data/quickbar.lua @@ -0,0 +1,54 @@ +--[[-- Commands Module - Quickbar + - Adds a command that allows players to load Quickbar presets + @data Quickbar +]] + +local Commands = require 'expcore.commands' --- @dep expcore.commands +local config = require 'config.preset_player_quickbar' --- @dep config.preset_player_quickbar + +--- Stores the quickbar filters for a player +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local PlayerFilters = PlayerData.Settings:combine('QuickbarFilters') +PlayerFilters:set_metadata{ + permission = 'command/save-quickbar', + stringify = function(value) + if not value then return 'No filters set' end + local count = 0 + for _ in pairs(value) do count = count + 1 end + return count..' filters set' + end +} + +--- Loads your quickbar preset +PlayerFilters:on_load(function(player_name, filters) + if not filters then filters = config[player_name] end + if not filters then return end + local player = game.players[player_name] + for i, item_name in pairs(filters) do + if item_name ~= nil and item_name ~= '' then + player.set_quick_bar_slot(i, item_name) + end + end +end) + +--- Saves your quickbar preset to the script-output folder +-- @command save-quickbar +Commands.new_command('save-quickbar', 'Saves your Quickbar preset items to file') +:add_alias('save-toolbar') +:register(function(player) + local filters = {} + for i = 1, 100 do + local slot = player.get_quick_bar_slot(i) + if slot ~= nil then + filters[i] = slot.name + end + end + + if next(filters) then + PlayerFilters:set(player, filters) + else + PlayerFilters:remove(player) + end + + return {'quickbar.saved'} +end) \ No newline at end of file diff --git a/modules/data/statistics.lua b/modules/data/statistics.lua new file mode 100644 index 0000000000..709610fb26 --- /dev/null +++ b/modules/data/statistics.lua @@ -0,0 +1,152 @@ + +local Event = require 'utils.event' ---@dep utils.event +local config = require 'config.statistics' ---@dep config.statistics +local format_time = _C.format_time +local floor = math.floor +local afk_required = 5*3600 -- 5 minutes + +--- Stores the statistics on a player +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local AllPlayerData = PlayerData.All +local Statistics = PlayerData.Statistics +Statistics:set_metadata{ + display_order = config.display_order +} + +--- Update your statistics with any which happened before the data was valid +Statistics:on_load(function(player_name, player_statistics) + local existing_data = AllPlayerData:get(player_name) + if existing_data and existing_data.valid then return end + local counters = config.counters + for key, value in pairs(Statistics:get(player_name, {})) do + if config[key] or counters[key] then + if not player_statistics[key] then + player_statistics[key] = value + else + player_statistics[key] = player_statistics[key] + value + end + end + end + return player_statistics +end) + +--- Used to format time in minute format +local function format_minutes(value) + return format_time(value*3600, { + long = true, + hours = true, + minutes = true + }) +end + +--- Add Playtime and AfkTime if it is enabled +if config.Playtime or config.AfkTime then + local playtime, afk_time + if config.Playtime then playtime = Statistics:combine('Playtime') playtime:set_metadata{stringify=format_minutes} end + if config.AfkTime then afk_time = Statistics:combine('AfkTime') afk_time:set_metadata{stringify=format_minutes} end + Event.on_nth_tick(3600, function() + if game.tick == 0 then return end + for _, player in pairs(game.connected_players) do + if playtime then playtime:increment(player) end + if afk_time and player.afk_time > afk_required then afk_time:increment(player) end + end + end) +end + +--- Add DistanceTravelled if it is enabled +if config.DistanceTravelled then + local stat = Statistics:combine('DistanceTravelled') + stat:set_metadata{unit=' tiles'} + Event.add(defines.events.on_player_changed_position, function(event) + local player = game.players[event.player_index] + if not player.valid or not player.connected or player.afk_time > afk_required then return end + stat:increment(player) + end) +end + +--- Add MachinesRemoved and TreesDestroyed and config.OreMined if it is enabled +if config.MachinesRemoved or config.TreesDestroyed or config.OreMined then + local machines, trees, ore + if config.MachinesRemoved then machines = Statistics:combine('MachinesRemoved') end + if config.TreesDestroyed then trees = Statistics:combine('TreesDestroyed') end + if config.OreMined then ore = Statistics:combine('OreMined') end + local function on_event(event) + if not event.player_index then return end -- Check player is valid + local player = game.players[event.player_index] + if not player.valid or not player.connected then return end + local entity = event.entity -- Check entity is valid + if not entity.valid then return end + if entity.type == 'resource' then ore:increment(player) + elseif entity.type == 'tree' then trees:increment(player) + elseif entity.force == player.force then machines:increment(player) end + end + Event.add(defines.events.on_marked_for_deconstruction, on_event) + Event.add(defines.events.on_player_mined_entity, on_event) +end + +--- Add DamageDealt if it is enabled +if config.DamageDealt then + local stat = Statistics:combine('DamageDealt') + Event.add(defines.events.on_entity_damaged, function(event) + local character = event.cause -- Check character is valid + if not character or not character.valid or character.type ~= 'character' then return end + local player = character.player -- Check player is valid + if not player.valid or not player.connected then return end + local entity = event.entity -- Check entity is valid + if not entity.valid or entity.force == player.force or entity.force.name == 'neutral' then return end + stat:increment(player, floor(event.final_damage_amount)) + end) +end + +--- Add Kills if it is enabled +if config.Kills then + local stat = Statistics:combine('Kills') + Event.add(defines.events.on_entity_died, function(event) + local character = event.cause -- Check character is valid + if not character or not character.valid or character.type ~= 'character' then return end + local player = character.player -- Check player is valid + if not player.valid or not player.connected then return end + local entity = event.entity -- Check entity is valid + if not entity.valid or entity.force == player.force or entity.force.name == 'neutral' then return end + stat:increment(player) + end) +end + +--- Add RocketsLaunched if it is enabled +if config.RocketsLaunched then + local stat = Statistics:combine('RocketsLaunched') + Event.add(defines.events.on_rocket_launched, function(event) + local silo = event.rocket_silo -- Check silo is valid + if not silo or not silo.valid then return end + local force = silo.force -- Check force is valid + if not force or not force.valid then return end + for _, player in pairs(force.connected_players) do + stat:increment(player) + end + end) +end + +--- Add RocketsLaunched if it is enabled +if config.ResearchCompleted then + local stat = Statistics:combine('ResearchCompleted') + Event.add(defines.events.on_research_finished, function(event) + local research = event.research -- Check research is valid + if event.by_script or not research or not research.valid then return end + local force = research.force -- Check force is valid + if not force or not force.valid then return end + for _, player in pairs(force.connected_players) do + stat:increment(player) + end + end) +end + +--- Add all the remaining statistics from the config +for statistic, event_name in pairs(config.counters) do + local stat = Statistics:combine(statistic) + Event.add(event_name, function(event) + if not event.player_index then return end + local player = game.players[event.player_index] + if not player.valid or not player.connected then return end + stat:increment(player) + end) +end \ No newline at end of file diff --git a/modules/commands/tag.lua b/modules/data/tag.lua similarity index 51% rename from modules/commands/tag.lua rename to modules/data/tag.lua index a0400cf293..27190b7ba2 100644 --- a/modules/commands/tag.lua +++ b/modules/data/tag.lua @@ -1,6 +1,6 @@ --[[-- Commands Module - Tag - Adds a command that allows players to have a custom tag after their name - @commands Tag + @data Tag ]] local Commands = require 'expcore.commands' --- @dep expcore.commands @@ -8,31 +8,48 @@ local Roles = require 'expcore.roles' --- @dep expcore.roles require 'config.expcore.command_general_parse' require 'config.expcore.command_role_parse' +--- Stores the tag for a player +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local PlayerTags = PlayerData.Settings:combine('Tag') +PlayerTags:set_metadata{ + permission = 'command/tag' +} + +--- When your tag is updated then apply the changes +PlayerTags:on_update(function(player_name, player_tag) + local player = game.players[player_name] + if player_tag == nil or player_tag == '' then + player.tag = '' + else + player.tag = '- '..player_tag + end +end) + --- Sets your player tag. -- @command tag -- @tparam string tag the tag that will be after the name, there is a max length -Commands.new_command('tag','Sets your player tag.') -:add_param('tag',false,'string-max-length',20) +Commands.new_command('tag', 'Sets your player tag.') +:add_param('tag', false, 'string-max-length', 20) :enable_auto_concat() -:register(function(player,tag,raw) - player.tag = '- '..tag +:register(function(player, tag) + PlayerTags:set(player, tag) end) --- Clears your tag. Or another player if you are admin. -- @command tag-clear -- @tparam[opt=self] LuaPlayer player the player to remove the tag from, nil will apply to self -Commands.new_command('tag-clear','Clears your tag. Or another player if you are admin.') -:add_param('player',true,'player-role') +Commands.new_command('tag-clear', 'Clears your tag. Or another player if you are admin.') +:add_param('player', true, 'player-role') :set_defaults{player=function(player) return player -- default is the user using the command end} -:register(function(player,action_player,raw) +:register(function(player, action_player) if action_player.index == player.index then -- no player given so removes your tag - action_player.tag = '' - elseif Roles.player_allowed(player,'command/clear-tag/always') then + PlayerTags:remove(action_player) + elseif Roles.player_allowed(player, 'command/clear-tag/always') then -- player given and user is admin so clears that player's tag - action_player.tag = '' + PlayerTags:remove(action_player) else -- user is not admin and tried to clear another users tag return Commands.error{'expcore-commands.unauthorized'} diff --git a/modules/factorio-control.lua b/modules/factorio-control.lua index 500d1c0a6e..f7614f7d3e 100644 --- a/modules/factorio-control.lua +++ b/modules/factorio-control.lua @@ -10,7 +10,7 @@ if use_silo_script then end local global = {} -Global.register(global,function(tbl) +Global.register(global, function(tbl) global = tbl end) @@ -35,7 +35,7 @@ local respawn_items = function() end if use_silo_script then - for k,v in pairs(silo_script.get_events()) do + for k, v in pairs(silo_script.get_events()) do Event.add(k, v) end end diff --git a/modules/gui/debug/expcore_store_view.lua b/modules/gui/debug/expcore_datastore_view.lua similarity index 75% rename from modules/gui/debug/expcore_store_view.lua rename to modules/gui/debug/expcore_datastore_view.lua index 36ab8027f4..cecd92c61f 100644 --- a/modules/gui/debug/expcore_store_view.lua +++ b/modules/gui/debug/expcore_datastore_view.lua @@ -1,10 +1,9 @@ local Gui = require 'utils.gui' --- @dep utils.gui -local Store = require 'expcore.store' --- @dep utils.global +local Datastore = require 'expcore.datastore' --- @dep expcore.datastore local Color = require 'utils.color_presets' --- @dep utils.color_presets local Model = require 'modules.gui.debug.model' --- @dep modules.gui.debug.model local dump = Model.dump -local dump_text = Model.dump_text local concat = table.concat local Public = {} @@ -15,7 +14,7 @@ local right_panel_name = Gui.uid_name() local input_text_box_name = Gui.uid_name() local refresh_name = Gui.uid_name() -Public.name = 'Store' +Public.name = 'Datastore' function Public.show(container) local main_flow = container.add {type = 'flow', direction = 'horizontal'} @@ -24,9 +23,9 @@ function Public.show(container) local left_panel_style = left_panel.style left_panel_style.width = 300 - for store_id, file_path in pairs(Store.file_paths) do - local header = left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = store_id..' - '..file_path} - Gui.set_data(header, store_id) + for name in pairs(table.keysort(Datastore.debug())) do + local header = left_panel.add({type = 'flow'}).add {type = 'label', name = header_name, caption = name} + Gui.set_data(header, name) end local right_flow = main_flow.add {type = 'flow', direction = 'vertical'} @@ -70,7 +69,7 @@ Gui.on_click( header_name, function(event) local element = event.element - local store_id = Gui.get_data(element) + local tableName = Gui.get_data(element) local left_panel = element.parent.parent local data = Gui.get_data(left_panel) @@ -85,22 +84,25 @@ Gui.on_click( element.style.font_color = Color.orange data.selected_header = element - input_text_box.text = concat {'global.data_store[', store_id, ']'} + input_text_box.text = tableName input_text_box.style.font_color = Color.black - local content = dump(Store.get(store_id)) or 'nil' - right_panel.text = content + local content = Datastore.debug(tableName) + local content_string = {} + for key, value in pairs(content) do + content_string[#content_string+1] = key:gsub('^%l', string.upper)..' = '..dump(value) + end + right_panel.text = concat(content_string, '\n') end ) -local function update_dump(text_input, data, player) - local suc, ouput = dump_text(text_input.text, player) - if not suc then - text_input.style.font_color = Color.red - else - text_input.style.font_color = Color.black - data.right_panel.text = ouput +local function update_dump(text_input, data) + local content = Datastore.debug(text_input.text) + local content_string = {} + for key, value in pairs(content) do + content_string[#content_string+1] = key:gsub('^%l', string.upper)..' = '..dump(value) end + data.right_panel.text = concat(content_string, '\n') end Gui.on_text_changed( @@ -109,7 +111,7 @@ Gui.on_text_changed( local element = event.element local data = Gui.get_data(element) - update_dump(element, data, event.player) + update_dump(element, data) end ) @@ -121,7 +123,7 @@ Gui.on_click( local input_text_box = data.input_text_box - update_dump(input_text_box, data, event.player) + update_dump(input_text_box, data) end ) diff --git a/modules/gui/debug/global_view.lua b/modules/gui/debug/global_view.lua index 3ab51d8dac..aff9a6fd7c 100644 --- a/modules/gui/debug/global_view.lua +++ b/modules/gui/debug/global_view.lua @@ -8,7 +8,7 @@ local concat = table.concat local Public = {} -local ignore = {tokens = true, data_store = true} +local ignore = {tokens = true, data_store = true, datastores = true} local header_name = Gui.uid_name() local left_panel_name = Gui.uid_name() diff --git a/modules/gui/debug/main_view.lua b/modules/gui/debug/main_view.lua index 0771bdb1f2..6fef9c169f 100644 --- a/modules/gui/debug/main_view.lua +++ b/modules/gui/debug/main_view.lua @@ -5,7 +5,7 @@ local Public = {} local pages = { require 'modules.gui.debug.redmew_global_view', - require 'modules.gui.debug.expcore_store_view', + require 'modules.gui.debug.expcore_datastore_view', require 'modules.gui.debug.expcore_gui_view', require 'modules.gui.debug.global_view', require 'modules.gui.debug.package_view', diff --git a/modules/gui/player-list.lua b/modules/gui/player-list.lua index 3ceeb0dff1..f09230733b 100644 --- a/modules/gui/player-list.lua +++ b/modules/gui/player-list.lua @@ -4,27 +4,23 @@ @alias player_list ]] +-- luacheck:ignore 211/Colors local Gui = require 'expcore.gui' --- @dep expcore.gui local Roles = require 'expcore.roles' --- @dep expcore.roles -local Store = require 'expcore.store' --- @dep expcore.store -local Game = require 'utils.game' --- @dep utils.game +local Datastore = require 'expcore.datastore' --- @dep expcore.datastore local Event = require 'utils.event' --- @dep utils.event local config = require 'config.gui.player_list_actions' --- @dep config.gui.player_list_actions local Colors = require 'utils.color_presets' --- @dep utils.color_presets local format_time = _C.format_time --- @dep expcore.common --- Stores the name of the player a player has selected -local selected_player_store = Store.register(function(player) - return player.name -end) - --- Stores the current action that a player wants to do -local selected_action_store = Store.register(function(player) - return player.name -end) +--- Stores all data for the warp gui +local PlayerListData = Datastore.connect('PlayerListData') +PlayerListData:set_serializer(Datastore.name_serializer) +local SelectedPlayer = PlayerListData:combine('SelectedPlayer') +local SelectedAction = PlayerListData:combine('SelectedAction') -- Set the config to use these stores -config.set_store_uids(selected_player_store,selected_action_store) +config.set_datastores(SelectedPlayer, SelectedAction) --- Button used to open the action bar -- @element open_action_bar @@ -40,13 +36,13 @@ Gui.element{ width = 8, height = 14 } -:on_click(function(player,element,_) +:on_click(function(player, element, _) local selected_player_name = element.parent.name - local old_selected_player_name = Store.get(selected_player_store,player) + local old_selected_player_name = SelectedPlayer:get(player) if selected_player_name == old_selected_player_name then - Store.clear(selected_player_store,player) + SelectedPlayer:remove(player) else - Store.set(selected_player_store,player,selected_player_name) + SelectedPlayer:set(player, selected_player_name) end end) @@ -59,10 +55,10 @@ Gui.element{ tooltip = {'player-list.close-action-bar'}, style = 'slot_sized_button_red' } -:style(Gui.sprite_style(30,-1,{ top_margin = -1, right_margin = -1 })) -:on_click(function(player,_) - Store.clear(selected_player_store,player) - Store.clear(selected_action_store,player) +:style(Gui.sprite_style(30, -1, { top_margin = -1, right_margin = -1 })) +:on_click(function(player, _) + SelectedPlayer:remove(player) + SelectedAction:remove(player) end) --- Button used to confirm a reason @@ -74,21 +70,21 @@ Gui.element{ tooltip = {'player-list.reason-confirm'}, style = 'slot_sized_button_green' } -:style(Gui.sprite_style(30,-1,{ left_margin = -2, right_margin = -1 })) -:on_click(function(player,element) +:style(Gui.sprite_style(30, -1, { left_margin = -2, right_margin = -1 })) +:on_click(function(player, element) local reason = element.parent.entry.text or 'Non Given' - local action_name = Store.get(selected_action_store,player) + local action_name = SelectedAction:get(player) local reason_callback = config.buttons[action_name].reason_callback - reason_callback(player,reason) - Store.clear(selected_player_store,player) - Store.clear(selected_action_store,player) + reason_callback(player, reason) + SelectedPlayer:remove(player) + SelectedAction:remove(player) element.parent.entry.text = '' end) --- Set of elements that are used to make up a row of the player table -- @element add_player_base local add_player_base = -Gui.element(function(event_trigger,parent,player_data) +Gui.element(function(event_trigger, parent, player_data) -- Add the button to open the action bar local toggle_action_bar_flow = parent.add{ type = 'flow', name = player_data.name } open_action_bar(toggle_action_bar_flow) @@ -99,13 +95,13 @@ Gui.element(function(event_trigger,parent,player_data) type = 'label', name = event_trigger, caption = player_data.name, - tooltip = {'player-list.open-map',player_data.name,player_data.tag,player_data.role_name} + tooltip = {'player-list.open-map', player_data.name, player_data.tag, player_data.role_name} } - player_name.style.padding = {0,2,0,0} + player_name.style.padding = {0, 2,0, 0} player_name.style.font_color = player_data.chat_color -- Add the time played label - local alignment = Gui.alignment(parent,'player-time-'..player_data.index) + local alignment = Gui.alignment(parent, 'player-time-'..player_data.index) local time_label = alignment.add{ name = 'label', type = 'label', @@ -116,34 +112,34 @@ Gui.element(function(event_trigger,parent,player_data) return time_label end) -:on_click(function(player,element,event) +:on_click(function(player, element, event) local selected_player_name = element.caption - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player = game.players[selected_player_name] if event.button == defines.mouse_button_type.left then -- LMB will open the map to the selected player local position = selected_player.position - event.player.zoom_to_world(position,1.75) + event.player.zoom_to_world(position, 1.75) else -- RMB will toggle the settings - local old_selected_player_name = Store.get(selected_player_store,player) + local old_selected_player_name = SelectedPlayer:get(player) if selected_player_name == old_selected_player_name then - Store.clear(selected_player_store,player) - Store.clear(selected_action_store,player) + SelectedPlayer:remove(player) + SelectedAction:remove(player) else - Store.set(selected_player_store,player,selected_player_name) + SelectedPlayer:set(player, selected_player_name) end end end) -- Removes the three elements that are added as part of the base -local function remove_player_base(parent,player) +local function remove_player_base(parent, player) Gui.destroy_if_valid(parent[player.name]) Gui.destroy_if_valid(parent['player-name-'..player.index]) Gui.destroy_if_valid(parent['player-time-'..player.index]) end -- Update the time label for a player using there player time data -local function update_player_base(parent,player_time) +local function update_player_base(parent, player_time) local time_element = parent[player_time.element_name] if time_element and time_element.valid then time_element.label.caption = player_time.caption @@ -154,15 +150,15 @@ end --- Adds all the buttons and flows that make up the action bar -- @element add_action_bar local add_action_bar_buttons = -Gui.element(function(_,parent) +Gui.element(function(_, parent) close_action_bar(parent) -- Loop over all the buttons in the config - for action_name,button_data in pairs(config.buttons) do + for action_name, button_data in pairs(config.buttons) do -- Added the permission flow local permission_flow = parent.add{ type = 'flow', name = action_name } permission_flow.visible = false -- Add the buttons under that permission - for _,button in ipairs(button_data) do + for _, button in ipairs(button_data) do button(permission_flow) end end @@ -173,27 +169,27 @@ end) --- Updates the visible state of the action bar buttons local function update_action_bar(element) local player = Gui.get_player_from_element(element) - local selected_player_name = Store.get(selected_player_store,player) + local selected_player_name = SelectedPlayer:get(player) if not selected_player_name then -- Hide the action bar when no player is selected element.visible = false else - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player = game.players[selected_player_name] if not selected_player.connected then -- If the player is offline then reest stores element.visible = false - Store.clear(selected_player_store,player) - Store.clear(selected_action_store,player) + SelectedPlayer:remove(player) + SelectedAction:remove(player) else -- Otherwise check what actions the player is allowed to use element.visible = true - for action_name,buttons in pairs(config.buttons) do - if buttons.auth and not buttons.auth(player,selected_player) then + for action_name, buttons in pairs(config.buttons) do + if buttons.auth and not buttons.auth(player, selected_player) then element[action_name].visible = false - elseif Roles.player_allowed(player,action_name) then + elseif Roles.player_allowed(player, action_name) then element[action_name].visible = true end end @@ -205,36 +201,36 @@ end --- Main player list container for the left flow -- @element player_list_container local player_list_container = -Gui.element(function(event_trigger,parent) +Gui.element(function(event_trigger, parent) -- Draw the internal container - local container = Gui.container(parent,event_trigger,200) + local container = Gui.container(parent, event_trigger, 200) -- Draw the scroll table for the players - local scroll_table = Gui.scroll_table(container,184,3) + local scroll_table = Gui.scroll_table(container, 184, 3) -- Change the style of the scroll table local scroll_table_style = scroll_table.style - scroll_table_style.padding = {1,0,1,2} + scroll_table_style.padding = {1, 0,1, 2} -- Add the action bar - local action_bar = Gui.footer(container,nil,nil,false,'action_bar') + local action_bar = Gui.footer(container, nil, nil, false, 'action_bar') -- Change the style of the action bar local action_bar_style = action_bar.style action_bar_style.height = 35 - action_bar_style.padding = {1,3} + action_bar_style.padding = {1, 3} action_bar.visible = false -- Add the buttons to the action bar add_action_bar_buttons(action_bar) -- Add the reason bar - local reason_bar = Gui.footer(container,nil,nil,false,'reason_bar') + local reason_bar = Gui.footer(container, nil, nil, false, 'reason_bar') -- Change the style of the reason bar local reason_bar_style = reason_bar.style reason_bar_style.height = 35 - reason_bar_style.padding = {-1,3} + reason_bar_style.padding = {-1, 3} reason_bar.visible = false -- Add the text entry for the reason bar @@ -263,15 +259,15 @@ end) --- Button on the top flow used to toggle the player list container -- @element toggle_left_element Gui.left_toolbar_button('entity/character', {'player-list.main-tooltip'}, player_list_container, function(player) - return Roles.player_allowed(player,'gui/player-list') + return Roles.player_allowed(player, 'gui/player-list') end) -- Get caption and tooltip format for a player -local function get_time_formats(online_time,afk_time) +local function get_time_formats(online_time, afk_time) local tick = game.tick > 0 and game.tick or 1 - local percent = math.round(online_time/tick,3)*100 + local percent = math.round(online_time/tick, 3)*100 local caption = format_time(online_time) - local tooltip = {'player-list.afk-time', percent, format_time(afk_time,{minutes=true,long=true})} + local tooltip = {'player-list.afk-time', percent, format_time(afk_time, {minutes=true, long=true})} return caption, tooltip end @@ -297,20 +293,20 @@ end local function get_player_list_order() -- Sort all the online players into roles local players = {} - for _,player in pairs(game.connected_players) do + for _, player in pairs(game.connected_players) do local highest_role = Roles.get_player_highest_role(player) if not players[highest_role.name] then players[highest_role.name] = {} end - table.insert(players[highest_role.name],player) + table.insert(players[highest_role.name], player) end -- Sort the players from roles into a set order local ctn = 0 local player_list_order = {} - for _,role_name in pairs(Roles.config.order) do + for _, role_name in pairs(Roles.config.order) do if players[role_name] then - for _,player in pairs(players[role_name]) do + for _, player in pairs(players[role_name]) do ctn = ctn + 1 -- Add the player data to the array local caption, tooltip = get_time_formats(player.online_time, player.afk_time) @@ -328,9 +324,10 @@ local function get_player_list_order() end --[[Adds fake players to the player list + local tick = game.tick+1 for i = 1, 10 do - local online_time = math.random(1,tick) - local afk_time = math.random(online_time-(tick/10),tick) + local online_time = math.random(1, tick) + local afk_time = math.random(online_time-(tick/10), tick) local caption, tooltip = get_time_formats(online_time, afk_time) player_list_order[ctn+i] = { name='Player '..i, @@ -341,35 +338,35 @@ local function get_player_list_order() caption = caption, tooltip = tooltip } - end]] + end--]] return player_list_order end --- Update the play times every 30 sections -Event.on_nth_tick(1800,function() +Event.on_nth_tick(1800, function() local player_times = get_player_times() - for _,player in pairs(game.connected_players) do - local frame = Gui.get_left_element(player,player_list_container) + for _, player in pairs(game.connected_players) do + local frame = Gui.get_left_element(player, player_list_container) local scroll_table = frame.container.scroll.table - for _,player_time in pairs(player_times) do - update_player_base(scroll_table,player_time) + for _, player_time in pairs(player_times) do + update_player_base(scroll_table, player_time) end end end) --- When a player leaves only remove they entry -Event.add(defines.events.on_player_left_game,function(event) - local remove_player = Game.get_player_by_index(event.player_index) - for _,player in pairs(game.connected_players) do - local frame = Gui.get_left_element(player,player_list_container) +Event.add(defines.events.on_player_left_game, function(event) + local remove_player = game.players[event.player_index] + for _, player in pairs(game.connected_players) do + local frame = Gui.get_left_element(player, player_list_container) local scroll_table = frame.container.scroll.table - remove_player_base(scroll_table,remove_player) + remove_player_base(scroll_table, remove_player) - local selected_player_name = Store.get(selected_player_store,player) + local selected_player_name = SelectedPlayer:get(player) if selected_player_name == remove_player.name then - Store.clear(selected_player_store,player) - Store.clear(selected_action_store,player) + SelectedPlayer:remove(player) + SelectedAction:remove(player) end end end) @@ -377,30 +374,30 @@ end) --- All other events require a full redraw of the table local function redraw_player_list() local player_list_order = get_player_list_order() - for _,player in pairs(game.connected_players) do - local frame = Gui.get_left_element(player,player_list_container) + for _, player in pairs(game.connected_players) do + local frame = Gui.get_left_element(player, player_list_container) local scroll_table = frame.container.scroll.table scroll_table.clear() - for _,next_player_data in ipairs(player_list_order) do - add_player_base(scroll_table,next_player_data) + for _, next_player_data in ipairs(player_list_order) do + add_player_base(scroll_table, next_player_data) end end end -Event.add(defines.events.on_player_joined_game,redraw_player_list) -Event.add(Roles.events.on_role_assigned,redraw_player_list) -Event.add(Roles.events.on_role_unassigned,redraw_player_list) +Event.add(defines.events.on_player_joined_game, redraw_player_list) +Event.add(Roles.events.on_role_assigned, redraw_player_list) +Event.add(Roles.events.on_role_unassigned, redraw_player_list) --- When the action player is changed the action bar will update -Store.watch(selected_player_store,function(value,player_name) - local player = Game.get_player_from_any(player_name) - local frame = Gui.get_left_element(player,player_list_container) +SelectedPlayer:on_update(function(player_name, selected_player) + local player = game.players[player_name] + local frame = Gui.get_left_element(player, player_list_container) local scroll_table = frame.container.scroll.table update_action_bar(frame.container.action_bar) - for _,next_player in pairs(game.connected_players) do + for _, next_player in pairs(game.connected_players) do local element = scroll_table[next_player.name][open_action_bar.name] local style = 'frame_button' - if next_player.name == value then + if next_player.name == selected_player then style = 'tool_button' end element.style = style @@ -412,20 +409,20 @@ Store.watch(selected_player_store,function(value,player_name) end) --- When the action name is changed the reason input will update -Store.watch(selected_action_store,function(value,player_name) - local player = Game.get_player_from_any(player_name) - local frame = Gui.get_left_element(player,player_list_container) +SelectedAction:on_update(function(player_name, selected_action) + local player = game.players[player_name] + local frame = Gui.get_left_element(player, player_list_container) local element = frame.container.reason_bar - if value then + if selected_action then -- if there is a new value then check the player is still online - local selected_player_name = Store.get(selected_player_store,player_name) - local selected_player = Game.get_player_from_any(selected_player_name) + local selected_player_name = SelectedPlayer:get(player_name) + local selected_player = game.players[selected_player_name] if selected_player.connected then element.visible = true else -- Clear if the player is offline - Store.clear(selected_player_store,player_name) - Store.clear(selected_action_store,player_name) + SelectedPlayer:remove(player) + SelectedAction:remove(player) end else diff --git a/modules/gui/readme.lua b/modules/gui/readme.lua index 7c6e4dd156..ca38e40e43 100644 --- a/modules/gui/readme.lua +++ b/modules/gui/readme.lua @@ -4,26 +4,28 @@ @alias readme ]] +local Event = require 'utils.event' --- @dep utils.event local Gui = require 'expcore.gui' --- @dep expcore.gui local Roles = require 'expcore.roles' --- @dep expcore.roles local Commands = require 'expcore.commands' --- @dep expcore.commands -local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local External = require 'expcore.external' --- @dep expcore.external local format_time = _C.format_time --- @dep expcore.common +local format_number = require('util').format_number --- @dep util local tabs = {} -local function Tab(caption,tooltip,element_define) +local function Tab(caption, tooltip, element_define) tabs[#tabs+1] = {caption, tooltip, element_define} end -local frame_width = 595 -- controls width of top descritions +local frame_width = 595 -- controls width of top descriptions local title_width = 270 -- controls the centering of the titles -local scroll_hieght = 275 -- controls the height of the scrolls +local scroll_height = 275 -- controls the height of the scrolls --- Sub content area used within the content areas -- @element sub_content local sub_content = -Gui.element(function(_,parent) +Gui.element(function(_, parent) return parent.add{ type = 'frame', direction = 'vertical', @@ -40,7 +42,7 @@ end) --- Table which has a title above it above it -- @element title_table local title_table = -Gui.element(function(_,parent,bar_size,caption,column_count) +Gui.element(function(_, parent, bar_size, caption, column_count) Gui.title_label(parent, bar_size, caption) return parent.add{ @@ -67,16 +69,54 @@ Gui.element{ style = 'scroll_pane_under_subheader' } :style{ - padding = {1,3}, - maximal_height = scroll_hieght, + padding = {1, 3}, + maximal_height = scroll_height, horizontally_stretchable = true, } +--- Used to connect to servers in server list +-- @element join_server +local join_server = +Gui.element(function(event_trigger, parent, server_id, wrong_version) + local status = External.get_server_status(server_id) or 'Offline' + if wrong_version then status = 'Version' end + local flow = parent.add{ name = server_id, type = 'flow' } + local button = flow.add{ + name = event_trigger, + type = 'sprite-button', + sprite = 'utility/circuit_network_panel_white', --- network panel white, warning white, download white + hovered_sprite = 'utility/circuit_network_panel_black', --- network panel black, warning black, download black + tooltip = {'readme.servers-connect-'..status, wrong_version} + } + + if status == 'Offline' or status == 'Current' then + button.enabled = false + button.sprite = 'utility/circuit_network_panel_black' + elseif status == 'Version' then + button.enabled = false + button.sprite = 'utility/shuffle' + elseif status == 'Password' then + button.sprite = 'utility/warning_white' + button.hovered_sprite = 'utility/warning' + elseif status == 'Modded' then + button.sprite = 'utility/downloading_white' + button.hovered_sprite = 'utility/downloading' + end + + return button +end) +:style(Gui.sprite_style(20, -1)) +:on_click(function(player, element, _) + local server_id = element.parent.name + External.request_connection(player, server_id, true) +end) + --- Content area for the welcome tab -- @element welcome_content -Tab({'readme.welcome-tab'},{'readme.welcome-tooltip'}, -Gui.element(function(_,parent) - local server_details = global.server_details or { name='ExpGaming S0 - Local', description='Failed to load description: disconnected from sync api.', reset_time='Non Set', branch='Unknown'} +Tab({'readme.welcome-tab'}, {'readme.welcome-tooltip'}, +Gui.element(function(_, parent) + local server_details = { name='ExpGaming S0 - Local', welcome='Failed to load description: disconnected from external api.', reset_time='Non Set', branch='Unknown'} + if External.valid() then server_details = External.get_current_server() end local container = parent.add{ type='flow', direction='vertical' } local player = Gui.get_player_from_element(parent) @@ -89,21 +129,21 @@ Gui.element(function(_,parent) -- Add the title and description to the top flow Gui.title_label(top_vertical_flow, 62, 'Welcome to '..server_details.name) - Gui.centered_label(top_vertical_flow, 380, server_details.description) + Gui.centered_label(top_vertical_flow, 380, server_details.welcome) Gui.bar(container) -- Get the names of the roles the player has local player_roles = Roles.get_player_roles(player) local role_names = {} - for i,role in ipairs(player_roles) do + for i, role in ipairs(player_roles) do role_names[i] = role.name end -- Add the other information to the gui container.add{ type='flow' }.style.height = 4 - local online_time = format_time(game.tick,{days=true,hours=true,minutes=true,long=true}) + local online_time = format_time(game.tick, {days=true, hours=true, minutes=true, long=true}) Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-general', server_details.reset_time, online_time}) - Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-roles', table.concat(role_names,', ')}) + Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-roles', table.concat(role_names, ', ')}) Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-chat'}) return container @@ -111,8 +151,8 @@ end)) --- Content area for the rules tab -- @element rules_content -Tab({'readme.rules-tab'},{'readme.rules-tooltip'}, -Gui.element(function(_,parent) +Tab({'readme.rules-tab'}, {'readme.rules-tooltip'}, +Gui.element(function(_, parent) local container = parent.add{ type='flow', direction='vertical' } -- Add the title and description to the content @@ -122,12 +162,12 @@ Gui.element(function(_,parent) container.add{ type='flow' } -- Add a table for the rules - local rules = Gui.scroll_table(container, scroll_hieght, 1) + local rules = Gui.scroll_table(container, scroll_height, 1) rules.style = 'bordered_table' rules.style.cell_padding = 4 -- Add the rules to the table - for i = 1,15 do + for i = 1, 15 do Gui.centered_label(rules, 565, {'readme.rules-'..i}) end @@ -136,8 +176,8 @@ end)) --- Content area for the commands tab -- @element commands_content -Tab({'readme.commands-tab'},{'readme.commands-tooltip'}, -Gui.element(function(_,parent) +Tab({'readme.commands-tab'}, {'readme.commands-tooltip'}, +Gui.element(function(_, parent) local container = parent.add{ type='flow', direction='vertical' } local player = Gui.get_player_from_element(parent) @@ -148,12 +188,12 @@ Gui.element(function(_,parent) container.add{ type='flow' } -- Add a table for the commands - local commands = Gui.scroll_table(container, scroll_hieght, 2) + local commands = Gui.scroll_table(container, scroll_height, 2) commands.style = 'bordered_table' commands.style.cell_padding = 0 -- Add the rules to the table - for name,command in pairs(Commands.get(player)) do + for name, command in pairs(Commands.get(player)) do Gui.centered_label(commands, 120, name) Gui.centered_label(commands, 450, command.help) end @@ -163,8 +203,8 @@ end)) --- Content area for the servers tab -- @element servers_content -Tab({'readme.servers-tab'},{'readme.servers-tooltip'}, -Gui.element(function(_,parent) +Tab({'readme.servers-tab'}, {'readme.servers-tooltip'}, +Gui.element(function(_, parent) local container = parent.add{ type='flow', direction='vertical' } -- Add the title and description to the content @@ -175,18 +215,28 @@ Gui.element(function(_,parent) -- Draw the scroll local scroll_pane = title_table_scroll(container) - scroll_pane.style.maximal_height = scroll_hieght + 20 -- the text is a bit shorter + scroll_pane.style.maximal_height = scroll_height + 20 -- the text is a bit shorter -- Add the factorio servers - local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 2) - for i = 1,8 do - Gui.centered_label(factorio_servers, 110, {'readme.servers-'..i}) - Gui.centered_label(factorio_servers, 460, {'readme.servers-d'..i}) + if External.valid() then + local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 3) + local current_version = External.get_current_server().version + for server_id, server in pairs(External.get_servers()) do + Gui.centered_label(factorio_servers, 110, server.short_name) + Gui.centered_label(factorio_servers, 436, server.description) + join_server(factorio_servers, server_id, current_version ~= server.version and server.version) + end + else + local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 2) + for i = 1, 8 do + Gui.centered_label(factorio_servers, 110, {'readme.servers-'..i}) + Gui.centered_label(factorio_servers, 460, {'readme.servers-d'..i}) + end end -- Add the external links local external_links = title_table(scroll_pane, 235, {'readme.servers-external'}, 2) - for _,key in ipairs{'discord','website','patreon','status','github'} do + for _, key in ipairs{'discord', 'website', 'patreon', 'status', 'github'} do local upper_key = key:gsub("^%l", string.upper) Gui.centered_label(external_links, 110, upper_key) Gui.centered_label(external_links, 460, {'links.'..key}, {'readme.servers-open-in-browser'}) @@ -197,8 +247,8 @@ end)) --- Content area for the servers tab -- @element backers_content -Tab({'readme.backers-tab'},{'readme.backers-tooltip'}, -Gui.element(function(_,parent) +Tab({'readme.backers-tab'}, {'readme.backers-tooltip'}, +Gui.element(function(_, parent) local container = parent.add{ type='flow', direction='vertical' } -- Add the title and description to the content @@ -210,10 +260,10 @@ Gui.element(function(_,parent) -- Find which players will go where local done = {} local groups = { - { _roles={'Senior Administrator','Administrator'}, _title={'readme.backers-management'}, _width=230 }, - { _roles={'Board Member','Senior Backer'}, _title={'readme.backers-board'}, _width=145 }, -- change role to board - { _roles={'Sponsor','Supporter'}, _title={'readme.backers-backers'}, _width=196 }, -- change to backer - { _roles={'Moderator','Trainee'}, _title={'readme.backers-staff'}, _width=235 }, + { _roles={'Senior Administrator', 'Administrator'}, _title={'readme.backers-management'}, _width=230 }, + { _roles={'Board Member', 'Senior Backer'}, _title={'readme.backers-board'}, _width=145 }, -- change role to board + { _roles={'Sponsor', 'Supporter'}, _title={'readme.backers-backers'}, _width=196 }, -- change to backer + { _roles={'Moderator', 'Trainee'}, _title={'readme.backers-staff'}, _width=235 }, { _roles={}, _time=3*3600*60, _title={'readme.backers-active'}, _width=235 }, } @@ -245,12 +295,12 @@ Gui.element(function(_,parent) local scroll_pane = title_table_scroll(container) for _, players in ipairs(groups) do local table = title_table(scroll_pane, players._width, players._title, 4) - for _,player_name in ipairs(players) do + for _, player_name in ipairs(players) do Gui.centered_label(table, 140, player_name) end if #players < 4 then - for i = 1,4-#players do + for i = 1, 4-#players do Gui.centered_label(table, 140) end end @@ -259,11 +309,102 @@ Gui.element(function(_,parent) return container end)) +--- Content area for the player data tab +-- @element commands_content +Tab({'readme.data-tab'}, {'readme.data-tooltip'}, +Gui.element(function(_, parent) + local container = parent.add{ type='flow', direction='vertical' } + local player = Gui.get_player_from_element(parent) + local player_name = player.name + + local enum = PlayerData.PreferenceEnum + local preference = PlayerData.DataSavingPreference:get(player_name) + local preference_meta = PlayerData.DataSavingPreference.metadata + preference = enum[preference] + + -- Add the title and description to the content + Gui.title_label(container, title_width, {'readme.data-tab'}) + Gui.centered_label(container, frame_width, {'readme.data-general'}) + Gui.bar(container) + container.add{ type='flow' } + local scroll_pane = title_table_scroll(container) + + -- Add the required area + local required = title_table(scroll_pane, 250, {'readme.data-required'}, 2) + Gui.centered_label(required, 150, preference_meta.name, preference_meta.tooltip) + Gui.centered_label(required, 420, {'expcore-data.preference-'..enum[preference]}, preference_meta.value_tooltip) + + for name, child in pairs(PlayerData.Required.children) do + local metadata = child.metadata + local value = child:get(player_name) + if value ~= nil or metadata.show_always then + if metadata.stringify then value = metadata.stringify(value) end + Gui.centered_label(required, 150, metadata.name or {'exp-required.'..name}, metadata.tooltip or {'exp-required.'..name..'-tooltip'}) + Gui.centered_label(required, 420, tostring(value), metadata.value_tooltip or {'exp-required.'..name..'-value-tooltip'}) + end + end + + -- Add the settings area + if preference <= enum.Settings then + local settings = title_table(scroll_pane, 255, {'readme.data-settings'}, 2) + for name, child in pairs(PlayerData.Settings.children) do + local metadata = child.metadata + local value = child:get(player_name) + if not metadata.permission or Roles.player_allowed(player, metadata.permission) then + if metadata.stringify then value = metadata.stringify(value) end + if value == nil then value = 'None set' end + Gui.centered_label(settings, 150, metadata.name or {'exp-settings.'..name}, metadata.tooltip or {'exp-settings.'..name..'-tooltip'}) + Gui.centered_label(settings, 420, tostring(value), metadata.value_tooltip or {'exp-settings.'..name..'-value-tooltip'}) + end + end + end + + -- Add the statistics area + if preference <= enum.Statistics then + local count = 4 + local statistics = title_table(scroll_pane, 250, {'readme.data-statistics'}, 4) + for _, name in pairs(PlayerData.Statistics.metadata.display_order) do + local child = PlayerData.Statistics[name] + local metadata = child.metadata + local value = child:get(player_name) + if value ~= nil or metadata.show_always then + count = count - 2 + if metadata.stringify then value = metadata.stringify(value) + else value = format_number(value or 0) end + Gui.centered_label(statistics, 150, metadata.name or {'exp-statistics.'..name}, metadata.tooltip or {'exp-statistics.'..name..'-tooltip'}) + Gui.centered_label(statistics, 130, {'readme.data-format', value, metadata.unit or ''}, metadata.value_tooltip or {'exp-statistics.'..name..'-tooltip'}) + end + end + if count > 0 then for i = 1, count do Gui.centered_label(statistics, 140) end end + end + + -- Add the misc area + local skip = {DataSavingPreference=true, Settings=true, Statistics=true, Required=true} + local count = 0; for _ in pairs(PlayerData.All.children) do count = count + 1 end + if preference <= enum.All and count > 4 then + local misc = title_table(scroll_pane, 232, {'readme.data-misc'}, 2) + for name, child in pairs(PlayerData.All.children) do + if not skip[name] then + local metadata = child.metadata + local value = child:get(player_name) + if value ~= nil or metadata.show_always then + if metadata.stringify then value = metadata.stringify(value) end + Gui.centered_label(misc, 150, metadata.name or name, metadata.tooltip) + Gui.centered_label(misc, 420, tostring(value), metadata.value_tooltip) + end + end + end + end + + return container +end)) + + --- Main readme container for the center flow -- @element readme local readme_toggle local readme = -Gui.element(function(event_trigger,parent) +Gui.element(function(event_trigger, parent) local container = parent.add{ name = event_trigger, type = 'frame', @@ -272,7 +413,7 @@ Gui.element(function(event_trigger,parent) -- Add the left hand side of the frame back, removed because of frame_tabbed_pane style local left_alignment = Gui.alignment(container, nil, nil, 'bottom') - left_alignment.style.padding = {32,0,0,0} + left_alignment.style.padding = {32, 0,0, 0} local left_side = left_alignment.add{ @@ -291,7 +432,7 @@ Gui.element(function(event_trigger,parent) } -- Add the different content areas - for _,tab_details in ipairs(tabs) do + for _, tab_details in ipairs(tabs) do local tab = tab_pane.add{ type = 'tab', style = 'frame_tab', caption = tab_details[1], tooltip = tab_details[2] } tab_pane.add_tab(tab, tab_details[3](tab_pane)) end @@ -302,7 +443,7 @@ end) local toggle_button = Gui.get_top_element(player, readme_toggle) Gui.toolbar_button_style(toggle_button, true) end) -:on_close(function(player,element) +:on_close(function(player, element) local toggle_button = Gui.get_top_element(player, readme_toggle) Gui.toolbar_button_style(toggle_button, false) Gui.destroy_if_valid(element) @@ -311,10 +452,10 @@ end) --- Toggle button for the readme gui -- @element readme_toggle readme_toggle = -Gui.toolbar_button('virtual-signal/signal-info',{'readme.main-tooltip'},function(player) - return Roles.player_allowed(player,'gui/readme') +Gui.toolbar_button('virtual-signal/signal-info', {'readme.main-tooltip'}, function(player) + return Roles.player_allowed(player, 'gui/readme') end) -:on_click(function(player,_) +:on_click(function(player, _) local center = player.gui.center if center[readme.name] then player.opened = nil @@ -324,24 +465,24 @@ end) end) --- When a player joins the game for the first time show this gui -Event.add(defines.events.on_player_created,function(event) - local player = Game.get_player_by_index(event.player_index) +Event.add(defines.events.on_player_created, function(event) + local player = game.players[event.player_index] local element = readme(player.gui.center) element.pane.selected_tab_index = 1 player.opened = element end) --- When a player joins clear center unless the player has something open -Event.add(defines.events.on_player_joined_game,function(event) - local player = Game.get_player_by_index(event.player_index) +Event.add(defines.events.on_player_joined_game, function(event) + local player = game.players[event.player_index] if not player.opened then player.gui.center.clear() end end) --- When a player respawns clear center unless the player has something open -Event.add(defines.events.on_player_respawned,function(event) - local player = Game.get_player_by_index(event.player_index) +Event.add(defines.events.on_player_respawned, function(event) + local player = game.players[event.player_index] if not player.opened then player.gui.center.clear() end diff --git a/modules/gui/rocket-info.lua b/modules/gui/rocket-info.lua index 76eff7018d..87a6378caf 100644 --- a/modules/gui/rocket-info.lua +++ b/modules/gui/rocket-info.lua @@ -20,7 +20,7 @@ local time_formats = { } --- Check if a player is allowed to use certain interactions -local function check_player_permissions(player,action) +local function check_player_permissions(player, action) if not config.progress['allow_'..action] then return false end @@ -30,7 +30,7 @@ local function check_player_permissions(player,action) end if config.progress[action..'_role_permission'] - and not Roles.player_allowed(player,config.progress[action..'_role_permission']) then + and not Roles.player_allowed(player, config.progress[action..'_role_permission']) then return false end @@ -46,7 +46,7 @@ Gui.element{ tooltip = {'rocket-info.toggle-rocket-tooltip'} } :style(Gui.sprite_style(16)) -:on_click(function(_,element,_) +:on_click(function(_, element, _) local rocket_silo_name = element.parent.name:sub(8) local rocket_silo = Rockets.get_silo_entity(rocket_silo_name) if rocket_silo.auto_launch then @@ -68,21 +68,21 @@ Gui.element{ sprite = 'utility/center', tooltip = {'rocket-info.launch-tooltip'} } -:style(Gui.sprite_style(16,-1)) -:on_click(function(player,element,_) +:style(Gui.sprite_style(16, -1)) +:on_click(function(player, element, _) local rocket_silo_name = element.parent.name:sub(8) local silo_data = Rockets.get_silo_data_by_name(rocket_silo_name) if silo_data.entity.launch_rocket() then element.enabled = false else - player.print({'rocket-info.launch-failed'},Colors.orange_red) + player.print({'rocket-info.launch-failed'}, Colors.orange_red) end end) --- XY cords that allow zoom to map when pressed -- @element silo_cords local silo_cords = -Gui.element(function(event_trigger,parent,silo_data) +Gui.element(function(event_trigger, parent, silo_data) local silo_name = silo_data.silo_name local pos = silo_data.position local name = config.progress.allow_zoom_to_map and event_trigger or nil @@ -94,13 +94,13 @@ Gui.element(function(event_trigger,parent,silo_data) name = 'label-x-'..silo_name, caption = silo_name } - flow_x.style.padding = {0,2,0,1} + flow_x.style.padding = {0, 2,0, 1} -- Add the x cord label flow_x.add{ type = 'label', name = name, - caption = {'rocket-info.progress-x-pos',pos.x}, + caption = {'rocket-info.progress-x-pos', pos.x}, tooltip = tooltip } @@ -110,32 +110,32 @@ Gui.element(function(event_trigger,parent,silo_data) name = 'label-y-'..silo_name, caption = silo_name } - flow_y.style.padding = {0,2,0,1} + flow_y.style.padding = {0, 2,0, 1} -- Add the y cord label flow_y.add{ type = 'label', name = name, - caption = {'rocket-info.progress-y-pos',pos.y}, + caption = {'rocket-info.progress-y-pos', pos.y}, tooltip = tooltip } end) -:on_click(function(player,element,_) +:on_click(function(player, element, _) local rocket_silo_name = element.parent.caption local rocket_silo = Rockets.get_silo_entity(rocket_silo_name) - player.zoom_to_world(rocket_silo.position,2) + player.zoom_to_world(rocket_silo.position, 2) end) --- Base element for each rocket in the progress list -- @element rocket_entry local rocket_entry = -Gui.element(function(_,parent,silo_data) +Gui.element(function(_, parent, silo_data) local silo_name = silo_data.silo_name local player = Gui.get_player_from_element(parent) -- Add the toggle auto launch if the player is allowed it - if check_player_permissions(player,'toggle_active') then + if check_player_permissions(player, 'toggle_active') then local flow = parent.add{ type = 'flow', name = 'toggle-'..silo_name} local button = toggle_launch(flow) button.tooltip = silo_data.toggle_tooltip @@ -143,17 +143,17 @@ Gui.element(function(_,parent,silo_data) end -- Add the remote launch if the player is allowed it - if check_player_permissions(player,'remote_launch') then + if check_player_permissions(player, 'remote_launch') then local flow = parent.add{ type = 'flow', name = 'launch-'..silo_name} local button = launch_rocket(flow) button.enabled = silo_data.allow_launch end -- Draw the silo cords element - silo_cords(parent,silo_data) + silo_cords(parent, silo_data) -- Add a progress label - local alignment = Gui.alignment(parent,silo_name) + local alignment = Gui.alignment(parent, silo_name) local element = alignment.add{ type = 'label', @@ -169,7 +169,7 @@ end) --- Data label which contains a name and a value label pair -- @element data_label local data_label = -Gui.element(function(_,parent,label_data) +Gui.element(function(_, parent, label_data) local data_name = label_data.name local data_subname = label_data.subname local data_fullname = data_subname and data_name..data_subname or data_name @@ -178,13 +178,13 @@ Gui.element(function(_,parent,label_data) local name_label = parent.add{ type = 'label', name = data_fullname..'-label', - caption = {'rocket-info.data-caption-'..data_name,data_subname}, - tooltip = {'rocket-info.data-tooltip-'..data_name,data_subname} + caption = {'rocket-info.data-caption-'..data_name, data_subname}, + tooltip = {'rocket-info.data-tooltip-'..data_name, data_subname} } - name_label.style.padding = {0,2} + name_label.style.padding = {0, 2} --- Right aligned label to store the data - local alignment = Gui.alignment(parent,data_fullname) + local alignment = Gui.alignment(parent, data_fullname) local element = alignment.add{ type = 'label', @@ -192,17 +192,17 @@ Gui.element(function(_,parent,label_data) caption = label_data.value, tooltip = label_data.tooltip } - element.style.padding = {0,2} + element.style.padding = {0, 2} return element end) -- Used to update the captions and tooltips on the data labels -local function update_data_labels(parent,data_label_data) +local function update_data_labels(parent, data_label_data) for _, label_data in ipairs(data_label_data) do local data_name = label_data.subname and label_data.name..label_data.subname or label_data.name if not parent[data_name] then - data_label(parent,label_data) + data_label(parent, label_data) else local data_label_element = parent[data_name].label data_label_element.tooltip = label_data.tooltip @@ -220,7 +220,7 @@ local function get_progress_data(force_name) if not rocket_silo or not rocket_silo.valid then -- Remove from list if not valid force_silos[silo_data.name] = nil - table.insert(progress_data,{ + table.insert(progress_data, { silo_name = silo_data.name, remove = true }) @@ -228,14 +228,14 @@ local function get_progress_data(force_name) else -- Get the progress caption and tooltip local progress_color = Colors.white - local progress_caption = {'rocket-info.progress-caption',rocket_silo.rocket_parts} - local progress_tooltip = {'rocket-info.progress-tooltip',silo_data.launched or 0} + local progress_caption = {'rocket-info.progress-caption', rocket_silo.rocket_parts} + local progress_tooltip = {'rocket-info.progress-tooltip', silo_data.launched or 0} local status = rocket_silo.status == defines.entity_status.waiting_to_launch_rocket if status and silo_data.awaiting_reset then progress_caption = {'rocket-info.progress-launched'} progress_color = Colors.green elseif status then - progress_caption = {'rocket-info.progress-caption',100} + progress_caption = {'rocket-info.progress-caption', 100} progress_color = Colors.cyan else silo_data.awaiting_reset = false @@ -250,7 +250,7 @@ local function get_progress_data(force_name) end -- Insert the gui data - table.insert(progress_data,{ + table.insert(progress_data, { silo_name = silo_data.name, position = rocket_silo.position, allow_launch = not silo_data.awaiting_reset and status or false, @@ -267,7 +267,7 @@ local function get_progress_data(force_name) end --- Update the build progress section -local function update_build_progress(parent,progress_data) +local function update_build_progress(parent, progress_data) local show_message = true for _, silo_data in ipairs(progress_data) do parent.parent.no_silos.visible = false @@ -285,7 +285,7 @@ local function update_build_progress(parent,progress_data) elseif not progress_label then -- Add the rocket to the list show_message = false - rocket_entry(parent,silo_data) + rocket_entry(parent, silo_data) else show_message = false @@ -323,7 +323,7 @@ local function get_stats_data(force_name) -- Format the first launch data if config.stats.show_first_rocket then local value = stats.first_launch or 0 - table.insert(stats_data,{ + table.insert(stats_data, { name = 'first-launch', value = time_formats.caption_hours(value), tooltip = time_formats.tooltip_hours(value) @@ -333,7 +333,7 @@ local function get_stats_data(force_name) -- Format the last launch data if config.stats.show_last_rocket then local value = stats.last_launch or 0 - table.insert(stats_data,{ + table.insert(stats_data, { name = 'last-launch', value = time_formats.caption_hours(value), tooltip = time_formats.tooltip_hours(value) @@ -343,7 +343,7 @@ local function get_stats_data(force_name) -- Format fastest launch data if config.stats.show_fastest_rocket then local value = stats.fastest_launch or 0 - table.insert(stats_data,{ + table.insert(stats_data, { name = 'fastest-launch', value = time_formats.caption_hours(value), tooltip = time_formats.tooltip_hours(value) @@ -354,18 +354,18 @@ local function get_stats_data(force_name) if config.stats.show_total_rockets then local total_rockets = Rockets.get_game_rocket_count() total_rockets = total_rockets == 0 and 1 or total_rockets - local percentage = math.round(force_rockets/total_rockets,3)*100 - table.insert(stats_data,{ + local percentage = math.round(force_rockets/total_rockets, 3)*100 + table.insert(stats_data, { name = 'total-rockets', value = force_rockets, - tooltip = {'rocket-info.value-tooltip-total-rockets',percentage} + tooltip = {'rocket-info.value-tooltip-total-rockets', percentage} }) end -- Format game avg data if config.stats.show_game_avg then local avg = force_rockets > 0 and math.floor(game.tick/force_rockets) or 0 - table.insert(stats_data,{ + table.insert(stats_data, { name = 'avg-launch', value = time_formats.caption(avg), tooltip = time_formats.tooltip(avg) @@ -373,9 +373,9 @@ local function get_stats_data(force_name) end -- Format rolling avg data - for _,avg_over in pairs(config.stats.rolling_avg) do - local avg = Rockets.get_rolling_average(force_name,avg_over) - table.insert(stats_data,{ + for _, avg_over in pairs(config.stats.rolling_avg) do + local avg = Rockets.get_rolling_average(force_name, avg_over) + table.insert(stats_data, { name = 'avg-launch-n', subname = avg_over, value = time_formats.caption(avg), @@ -392,17 +392,17 @@ local function get_milestone_data(force_name) local force_rockets = Rockets.get_rocket_count(force_name) local milestone_data = {} - for _,milestone in ipairs(config.milestones) do + for _, milestone in ipairs(config.milestones) do if milestone <= force_rockets then - local time = Rockets.get_rocket_time(force_name,milestone) - table.insert(milestone_data,{ + local time = Rockets.get_rocket_time(force_name, milestone) + table.insert(milestone_data, { name = 'milestone-n', subname = milestone, value = time_formats.caption_hours(time), tooltip = time_formats.tooltip_hours(time) }) else - table.insert(milestone_data,{ + table.insert(milestone_data, { name = 'milestone-n', subname = milestone, value = {'rocket-info.data-caption-milestone-next'}, @@ -425,7 +425,7 @@ Gui.element{ tooltip = {'rocket-info.toggle-section-tooltip'} } :style(Gui.sprite_style(20)) -:on_click(function(_,element,_) +:on_click(function(_, element, _) local header_flow = element.parent local flow_name = header_flow.caption local flow = header_flow.parent.parent[flow_name] @@ -451,7 +451,7 @@ end) -- Draw a section header and main scroll -- @element rocket_list_container local section = -Gui.element(function(_,parent,section_name,table_size) +Gui.element(function(_, parent, section_name, table_size) -- Draw the header for the section local header = Gui.header( parent, @@ -467,7 +467,7 @@ Gui.element(function(_,parent,section_name,table_size) toggle_section(header) -- Table used to store the data - local scroll_table = Gui.scroll_table(parent,215,table_size,section_name) + local scroll_table = Gui.scroll_table(parent, 215, table_size, section_name) scroll_table.parent.visible = false -- Return the flow table @@ -477,9 +477,9 @@ end) --- Main gui container for the left flow -- @element rocket_list_container local rocket_list_container = -Gui.element(function(event_trigger,parent) +Gui.element(function(event_trigger, parent) -- Draw the internal container - local container = Gui.container(parent,event_trigger,200) + local container = Gui.container(parent, event_trigger, 200) -- Set the container style local style = container.style @@ -489,27 +489,27 @@ Gui.element(function(event_trigger,parent) local force_name = player.force.name -- Draw stats section if config.stats.show_stats then - update_data_labels(section(container,'stats',2),get_stats_data(force_name)) + update_data_labels(section(container, 'stats', 2), get_stats_data(force_name)) end -- Draw milestones section if config.milestones.show_milestones then - update_data_labels(section(container,'milestones',2),get_milestone_data(force_name)) + update_data_labels(section(container, 'milestones', 2), get_milestone_data(force_name)) end -- Draw build progress list if config.progress.show_progress then local col_count = 3 - if check_player_permissions(player,'remote_launch') then col_count = col_count+1 end - if check_player_permissions(player,'toggle_active') then col_count = col_count+1 end - local progress = section(container,'progress',col_count) + if check_player_permissions(player, 'remote_launch') then col_count = col_count+1 end + if check_player_permissions(player, 'toggle_active') then col_count = col_count+1 end + local progress = section(container, 'progress', col_count) -- Label used when there are no active silos local no_silos = progress.parent.add{ type = 'label', name = 'no_silos', caption = {'rocket-info.progress-no-silos'} } - no_silos.style.padding = {1,2} + no_silos.style.padding = {1, 2} update_build_progress(progress, get_progress_data(force_name)) end @@ -517,13 +517,13 @@ Gui.element(function(event_trigger,parent) return container.parent end) :add_to_left_flow(function(player) - return player.force.rockets_launched > 0 and Roles.player_allowed(player,'gui/rocket-info') + return player.force.rockets_launched > 0 and Roles.player_allowed(player, 'gui/rocket-info') end) --- Button on the top flow used to toggle the container -- @element toggle_left_element Gui.left_toolbar_button('item/satellite', {'rocket-info.main-tooltip'}, rocket_list_container, function(player) - return Roles.player_allowed(player,'gui/rocket-info') + return Roles.player_allowed(player, 'gui/rocket-info') end) --- Update the gui for all players on a force @@ -531,17 +531,17 @@ local function update_rocket_gui_all(force_name) local stats = get_stats_data(force_name) local milestones = get_milestone_data(force_name) local progress = get_progress_data(force_name) - for _,player in pairs(game.forces[force_name].players) do - local frame = Gui.get_left_element(player,rocket_list_container) + for _, player in pairs(game.forces[force_name].players) do + local frame = Gui.get_left_element(player, rocket_list_container) local container = frame.container - update_data_labels(container.stats.table,stats) - update_data_labels(container.milestones.table,milestones) - update_build_progress(container.progress.table,progress) + update_data_labels(container.stats.table, stats) + update_data_labels(container.milestones.table, milestones) + update_build_progress(container.progress.table, progress) end end --- Event used to update the stats when a rocket is launched -Event.add(defines.events.on_rocket_launched,function(event) +Event.add(defines.events.on_rocket_launched, function(event) local force = event.rocket_silo.force update_rocket_gui_all(force.name) end) @@ -549,23 +549,23 @@ end) --- Update only the progress gui for a force local function update_rocket_gui_progress(force_name) local progress = get_progress_data(force_name) - for _,player in pairs(game.forces[force_name].players) do - local frame = Gui.get_left_element(player,rocket_list_container) + for _, player in pairs(game.forces[force_name].players) do + local frame = Gui.get_left_element(player, rocket_list_container) local container = frame.container - update_build_progress(container.progress.table,progress) + update_build_progress(container.progress.table, progress) end end --- Event used to set a rocket silo to be awaiting reset -Event.add(defines.events.on_rocket_launch_ordered,function(event) +Event.add(defines.events.on_rocket_launch_ordered, function(event) local silo = event.rocket_silo local silo_data = Rockets.get_silo_data(silo) silo_data.awaiting_reset = true update_rocket_gui_progress(silo.force.name) end) -Event.on_nth_tick(150,function() - for _,force in pairs(game.forces) do +Event.on_nth_tick(150, function() + for _, force in pairs(game.forces) do if #Rockets.get_silos(force.name) > 0 then update_rocket_gui_progress(force.name) end @@ -580,20 +580,20 @@ local function on_built(event) end end -Event.add(defines.events.on_built_entity,on_built) -Event.add(defines.events.on_robot_built_entity,on_built) +Event.add(defines.events.on_built_entity, on_built) +Event.add(defines.events.on_robot_built_entity, on_built) --- Redraw the progress section on role change local function role_update_event(event) if not config.progress.show_progress then return end local player = game.players[event.player_index] - local container = Gui.get_left_element(player,rocket_list_container).container + local container = Gui.get_left_element(player, rocket_list_container).container local progress_scroll = container.progress Gui.destroy_if_valid(progress_scroll.table) local col_count = 3 - if check_player_permissions(player,'remote_launch') then col_count = col_count+1 end - if check_player_permissions(player,'toggle_active') then col_count = col_count+1 end + if check_player_permissions(player, 'remote_launch') then col_count = col_count+1 end + if check_player_permissions(player, 'toggle_active') then col_count = col_count+1 end local progress = progress_scroll.add{ type = 'table', name = 'table', @@ -603,7 +603,7 @@ local function role_update_event(event) update_build_progress(progress, get_progress_data(player.force.name)) end -Event.add(Roles.events.on_role_assigned,role_update_event) -Event.add(Roles.events.on_role_unassigned,role_update_event) +Event.add(Roles.events.on_role_assigned, role_update_event) +Event.add(Roles.events.on_role_unassigned, role_update_event) return rocket_list_container \ No newline at end of file diff --git a/modules/gui/science-info.lua b/modules/gui/science-info.lua index 01450b7f74..dad0e6c613 100644 --- a/modules/gui/science-info.lua +++ b/modules/gui/science-info.lua @@ -11,19 +11,19 @@ local config = require 'config.gui.science' --- @dep config.gui.science local Production = require 'modules.control.production' --- @dep modules.control.production local format_time = _C.format_time --- @dep expcore.common -local null_time_short = {'science-info.eta-time',format_time(0,{hours=true,minutes=true,seconds=true,time=true,null=true})} -local null_time_long = format_time(0,{hours=true,minutes=true,seconds=true,long=true,null=true}) +local null_time_short = {'science-info.eta-time', format_time(0, {hours=true, minutes=true, seconds=true, time=true, null=true})} +local null_time_long = format_time(0, {hours=true, minutes=true, seconds=true, long=true, null=true}) --- Data label that contains the value and the surfix -- @element production_label local production_label = -Gui.element(function(_,parent,production_label_data) +Gui.element(function(_, parent, production_label_data) local name = production_label_data.name local tooltip = production_label_data.tooltip local color = production_label_data.color -- Add an alignment for the number - local alignment = Gui.alignment(parent,name) + local alignment = Gui.alignment(parent, name) -- Add the main value label local element = @@ -42,7 +42,7 @@ Gui.element(function(_,parent,production_label_data) parent.add{ name = 'surfix-'..name, type = 'label', - caption = {'science-info.unit',production_label_data.surfix}, + caption = {'science-info.unit', production_label_data.surfix}, tooltip = tooltip } @@ -70,20 +70,20 @@ local function get_production_label_data(name, tooltip, value, cutout, secondary end -- Updates a prodution label to match the current data -local function update_production_label(parent,production_label_data) +local function update_production_label(parent, production_label_data) local name = production_label_data.name local tooltip = production_label_data.tooltip local color = production_label_data.color -- Update the production label - local production_label_element = parent[name] and parent[name].label or production_label(parent,production_label_data) + local production_label_element = parent[name] and parent[name].label or production_label(parent, production_label_data) production_label_element.caption = production_label_data.caption production_label_element.tooltip = production_label_data.tooltip production_label_element.style.font_color = color -- Update the surfix label local surfix_element = parent['surfix-'..name] - surfix_element.caption = {'science-info.unit',production_label_data.surfix} + surfix_element.caption = {'science-info.unit', production_label_data.surfix} surfix_element.tooltip = tooltip surfix_element.style.font_color = color @@ -92,7 +92,7 @@ end --- Adds 4 elements that show the data for a science pack -- @element science_pack_base local science_pack_base = -Gui.element(function(_,parent,science_pack_data) +Gui.element(function(_, parent, science_pack_data) local science_pack = science_pack_data.science_pack -- Draw the icon for the science pack @@ -111,7 +111,7 @@ Gui.element(function(_,parent,science_pack_data) pack_icon.ignored_by_interaction = true pack_icon_style.height = 55 if icon_style == 'slot_button' then - pack_icon_style.padding = {0,-2} + pack_icon_style.padding = {0, -2} pack_icon_style.width = 36 end @@ -122,7 +122,7 @@ Gui.element(function(_,parent,science_pack_data) type = 'frame', style = 'bordered_frame' } - delta_flow.style.padding = {0,3} + delta_flow.style.padding = {0, 3} -- Draw the delta flow table local delta_table = @@ -142,7 +142,7 @@ Gui.element(function(_,parent,science_pack_data) return pack_icon end) -local function get_science_pack_data(player,science_pack) +local function get_science_pack_data(player, science_pack) local force = player.force -- Check that some packs have been made @@ -186,28 +186,28 @@ local function get_science_pack_data(player,science_pack) end -local function update_science_pack(pack_table,science_pack_data) +local function update_science_pack(pack_table, science_pack_data) if not science_pack_data then return end local science_pack = science_pack_data.science_pack pack_table.parent.non_made.visible = false -- Update the icon - local pack_icon = pack_table['icon-'..science_pack] or science_pack_base(pack_table,science_pack_data) + local pack_icon = pack_table['icon-'..science_pack] or science_pack_base(pack_table, science_pack_data) local icon_style = science_pack_data.icon_style pack_icon.style = icon_style local pack_icon_style = pack_icon.style pack_icon_style.height = 55 if icon_style == 'slot_button' then - pack_icon_style.padding = {0,-2} + pack_icon_style.padding = {0, -2} pack_icon_style.width = 36 end -- Update the production labels local delta_table = pack_table['delta-'..science_pack].table - update_production_label(delta_table,science_pack_data.positive) - update_production_label(delta_table,science_pack_data.negative) - update_production_label(pack_table,science_pack_data.net) + update_production_label(delta_table, science_pack_data.positive) + update_production_label(delta_table, science_pack_data.negative) + update_production_label(pack_table, science_pack_data.net) end @@ -226,7 +226,7 @@ local function get_eta_label_data(player) local remaining = research.research_unit_count*(1-progress) -- Check for the limiting science pack - for _,ingredient in pairs(research.research_unit_ingredients) do + for _, ingredient in pairs(research.research_unit_ingredients) do local pack_name = ingredient.name local required = ingredient.amount * remaining local time = Production.get_consumsion_eta(force, pack_name, defines.flow_precision_index.one_minute, required) @@ -238,14 +238,14 @@ local function get_eta_label_data(player) -- Return the caption and tooltip return limit and limit > 0 and { research = true, - caption = format_time(limit,{hours=true,minutes=true,seconds=true,time=true}), - tooltip = format_time(limit,{hours=true,minutes=true,seconds=true,long=true}) + caption = format_time(limit, {hours=true, minutes=true, seconds=true, time=true}), + tooltip = format_time(limit, {hours=true, minutes=true, seconds=true, long=true}) } or { research = false } end -- Updates the eta label -local function update_eta_label(element,eta_label_data) +local function update_eta_label(element, eta_label_data) -- If no research selected show null if not eta_label_data.research then element.caption = null_time_short @@ -254,24 +254,24 @@ local function update_eta_label(element,eta_label_data) end -- Update the element - element.caption = {'science-info.eta-time',eta_label_data.caption} + element.caption = {'science-info.eta-time', eta_label_data.caption} element.tooltip = eta_label_data.tooltip end --- Main task list container for the left flow -- @element task_list_container local science_info_container = -Gui.element(function(event_trigger,parent) +Gui.element(function(event_trigger, parent) local player = Gui.get_player_from_element(parent) -- Draw the internal container - local container = Gui.container(parent,event_trigger,200) + local container = Gui.container(parent, event_trigger, 200) -- Draw the header Gui.header(container, {'science-info.main-caption'}, {'science-info.main-tooltip'}) -- Draw the scroll table for the tasks - local scroll_table = Gui.scroll_table(container,178,4) + local scroll_table = Gui.scroll_table(container, 178, 4) -- Draw the no packs label local no_packs_label = @@ -283,7 +283,7 @@ Gui.element(function(event_trigger,parent) -- Change the style of the no packs label local no_packs_style = no_packs_label.style - no_packs_style.padding = {2,4} + no_packs_style.padding = {2, 4} no_packs_style.single_line = false no_packs_style.width = 200 @@ -303,13 +303,13 @@ Gui.element(function(event_trigger,parent) } -- Update the eta - update_eta_label(eta_label,get_eta_label_data(player)) + update_eta_label(eta_label, get_eta_label_data(player)) end -- Add packs which have been made - for _,science_pack in ipairs(config) do - update_science_pack(scroll_table,get_science_pack_data(player,science_pack)) + for _, science_pack in ipairs(config) do + update_science_pack(scroll_table, get_science_pack_data(player, science_pack)) end -- Return the exteral container @@ -320,16 +320,16 @@ end) --- Button on the top flow used to toggle the task list container -- @element toggle_left_element Gui.left_toolbar_button('entity/lab', {'science-info.main-tooltip'}, science_info_container, function(player) - return Roles.player_allowed(player,'gui/science-info') + return Roles.player_allowed(player, 'gui/science-info') end) --- Updates the gui every 1 second -Event.on_nth_tick(60,function() +Event.on_nth_tick(60, function() local force_pack_data = {} local force_eta_data = {} - for _,player in pairs(game.connected_players) do + for _, player in pairs(game.connected_players) do local force_name = player.force.name - local frame = Gui.get_left_element(player,science_info_container) + local frame = Gui.get_left_element(player, science_info_container) local container = frame.container -- Update the science packs diff --git a/modules/gui/server-ups.lua b/modules/gui/server-ups.lua index 29ca65425f..9d294b365b 100644 --- a/modules/gui/server-ups.lua +++ b/modules/gui/server-ups.lua @@ -7,6 +7,16 @@ local Gui = require 'expcore.gui' --- @dep expcore.gui local Event = require 'utils.event' --- @dep utils.event local Commands = require 'expcore.commands' --- @dep expcore.commands +local External = require 'expcore.external' --- @dep expcore.external + +--- Stores the visible state of server ups +local PlayerData = require 'expcore.player_data' --- @dep expcore.player_data +local UsesServerUps = PlayerData.Settings:combine('UsesServerUps') +UsesServerUps:set_default(false) +UsesServerUps:set_metadata{ + permission = 'command/server-ups', + stringify = function(value) return value and 'Visible' or 'Hidden' end +} --- Label to show the server ups -- @element server_ups @@ -19,16 +29,26 @@ Gui.element{ font = 'default-game' } +--- Change the visible state when your data loads +UsesServerUps:on_load(function(player_name, visible) + local player = game.players[player_name] + local label = player.gui.screen[server_ups.name] + if not External.valid() or not global.ext.var.server_ups then visible = false end + label.visible = visible +end) + --- Toggles if the server ups is visbile -- @command server-ups -Commands.new_command('server-ups','Toggle the server ups display') -:add_alias('sups','ups') +Commands.new_command('server-ups', 'Toggle the server UPS display') +:add_alias('sups', 'ups') :register(function(player) local label = player.gui.screen[server_ups.name] - if not global.ext or not global.ext.server_ups then + if not External.valid() then + label.visible = false return Commands.error{'expcom-server-ups.no-ext'} end label.visible = not label.visible + UsesServerUps:set(player, label.visible) end) -- Set the location of the label @@ -42,7 +62,7 @@ local function set_location(event) end -- Draw the label when the player joins -Event.add(defines.events.on_player_created,function(event) +Event.add(defines.events.on_player_created, function(event) local player = game.players[event.player_index] local label = server_ups(player.gui.screen) label.visible = false @@ -50,15 +70,15 @@ Event.add(defines.events.on_player_created,function(event) end) -- Update the caption for all online players -Event.on_nth_tick(60,function() - if global.ext and global.ext.server_ups then - local caption = 'SUPS = '..global.ext.server_ups - for _,player in pairs(game.connected_players) do +Event.on_nth_tick(60, function() + if External.valid() then + local caption = 'SUPS = '..External.get_server_ups() + for _, player in pairs(game.connected_players) do player.gui.screen[server_ups.name].caption = caption end end end) -- Update when res or ui scale changes -Event.add(defines.events.on_player_display_resolution_changed,set_location) -Event.add(defines.events.on_player_display_scale_changed,set_location) \ No newline at end of file +Event.add(defines.events.on_player_display_resolution_changed, set_location) +Event.add(defines.events.on_player_display_scale_changed, set_location) \ No newline at end of file diff --git a/modules/gui/task-list.lua b/modules/gui/task-list.lua index 6bac376ce7..a83b3aa583 100644 --- a/modules/gui/task-list.lua +++ b/modules/gui/task-list.lua @@ -18,7 +18,7 @@ local Styles = { } --- If a player is allowed to use the edit buttons -local function check_player_permissions(player,task) +local function check_player_permissions(player, task) if task then -- When a task is given check if the player can edit it local allow_edit_task = config.allow_edit_task @@ -34,7 +34,7 @@ local function check_player_permissions(player,task) elseif allow_edit_task == 'admin' then return player.admin elseif allow_edit_task == 'expcore.roles' then - return Roles.player_allowed(player,config.expcore_roles_allow_edit_task) + return Roles.player_allowed(player, config.expcore_roles_allow_edit_task) end -- Return false as all other condidtions have not been met @@ -49,7 +49,7 @@ local function check_player_permissions(player,task) elseif allow_add_task == 'admin' then return player.admin elseif allow_add_task == 'expcore.roles' then - return Roles.player_allowed(player,config.expcore_roles_allow_add_task) + return Roles.player_allowed(player, config.expcore_roles_allow_add_task) end -- Return false as all other condidtions have not been met @@ -67,8 +67,8 @@ Gui.element{ style = 'tool_button' } :style(Styles.sprite20) -:on_click(function(player,_,_) - Tasks.add_task(player.force.name,nil,player.name) +:on_click(function(player, _,_) + Tasks.add_task(player.force.name, nil, player.name) end) --- Button displayed next to tasks which the user is can edit, used to start editing a task @@ -81,9 +81,9 @@ Gui.element{ style = 'tool_button' } :style(Styles.sprite20) -:on_click(function(player,element,_) +:on_click(function(player, element, _) local task_id = element.parent.name:sub(6) - Tasks.set_editing(task_id,player.name,true) + Tasks.set_editing(task_id, player.name, true) end) --- Button displayed next to tasks which the user is can edit, used to delete a task from the list @@ -96,7 +96,7 @@ Gui.element{ style = 'tool_button' } :style(Styles.sprite20) -:on_click(function(_,element,_) +:on_click(function(_, element, _) local task_id = element.parent.name:sub(6) Tasks.remove_task(task_id) end) @@ -104,7 +104,7 @@ end) --- Set of three elements which make up each row of the task table -- @element add_task_base local add_task_base = -Gui.element(function(_,parent,task_id) +Gui.element(function(_, parent, task_id) -- Add the task number label local task_number = parent.add{ name = 'count-'..task_id, @@ -118,7 +118,7 @@ Gui.element(function(_,parent,task_id) task_flow.style.padding = 0 -- Add the two edit buttons outside the task flow - local edit_flow = Gui.alignment(parent,'edit-'..task_id) + local edit_flow = Gui.alignment(parent, 'edit-'..task_id) edit_task(edit_flow) discard_task(edit_flow) @@ -127,7 +127,7 @@ Gui.element(function(_,parent,task_id) end) -- Removes the three elements that are added as part of the task base -local function remove_task_base(parent,task_id) +local function remove_task_base(parent, task_id) Gui.destroy_if_valid(parent['count-'..task_id]) Gui.destroy_if_valid(parent['edit-'..task_id]) Gui.destroy_if_valid(parent[task_id]) @@ -144,11 +144,11 @@ Gui.element{ style = 'shortcut_bar_button_green' } :style(Styles.sprite22) -:on_click(function(player,element,_) +:on_click(function(player, element, _) local task_id = element.parent.name local new_message = element.parent[task_editing.name].text - Tasks.set_editing(task_id,player.name) - Tasks.update_task(task_id,new_message,player.name) + Tasks.set_editing(task_id, player.name) + Tasks.update_task(task_id, new_message, player.name) end) --- Button displayed next to tasks which the user is currently editing, used to discard changes @@ -161,15 +161,15 @@ Gui.element{ style = 'shortcut_bar_button_red' } :style(Styles.sprite22) -:on_click(function(player,element,_) +:on_click(function(player, element, _) local task_id = element.parent.name - Tasks.set_editing(task_id,player.name) + Tasks.set_editing(task_id, player.name) end) --- Editing state for a task, contrins a text field and the two edit buttons -- @element task_editing task_editing = -Gui.element(function(event_trigger,parent,task) +Gui.element(function(event_trigger, parent, task) local message = task.message -- Draw the element @@ -192,17 +192,17 @@ end) maximal_width = 110, height = 20 } -:on_confirmed(function(player,element,_) +:on_confirmed(function(player, element, _) local task_id = element.parent.name local new_message = element.text - Tasks.set_editing(task_id,player.name) - Tasks.update_task(task_id,new_message,player.name) + Tasks.set_editing(task_id, player.name) + Tasks.update_task(task_id, new_message, player.name) end) --- Default state for a task, contains only a label with the task message -- @element task_label local task_label = -Gui.element(function(_,parent,task) +Gui.element(function(_, parent, task) local message = task.message local last_edit_name = task.last_edit_name local last_edit_time = task.last_edit_time @@ -220,7 +220,7 @@ end) } --- Updates a task for a player -local function update_task(player,task_table,task_id) +local function update_task(player, task_table, task_id) local task = Tasks.get_task(task_id) local task_ids = Tasks.get_force_task_ids(player.force.name) local task_number = table.get_index(task_ids, task_id) @@ -228,19 +228,19 @@ local function update_task(player,task_table,task_id) -- Task no longer exists so should be removed from the list if not task then task_table.parent.no_tasks.visible = #task_ids == 0 - remove_task_base(task_table,task_id) + remove_task_base(task_table, task_id) return end -- Get the task flow for this task - local task_flow = task_table[task_id] or add_task_base(task_table,task_id) + local task_flow = task_table[task_id] or add_task_base(task_table, task_id) task_table.parent.no_tasks.visible = false task_table['count-'..task_id].caption = task_number..')' -- Update the edit flow local edit_flow = task_table['edit-'..task_id] - local player_allowed_edit = check_player_permissions(player,task) - local players_editing = table.get_keys(task.curently_editing) + local player_allowed_edit = check_player_permissions(player, task) + local players_editing = table.get_keys(task.currently_editing) local edit_task_element = edit_flow[edit_task.name] local discard_task_element = edit_flow[discard_task.name] @@ -248,16 +248,16 @@ local function update_task(player,task_table,task_id) discard_task_element.visible = player_allowed_edit if #players_editing > 0 then edit_task_element.hovered_sprite = 'utility/warning_icon' - edit_task_element.tooltip = {'task-list.edit-tooltip',table.concat(players_editing,', ')} + edit_task_element.tooltip = {'task-list.edit-tooltip', table.concat(players_editing, ', ')} else edit_task_element.hovered_sprite = edit_task_element.sprite edit_task_element.tooltip = {'task-list.edit-tooltip-none'} end -- Check if the player is was editing and/or currently editing - local task_entry = task_flow[task_editing.name] or task_label(task_flow,task) + local task_entry = task_flow[task_editing.name] or task_label(task_flow, task) local player_was_editing = task_entry.type == 'textfield' - local player_is_editing = task.curently_editing[player.name] + local player_is_editing = task.currently_editing[player.name] -- Update the task flow if not player_was_editing and not player_is_editing then @@ -272,24 +272,24 @@ local function update_task(player,task_table,task_id) -- Player was editing but is no longer, remove text field and add label edit_task_element.enabled = true task_flow.clear() - task_label(task_flow,task) + task_label(task_flow, task) elseif not player_was_editing and player_is_editing then -- Player was not editing but now is, remove label and add text field edit_task_element.enabled = false task_flow.clear() - task_editing(task_flow,task).focus() - task_table.parent.scroll_to_element(task_flow,'top-third') + task_editing(task_flow, task).focus() + task_table.parent.scroll_to_element(task_flow, 'top-third') end end -- Update all the tasks for a player -local function update_all_tasks(player,scroll_table) +local function update_all_tasks(player, scroll_table) local task_ids = Tasks.get_force_task_ids(player.force.name) if #task_ids > 0 then - for _,task_id in ipairs(task_ids) do - update_task(player,scroll_table,task_id) + for _, task_id in ipairs(task_ids) do + update_task(player, scroll_table, task_id) end end end @@ -297,9 +297,9 @@ end --- Main task list container for the left flow -- @element task_list_container local task_list_container = -Gui.element(function(event_trigger,parent) +Gui.element(function(event_trigger, parent) -- Draw the internal container - local container = Gui.container(parent,event_trigger,200) + local container = Gui.container(parent, event_trigger, 200) -- Draw the header local header = Gui.header( @@ -315,7 +315,7 @@ Gui.element(function(event_trigger,parent) add_new_task_element.visible = check_player_permissions(player) -- Draw the scroll table for the tasks - local scroll_table = Gui.scroll_table(container,190,3) + local scroll_table = Gui.scroll_table(container, 190, 3) scroll_table.draw_horizontal_lines = true scroll_table.vertical_centering = false @@ -334,7 +334,7 @@ Gui.element(function(event_trigger,parent) -- Change the style of the no tasks label local no_tasks_style = no_tasks_label.style - no_tasks_style.padding = {2,4} + no_tasks_style.padding = {2, 4} no_tasks_style.single_line = false no_tasks_style.width = 200 @@ -342,8 +342,8 @@ Gui.element(function(event_trigger,parent) local task_ids = Tasks.get_force_task_ids(player.force.name) if #task_ids > 0 then no_tasks_label.visible = false - for _,task_id in ipairs(task_ids) do - update_task(player,scroll_table,task_id) + for _, task_id in ipairs(task_ids) do + update_task(player, scroll_table, task_id) end end @@ -358,27 +358,27 @@ end) --- Button on the top flow used to toggle the task list container -- @element toggle_left_element Gui.left_toolbar_button('utility/not_enough_repair_packs_icon', {'task-list.main-tooltip'}, task_list_container, function(player) - return Roles.player_allowed(player,'gui/task-list') + return Roles.player_allowed(player, 'gui/task-list') end) ---- When a new task is added it will udpate the task list for everyone on that force -Tasks.on_update(function(task,task_id,removed_task) +--- When a new task is added it will update the task list for everyone on that force +Tasks.on_update(function(task_id, task, old_task) -- Get the force to update, task is nil when removed local force if task then force = game.forces[task.force_name] else - force = game.forces[removed_task.force_name] + force = game.forces[old_task.force_name] end -- Update the task for all the players on the force local task_ids = Tasks.get_force_task_ids(force.name) - for _,player in pairs(force.connected_players) do - local frame = Gui.get_left_element(player,task_list_container) + for _, player in pairs(force.connected_players) do + local frame = Gui.get_left_element(player, task_list_container) local scroll_table = frame.container.scroll.table -- Update the task that was changed - update_task(player,scroll_table,task_id) + update_task(player, scroll_table, task_id) -- Update the numbering of the other tasks if the task was removed if not task then @@ -391,26 +391,26 @@ Tasks.on_update(function(task,task_id,removed_task) end) --- Update the tasks when the player joins -Event.add(defines.events.on_player_joined_game,function(event) +Event.add(defines.events.on_player_joined_game, function(event) local player = game.players[event.player_index] - local frame = Gui.get_left_element(player,task_list_container) + local frame = Gui.get_left_element(player, task_list_container) local scroll_table = frame.container.scroll.table - update_all_tasks(player,scroll_table) + update_all_tasks(player, scroll_table) end) --- Makes sure the right buttons are present when roles change local function role_update_event(event) local player = game.players[event.player_index] - local container = Gui.get_left_element(player,task_list_container).container + local container = Gui.get_left_element(player, task_list_container).container -- Update the tasks, incase the user can now edit them local scroll_table = container.scroll.table - update_all_tasks(player,scroll_table) + update_all_tasks(player, scroll_table) -- Update the new task button incase the user can now add them local add_new_task_element = container.header.alignment[add_new_task.name] add_new_task_element.visible = check_player_permissions(player) end -Event.add(Roles.events.on_role_assigned,role_update_event) -Event.add(Roles.events.on_role_unassigned,role_update_event) \ No newline at end of file +Event.add(Roles.events.on_role_assigned, role_update_event) +Event.add(Roles.events.on_role_unassigned, role_update_event) \ No newline at end of file diff --git a/modules/gui/warp-list.lua b/modules/gui/warp-list.lua index a2079c1539..889792470d 100644 --- a/modules/gui/warp-list.lua +++ b/modules/gui/warp-list.lua @@ -5,33 +5,30 @@ ]] local Gui = require 'expcore.gui' --- @dep expcore.gui -local Store = require 'expcore.store' --- @dep expcore.store +local Datastore = require 'expcore.datastore' --- @dep expcore.datastore local Global = require 'utils.global' --- @dep utils.global local Event = require 'utils.event' --- @dep utils.event -local Game = require 'utils.game' --- @dep utils.game local Roles = require 'expcore.roles' --- @dep expcore.roles local Colors = require 'utils.color_presets' --- @dep utils.color_presets local config = require 'config.gui.warps' --- @dep config.gui.warps local Warps = require 'modules.control.warps' --- @dep modules.control.warps local format_time = _C.format_time --- @dep expcore.common --- Stores a boolean value indexed by player name -local player_in_range_store = Store.register(function(player) - return player.name -end) - --- Stores the time remaing for a players warp cooldown -local player_warp_cooldown_store = Store.register(function(player) - return player.name -end) +--- Stores all data for the warp gui +local WrapGuiData = Datastore.connect('WrapGuiData') +WrapGuiData:set_serializer(Datastore.name_serializer) +local PlayerInRange = WrapGuiData:combine('PlayerInRange') +PlayerInRange:set_default(false) +local PlayerCooldown = WrapGuiData:combine('PlayerCooldown') +PlayerCooldown:set_default(0) --- Table that stores a boolean value of weather to keep the warp gui open +--- Table that stores a boolean value of weather to keep the warp gui open local keep_gui_open = {} -Global.register(keep_gui_open,function(tbl) +Global.register(keep_gui_open, function(tbl) keep_gui_open = tbl end) --- Styles used for sprite buttons +--- Styles used for sprite buttons local Styles = { sprite20 = Gui.sprite_style(20), sprite22 = Gui.sprite_style(20, nil, { right_margin = -3 }), @@ -40,7 +37,7 @@ local Styles = { --- Returns if a player is allowed to edit the given warp --- If a player is allowed to use the edit buttons -local function check_player_permissions(player,action,warp) +local function check_player_permissions(player, action, warp) -- Check if the action is allow edit and then check bypass settings if action == 'allow_edit_warp' then -- Check if the warp is the spawn then it cant be edited @@ -55,17 +52,17 @@ local function check_player_permissions(player,action,warp) end end - -- Check player has permisison based on value in the config + -- Check player has permission based on value in the config local action_config = config[action] if action_config == 'all' then return true elseif action_config == 'admin' then return player.admin elseif action_config == 'expcore.roles' then - return Roles.player_allowed(player,config['expcore_roles_'..action]) + return Roles.player_allowed(player, config['expcore_roles_'..action]) end - -- Return false as all other condidtions have not been met + -- Return false as all other conditions have not been met return false end @@ -79,12 +76,12 @@ Gui.element{ style = 'tool_button' } :style(Styles.sprite20) -:on_click(function(player,_) +:on_click(function(player, _) -- Add the new warp local force_name = player.force.name local surface = player.surface local position = player.position - local warp_id = Warps.add_warp(force_name,surface,position,player.name) + local warp_id = Warps.add_warp(force_name, surface, position, player.name) Warps.make_warp_tag(warp_id) Warps.make_warp_area(warp_id) end) @@ -99,7 +96,7 @@ Gui.element{ style = 'tool_button' } :style(Styles.sprite20) -:on_click(function(_,element) +:on_click(function(_, element) local warp_id = element.parent.name:sub(6) Warps.remove_warp(warp_id) end) @@ -114,15 +111,15 @@ Gui.element{ style = 'tool_button' } :style(Styles.sprite20) -:on_click(function(player,element) +:on_click(function(player, element) local warp_id = element.parent.name:sub(6) - Warps.set_editing(warp_id,player.name,true) + Warps.set_editing(warp_id, player.name, true) end) --- Set of three elements which make up each row of the warp table -- @element add_warp_base local add_warp_base = -Gui.element(function(_,parent,warp_id) +Gui.element(function(_, parent, warp_id) -- Add the icon flow local icon_flow = parent.add{ @@ -137,7 +134,7 @@ Gui.element(function(_,parent,warp_id) warp_flow.style.padding = 0 -- Add the two edit buttons outside the warp flow - local edit_flow = Gui.alignment(parent,'edit-'..warp_id) + local edit_flow = Gui.alignment(parent, 'edit-'..warp_id) edit_warp(edit_flow) discard_warp(edit_flow) @@ -146,7 +143,7 @@ Gui.element(function(_,parent,warp_id) end) -- Removes the three elements that are added as part of the warp base -local function remove_warp_base(parent,warp_id) +local function remove_warp_base(parent, warp_id) Gui.destroy_if_valid(parent['icon-'..warp_id]) Gui.destroy_if_valid(parent['edit-'..warp_id]) Gui.destroy_if_valid(parent[warp_id]) @@ -164,12 +161,12 @@ Gui.element{ style = 'shortcut_bar_button_green' } :style(Styles.sprite22) -:on_click(function(player,element) +:on_click(function(player, element) local warp_id = element.parent.name local warp_name = element.parent[warp_editing.name].text local warp_icon = element.parent.parent['icon-'..warp_id][warp_icon_button.name].elem_value - Warps.set_editing(warp_id,player.name) - Warps.update_warp(warp_id,warp_name,warp_icon,player.name) + Warps.set_editing(warp_id, player.name) + Warps.update_warp(warp_id, warp_name, warp_icon, player.name) end) --- Cancels the editing changes of the selected warp name or icon @@ -182,15 +179,15 @@ Gui.element{ style = 'shortcut_bar_button_red' } :style(Styles.sprite22) -:on_click(function(player,element) +:on_click(function(player, element) local warp_id = element.parent.name - Warps.set_editing(warp_id,player.name) + Warps.set_editing(warp_id, player.name) end) ---- Editing state for a warp, contrins a text field and the two edit buttons +--- Editing state for a warp, contains a text field and the two edit buttons -- @element warp_editing warp_editing = -Gui.element(function(event_trigger,parent,warp) +Gui.element(function(event_trigger, parent, warp) local name = warp.name -- Draw the element @@ -213,18 +210,18 @@ end) maximal_width = 110, height = 20 } -:on_confirmed(function(player,element,_) +:on_confirmed(function(player, element, _) local warp_id = element.parent.name local warp_name = element.text local warp_icon = element.parent.parent['icon-'..warp_id][warp_icon_button.name].elem_value - Warps.set_editing(warp_id,player.name) - Warps.update_warp(warp_id,warp_name,warp_icon,player.name) + Warps.set_editing(warp_id, player.name) + Warps.update_warp(warp_id, warp_name, warp_icon, player.name) end) --- Default state for a warp, contains only a label with the warp name -- @element warp_label local warp_label = -Gui.element(function(event_trigger,parent,warp) +Gui.element(function(event_trigger, parent, warp) local last_edit_name = warp.last_edit_name local last_edit_time = warp.last_edit_time -- Draw the element @@ -232,52 +229,52 @@ Gui.element(function(event_trigger,parent,warp) name = event_trigger, type = 'label', caption = warp.name, - tooltip = {'warp-list.last-edit',last_edit_name,format_time(last_edit_time)} + tooltip = {'warp-list.last-edit', last_edit_name, format_time(last_edit_time)} } end) :style{ single_line = false, maximal_width = 150 } -:on_click(function(player,element,_) +:on_click(function(player, element, _) local warp_id = element.parent.name local warp = Warps.get_warp(warp_id) local position = warp.position - player.zoom_to_world(position,1.5) + player.zoom_to_world(position, 1.5) end) - +local update_wrap_buttons --- Default state for the warp icon, when pressed teleports the player -- @element warp_icon_button warp_icon_button = -Gui.element(function(event_trigger,parent,warp) +Gui.element(function(event_trigger, parent, warp) local warp_position = warp.position -- Draw the element return parent.add{ name = event_trigger, type = 'sprite-button', sprite = 'item/'..warp.icon, - tooltip = {'warp-list.goto-tooltip',warp_position.x,warp_position.y}, + tooltip = {'warp-list.goto-tooltip', warp_position.x, warp_position.y}, style = 'slot_button' } end) :style(Styles.sprite32) -:on_click(function(player,element,_) +:on_click(function(player, element, _) if element.type == 'choose-elem-button' then return end local warp_id = element.parent.caption - Warps.teleport_player(warp_id,player) + Warps.teleport_player(warp_id, player) -- Reset the warp cooldown if the player does not have unlimited warps - if not check_player_permissions(player,'bypass_warp_cooldown') then - Store.set(player_warp_cooldown_store,player,config.cooldown_duraction) - Store.trigger(player_in_range_store,player) + if not check_player_permissions(player, 'bypass_warp_cooldown') then + PlayerCooldown:set(player, config.cooldown_duration) + update_wrap_buttons(player) end end) --- Editing state for the warp icon, chose elem used to chosse icon -- @element warp_icon_editing local warp_icon_editing = -Gui.element(function(_,parent,warp) +Gui.element(function(_, parent, warp) return parent.add{ name = warp_icon_button.name, type = 'choose-elem-button', @@ -293,32 +290,60 @@ end) local warp_timer = Gui.element{ type = 'progressbar', - tooltip = {'warp-list.timer-tooltip',config.cooldown_duraction}, + tooltip = {'warp-list.timer-tooltip', config.cooldown_duration}, minimum_value = 0, - maximum_value = config.cooldown_duraction*config.update_smoothing + maximum_value = config.cooldown_duration*config.update_smoothing } :style{ horizontally_stretchable = true, color = Colors.light_blue } +local warp_list_container +--- Update the warp buttons for a player +function update_wrap_buttons(player, timer, in_range) + -- Get the warp table + local frame = Gui.get_left_element(player, warp_list_container) + local scroll_table = frame.container.scroll.table + + -- Check if the buttons should be active + timer = timer or PlayerCooldown:get(player) + in_range = in_range or PlayerInRange:get(player) + local button_disabled = timer > 0 or not in_range + + -- Change the enabled state of the warp buttons + local warp_ids = Warps.get_force_warp_ids(player.force.name) + for _, warp_id in pairs(warp_ids) do + local element = scroll_table['icon-'..warp_id][warp_icon_button.name] + if element and element.valid then + element.enabled = not button_disabled + if button_disabled then + element.tooltip = {'warp-list.goto-disabled'} + else + local position = Warps.get_warp(warp_id).position + element.tooltip = {'warp-list.goto-tooltip', position.x, position.y} + end + end + end +end + --- Updates a warp for a player -local function update_warp(player,warp_table,warp_id) +local function update_warp(player, warp_table, warp_id) local warp = Warps.get_warp(warp_id) -- Warp no longer exists so should be removed from the list if not warp then - remove_warp_base(warp_table,warp_id) + remove_warp_base(warp_table, warp_id) return end -- Get the warp flow for this warp - local warp_flow = warp_table[warp_id] or add_warp_base(warp_table,warp_id) + local warp_flow = warp_table[warp_id] or add_warp_base(warp_table, warp_id) local icon_flow = warp_table['icon-'..warp_id] -- Update the edit flow local edit_flow = warp_table['edit-'..warp_id] - local player_allowed_edit = check_player_permissions(player,'allow_edit_warp',warp) + local player_allowed_edit = check_player_permissions(player, 'allow_edit_warp', warp) local players_editing = table.get_keys(warp.currently_editing) local edit_warp_element = edit_flow[edit_warp.name] local discard_warp_element = edit_flow[discard_warp.name] @@ -327,15 +352,15 @@ local function update_warp(player,warp_table,warp_id) discard_warp_element.visible = player_allowed_edit if #players_editing > 0 then edit_warp_element.hovered_sprite = 'utility/warning_icon' - edit_warp_element.tooltip = {'warp-list.edit-tooltip',table.concat(players_editing,', ')} + edit_warp_element.tooltip = {'warp-list.edit-tooltip', table.concat(players_editing, ', ')} else edit_warp_element.hovered_sprite = edit_warp_element.sprite edit_warp_element.tooltip = {'warp-list.edit-tooltip-none'} end -- Check if the player is was editing and/or currently editing - local warp_label_element = warp_flow[warp_label.name] or warp_label(warp_flow,warp) - local icon_entry = icon_flow[warp_icon_button.name] or warp_icon_button(icon_flow,warp) + local warp_label_element = warp_flow[warp_label.name] or warp_label(warp_flow, warp) + local icon_entry = icon_flow[warp_icon_button.name] or warp_icon_button(icon_flow, warp) local player_was_editing = icon_entry.type == 'choose-elem-button' local player_is_editing = warp.currently_editing[player.name] @@ -347,21 +372,21 @@ local function update_warp(player,warp_table,warp_id) local last_edit_name = warp.last_edit_name local last_edit_time = warp.last_edit_time warp_label_element.caption = warp_name - warp_label_element.tooltip = {'warp-list.last-edit',last_edit_name,format_time(last_edit_time)} + warp_label_element.tooltip = {'warp-list.last-edit', last_edit_name, format_time(last_edit_time)} icon_entry.sprite = 'item/'..warp_icon elseif player_was_editing and not player_is_editing then -- Player was editing but is no longer, remove text field and add label edit_warp_element.enabled = true warp_flow.clear() - warp_label(warp_flow,warp) + warp_label(warp_flow, warp) icon_flow.clear() - local warp_icon_element = warp_icon_button(icon_flow,warp) - local timer = Store.get(player_warp_cooldown_store,player) - local in_range = Store.get(player_in_range_store,player) - local apply_proximity = not check_player_permissions(player,'bypass_warp_proximity') - if (timer and timer > 0) or (apply_proximity and not in_range) then + local warp_icon_element = warp_icon_button(icon_flow, warp) + local timer = PlayerCooldown:get(player) + local in_range = PlayerInRange:get(player) + local apply_proximity = not check_player_permissions(player, 'bypass_warp_proximity') + if timer > 0 or (apply_proximity and not in_range) then warp_icon_element.enabled = false warp_icon_element.tooltip = {'warp-list.goto-disabled'} end @@ -370,46 +395,59 @@ local function update_warp(player,warp_table,warp_id) -- Player was not editing but now is, remove label and add text field edit_warp_element.enabled = false warp_flow.clear() - warp_editing(warp_flow,warp).focus() - warp_table.parent.scroll_to_element(warp_flow,'top-third') + warp_editing(warp_flow, warp).focus() + warp_table.parent.scroll_to_element(warp_flow, 'top-third') icon_flow.clear() - warp_icon_editing(icon_flow,warp) + warp_icon_editing(icon_flow, warp) end end -- Update all the warps for a player -local function update_all_warps(player,warp_table) +local function update_all_warps(player, warp_table) local warp_ids = Warps.get_force_warp_ids(player.force.name) - if #warp_ids > 0 then - for _,warp_id in ipairs(warp_ids) do - update_warp(player,warp_table,warp_id) + warp_table.clear() + for _, warp_id in ipairs(warp_ids) do + update_warp(player, warp_table, warp_id) + end +end + +-- Update all warps for all players on a force +local function update_all_wrap_force(force) + local warp_ids = Warps.get_force_warp_ids(force.name) + for _, player in pairs(force.connected_players) do + local frame = Gui.get_left_element(player, warp_list_container) + local warp_table = frame.container.scroll.table + + warp_table.clear() + for _, warp_id in ipairs(warp_ids) do + update_warp(player, warp_table, warp_id) end end end --- Main warp list container for the left flow -- @element warp_list_container -local warp_list_container = -Gui.element(function(event_trigger,parent) +warp_list_container = +Gui.element(function(event_trigger, parent) -- Draw the internal container - local container = Gui.container(parent,event_trigger,200) + local container = Gui.container(parent, event_trigger, 200) -- Draw the header local header = Gui.header( container, {'warp-list.main-caption'}, - {'warp-list.sub-tooltip', config.cooldown_duraction, config.standard_proximity_radius}, + {'warp-list.sub-tooltip', config.cooldown_duration, config.standard_proximity_radius}, true ) -- Draw the new warp button local player = Gui.get_player_from_element(parent) local add_new_warp_element = add_new_warp(header) - add_new_warp_element.visible = check_player_permissions(player,'allow_add_warp') + add_new_warp_element.visible = check_player_permissions(player, 'allow_add_warp') -- Draw the scroll table for the warps - local scroll_table = Gui.scroll_table(container,250,3) + local scroll_table = Gui.scroll_table(container, 250, 3) -- Change the style of the scroll table local scroll_table_style = scroll_table.style @@ -421,137 +459,72 @@ Gui.element(function(event_trigger,parent) -- Change the progress of the warp timer local progress = 1 - local timer = Store.get(player_warp_cooldown_store,player) - if timer and timer > 0 then - progress = 1 - (timer/config.cooldown_duraction) + local timer = PlayerCooldown:get(player) + if timer > 0 then + progress = 1 - (timer/config.cooldown_duration) end warp_timer_element.value = progress -- Add any existing warps - update_all_warps(player,scroll_table) + update_all_warps(player, scroll_table) - -- Return the exteral container + -- Return the external container return container.parent end) :add_to_left_flow() --- Button on the top flow used to toggle the warp list container -- @element warp_list_toggle -Gui.left_toolbar_button('item/'..config.default_icon,{'warp-list.main-tooltip',config.standard_proximity_radius},warp_list_container, function(player) - return Roles.player_allowed(player,'gui/warp-list') +Gui.left_toolbar_button('item/'..config.default_icon, {'warp-list.main-tooltip', config.standard_proximity_radius}, warp_list_container, function(player) + return Roles.player_allowed(player, 'gui/warp-list') end) -:on_custom_event(Gui.events.on_visibility_changed_by_click, function(player,_,event) +:on_custom_event(Gui.events.on_visibility_changed_by_click, function(player, _,event) -- Set gui keep open state for player that clicked the button: true if visible, false if invisible keep_gui_open[player.name] = event.state end) --- When the name of a warp is updated this is triggered -Warps.on_update(function(warp,_,removed_warp) +Warps.on_update(function(_, warp, old_warp) -- Get the force to update, warp is nil when removed - local force if warp then - force = game.forces[warp.force_name] + update_all_wrap_force(game.forces[warp.force_name]) else - force = game.forces[removed_warp.force_name] + update_all_wrap_force(game.forces[old_warp.force_name]) end - - -- Update the gui for selected players - local warp_ids = Warps.get_force_warp_ids(force.name) - for _,player in pairs(force.connected_players) do - local frame = Gui.get_left_element(player,warp_list_container) - local scroll_table = frame.container.scroll.table - - -- Update the gui - scroll_table.clear() - for _,next_warp_id in ipairs(warp_ids) do - update_warp(player,scroll_table,next_warp_id) - end - end -end) - ---- Update the warps when the player joins -Event.add(defines.events.on_player_joined_game,function(event) - local player = game.players[event.player_index] - local frame = Gui.get_left_element(player,warp_list_container) - local scroll_table = frame.container.scroll.table - update_all_warps(player,scroll_table) end) ---- Makes sure the right buttons are present when roles change -local function role_update_event(event) - local player = game.players[event.player_index] - local container = Gui.get_left_element(player,warp_list_container).container - - -- Update the warps, incase the user can now edit them - local scroll_table = container.scroll.table - update_all_warps(player,scroll_table) - - -- Update the new warp button incase the user can now add them - local add_new_warp_element = container.header.alignment[add_new_warp.name] - add_new_warp_element.visible = check_player_permissions(player,'allow_add_warp') -end - -Event.add(Roles.events.on_role_assigned,role_update_event) -Event.add(Roles.events.on_role_unassigned,role_update_event) - --- When the player leaves or enters range of a warp this is triggered -Store.watch(player_in_range_store,function(value,player_name) +PlayerInRange:on_update(function(player_name, player_in_range) local player = game.players[player_name] - local force = player.force -- Change if the frame is visible based on if the player is in range if not keep_gui_open[player.name] then - Gui.toggle_left_element(player,warp_list_container,value) + Gui.toggle_left_element(player, warp_list_container, player_in_range) end -- Check if the player requires proximity - if check_player_permissions(player,'bypass_warp_proximity') then - return - end - - -- Get the warp table - local frame = Gui.get_left_element(player,warp_list_container) - local scroll_table = frame.container.scroll.table - - -- Check if the buttons should be active - local timer = Store.get(player_warp_cooldown_store,player) - local button_disabled = timer and timer > 0 or not value - - -- Change the enabled state of the warp buttons - local warp_ids = Warps.get_force_warp_ids(force.name) - for _,warp_id in pairs(warp_ids) do - local element = scroll_table['icon-'..warp_id][warp_icon_button.name] - if element and element.valid then - element.enabled = not button_disabled - if button_disabled then - element.tooltip = {'warp-list.goto-disabled'} - else - local position = Warps.get_warp(warp_id).position - element.tooltip = {'warp-list.goto-tooltip',position.x,position.y} - end - end + if not check_player_permissions(player, 'bypass_warp_proximity') then + update_wrap_buttons(player, nil, player_in_range) end end) ---- Update the warp cooldown progress bars to match the store -Store.watch(player_warp_cooldown_store,function(value,player_name,old_value) - if value == old_value then return end +--- Update the warp cooldown progress bars to match the current cooldown +PlayerCooldown:on_update(function(player_name, player_cooldown) -- Get the progress bar element local player = game.players[player_name] - local frame = Gui.get_left_element(player,warp_list_container) + local frame = Gui.get_left_element(player, warp_list_container) local warp_timer_element = frame.container[warp_timer.name] -- Set the progress local progress = 1 - local timer = Store.get(player_warp_cooldown_store,player) - if timer and timer > 0 then - progress = 1 - (timer/config.cooldown_duraction) + if player_cooldown and player_cooldown > 0 then + progress = 1 - (player_cooldown/config.cooldown_duration) end warp_timer_element.value = progress -- Trigger update of buttons if cooldown is now 0 - if value == 0 then - Store.trigger(player_in_range_store,player_name) + if player_cooldown == 0 then + update_wrap_buttons(player, player_cooldown, nil) end end) @@ -559,17 +532,15 @@ end) local r2 = config.standard_proximity_radius^2 local rs2 = config.spawn_proximity_radius^2 local mr2 = config.minimum_distance^2 -Event.on_nth_tick(math.floor(60/config.update_smoothing),function() - Store.map(player_warp_cooldown_store,function(value) - if value > 0 then - return value - 1 - end +Event.on_nth_tick(math.floor(60/config.update_smoothing), function() + PlayerCooldown:update_all(function(_, player_cooldown) + if player_cooldown > 0 then return player_cooldown - 1 end end) local force_warps = {} local warps = {} - for _,player in pairs(game.connected_players) do - local was_in_range = Store.get(player_in_range_store,player) + for _, player in pairs(game.connected_players) do + local was_in_range = PlayerInRange:get(player) -- Get the ids of all the warps on the players force local force_name = player.force.name @@ -585,11 +556,11 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function() if #warp_ids > 0 then local surface = player.surface local pos = player.position - local px,py = pos.x,pos.y + local px, py = pos.x, pos.y -- Loop over each warp - for _,warp_id in ipairs(warp_ids) do - -- Check if warp id is chached + for _, warp_id in ipairs(warp_ids) do + -- Check if warp id is cached local warp = warps[warp_id] if not warp then warp = Warps.get_warp(warp_id) @@ -612,13 +583,13 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function() -- Check the dist to the closest warp local in_range = closest_warp.warp_id == warp_ids.spawn and closest_distance < rs2 or closest_distance < r2 if was_in_range and not in_range then - Store.set(player_in_range_store,player,false) + PlayerInRange:set(player, false) elseif not was_in_range and in_range then - Store.set(player_in_range_store,player,true) + PlayerInRange:set(player, true) end -- Change the enabled state of the add warp button - local frame = Gui.get_left_element(player,warp_list_container) + local frame = Gui.get_left_element(player, warp_list_container) local add_warp_element = frame.container.header.alignment[add_new_warp.name] local old_closest_warp_name = add_warp_element.tooltip[2] or closest_warp.name local was_able_to_make_warp = add_warp_element.enabled @@ -628,7 +599,7 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function() add_warp_element.tooltip = {'warp-list.add-tooltip'} elseif not can_make_warp and was_able_to_make_warp or old_closest_warp_name ~= closest_warp.name then add_warp_element.enabled = false - add_warp_element.tooltip = {'warp-list.too-close',closest_warp.name} + add_warp_element.tooltip = {'warp-list.too-close', closest_warp.name} end end @@ -638,30 +609,54 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function() end) --- When a player is created make sure that there is a spawn warp created -Event.add(defines.events.on_player_created,function(event) +Event.add(defines.events.on_player_created, function(event) -- If the force has no spawn then make a spawn warp - local player = Game.get_player_by_index(event.player_index) + local player = game.players[event.player_index] local force = player.force local spawn_id = Warps.get_spawn_warp_id(force.name) if not spawn_id then local spawn_position = force.get_spawn_position(player.surface) - spawn_id = Warps.add_warp(force.name,player.surface,spawn_position,nil,'Spawn') - Warps.set_spawn_warp(spawn_id,force) - Store.trigger(Warps.store,spawn_id) + spawn_id = Warps.add_warp(force.name, player.surface, spawn_position, nil, 'Spawn') + Warps.set_spawn_warp(spawn_id, force) Warps.make_warp_tag(spawn_id) end end) +--- Update the warps when the player joins +Event.add(defines.events.on_player_joined_game, function(event) + local player = game.players[event.player_index] + local frame = Gui.get_left_element(player, warp_list_container) + local scroll_table = frame.container.scroll.table + update_all_warps(player, scroll_table) +end) + +--- Makes sure the right buttons are present when roles change +local function role_update_event(event) + local player = game.players[event.player_index] + local container = Gui.get_left_element(player, warp_list_container).container + + -- Update the warps, incase the user can now edit them + local scroll_table = container.scroll.table + update_all_warps(player, scroll_table) + + -- Update the new warp button incase the user can now add them + local add_new_warp_element = container.header.alignment[add_new_warp.name] + add_new_warp_element.visible = check_player_permissions(player, 'allow_add_warp') +end + +Event.add(Roles.events.on_role_assigned, role_update_event) +Event.add(Roles.events.on_role_unassigned, role_update_event) + --- When a chart tag is removed or edited make sure it is not one that belongs to a warp local function maintain_tag(event) if not event.player_index then return end local tag = event.tag local force_name = event.force.name local warp_ids = Warps.get_force_warp_ids(force_name) - for _,warp_id in pairs(warp_ids) do + for _, warp_id in pairs(warp_ids) do local warp = Warps.get_warp(warp_id) - local wtag = warp.tag - if not wtag or not wtag.valid or wtag == tag then + local warp_tag = warp.tag + if not warp_tag or not warp_tag.valid or warp_tag == tag then if event.name == defines.events.on_chart_tag_removed then warp.tag = nil end @@ -670,5 +665,5 @@ local function maintain_tag(event) end end -Event.add(defines.events.on_chart_tag_modified,maintain_tag) -Event.add(defines.events.on_chart_tag_removed,maintain_tag) \ No newline at end of file +Event.add(defines.events.on_chart_tag_modified, maintain_tag) +Event.add(defines.events.on_chart_tag_removed, maintain_tag) \ No newline at end of file diff --git a/overrides/inspect.lua b/overrides/inspect.lua index 76605169b5..6cf7296f79 100644 --- a/overrides/inspect.lua +++ b/overrides/inspect.lua @@ -99,10 +99,10 @@ end -- tables aren't pure sequences. So we implement our own # operator. local function getSequenceLength(t) local len = 1 - local v = rawget(t,len) + local v = rawget(t, len) while v ~= nil do len = len + 1 - v = rawget(t,len) + v = rawget(t, len) end return len - 1 end @@ -110,7 +110,7 @@ end local function getNonSequentialKeys(t) local keys = {} local sequenceLength = getSequenceLength(t) - for k,_ in pairs(t) do + for k, _ in pairs(t) do if not isSequenceKey(k, sequenceLength) then table.insert(keys, k) end end table.sort(keys, sortKeys) @@ -133,7 +133,7 @@ local function countTableAppearances(t, tableAppearances) if type(t) == 'table' then if not tableAppearances[t] then tableAppearances[t] = 1 - for k,v in pairs(t) do + for k, v in pairs(t) do countTableAppearances(k, tableAppearances) countTableAppearances(v, tableAppearances) end @@ -172,7 +172,7 @@ local function processRecursive(process, item, path, visited) visited[item] = processedCopy local processedKey - for k,v in pairs(processed) do + for k, v in pairs(processed) do processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited) if processedKey ~= nil then processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited) @@ -258,14 +258,14 @@ function Inspector:putTable(t) local count = 0 for i=1, sequenceLength do - if count > 0 then self:puts(',') end + if count > 0 then self:puts(', ') end self:puts(' ') self:putValue(t[i]) count = count + 1 end - for _,k in ipairs(nonSequentialKeys) do - if count > 0 then self:puts(',') end + for _, k in ipairs(nonSequentialKeys) do + if count > 0 then self:puts(', ') end self:tabify() self:putKey(k) self:puts(' = ') @@ -274,7 +274,7 @@ function Inspector:putTable(t) end if mt then - if count > 0 then self:puts(',') end + if count > 0 then self:puts(', ') end self:tabify() self:puts(' = ') self:putValue(mt) @@ -302,7 +302,7 @@ function Inspector:putValue(v) elseif tv == 'table' then self:putTable(v) else - self:puts('<',tv,' ',self:getId(v),'>') + self:puts('<', tv, ' ', self:getId(v), '>') end end diff --git a/overrides/require.lua b/overrides/require.lua index 364302487c..4436e5d8db 100644 --- a/overrides/require.lua +++ b/overrides/require.lua @@ -1,4 +1,3 @@ ---luacheck:ignore global require local loaded = package.loaded local raw_require = require diff --git a/overrides/table.lua b/overrides/table.lua index e382330257..3d0233d7ab 100644 --- a/overrides/table.lua +++ b/overrides/table.lua @@ -54,10 +54,10 @@ end @usage-- Adding 1000 values into the middle of the array local tbl = {} local values = {} -for i = 1,1000 do tbl[i] = i values[i] = i end -table.array_insert(tbl,500,values) -- around 0.4ms +for i = 1, 1000 do tbl[i] = i values[i] = i end +table.array_insert(tbl, 500, values) -- around 0.4ms ]] -function table.array_insert(tbl,start_index,values) +function table.array_insert(tbl, start_index, values) if not values then values = start_index start_index = nil @@ -90,16 +90,16 @@ end @usage-- Merging two tables local tbl = {} local tbl2 = {} -for i = 1,100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end -table.table_insert(tbl,50,tbl2) +for i = 1, 100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end +table.table_insert(tbl, 50, tbl2) ]] -function table.table_insert(tbl,start_index,tbl2) +function table.table_insert(tbl, start_index, tbl2) if not tbl2 then tbl2 = start_index start_index = nil end - table.array_insert(tbl,start_index,tbl2) + table.array_insert(tbl, start_index, tbl2) for key, value in pairs(tbl2) do if not tonumber(key) then tbl[key] = value @@ -152,14 +152,14 @@ function table.array_contains(t, e) end --- Extracts certain keys from a table --- @usage local key_three, key_one = extract({key_one='foo',key_two='bar',key_three=true},'key_three','key_one') +-- @usage local key_three, key_one = extract({key_one='foo', key_two='bar', key_three=true}, 'key_three', 'key_one') -- @tparam table tbl table the which contains the keys -- @tparam string ... the names of the keys you want extracted -- @return the keys in the order given -function table.extract_keys(tbl,...) +function table.extract_keys(tbl, ...) local values = {} - for _,key in pairs({...}) do - table.insert(values,tbl[key]) + for _, key in pairs({...}) do + table.insert(values, tbl[key]) end return unpack(values) end @@ -302,7 +302,7 @@ function table.get_values(tbl, sorted, as_string) end end if sorted then - table.sort(valueset,sortFunc) + table.sort(valueset, sortFunc) end return valueset end @@ -328,7 +328,7 @@ function table.get_keys(tbl, sorted, as_string) end end if sorted then - table.sort(keyset,sortFunc) + table.sort(keyset, sortFunc) end return keyset end @@ -340,11 +340,11 @@ function table.alphanumsort(tbl) local o = table.get_keys(tbl) local function padnum(d) local dec, n = string.match(d, "(%.?)0*(.+)") return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) end - table.sort(o, function(a,b) - return tostring(a):gsub("%.?%d+",padnum)..("%3d"):format(#b) - < tostring(b):gsub("%.?%d+",padnum)..("%3d"):format(#a) end) + table.sort(o, function(a, b) + return tostring(a):gsub("%.?%d+", padnum)..("%3d"):format(#b) + < tostring(b):gsub("%.?%d+", padnum)..("%3d"):format(#a) end) local _tbl = {} - for _,k in pairs(o) do _tbl[k] = tbl[k] end + for _, k in pairs(o) do _tbl[k] = tbl[k] end return _tbl end @@ -352,9 +352,9 @@ end -- @tparam table tbl the table to be sorted -- @treturn table the sorted table function table.keysort(tbl) - local o = table.get_keys(tbl,true) + local o = table.get_keys(tbl, true) local _tbl = {} - for _,k in pairs(o) do _tbl[k] = tbl[k] end + for _, k in pairs(o) do _tbl[k] = tbl[k] end return _tbl end @@ -365,7 +365,7 @@ end t must be a list in ascending order for the return value to be valid. Usage example: - local t = {1,3,5,7,9} + local t = {1, 3,5, 7,9} local x = 5 local index = table.binary_search(t, x) if index < 0 then diff --git a/overrides/version.lua b/overrides/version.lua index 5afe94d947..663ad0a137 100644 --- a/overrides/version.lua +++ b/overrides/version.lua @@ -1,3 +1,5 @@ return { - expgaming = '6.0.0' + expgaming_lua = '6.0.0', + expgaming_api = '2.0.0', + redmew_lua = '2019-02-24-76871ee' } \ No newline at end of file diff --git a/utils/event_core.lua b/utils/event_core.lua index b34715e133..9525167ab6 100644 --- a/utils/event_core.lua +++ b/utils/event_core.lua @@ -11,11 +11,16 @@ local event_handlers = {} -- map of nth_tick to handlers[] local on_nth_tick_event_handlers = {} -local pcall = pcall +local trace = debug.traceback +local xpcall = xpcall local log = log local script_on_event = script.on_event local script_on_nth_tick = script.on_nth_tick +local function handler_error(err) + log('\n\t'..trace(err)) +end + local function call_handlers(handlers, event) if _DEBUG then for i = 1, #handlers do @@ -24,11 +29,7 @@ local function call_handlers(handlers, event) end else for i = 1, #handlers do - local handler = handlers[i] - local success, error = pcall(handler, event) - if not success then - log('\n\t'..error) - end + xpcall(handlers[i], handler_error, event) end end end diff --git a/utils/game.lua b/utils/game.lua index c5ff5db2d6..f2259bf640 100644 --- a/utils/game.lua +++ b/utils/game.lua @@ -1,64 +1,39 @@ -local Global = require 'utils.global' --- @dep utils.global -local Color = require 'utils.color_presets' --- @dep utils.color_presets -local pairs = pairs +local Color = require 'utils.color_presets' --- @dep utils.color_presets local Game = {} -local bad_name_players = {} -Global.register( - bad_name_players, - function(tbl) - bad_name_players = tbl - end -) +--[[ Note to readers +Game.get_player_from_name was removed because game.players[name] works without any edge cases +always true: game.players[name].name == name ---[[ - Due to a bug in the Factorio api the following expression isn't guaranteed to be true. - game.players[player.index] == player - get_player_by_index(index) will always return the correct player. - When looking up players by name or iterating through all players use game.players instead. -]] -function Game.get_player_by_index(index) - local p = game.players[index] +Game.get_player_by_index was added originally as a workaround for the following edge case: +player with index of 5 and name of "Cooldude2606" +player with index of 10 and name of "5" +game.players[5].name == "5" - if not p then - return nil - end - if p.index == index then - return p - end +Discovered the following logic: +all keys are first converted to string and search against player names +if this fails it attempts to convert it to a number and search against player indexes +sometimes fails: game.players[index].index == index - p = bad_name_players[index] - if p then - if p.valid then - return p - else - return nil - end - end +Game.get_player_by_index was removed after the above logic was corrected to the following: +when a key is a number it is searched against player indexes, and only their indexes +when a key is a string it is searched against player names, and then against their indexes +always true: game.players[name].name == name; game.players[index].index == index - for k, v in pairs(game.players) do - if k == index then - bad_name_players[index] = v - return v - end - end -end +]] --- Returns a valid LuaPlayer if given a number, string, or LuaPlayer. Returns nil otherwise. -- obj function Game.get_player_from_any(obj) - local o_type = type(obj) - local p - if o_type == 'number' then - p = Game.get_player_by_index(obj) - elseif o_type == 'string' then + local o_type, p = type(obj) + if o_type == 'table' then + p = obj + elseif o_type == 'string' or o_type == 'number' then p = game.players[obj] - elseif o_type == 'table' and obj.valid and obj.is_player() then - return obj end - if p and p.valid then + if p and p.valid and p.is_player() then return p end end @@ -95,16 +70,18 @@ function Game.print_floating_text(surface, position, text, color) end --[[ - Creates a floating text entity at the player location with the specified color in {r, g, b} format. + Creates a floating text entity at the player location with the specified color and offset. Example: "+10 iron" or "-10 coins" @param text String to display @param color table in {r = 0~1, g = 0~1, b = 0~1}, defaults to white. + @param x_offset number the x offset for the floating text + @param y_offset number the y offset for the floating text @return the created entity ]] -function Game.print_player_floating_text_position(player_index, text, color, x_offset, y_offset) - local player = Game.get_player_by_index(player_index) +function Game.print_player_floating_text_position(player, text, color, x_offset, y_offset) + player = Game.get_player_from_any(player) if not player or not player.valid then return end @@ -113,8 +90,17 @@ function Game.print_player_floating_text_position(player_index, text, color, x_o return Game.print_floating_text(player.surface, {x = position.x + x_offset, y = position.y + y_offset}, text, color) end -function Game.print_player_floating_text(player_index, text, color) - Game.print_player_floating_text_position(player_index, text, color, 0, -1.5) +--[[ + Creates a floating text entity at the player location with the specified color in {r, g, b} format. + Example: "+10 iron" or "-10 coins" + + @param text String to display + @param color table in {r = 0~1, g = 0~1, b = 0~1}, defaults to white. + + @return the created entity +]] +function Game.print_player_floating_text(player, text, color) + Game.print_player_floating_text_position(player, text, color, 0, -1.5) end -return Game +return Game \ No newline at end of file diff --git a/utils/gui.lua b/utils/gui.lua index 36fc1d61f1..12bb480656 100644 --- a/utils/gui.lua +++ b/utils/gui.lua @@ -72,7 +72,7 @@ local function handler_factory(event_name) return function(element_name, handler) local element = ExpGui.defines[element_name] if not element then return end - element[event_name](element,function(_,_,event) + element[event_name](element, function(_, _,event) handler(event) end) end