Fixed Existing Lua Check Errors

This commit is contained in:
Cooldude2606
2020-05-26 18:21:10 +01:00
parent 2aaeb06be3
commit 32507492b8
76 changed files with 1622 additions and 1617 deletions

View File

@@ -70,6 +70,14 @@ do -- Assume Factorio Control Stage as Default
} }
end 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 do -- Set default prototype files
files['**/data.lua'].std = STD_DATA files['**/data.lua'].std = STD_DATA
files['**/data-updates.lua'].std = STD_DATA files['**/data-updates.lua'].std = STD_DATA

View File

@@ -4,15 +4,17 @@
--- These are called factories because they return another function --- These are called factories because they return another function
-- use these as a simple methods of adding new items -- use these as a simple methods of adding new items
-- they will do most of the work for you -- 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 -- 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 local seconds, minutes, hours = 60, 3600, 216000
--- Use to make a split point for the number of items given based on time --- 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 -- ['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) local function cutoff_time(time, before, after)
return function(amount_made,items_made,player) return function(amount_made, items_made, player)
if game.tick < time then return before if game.tick < time then return before
else return after else return after
end end
@@ -20,9 +22,9 @@ local function cutoff_time(time,before,after)
end end
--- Use to make a split point for the number of items given based on amount made --- 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 -- ['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) local function cutoff_amount_made(amount, before, after)
return function(amount_made,items_made,player) return function(amount_made, items_made, player)
if amount_made < amount then return before if amount_made < amount then return before
else return after else return after
end end
@@ -30,9 +32,9 @@ local function cutoff_amount_made(amount,before,after)
end end
--- Same as above but will not give any items if x amount has been made of another item, useful for tiers --- 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 -- ['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) local function cutoff_amount_made_unless(amount, before, after, second_item, second_amount)
return function(amount_made,items_made,player) return function(amount_made, items_made, player)
if items_made(second_item) < second_amount then if items_made(second_item) < second_amount then
if amount_made < amount then return before if amount_made < amount then return before
else return after else return after
@@ -43,11 +45,11 @@ local function cutoff_amount_made_unless(amount,before,after,second_item,second_
end end
-- Use for mass production items where you want the amount to change based on the amount already made -- 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 -- ['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) local function scale_amount_made(amount, before, scalar)
return function(amount_made,items_made,player) return function(amount_made, items_made, player)
if amount_made < amount then return before 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 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_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 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 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 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 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 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 items = { --- @setting items items and there condition for being given
-- ['item-name'] = function(amount_made,production_stats,player) return <Number> end -- 0 means no items given -- ['item-name'] = function(amount_made, production_stats, player) return <Number> end -- 0 means no items given
-- Plates -- Plates
['iron-plate']=scale_amount_made(100,10,10), ['iron-plate']=scale_amount_made(100, 10, 10),
['copper-plate']=scale_amount_made(100,0,8), ['copper-plate']=scale_amount_made(100, 0,8),
['steel-plate']=scale_amount_made(100,0,4), ['steel-plate']=scale_amount_made(100, 0,4),
-- Secondary Items -- Secondary Items
['electronic-circuit']=scale_amount_made(1000,0,6), ['electronic-circuit']=scale_amount_made(1000, 0,6),
['iron-gear-wheel']=scale_amount_made(1000,0,6), ['iron-gear-wheel']=scale_amount_made(1000, 0,6),
-- Starting Items -- Starting Items
['burner-mining-drill']=cutoff_time(10*minutes,4,0), ['burner-mining-drill']=cutoff_time(10*minutes, 4,0),
['stone-furnace']=cutoff_time(10*minutes,4,0), ['stone-furnace']=cutoff_time(10*minutes, 4,0),
-- Armor -- Armor
['light-armor']=cutoff_amount_made_unless(5,0,1,'heavy-armor',5), ['light-armor']=cutoff_amount_made_unless(5, 0,1,'heavy-armor',5),
['heavy-armor']=cutoff_amount_made(5,0,1), ['heavy-armor']=cutoff_amount_made(5, 0,1),
-- Weapon -- Weapon
['pistol']=cutoff_amount_made_unless(0,1,1,'submachine-gun',5), ['pistol']=cutoff_amount_made_unless(0, 1,1,'submachine-gun',5),
['submachine-gun']=cutoff_amount_made(5,0,1), ['submachine-gun']=cutoff_amount_made(5, 0,1),
-- Ammo -- Ammo
['firearm-magazine']=cutoff_amount_made_unless(100,10,0,'piercing-rounds-magazine',100), ['firearm-magazine']=cutoff_amount_made_unless(100, 10, 0,'piercing-rounds-magazine',100),
['piercing-rounds-magazine']=cutoff_amount_made(100,0,10), ['piercing-rounds-magazine']=cutoff_amount_made(100, 0,10),
} }
} }

View File

@@ -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; -- 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 -- either way you can change the requirements to be "admin" if you wanted to
-- @config Commands-Auth-Admin -- @config Commands-Auth-Admin
local Commands = require 'expcore.commands' --- @dep expcore.commands 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 tags.admin_only then
if player.admin then if player.admin then
return true return true

View File

@@ -4,7 +4,8 @@
local Commands = require 'expcore.commands' --- @dep expcore.commands local Commands = require 'expcore.commands' --- @dep expcore.commands
local Roles = require 'expcore.roles' --- @dep expcore.roles 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 if Roles.player_allowed(player,'command/'..command) then
return true return true
else else

View File

@@ -1,7 +1,7 @@
--[[-- This file contains some common command param parse functions; --[[-- 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; 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; 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 see ./expcore/commands.lua for more details
@config Commands-Parse @config Commands-Parse
@usage Adds Parses: @usage Adds Parses:
@@ -22,9 +22,8 @@ see ./expcore/commands.lua for more details
local Commands = require 'expcore.commands' --- @dep expcore.commands local Commands = require 'expcore.commands' --- @dep expcore.commands
local Game = require 'utils.game' --- @dep utils.game local Game = require 'utils.game' --- @dep utils.game
-- luacheck:ignore 212/player
Commands.add_parse('boolean',function(input, player)
Commands.add_parse('boolean',function(input,player,reject)
if not input then return end -- nil check if not input then return end -- nil check
input = input:lower() input = input:lower()
if input == 'yes' if input == 'yes'
@@ -37,7 +36,7 @@ Commands.add_parse('boolean',function(input,player,reject)
end end
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 if not input then return end -- nil check
input = input:lower() input = input:lower()
for option in options do for option in options do
@@ -48,7 +47,7 @@ Commands.add_parse('string-options',function(input,player,reject,options)
return reject{'reject-string-options',options:concat(', ')} return reject{'reject-string-options',options:concat(', ')}
end) 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 if not input then return end -- nil check
local length = input:len() local length = input:len()
if length > max_length then if length > max_length then
@@ -58,7 +57,7 @@ Commands.add_parse('string-max-length',function(input,player,reject,max_length)
end end
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 if not input then return end -- nil check
local number = tonumber(input) local number = tonumber(input)
if not number then if not number then
@@ -68,7 +67,7 @@ Commands.add_parse('number',function(input,player,reject)
end end
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 if not input then return end -- nil check
local number = tonumber(input) local number = tonumber(input)
if not number then if not number then
@@ -78,27 +77,27 @@ Commands.add_parse('integer',function(input,player,reject)
end end
end) end)
Commands.add_parse('number-range',function(input,player,reject,range_min,range_max) Commands.add_parse('number-range',function(input, player, reject, range_min, range_max)
local number = Commands.parse('number',input,player,reject) local number = Commands.parse('number',input, player, reject)
if not number then return end -- nil check if not number then return end -- nil check
if number < range_min or number > range_max then 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 else
return number return number
end end
end) end)
Commands.add_parse('integer-range',function(input,player,reject,range_min,range_max) Commands.add_parse('integer-range',function(input, player, reject, range_min, range_max)
local number = Commands.parse('integer',input,player,reject) local number = Commands.parse('integer',input, player, reject)
if not number then return end -- nil check if not number then return end -- nil check
if number < range_min or number > range_max then 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 else
return number return number
end end
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 if not input then return end -- nil check
local input_player = Game.get_player_from_any(input) local input_player = Game.get_player_from_any(input)
if not input_player then if not input_player then
@@ -108,8 +107,8 @@ Commands.add_parse('player',function(input,player,reject)
end end
end) end)
Commands.add_parse('player-online',function(input,player,reject) Commands.add_parse('player-online',function(input, player, reject)
local input_player = Commands.parse('player',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 then return end -- nil check
if not input_player.connected then if not input_player.connected then
return reject{'expcore-commands.reject-player-online'} return reject{'expcore-commands.reject-player-online'}
@@ -118,8 +117,8 @@ Commands.add_parse('player-online',function(input,player,reject)
end end
end) end)
Commands.add_parse('player-alive',function(input,player,reject) Commands.add_parse('player-alive',function(input, player, reject)
local input_player = Commands.parse('player-online',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 then return end -- nil check
if not input_player.character or not input_player.character.health or input_player.character.health <= 0 then 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'} return reject{'expcore-commands.reject-player-alive'}
@@ -128,7 +127,7 @@ Commands.add_parse('player-alive',function(input,player,reject)
end end
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 if not input then return end -- nil check
local force = game.forces[input] local force = game.forces[input]
if not force then if not force then
@@ -138,7 +137,7 @@ Commands.add_parse('force',function(input,player,reject)
end end
end) end)
Commands.add_parse('surface',function(input,player,reject) Commands.add_parse('surface',function(input, player, reject)
if not input then return end if not input then return end
local surface = game.surfaces[input] local surface = game.surfaces[input]
if not surface then if not surface then

View File

@@ -12,14 +12,15 @@ local Roles = require 'expcore.roles' --- @dep expcore.roles
local auto_complete = _C.auto_complete --- @dep expcore.common local auto_complete = _C.auto_complete --- @dep expcore.common
require 'config.expcore.command_general_parse' 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 if not input then return end
local roles = Roles.config.order local roles = Roles.config.order
local rev_roles = {} local rev_roles = {}
for i=#roles,1,-1 do for i=#roles, 1,-1 do
table.insert(rev_roles,roles[i]) table.insert(rev_roles, roles[i])
end end
local role = auto_complete(rev_roles,input) local role = auto_complete(rev_roles, input)
role = Roles.get_role_by_name(role) role = Roles.get_role_by_name(role)
if not role then if not role then
return reject{'expcore-role.reject-role'} return reject{'expcore-role.reject-role'}
@@ -28,8 +29,8 @@ Commands.add_parse('role',function(input,player,reject)
end end
end) end)
Commands.add_parse('player-role',function(input,player,reject) Commands.add_parse('player-role',function(input, player, reject)
local input_player = Commands.parse('player',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 then return end -- nil check
local player_highest = Roles.get_player_highest_role(player) local player_highest = Roles.get_player_highest_role(player)
local input_player_highest = Roles.get_player_highest_role(input_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
end) end)
Commands.add_parse('player-role-online',function(input,player,reject) Commands.add_parse('player-role-online',function(input, player, reject)
local input_player = Commands.parse('player-role',input,player,reject) local input_player = Commands.parse('player-role',input, player, reject)
if not input_player then return end -- nil check 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, player, reject)
end) end)
Commands.add_parse('player-role-alive',function(input,player,reject) Commands.add_parse('player-role-alive',function(input, player, reject)
local input_player = Commands.parse('player-role',input,player,reject) local input_player = Commands.parse('player-role',input, player, reject)
if not input_player then return end -- nil check 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, player, reject)
end) end)

View File

@@ -6,7 +6,7 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands
local Global = require 'utils.global' --- @dep utils.global local Global = require 'utils.global' --- @dep utils.global
local disabled_commands = {} local disabled_commands = {}
Global.register(disabled_commands,function(tbl) Global.register(disabled_commands, function(tbl)
disabled_commands = tbl disabled_commands = tbl
end) end)
@@ -22,7 +22,8 @@ function Commands.enable(command_name)
disabled_commands[command_name] = nil disabled_commands[command_name] = nil
end 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 if disabled_commands[command] then
return reject{'command-auth.command-disabled'} return reject{'command-auth.command-disabled'}
else else

View File

@@ -22,23 +22,23 @@ log('[INFO] Getting file loader config')
local files = require 'config._file_loader' --- @dep config._file_loader local files = require 'config._file_loader' --- @dep config._file_loader
-- Loads all files from the config and logs that they are loaded -- 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 = {} local errors = {}
for index,path in pairs(files) do for index, path in pairs(files) do
-- Loads the next file in the list -- Loads the next file in the list
log(string.format('[INFO] Loading file %3d/%s (%s)',index,total_file_count,path)) log(string.format('[INFO] Loading file %3d/%s (%s)', index, total_file_count, path))
local success,file = pcall(require,path) local success, file = pcall(require, path)
-- Error Checking -- Error Checking
if not success then if not success then
-- Failed to load a file -- Failed to load a file
log('[ERROR] Failed to load file: '..path) 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 elseif type(file) == 'string' and file:find('not found') then
-- Returned a file not found message -- Returned a file not found message
log('[ERROR] File not found: '..path) log('[ERROR] File not found: '..path)
table.insert(errors,'[ERROR] '..path..' :: Not Found') table.insert(errors, '[ERROR] '..path..' :: Not Found')
end end
end end
@@ -49,5 +49,5 @@ require 'overrides.require'
-- Logs all errors again to make it make it easy to find -- Logs all errors again to make it make it easy to find
log('[INFO] All files loaded with '..#errors..' errors:') 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 |-----') log('[END] -----| Explosive Gaming Scenario Loader |-----')

View File

@@ -16,11 +16,11 @@ Async.register(function(player)
end) end)
-- This will allow us to bypass the error by running one tick later outside of any player scope -- 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 -- Here we make an sync function that we want to have a delay, note the delay is not defined here
local print_message = local print_message =
Async.register(function(player,message) Async.register(function(player, message)
player.print(message) player.print(message)
end) end)
@@ -71,7 +71,7 @@ Async.register = Token.register
Async.run(set_admin, player, true) Async.run(set_admin, player, true)
]] ]]
function Async.run(token,...) function Async.run(token, ...)
Task.queue_task(internal_run, { Task.queue_task(internal_run, {
token = token, token = token,
params = {...} params = {...}
@@ -87,15 +87,15 @@ end
Async.wait(300, print_to_player, 'Hello, World!') 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, { Task.set_timeout_in_ticks(ticks, internal_run, {
token = token, token = token,
params = {...} params = {...}
}) })
end end
return setmetatable(Async,{ return setmetatable(Async, {
__call = function(self,...) __call = function(self, ...)
self.run(...) self.run(...)
end end
}) })

View File

@@ -25,7 +25,7 @@ end)
msg = ':'..msg msg = ':'..msg
end end
for 1 = 1,repeat_count do for 1 = 1, repeat_count do
Command.print(1..msg) Command.print(1..msg)
end end
end) end)
@@ -91,7 +91,7 @@ end)
-- this is where that smiley param is used -- this is where that smiley param is used
msg = ':'..msg msg = ':'..msg
end 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 -- 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) Command.print(1..msg)
end end
@@ -99,7 +99,7 @@ end)
end) end)
-- Other values that can be returned from register -- 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.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 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 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 Commands.success(message[opt]) -- used to return a success message however don't use this method see below
@@ -178,7 +178,7 @@ input = Commands.parse('number-int', input, player, reject)
if not input then return end -- nil check if not input then return end -- nil check
-- Example Code: -- 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 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 if not rtn or rtn < range_min or rtn > range_max then
-- the input is either not a number or is outside the range -- the input is either not a number or is outside the range
@@ -192,7 +192,7 @@ end)
]] ]]
local Game = require 'utils.game' --- @dep utils.game 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 Commands = { local Commands = {
--- Values returned by the signal functions to cause the command system to react --- Values returned by the signal functions to cause the command system to react
@@ -235,7 +235,7 @@ end)
]] ]]
function Commands.add_authenticator(callback) function Commands.add_authenticator(callback)
table.insert(Commands.authorization,callback) table.insert(Commands.authorization, callback)
return #Commands.authorization return #Commands.authorization
end end
@@ -251,13 +251,13 @@ function Commands.remove_authenticator(callback)
if type(callback) == 'number' then if type(callback) == 'number' then
-- if a number is passed then it is assumed to be the index -- if a number is passed then it is assumed to be the index
if Commands.authorization[callback] then if Commands.authorization[callback] then
table.remove(Commands.authorization,callback) table.remove(Commands.authorization, callback)
return true return true
end end
else else
-- will search the array and remove the key -- will search the array and remove the key
local index local index
for key,value in pairs(Commands.authorization) do for key, value in pairs(Commands.authorization) do
if value == callback then if value == callback then
index = key index = key
break break
@@ -265,7 +265,7 @@ function Commands.remove_authenticator(callback)
end end
-- if the function was found it is removed -- if the function was found it is removed
if index then if index then
table.remove(Commands.authorization,index) table.remove(Commands.authorization, index)
return true return true
end end
end end
@@ -284,7 +284,7 @@ end
local authorized, status = Commands.authorize(game.player, 'repeat-name') local authorized, status = Commands.authorize(game.player, 'repeat-name')
]] ]]
function Commands.authorize(player,command_name) function Commands.authorize(player, command_name)
local failed local failed
if not player then return true end if not player then return true end
local command_data = Commands.commands[command_name] local command_data = Commands.commands[command_name]
@@ -297,9 +297,9 @@ function Commands.authorize(player,command_name)
end end
-- loops over each authorization callback if any return false or unauthorized command will fail -- loops over each authorization callback if any return false or unauthorized command will fail
for _,callback in pairs(Commands.authorization) do for _, callback in pairs(Commands.authorization) do
-- callback(player: LuaPlayer, command: string, flags: table, reject: function(error_message?: string)) -- 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) local success, rtn = pcall(callback, player, command_name, command_data.flags, auth_fail)
-- error handler -- error handler
if not success then if not success then
-- the callback failed to run -- the callback failed to run
@@ -341,8 +341,8 @@ function Commands.get(player)
player = Game.get_player_from_any(player) player = Game.get_player_from_any(player)
if not player then return Commands.commands end if not player then return Commands.commands end
local allowed = {} local allowed = {}
for name,command_data in pairs(Commands.commands) do for name, command_data in pairs(Commands.commands) do
if Commands.authorize(player,name) then if Commands.authorize(player, name) then
allowed[name]=command_data allowed[name]=command_data
end end
end end
@@ -361,20 +361,20 @@ local commands = Commands.search('repeat')
local commands = Commands.search('repeat', game.player) local commands = Commands.search('repeat', game.player)
]] ]]
function Commands.search(keyword,player) function Commands.search(keyword, player)
local custom_commands = Commands.get(player) local custom_commands = Commands.get(player)
local matches = {} local matches = {}
keyword = keyword:lower() keyword = keyword:lower()
-- loops over custom commands -- loops over custom commands
for name,command_data in pairs(custom_commands) do for name, command_data in pairs(custom_commands) do
-- combines name help and aliases into one message to be searched -- 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 if search:lower():match(keyword) then
matches[name] = command_data matches[name] = command_data
end end
end end
-- loops over the names of game commands -- loops over the names of game commands
for name,description in pairs(commands.game_commands) do for name, description in pairs(commands.game_commands) do
if name:lower():match(keyword) then 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 formated
matches[name] = { matches[name] = {
@@ -411,7 +411,7 @@ Commands.add_parse('number-range-int', function(input, player, reject, range_min
end) end)
]] ]]
function Commands.add_parse(name,callback) function Commands.add_parse(name, callback)
if Commands.parse_functions[name] then if Commands.parse_functions[name] then
return false return false
else else
@@ -442,10 +442,10 @@ end
local parsed_input = Commands.parse('number-range-int', '7', player, reject, 1, 10) -- valid range 1 to 10 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,...) function Commands.parse(name, input, player, reject, ...)
if not Commands.parse_functions[name] then return end if not Commands.parse_functions[name] then return end
local success,rtn = pcall(Commands.parse_functions[name],input,player,reject,...) local success, rtn = pcall(Commands.parse_functions[name], input, player, reject, ...)
if not success then error(rtn,2) return end if not success then error(rtn, 2) return end
if not rtn then return end if not rtn then return end
if rtn == Commands.defines.error then return end if rtn == Commands.defines.error then return end
return rtn return rtn
@@ -465,11 +465,11 @@ 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.')
]] ]]
function Commands.new_command(name,help) function Commands.new_command(name, help)
local command = setmetatable({ local command = setmetatable({
name=name, name=name,
help=help, help=help,
callback=function() Commands.internal_error(false,name,'No callback registered') end, callback=function() Commands.internal_error(false, name, 'No callback registered') end,
auto_concat=false, auto_concat=false,
min_param_count=0, min_param_count=0,
max_param_count=0, max_param_count=0,
@@ -500,10 +500,10 @@ command:add_param('smiley', true, function(input, player, reject)
end) end)
]] ]]
function Commands._prototype:add_param(name,optional,parse,...) function Commands._prototype:add_param(name, optional, parse, ...)
local parse_args = {...} local parse_args = {...}
if type(optional) ~= 'boolean' then if type(optional) ~= 'boolean' then
parse_args = {parse,...} parse_args = {parse, ...}
parse = optional parse = optional
optional = false optional = false
end end
@@ -535,7 +535,7 @@ command:set_defaults{
]] ]]
function Commands._prototype:set_defaults(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 if self.params[name] then
self.params[name].default = value self.params[name].default = value
end end
@@ -555,7 +555,7 @@ command:set_flag('admin_only', true)
command:set_flag('admin_only') command:set_flag('admin_only')
]] ]]
function Commands._prototype:set_flag(name,value) function Commands._prototype:set_flag(name, value)
value = value or true value = value or true
self.flags[name] = value self.flags[name] = value
return self return self
@@ -570,8 +570,8 @@ command:add_alias('name', 'rname')
]] ]]
function Commands._prototype:add_alias(...) function Commands._prototype:add_alias(...)
for _,alias in pairs({...}) do for _, alias in pairs({...}) do
table.insert(self.aliases,alias) table.insert(self.aliases, alias)
--Commands.alias_map[alias] = self.name --Commands.alias_map[alias] = self.name
end end
return self return self
@@ -600,7 +600,7 @@ command:register(function(player, repeat_count, smiley, _)
local msg = ') '..player.name local msg = ') '..player.name
if smiley then msg = ':'..msg end if smiley then msg = ':'..msg end
for 1 = 1,repeat_count do for 1 = 1, repeat_count do
Command.print(1..msg) Command.print(1..msg)
end end
end) end)
@@ -610,26 +610,26 @@ function Commands._prototype:register(callback)
-- generates a description to be used -- generates a description to be used
self.callback = callback self.callback = callback
local description = '' 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 if param_details.optional then
description = string.format('%s [%s]',description,param_name) description = string.format('%s [%s]', description, param_name)
else else
description = string.format('%s <%s>',description,param_name) description = string.format('%s <%s>', description, param_name)
end end
end end
self.description = description self.description = description
-- registers the command under its own name -- registers the command under its own name
commands.add_command(self.name,{'expcore-commands.command-help',description,self.help},function(command_event) commands.add_command(self.name, {'expcore-commands.command-help', description, self.help}, function(command_event)
local success, err = pcall(Commands.run_command,command_event) local success, err = pcall(Commands.run_command, command_event)
if not success then log('[ERROR] command/'..self.name..' :: '..err) end if not success then log('[ERROR] command/'..self.name..' :: '..err) end
end) end)
-- adds any aliases that it has -- adds any aliases that it has
for _,alias in pairs(self.aliases) do for _, alias in pairs(self.aliases) do
if not commands.commands[alias] and not commands.game_commands[alias] then 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) commands.add_command(alias, {'expcore-commands.command-help', description, self.help}, function(command_event)
command_event.name = self.name command_event.name = self.name
local success, err = pcall(Commands.run_command,command_event) local success, err = pcall(Commands.run_command, command_event)
Commands.internal_error(success,self.name,err) Commands.internal_error(success, self.name, err)
end) end)
end end
end end
@@ -649,9 +649,9 @@ nb: this is for non fatal errors meaning there is no log of this event, use duri
return Commands.error('The player you selected is offline') 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 '' 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 if play_sound ~= false then
play_sound = play_sound or 'utility/wire_pickup' play_sound = play_sound or 'utility/wire_pickup'
if game.player then game.player.play_sound{path=play_sound} end if game.player then game.player.play_sound{path=play_sound} end
@@ -673,10 +673,10 @@ if Commands.internal_error(success, command_data.name, err) then
end end
]] ]]
function Commands.internal_error(success,command_name,error_message) function Commands.internal_error(success, command_name, error_message)
if not success then if not success then
Commands.error('Internal Error, Please contact an admin','utility/cannot_build') Commands.error('Internal Error, Please contact an admin', 'utility/cannot_build')
log{'expcore-commands.command-error-log-format',command_name,error_message} log{'expcore-commands.command-error-log-format', command_name, error_message}
end end
return not success return not success
end end
@@ -695,7 +695,7 @@ return 'Your message has been printed'
]] ]]
function Commands.success(value) function Commands.success(value)
if value ~= nil then player_return(value) end if value ~= nil then player_return(value) end
player_return({'expcore-commands.command-ran'},'cyan') player_return({'expcore-commands.command-ran'}, 'cyan')
return Commands.defines.success return Commands.defines.success
end end
@@ -710,9 +710,9 @@ Commands.print('Your command is in progress')
]] ]]
-- logs command usage to file -- logs command usage to file
local function command_log(player,command,comment,params,raw,details) local function command_log(player, command, comment, params, raw, details)
local player_name = player and player.name or '<Server>' local player_name = player and player.name or '<Server>'
write_json('log/commands.log',{ write_json('log/commands.log', {
player_name=player_name, player_name=player_name,
command_name=command.name, command_name=command.name,
comment=comment, comment=comment,
@@ -734,27 +734,27 @@ function Commands.run_command(command_event)
end end
-- checks if player is allowed to use the command -- checks if player is allowed to use the command
local authorized, auth_fail = Commands.authorize(player,command_data.name) local authorized, auth_fail = Commands.authorize(player, command_data.name)
if not authorized then if not authorized then
command_log(player,command_data,'Failed Auth',{},command_event.parameter) command_log(player, command_data, 'Failed Auth', {}, command_event.parameter)
Commands.error(auth_fail,'utility/cannot_build') Commands.error(auth_fail, 'utility/cannot_build')
return return
end end
-- null param check -- null param check
if command_data.min_param_count > 0 and not command_event.parameter then if command_data.min_param_count > 0 and not command_event.parameter then
command_log(player,command_data,'No Params Given',{},command_event.parameter) command_log(player, command_data, 'No Params Given', {}, command_event.parameter)
Commands.error({'expcore-commands.invalid-inputs',command_data.name,command_data.description}) Commands.error({'expcore-commands.invalid-inputs', command_data.name, command_data.description})
return return
end end
-- splits the arguments -- splits the arguments
local input_string = command_event.parameter or '' local input_string = command_event.parameter or ''
local quote_params = {} -- stores any " " params local quote_params = {} -- stores any " " params
input_string = input_string:gsub(' "[^"]-"',function(w) input_string = input_string:gsub(' "[^"]-"', function(w)
-- finds all " " params are removes spaces for the next part -- finds all " " params are removes spaces for the next part
local no_spaces = w:gsub('%s','_') local no_spaces = w:gsub('%s', '_')
local no_quotes = w:sub(2,-2) local no_quotes = w:sub(2, -2)
quote_params[no_spaces]=no_quotes quote_params[no_spaces]=no_quotes
if command_data.auto_concat then if command_data.auto_concat then
-- if auto concat then don't remove quotes as it should be included later -- if auto concat then don't remove quotes as it should be included later
@@ -772,8 +772,8 @@ function Commands.run_command(command_event)
-- there are too many params given to the command -- there are too many params given to the command
if not command_data.auto_concat then if not command_data.auto_concat then
-- error as they should not be more -- error as they should not be more
command_log(player,command_data,'Invalid Input: Too Many Params',raw_params,input_string) 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}) Commands.error({'expcore-commands.invalid-inputs', command_data.name, command_data.description})
return return
else else
-- concat to the last param -- concat to the last param
@@ -789,10 +789,10 @@ function Commands.run_command(command_event)
-- all words are added to an array -- all words are added to an array
if quote_params[word] then if quote_params[word] then
-- if it was a " " param then the spaces are re added now -- if it was a " " param then the spaces are re added now
table.insert(raw_params,quote_params[word]) table.insert(raw_params, quote_params[word])
last_index = last_index + 1 last_index = last_index + 1
else else
table.insert(raw_params,word) table.insert(raw_params, word)
last_index = last_index + 1 last_index = last_index + 1
end end
end end
@@ -801,8 +801,8 @@ function Commands.run_command(command_event)
-- checks param count -- checks param count
local param_count = #raw_params local param_count = #raw_params
if param_count < command_data.min_param_count then if param_count < command_data.min_param_count then
command_log(player,command_data,'Invalid Input: Not Enough Params',raw_params,input_string) 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}) Commands.error({'expcore-commands.invalid-inputs', command_data.name, command_data.description})
return return
end end
@@ -817,58 +817,58 @@ function Commands.run_command(command_event)
end end
if not type(parse_callback) == 'function' then if not type(parse_callback) == 'function' then
-- if its not a function throw and error -- if its not a function throw and error
Commands.internal_error(false,command_data.name,'Invalid param parse '..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,command_event.parameter,tostring(param_data.parse)) command_log(player, command_data, 'Internal Error: Invalid Param Parse', params, command_event.parameter, tostring(param_data.parse))
return return
end end
-- used below as the reject function -- used below as the reject function
local parse_fail = function(error_message) local parse_fail = function(error_message)
error_message = error_message or '' error_message = error_message or ''
command_log(player,command_data,'Invalid Param Given',raw_params,input_string) command_log(player, command_data, 'Invalid Param Given', raw_params, input_string)
return Commands.error{'expcore-commands.invalid-param',param_name,error_message} return Commands.error{'expcore-commands.invalid-param', param_name, error_message}
end end
-- input: string, player: LuaPlayer, reject: function, ... extra args -- 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)) 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 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) return command_log(player, command_data, 'Internal Error: Param Parse Fail', params, command_event.parameter, param_parsed)
end end
if param_data.optional == true and raw_params[index] == nil then 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 it is optional and param is nil then it is set to default
param_parsed = param_data.default param_parsed = param_data.default
if type(param_parsed) == 'function' then if type(param_parsed) == 'function' then
-- player: LuaPlayer -- player: LuaPlayer
success,param_parsed = pcall(param_parsed,player) success, param_parsed = pcall(param_parsed, player)
if Commands.internal_error(success,command_data.name,param_parsed) then 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) return command_log(player, command_data, 'Internal Error: Default Value Fail', params, command_event.parameter, param_parsed)
end end
end end
elseif param_parsed == nil or param_parsed == Commands.defines.error or param_parsed == parse_fail then 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 -- no value was returned or error was returned, if nil then give generic error
if not param_parsed == Commands.defines.error then if not param_parsed == Commands.defines.error then
command_log(player,command_data,'Invalid Param Given',raw_params,input_string,param_name) 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'} Commands.error{'expcore-commands.command-error-param-format', param_name, 'please make sure it is the correct type'}
end end
return return
end end
-- adds the param to the table to be passed to the command callback -- adds the param to the table to be passed to the command callback
table.insert(params,param_parsed) table.insert(params, param_parsed)
index=index+1 index=index+1
end end
-- runs the command -- runs the command
-- player: LuaPlayer, ... command params, raw: string -- player: LuaPlayer, ... command params, raw: string
table.insert(params,command_data.max_param_count+1,input_string) table.insert(params, command_data.max_param_count+1, input_string)
local success, err = pcall(command_data.callback,player,unpack(params)) local success, err = pcall(command_data.callback, player, unpack(params))
if Commands.internal_error(success,command_data.name,err) then 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) return command_log(player, command_data, 'Internal Error: Command Callback Fail', raw_params, command_event.parameter, err)
end end
if err == Commands.defines.error or err == Commands.error then if err == Commands.defines.error or err == Commands.error then
return command_log(player,command_data,'Custom Error',raw_params,input_string) return command_log(player, command_data, 'Custom Error', raw_params, input_string)
elseif err ~= Commands.defines.success and err ~= Commands.success then elseif err ~= Commands.defines.success and err ~= Commands.success then
-- in this case the user has not received any output -- in this case the user has not received any output
Commands.success(err) Commands.success(err)
end end
command_log(player,command_data,'Success',raw_params,input_string) command_log(player, command_data, 'Success', raw_params, input_string)
end end
return Commands return Commands

View File

@@ -42,7 +42,7 @@ type_error(value, 'number', 'Value must be a number')
]] ]]
function Common.type_error(value, test_type, error_message, level) function Common.type_error(value, test_type, error_message, level)
level = level and level+1 or 2 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 end
--[[-- Asserts the argument is one of type test_types --[[-- Asserts the argument is one of type test_types
@@ -51,7 +51,7 @@ end
@treturn boolean true if value is one of test_types @treturn boolean true if value is one of test_types
@usage-- Check for a string or table @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) function Common.multi_type_check(value, test_types)
@@ -72,12 +72,12 @@ end
@treturn boolean true if no error was called @treturn boolean true if no error was called
@usage-- Raise error if value is not a string or table @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) function Common.multi_type_error(value, test_types, error_message, level)
level = level and level+1 or 2 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 end
--[[-- Raises an error when the value is the incorrect type, uses a consistent error message format --[[-- 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) function Common.validate_argument_type(value, test_type, param_number, param_name)
if not Common.test_type(value,test_type) then if not Common.test_type(value, test_type) then
local function_name = debug.getinfo(2,'n').name or '<anon>' local function_name = debug.getinfo(2, 'n').name or '<anon>'
local error_message local error_message
if param_name then 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) 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 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) 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 end
return error(error_message,3) return error(error_message, 3)
end end
return true return true
end end
@@ -116,22 +116,22 @@ end
@treturn boolean true if no error was raised @treturn boolean true if no error was raised
@usage-- Output: "Bad argument #2 to "<anon>"; argument is of type number expected string or table" @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)
@usage-- Output: "Bad argument #2 to "<anon>"; "player" is of type number expected string or table" @usage-- 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')
]] ]]
function Common.validate_argument_multi_type(value, test_types, param_number, param_name) function Common.validate_argument_multi_type(value, test_types, param_number, param_name)
if not Common.multi_type_check(value,test_types) then if not Common.multi_type_check(value, test_types) then
local function_name = debug.getinfo(2,'n').name or '<anon>' local function_name = debug.getinfo(2, 'n').name or '<anon>'
local error_message local error_message
if param_name then 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 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 end
return error(error_message,3) return error(error_message, 3)
end end
return true return true
end end
@@ -140,8 +140,8 @@ end
-- @usage error_if_runtime() -- @usage error_if_runtime()
function Common.error_if_runtime() function Common.error_if_runtime()
if _LIFECYCLE == 8 then if _LIFECYCLE == 8 then
local function_name = debug.getinfo(2,'n').name or '<anon>' local function_name = debug.getinfo(2, 'n').name or '<anon>'
error(function_name..' can not be called during runtime',3) error(function_name..' can not be called during runtime', 3)
end end
end end
@@ -149,8 +149,8 @@ end
-- @usage error_if_runetime_closure(func) -- @usage error_if_runetime_closure(func)
function Common.error_if_runetime_closure(func) function Common.error_if_runetime_closure(func)
if _LIFECYCLE == 8 and Debug.is_closure(func) then if _LIFECYCLE == 8 and Debug.is_closure(func) then
local function_name = debug.getinfo(2,'n').name or '<anon>' local function_name = debug.getinfo(2, 'n').name or '<anon>'
error(function_name..' can not be called during runtime with a closure',3) error(function_name..' can not be called during runtime with a closure', 3)
end end
end end
@@ -180,7 +180,7 @@ end
local value = Common.resolve_value(self.defaut_value, self) 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 return value and type(value) == 'function' and value(...) or value
end end
@@ -201,7 +201,7 @@ end
-- @usage comma_value(input_number) -- @usage comma_value(input_number)
function Common.comma_value(n) -- credit http://richard.warburton.it function Common.comma_value(n) -- credit http://richard.warburton.it
local left, num, right = string.match(n, '^([^%d]*%d)(%d*)(.-)$') 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 end
--[[-- Sets a table element to value while also returning value. --[[-- Sets a table element to value while also returning value.
@@ -227,8 +227,8 @@ end
write_json('dump', tbl) write_json('dump', tbl)
]] ]]
function Common.write_json(path,tbl) function Common.write_json(path, tbl)
game.write_file(path,game.table_to_json(tbl)..'\n',true,0) game.write_file(path, game.table_to_json(tbl)..'\n', true, 0)
end end
--[[-- Calls a require that will not error if the file is not found --[[-- 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) function Common.opt_require(path)
local success, rtn = pcall(require,path) local success, rtn = pcall(require, path)
if success then return rtn if success then return rtn
else return nil,rtn end else return nil, rtn end
end end
--[[-- Returns a desync safe file path for the current file --[[-- Returns a desync safe file path for the current file
@@ -273,17 +273,17 @@ local colors = enum{
]] ]]
function Common.enum(tbl) function Common.enum(tbl)
local rtn = {} local rtn = {}
for k,v in pairs(tbl) do for k, v in pairs(tbl) do
if type(k) ~= 'number' then if type(k) ~= 'number' then
rtn[v]=k rtn[v]=k
end end
end end
for k,v in pairs(tbl) do for k, v in pairs(tbl) do
if type(k) == 'number' then if type(k) == 'number' then
table.insert(rtn,v) table.insert(rtn, v)
end end
end end
for k,v in pairs(rtn) do for k, v in pairs(rtn) do
rtn[v]=k rtn[v]=k
end end
return rtn return rtn
@@ -306,20 +306,19 @@ local value = auto_complete(tbl, "foo", true)
local key = auto_complete(tbl, "foo", true, true) local key = auto_complete(tbl, "foo", true, true)
]] ]]
function Common.auto_complete(options,input,use_key,rtn_key) function Common.auto_complete(options, input, use_key, rtn_key)
local rtn = {}
if type(input) ~= 'string' then return end if type(input) ~= 'string' then return end
input = input:lower() 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 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 return rtn_key and key or value
end end
end end
end end
--- Formating. --- Formatting.
-- @section formating -- @section formatting
--[[-- Returns a valid string with the name of the actor of a command. --[[-- 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 @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 --[[-- Returns a message with valid chat tags to change its colour
@tparam string message the message that will be in the output @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 @treturn string the message with the color tags included
@usage-- Use factorio tags to color a chat message @usage-- Use factorio tags to color a chat message
local message = format_chat_colour('Hello, World!', { r=355, g=100, b=100 }) 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 color = color or Colours.white
local color_tag = '[color='..math.round(color.r,3)..','..math.round(color.g,3)..','..math.round(color.b,3)..']' 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) return string.format('%s%s[/color]', color_tag, message)
end end
--[[-- Returns a message with valid chat tags to change its colour, using localization --[[-- 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 ?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 @treturn table the message with the color tags included
@usage-- Use factorio tags and locale strings to color a chat message @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 }) 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 = color or Colours.white
color = math.round(color.r,3)..','..math.round(color.g,3)..','..math.round(color.b,3) color = math.round(color.r, 3)..', '..math.round(color.g, 3)..', '..math.round(color.b, 3)
return {'color-tag',color,message} return {'color-tag', color, message}
end end
--[[-- Returns the players name in the players color --[[-- Returns the players name in the players color
@@ -372,14 +371,14 @@ end
local message = format_chat_player_name(game.player, true) 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) player = Game.get_player_from_any(player)
local player_name = player and player.name or '<Server>' local player_name = player and player.name or '<Server>'
local player_chat_colour = player and player.chat_color or Colours.white local player_chat_colour = player and player.chat_color or Colours.white
if raw_string then 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 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
end end
@@ -398,16 +397,16 @@ player_return('Hello, World!', 'green')
player_return('Hello, World!', nil, player) player_return('Hello, World!', nil, player)
]] ]]
function Common.player_return(value,colour,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 colour = Common.type_check(colour, 'table') and colour or Colours[colour] ~= Colours.white and Colours[colour] or Colours.white
player = player or game.player player = player or game.player
-- converts the value to a string -- converts the value to a string
local returnAsString local returnAsString
if Common.type_check(value,'table') 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 if Common.type_check(value.__self, 'userdata') or type(value) == 'userdata' then
-- value is userdata -- value is userdata
returnAsString = 'Cant Display 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 -- value is a locale string
returnAsString = value returnAsString = value
elseif getmetatable(value) ~= nil and not tostring(value):find('table: 0x') then 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) returnAsString = tostring(value)
else else
-- value is a table -- value is a table
returnAsString = table.inspect(value,{depth=5,indent=' ',newline='\n'}) returnAsString = table.inspect(value, {depth=5, indent=' ', newline='\n'})
end end
elseif Common.type_check(value,'function') then elseif Common.type_check(value, 'function') then
-- value is a function -- value is a function
returnAsString = 'Cant Display Functions' returnAsString = 'Cant Display Functions'
else returnAsString = tostring(value) end else returnAsString = tostring(value) end
@@ -425,10 +424,10 @@ function Common.player_return(value,colour,player)
if player then if player then
-- allows any valid player identifier to be used -- allows any valid player identifier to be used
player = Game.get_player_from_any(player) 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 -- plays a nice sound that is different to normal message sound
player.play_sound{path='utility/scenario_message'} player.play_sound{path='utility/scenario_message'}
player.print(returnAsString,colour) player.print(returnAsString, colour)
else rcon.print(returnAsString) end else rcon.print(returnAsString) end
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 }) 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 -- Sets up the options
options = options or { options = options or {
days=false, days=false,
@@ -508,31 +507,31 @@ function Common.format_time(ticks,options)
rtn_minutes = long and rtn_minutes..' minutes' or rtn_minutes..'m' rtn_minutes = long and rtn_minutes..' minutes' or rtn_minutes..'m'
rtn_seconds = long and rtn_seconds..' seconds' or rtn_seconds..'s' rtn_seconds = long and rtn_seconds..' seconds' or rtn_seconds..'s'
else else
rtn_days = {suffix..'days'..suffix_2,rtn_days} rtn_days = {suffix..'days'..suffix_2, rtn_days}
rtn_hours = {suffix..'hours'..suffix_2,rtn_hours} rtn_hours = {suffix..'hours'..suffix_2, rtn_hours}
rtn_minutes = {suffix..'minutes'..suffix_2,rtn_minutes} rtn_minutes = {suffix..'minutes'..suffix_2, rtn_minutes}
rtn_seconds = {suffix..'seconds'..suffix_2,rtn_seconds} rtn_seconds = {suffix..'seconds'..suffix_2, rtn_seconds}
end end
elseif not options.null then elseif not options.null then
-- weather string or not it has same format -- weather string or not it has same format
rtn_days = string.format('%02d',rtn_days) rtn_days = string.format('%02d', rtn_days)
rtn_hours = string.format('%02d',rtn_hours) rtn_hours = string.format('%02d', rtn_hours)
rtn_minutes = string.format('%02d',rtn_minutes) rtn_minutes = string.format('%02d', rtn_minutes)
rtn_seconds = string.format('%02d',rtn_seconds) rtn_seconds = string.format('%02d', rtn_seconds)
end end
-- The final return is construed -- The final return is construed
local rtn local rtn
local append = function(dom,value) local append = function(dom, value)
if dom and options.string then if dom and options.string then
rtn = rtn and rtn..div..value or value rtn = rtn and rtn..div..value or value
elseif dom then elseif dom then
rtn = rtn and {div,rtn,value} or value rtn = rtn and {div, rtn, value} or value
end end
end end
append(options.days,rtn_days) append(options.days, rtn_days)
append(options.hours,rtn_hours) append(options.hours, rtn_hours)
append(options.minutes,rtn_minutes) append(options.minutes, rtn_minutes)
append(options.seconds,rtn_seconds) append(options.seconds, rtn_seconds)
return rtn return rtn
end end
@@ -542,31 +541,31 @@ end
--[[-- Moves items to the position and stores them in the closest entity of the type given --[[-- 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 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=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=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 @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 @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()) 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' chest_type = chest_type or 'iron-chest'
surface = surface or game.surfaces[1] surface = surface or game.surfaces[1]
if position and type(position) ~= 'table' then return end if position and type(position) ~= 'table' then return end
if type(items) ~= 'table' then return end if type(items) ~= 'table' then return end
-- Finds all entities of the given type -- 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 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 count = #entities
local current = 1 local current = 1
-- Makes a new empty chest when it is needed -- Makes a new empty chest when it is needed
local function make_new_chest() local function make_new_chest()
local pos = surface.find_non_colliding_position(chest_type,position,32,1) local pos = surface.find_non_colliding_position(chest_type, position, 32, 1)
local chest = surface.create_entity{name=chest_type,position=pos,force='neutral'} local chest = surface.create_entity{name=chest_type, position=pos, force='neutral'}
table.insert(entities,chest) table.insert(entities, chest)
count = count + 1 count = count + 1
return chest return chest
end end
@@ -581,16 +580,16 @@ function Common.move_items(items,surface,position,radius,chest_type)
return chest return chest
else else
-- Other wise it is removed from the list -- Other wise it is removed from the list
table.remove(entities,current) table.remove(entities, current)
count = count - 1 count = count - 1
end end
end end
-- Inserts the items into the chests -- Inserts the items into the chests
local last_chest local last_chest
for item_name,item_count in pairs(items) do for item_name, item_count in pairs(items) do
local chest = next_chest{name=item_name,count=item_count} 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 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}) Util.insert_safe(chest, {[item_name]=item_count})
last_chest = chest last_chest = chest
end end
return last_chest 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=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 @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 }) 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) function Common.clear_flying_text(surface)
local entities = surface.find_entities_filtered{name ='flying-text'} 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 if entity and entity.valid then
entity.destroy() entity.destroy()
end end

View File

@@ -18,7 +18,7 @@ Gui.element{
@usage-- Making a factory function for a button which is contained within a flow @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 -- This method is for when you still want to register event handlers but cant use the table method
local example_flow_with_button = 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 -- ... 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 -- Here we are adding a flow which we will then later add a button to
local flow = local flow =
@@ -60,7 +60,7 @@ Gui.element{
caption = 'Example Button', caption = 'Example Button',
style = 'forward_button' -- factorio styles can be applied here 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 -- style is the current style object for the elemenent
-- element is the element that is being changed -- element is the element that is being changed
-- ... shows that all other arguments from the factory call are passed to this function -- ... shows that all other arguments from the factory call are passed to this function
@@ -76,7 +76,7 @@ Gui.element{
type = 'button', type = 'button',
caption = 'Example 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 -- player is the player who interacted with the element to cause the event
-- element is a refrence to the element which caused 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 -- event is a raw refrence to the event data if player and element are not enough
@@ -98,21 +98,21 @@ Gui.element{
width = 18, width = 18,
height = 20 height = 20
} }
:on_click(function(player,_,_) :on_click(function(player, _,_)
Gui.hide_left_flow(player) Gui.hide_left_flow(player)
end) end)
@usage-- Eample from defines, Gui.alignment, called like: Gui.alignment(parent, name, horizontal_align, vertical_align) @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 -- Notice how _ are used to blank arguments that are not needed in that context and how they line up with above
Gui.alignment = Gui.alignment =
Gui.element(function(_,parent,name,_,_) Gui.element(function(_, parent, name, _,_)
return parent.add{ return parent.add{
name = name or 'alignment', name = name or 'alignment',
type = 'flow', type = 'flow',
} }
end) end)
:style(function(style,_,_,horizontal_align,vertical_align) :style(function(style, _,_, horizontal_align, vertical_align)
style.padding = {1,2} style.padding = {1, 2}
style.vertical_align = vertical_align or 'center' style.vertical_align = vertical_align or 'center'
style.horizontal_align = horizontal_align or 'right' style.horizontal_align = horizontal_align or 'right'
style.vertically_stretchable = style.vertical_align ~= 'center' style.vertically_stretchable = style.vertical_align ~= 'center'

View File

@@ -23,7 +23,7 @@ Gui.element{
width = 18, width = 18,
height = 36 height = 36
} }
:on_click(function(player,_,_) :on_click(function(player, _,_)
Gui.toggle_top_flow(player) Gui.toggle_top_flow(player)
end) end)
Gui.core_defines.hide_top_flow = hide_top_flow Gui.core_defines.hide_top_flow = hide_top_flow
@@ -42,7 +42,7 @@ Gui.element{
width = 18, width = 18,
height = 20 height = 20
} }
:on_click(function(player,_,_) :on_click(function(player, _,_)
Gui.toggle_top_flow(player) Gui.toggle_top_flow(player)
end) end)
Gui.core_defines.show_top_flow = show_top_flow Gui.core_defines.show_top_flow = show_top_flow
@@ -61,13 +61,13 @@ Gui.element{
width = 18, width = 18,
height = 20 height = 20
} }
:on_click(function(player,_,_) :on_click(function(player, _,_)
Gui.hide_left_flow(player) Gui.hide_left_flow(player)
end) end)
Gui.core_defines.hide_left_flow = hide_left_flow Gui.core_defines.hide_left_flow = hide_left_flow
--- Draw the core elements when a player joins the game --- 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] local player = game.players[event.player_index]
-- Draw the top flow -- Draw the top flow

View File

@@ -17,21 +17,21 @@ local Gui = require 'expcore.gui.prototype'
@treturn LuaGuiElement the alignment flow that was created @treturn LuaGuiElement the alignment flow that was created
@usage-- Adding a right align flow @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 @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.alignment =
Gui.element(function(_,parent,name,_,_) Gui.element(function(_, parent, name, _,_)
return parent.add{ return parent.add{
name = name or 'alignment', name = name or 'alignment',
type = 'flow', type = 'flow',
} }
end) end)
:style(function(style,_,_,horizontal_align,vertical_align) :style(function(style, _,_, horizontal_align, vertical_align)
style.padding = {1,2} style.padding = {1, 2}
style.vertical_align = vertical_align or 'center' style.vertical_align = vertical_align or 'center'
style.horizontal_align = horizontal_align or 'right' style.horizontal_align = horizontal_align or 'right'
style.vertically_stretchable = style.vertical_align ~= 'center' style.vertically_stretchable = style.vertical_align ~= 'center'
@@ -47,11 +47,11 @@ end)
@treturn LuaGuiElement the table that was created @treturn LuaGuiElement the table that was created
@usage-- Adding a scroll table with max height of 200 and column count of 3 @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.scroll_table =
Gui.element(function(_,parent,height,column_count,name) Gui.element(function(_, parent, height, column_count, name)
-- Draw the scroll -- Draw the scroll
local scroll_pane = local scroll_pane =
parent.add{ parent.add{
@@ -65,7 +65,7 @@ Gui.element(function(_,parent,height,column_count,name)
-- Set the style of the scroll pane -- Set the style of the scroll pane
local scroll_style = scroll_pane.style local scroll_style = scroll_pane.style
scroll_style.padding = {1,3} scroll_style.padding = {1, 3}
scroll_style.maximal_height = height scroll_style.maximal_height = height
scroll_style.horizontally_stretchable = true scroll_style.horizontally_stretchable = true
@@ -105,7 +105,7 @@ local header = Gui.header(
]] ]]
Gui.header = Gui.header =
Gui.element(function(_,parent,caption,tooltip,add_alignment,name) Gui.element(function(_, parent, caption, tooltip, add_alignment, name)
-- Draw the header -- Draw the header
local header = local header =
parent.add{ parent.add{
@@ -116,7 +116,7 @@ Gui.element(function(_,parent,caption,tooltip,add_alignment,name)
-- Change the style of the header -- Change the style of the header
local style = header.style local style = header.style
style.padding = {2,4} style.padding = {2, 4}
style.use_header_filler = false style.use_header_filler = false
style.horizontally_stretchable = true style.horizontally_stretchable = true
@@ -153,7 +153,7 @@ local footer = Gui.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 -- Draw the header
local footer = local footer =
parent.add{ parent.add{
@@ -164,7 +164,7 @@ Gui.element(function(_,parent,caption,tooltip,add_alignment,name)
-- Change the style of the footer -- Change the style of the footer
local style = footer.style local style = footer.style
style.padding = {2,4} style.padding = {2, 4}
style.use_header_filler = false style.use_header_filler = false
style.horizontally_stretchable = true style.horizontally_stretchable = true
@@ -190,11 +190,11 @@ end)
@tparam number width the minimal width that the frame will have @tparam number width the minimal width that the frame will have
@usage-- Adding a container as a base @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.container =
Gui.element(function(_,parent,name,_) Gui.element(function(_, parent, name, _)
-- Draw the external container -- Draw the external container
local frame = local frame =
parent.add{ parent.add{
@@ -210,7 +210,7 @@ Gui.element(function(_,parent,name,_)
style = 'window_content_frame_packed' style = 'window_content_frame_packed'
} }
end) end)
:style(function(style,element,_,width) :style(function(style, element, _,width)
style.vertically_stretchable = false style.vertically_stretchable = false
local frame_style = element.parent.style local frame_style = element.parent.style
frame_style.padding = 2 frame_style.padding = 2
@@ -227,16 +227,16 @@ local bar = Gui.bar(parent, 100)
]] ]]
Gui.bar = Gui.bar =
Gui.element(function(_,parent) Gui.element(function(_, parent)
return parent.add{ return parent.add{
type = 'progressbar', type = 'progressbar',
size = 1, size = 1,
value = 1 value = 1
} }
end) end)
:style(function(style,_,width) :style(function(style, _,width)
style.height = 3 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 if width then style.width = width
else style.horizontally_stretchable = true end else style.horizontally_stretchable = true end
end) end)
@@ -253,7 +253,7 @@ local label = Gui.centered_label(parent, 100, 'This is centered')
]] ]]
Gui.centered_label = Gui.centered_label =
Gui.element(function(_,parent,width,caption,tooltip) Gui.element(function(_, parent, width, caption, tooltip)
local label = parent.add{ local label = parent.add{
type = 'label', type = 'label',
caption = caption, caption = caption,
@@ -281,11 +281,11 @@ local label = Gui.centered_label(parent, 100, 'This is centered')
]] ]]
Gui.title_label = Gui.title_label =
Gui.element(function(_,parent,width,caption,tooltip) Gui.element(function(_, parent, width, caption, tooltip)
local title_flow = parent.add{ type='flow' } local title_flow = parent.add{ type='flow' }
title_flow.style.vertical_align = 'center' title_flow.style.vertical_align = 'center'
Gui.bar(title_flow,width) Gui.bar(title_flow, width)
local title_label = title_flow.add{ local title_label = title_flow.add{
type = 'label', type = 'label',
caption = caption, caption = caption,

View File

@@ -30,7 +30,7 @@ end
local new_enabled_state = Gui.toggle_enabled_state(element) 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 not element or not element.valid then return end
if state == nil then state = not element.enabled end if state == nil then state = not element.enabled end
element.enabled = state element.enabled = state
@@ -46,7 +46,7 @@ end
local new_visible_state = Gui.toggle_visible_state(element) 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 not element or not element.valid then return end
if state == nil then state = not element.visible end if state == nil then state = not element.visible end
element.visible = state element.visible = state
@@ -82,7 +82,7 @@ Gui.element{
:style(Gui.sprite_style(20)) :style(Gui.sprite_style(20))
]] ]]
function Gui.sprite_style(size,padding,style) function Gui.sprite_style(size, padding, style)
style = style or {} style = style or {}
style.padding = padding or -2 style.padding = padding or -2
style.height = size style.height = size

View File

@@ -55,11 +55,11 @@ Gui.left_toolbar_button('entity/inserter', 'Nothing to see here', example_flow_w
end) end)
]] ]]
function Gui.left_toolbar_button(sprite,tooltip,element_define,authenticator) function Gui.left_toolbar_button(sprite, tooltip, element_define, authenticator)
local button = Gui.toolbar_button(sprite,tooltip,authenticator) local button = Gui.toolbar_button(sprite, tooltip, authenticator)
-- Add on_click handler to handle click events comming from the player -- 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 top_flow = Gui.get_top_flow(player)
local element = top_flow[button.name] local element = top_flow[button.name]
local visibility_state = Gui.toggle_left_element(player, element_define) 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 -- Set the visible state of all elements in the flow
hide_button.visible = false 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 left_flow[name].visible = false
-- Check if the the element has a toobar button attached -- 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) 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) local left_flow = Gui.get_left_flow(player)
return left_flow[element_define.name] return left_flow[element_define.name]
end 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) 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 left_flow = Gui.get_left_flow(player)
local top_flow = Gui.get_top_flow(player) local top_flow = Gui.get_top_flow(player)

View File

@@ -22,9 +22,9 @@ local Gui = {
_prototype_element = {}, _prototype_element = {},
--- The prototype metatable applied to new element defines --- The prototype metatable applied to new element defines
_mt_element = { _mt_element = {
__call = function(self,parent,...) __call = function(self, parent, ...)
local element = self._draw(self.name,parent,...) local element = self._draw(self.name, parent, ...)
if self._style then self._style(element.style,element,...) end if self._style then self._style(element.style, element, ...) end
return element return element
end end
} }
@@ -50,7 +50,7 @@ Gui.element{
@usage-- Using element defines with a custom factory function @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 -- 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 = 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 -- ... 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 -- 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 -- 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 if type(element_define) == 'table' then
Gui.debug_info[name].draw = element_define Gui.debug_info[name].draw = element_define
element_define.name = name element_define.name = name
element._draw = function(_,parent) element._draw = function(_, parent)
return parent.add(element_define) return parent.add(element_define)
end end
else else
@@ -131,7 +131,7 @@ Gui.element{
caption = 'Example Button', caption = 'Example Button',
style = 'forward_button' -- factorio styles can be applied here 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 -- style is the current style object for the elemenent
-- element is the element that is being changed -- element is the element that is being changed
-- ... shows that all other arguments from the factory call are passed to this function -- ... 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 if type(style_define) == 'table' then
Gui.debug_info[self.name].style = style_define Gui.debug_info[self.name].style = style_define
self._style = function(style) self._style = function(style)
for key,value in pairs(style_define) do for key, value in pairs(style_define) do
style[key] = value style[key] = value
end end
end end
@@ -171,8 +171,8 @@ element_deinfe:on_custom_event('my_custom_event', function(event)
end) end)
]] ]]
function Gui._prototype_element:on_custom_event(event_name,handler) function Gui._prototype_element:on_custom_event(event_name, handler)
table.insert(Gui.debug_info[self.name].events,event_name) table.insert(Gui.debug_info[self.name].events, event_name)
Gui.events[event_name] = event_name Gui.events[event_name] = event_name
self[event_name] = handler self[event_name] = handler
return self return self
@@ -210,7 +210,7 @@ function Gui._prototype_element:raise_custom_event(event)
end end
event.player = player event.player = player
local success, err = pcall(handler,player,element,event) local success, err = pcall(handler, player, element, event)
if not success then if not success then
error('There as been an error with an event handler for a gui element:\n\t'..err) error('There as been an error with an event handler for a gui element:\n\t'..err)
end end
@@ -227,8 +227,8 @@ local function event_handler_factory(event_name)
element_define:raise_custom_event(event) element_define:raise_custom_event(event)
end) end)
return function(self,handler) return function(self, handler)
table.insert(Gui.debug_info[self.name].events,debug.getinfo(1, "n").name) table.insert(Gui.debug_info[self.name].events, debug.getinfo(1, "n").name)
self[event_name] = handler self[event_name] = handler
return self return self
end end

View File

@@ -87,10 +87,10 @@ end
Gui.toggle_top_flow(game.player) Gui.toggle_top_flow(game.player)
@usage-- Open your top flow @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 -- Get the top flow and hide button
local top_flow = Gui.get_top_flow(player) local top_flow = Gui.get_top_flow(player)
if state == nil then state = not top_flow.visible end if state == nil then state = not top_flow.visible end
@@ -130,7 +130,7 @@ Gui.left_toolbar_button('entity/inserter', 'Nothing to see here', function(playe
end) end)
]] ]]
function Gui.toolbar_button(sprite,tooltip,authenticator) function Gui.toolbar_button(sprite, tooltip, authenticator)
return Gui.element{ return Gui.element{
type = 'sprite-button', type = 'sprite-button',
sprite = sprite, sprite = sprite,

View File

@@ -35,14 +35,14 @@ local Permissions_Groups = {
-- Async function to add players to permission groups -- Async function to add players to permission groups
local add_to_permission_group = local add_to_permission_group =
Async.register(function(permission_group,player) Async.register(function(permission_group, player)
permission_group.add_player(player) permission_group.add_player(player)
end) end)
Permissions_Groups.async_token_add_to_permission_group = add_to_permission_group Permissions_Groups.async_token_add_to_permission_group = add_to_permission_group
-- Async function to remove players from permission groups -- Async function to remove players from permission groups
local remove_from_permission_group = local remove_from_permission_group =
Async.register(function(permission_group,player) Async.register(function(permission_group, player)
permission_group.remove_player(player) permission_group.remove_player(player)
end) end)
Permissions_Groups.async_token_remove_from_permission_group = remove_from_permission_group Permissions_Groups.async_token_remove_from_permission_group = remove_from_permission_group
@@ -64,7 +64,7 @@ function Permissions_Groups.new_group(name)
name=name, name=name,
actions={}, actions={},
allow_all_actions=true allow_all_actions=true
},{ }, {
__index= Permissions_Groups._prototype __index= Permissions_Groups._prototype
}) })
Permissions_Groups.groups[name] = group Permissions_Groups.groups[name] = group
@@ -111,7 +111,7 @@ Groups.reload_permissions()
]] ]]
function Permissions_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() group:create()
end end
end end
@@ -125,7 +125,7 @@ end
Groups.set_player_group(game.player, 'Admin') 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) player = Game.get_player_from_any(player)
group = Permissions_Groups.get_group_by_name(group) group = Permissions_Groups.get_group_by_name(group)
if not group or not player then return false end if not group or not player then return false end
@@ -146,7 +146,7 @@ end
group:set_action('toggle_map_editor', false) 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 if type(action) == 'string' then
action = defines.input_action[action] action = defines.input_action[action]
end end
@@ -168,8 +168,8 @@ function Permissions_Groups._prototype:allow(actions)
if type(actions) ~= 'table' then if type(actions) ~= 'table' then
actions = {actions} actions = {actions}
end end
for _,action in pairs(actions) do for _, action in pairs(actions) do
self:set_action(action,true) self:set_action(action, true)
end end
return self return self
end end
@@ -192,8 +192,8 @@ function Permissions_Groups._prototype:disallow(actions)
if type(actions) ~= 'table' then if type(actions) ~= 'table' then
actions = {actions} actions = {actions}
end end
for _,action in pairs(actions) do for _, action in pairs(actions) do
self:set_action(action,false) self:set_action(action, false)
end end
return self return self
end end
@@ -257,8 +257,8 @@ function Permissions_Groups._prototype:create()
if not group then if not group then
group = game.permissions.create_group(self.name) group = game.permissions.create_group(self.name)
end end
for _,action in pairs(defines.input_action) do for _, action in pairs(defines.input_action) do
group.set_allows_action(action,self:is_allowed(action)) group.set_allows_action(action, self:is_allowed(action))
end end
return group return group
end end
@@ -324,9 +324,9 @@ function Permissions_Groups._prototype:get_players(online)
if online == nil then if online == nil then
return group.players return group.players
else else
for _,player in pairs(group.players) do for _, player in pairs(group.players) do
if player.connected == online then if player.connected == online then
table.insert(player,player) table.insert(player, player)
end end
end end
end end
@@ -344,7 +344,7 @@ group:print('Hello, World!')
]] ]]
function Permissions_Groups._prototype:print(message) function Permissions_Groups._prototype:print(message)
local players = self:get_players(true) local players = self:get_players(true)
for _,player in pairs(players) do for _, player in pairs(players) do
player.print(message) player.print(message)
end end
return #players return #players

View File

@@ -6,13 +6,13 @@
@usage--- Using Role System (assignment): @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: --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{ Roles.override_player_roles{
Cooldude2606 = {'Owner','Admin','Member'}, Cooldude2606 = {'Owner', 'Admin', 'Member'},
NotCooldude2606 = {'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: --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.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.unassign_player(player, {'Admin', 'Moderator'}, by_player_name) -- this will remove "Admin" and "Moderator" role in one go
@usage--- Using Role System (role testing): @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: --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 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: --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_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_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_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: @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 --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: --a player has that tag present:
-- give you donators a speed boost when they join; these functions aren't required but can be useful -- 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 if state then
player.character_running_speed_modifier = 1.5 player.character_running_speed_modifier = 1.5
else else
@@ -45,30 +45,30 @@ Roles.new_role('Donator')
:set_flag('is_donator') :set_flag('is_donator')
-- and in your code you would test for -- 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 -- some donator only code
end end
@usage--- Example Role Define: @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 --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: --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: --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_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_permission_group('Staff') -- a second argument can be added if you have not used the custom permission group config
:set_flag('is_admin') :set_flag('is_admin')
--You will then want to decide if you want to allow all actions, this should of course be used sparely: --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... ...extras...
:set_allow_all() :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 --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: --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... ...extras...
:set_parent('Moderator') -- the admin can do anything that a moderator can do :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 :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: --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_tag('[Admin]')
:set_custom_color('red') :set_custom_color('red')
:set_permission_group('Staff') :set_permission_group('Staff')
@@ -132,10 +132,10 @@ local Roles = {
} }
--- When global is loaded it will have the metatable re-assigned to the roles --- When global is loaded it will have the metatable re-assigned to the roles
Global.register(Roles.config,function(tbl) Global.register(Roles.config, function(tbl)
Roles.config = tbl Roles.config = tbl
for _,role in pairs(Roles.config.roles) do for _, role in pairs(Roles.config.roles) do
setmetatable(role,{__index=Roles._prototype}) setmetatable(role, {__index=Roles._prototype})
local parent = Roles.config.roles[role.parent] local parent = Roles.config.roles[role.parent]
if parent then if parent then
setmetatable(role.allowed_actions, {__index=parent.allowed_actions}) setmetatable(role.allowed_actions, {__index=parent.allowed_actions})
@@ -150,7 +150,7 @@ end)
--- Internal function used to trigger a few different things when roles are changed --- 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 -- 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 -- 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 '<server>' by_player_name = game.player and game.player.name or by_player_name or '<server>'
local by_player = Game.get_player_from_any(by_player_name) local by_player = Game.get_player_from_any(by_player_name)
local by_player_index = by_player and by_player.index or 0 local by_player_index = by_player and by_player.index or 0
@@ -161,30 +161,30 @@ local function emit_player_roles_updated(player,type,roles,by_player_name,skip_g
end end
-- convert the roles to objects and get the names of the roles -- convert the roles to objects and get the names of the roles
local role_names = {} local role_names = {}
for index,role in pairs(roles) do for index, role in pairs(roles) do
role = Roles.get_role_from_any(role) role = Roles.get_role_from_any(role)
if role then if role then
roles[index] = role roles[index] = role
table.insert(role_names,role.name) table.insert(role_names, role.name)
end end
end end
-- output to all the different locations: game print, player sound, event trigger and role log -- output to all the different locations: game print, player sound, event trigger and role log
if not skip_game_print then 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 end
if type == 'assign' then if type == 'assign' then
player.play_sound{path='utility/achievement_unlocked'} player.play_sound{path='utility/achievement_unlocked'}
else else
player.play_sound{path='utility/game_lost'} player.play_sound{path='utility/game_lost'}
end end
script.raise_event(event,{ script.raise_event(event, {
name=event, name=event,
tick=game.tick, tick=game.tick,
player_index=player.index, player_index=player.index,
by_player_index=by_player_index, by_player_index=by_player_index,
roles=roles roles=roles
}) })
write_json('log/roles.log',{ write_json('log/roles.log', {
player_name=player.name, player_name=player.name,
by_player_name=by_player_name, by_player_name=by_player_name,
type=type, type=type,
@@ -201,11 +201,11 @@ game.player.print(Roles.debug())
]] ]]
function Roles.debug() function Roles.debug()
local output = '' local output = ''
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] local role = Roles.config.roles[role_name]
local color = role.custom_color or Colours.white local color = role.custom_color or Colours.white
color = string.format('[color=%d,%d,%d]',color.r,color.g,color.b) 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)) output = output..string.format('\n%s %s) %s[/color]', color, index, serpent.line(role))
end end
return output return output
end end
@@ -215,11 +215,11 @@ end
@tparam string message the message to send to the players @tparam string message the message to send to the players
@usage-- Print a message to the given roles @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) function Roles.print_to_roles(roles, message)
for _,role in pairs(roles) do for _, role in pairs(roles) do
role = Roles.get_role_from_any(role) role = Roles.get_role_from_any(role)
if role then role:print(message) end if role then role:print(message) end
end end
@@ -233,16 +233,16 @@ end
Roles.print_to_roles_higher('Moderator', 'Hello, World!') 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) role = Roles.get_role_from_any(role)
if not role then return end if not role then return end
local roles = {} local roles = {}
for index,role_name in pairs(Roles.config.order) do for index, role_name in pairs(Roles.config.order) do
if index <= role.index and role_name ~= Roles.config.internal.default then if index <= role.index and role_name ~= Roles.config.internal.default then
table.insert(roles,role_name) table.insert(roles, role_name)
end end
end end
Roles.print_to_roles(roles,message) Roles.print_to_roles(roles, message)
end end
--[[-- Prints a message to all players who have the given role or one which is lower (excluding default) --[[-- Prints a message to all players who have the given role or one which is lower (excluding default)
@@ -253,16 +253,16 @@ end
Roles.print_to_roles_higher('Moderator', 'Hello, World!') 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) role = Roles.get_role_from_any(role)
if not role then return end if not role then return end
local roles = {} local roles = {}
for index,role_name in pairs(Roles.config.order) do for index, role_name in pairs(Roles.config.order) do
if index >= role.index and role_name ~= Roles.config.internal.default then if index >= role.index and role_name ~= Roles.config.internal.default then
table.insert(roles,role_name) table.insert(roles, role_name)
end end
end end
Roles.print_to_roles(roles,message) Roles.print_to_roles(roles, message)
end end
--[[-- Get a role for the given name --[[-- Get a role for the given name
@@ -290,7 +290,7 @@ function Roles.get_role_by_order(index)
return Roles.config.roles[name] return Roles.config.roles[name]
end 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 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 @tparam ?number|string|table any the value used to find the role
@treturn Roles._prototype the role that was found or nil see above @treturn Roles._prototype the role that was found or nil see above
@@ -325,8 +325,8 @@ function Roles.get_player_roles(player)
local roles = Roles.config.players[player.name] or {} local roles = Roles.config.players[player.name] or {}
local default = Roles.config.roles[Roles.config.internal.default] local default = Roles.config.roles[Roles.config.internal.default]
local rtn = {default} local rtn = {default}
for _,role_name in pairs(roles) do for _, role_name in pairs(roles) do
table.insert(rtn,Roles.config.roles[role_name]) table.insert(rtn, Roles.config.roles[role_name])
end end
return rtn return rtn
end end
@@ -343,7 +343,7 @@ function Roles.get_player_highest_role(player)
local roles = Roles.get_player_roles(player) local roles = Roles.get_player_roles(player)
if not roles then return end if not roles then return end
local highest local highest
for _,role in pairs(roles) do for _, role in pairs(roles) do
if not highest or role.index < highest.index then if not highest or role.index < highest.index then
highest = role highest = role
end end
@@ -369,13 +369,13 @@ Roles.assign_player(game.player, 'Moderator')
Roles.assign_player('Cooldude2606', 'Moderator', nil, true) 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) local valid_player = Game.get_player_from_any(player)
if not skip_checks and not valid_player then return end if not skip_checks and not valid_player then return end
if type(roles) ~= 'table' or roles.name then if type(roles) ~= 'table' or roles.name then
roles = {roles} roles = {roles}
end end
for _,role in pairs(roles) do for _, role in pairs(roles) do
role = Roles.get_role_from_any(role) role = Roles.get_role_from_any(role)
if role then if role then
role:add_player(valid_player or player, valid_player == nil, true) role:add_player(valid_player or player, valid_player == nil, true)
@@ -400,14 +400,14 @@ Roles.unassign_player(game.player, 'Moderator')
Roles.unassign_player('Cooldude2606', 'Moderator', nil, true) 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) local valid_player = Game.get_player_from_any(player)
if not skip_checks and not valid_player then return end if not skip_checks and not valid_player then return end
if not player then return end if not player then return end
if type(roles) ~= 'table' or roles.name then if type(roles) ~= 'table' or roles.name then
roles = {roles} roles = {roles}
end end
for _,role in pairs(roles) do for _, role in pairs(roles) do
role = Roles.get_role_from_any(role) role = Roles.get_role_from_any(role)
if role then if role then
role:remove_player(valid_player or player, valid_player == nil, true) role:remove_player(valid_player or player, valid_player == nil, true)
@@ -427,12 +427,12 @@ Roles.override_player_roles('Cooldude2606', {'Moderator'})
@usage-- Override all existing roles, effects all users not just ones listed @usage-- Override all existing roles, effects all users not just ones listed
Roles.override_player_roles{ Roles.override_player_roles{
['Cooldude2606'] = {'Administrator','Moderator'}, ['Cooldude2606'] = {'Administrator', 'Moderator'},
['arty714'] = {'Administrator','Moderator'}, ['arty714'] = {'Administrator', 'Moderator'},
} }
]] ]]
function Roles.override_player_roles(player_name,roles) function Roles.override_player_roles(player_name, roles)
if not roles then if not roles then
Roles.config.players = player_name Roles.config.players = player_name
else else
@@ -453,12 +453,12 @@ end
local has_role = Roles.player_has_role(game.player, 'Moderator') 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) local roles = Roles.get_player_roles(player)
if not roles then return end if not roles then return end
search_role = Roles.get_role_from_any(search_role) search_role = Roles.get_role_from_any(search_role)
if not search_role then return end if not search_role then return end
for _,role in pairs(roles) do for _, role in pairs(roles) do
if role.name == search_role.name then return true end if role.name == search_role.name then return true end
end end
return false return false
@@ -473,10 +473,10 @@ end
local has_flag = Roles.player_has_flag(game.player, 'is_donator') 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) local roles = Roles.get_player_roles(player)
if not roles then return end if not roles then return end
for _,role in pairs(roles) do for _, role in pairs(roles) do
if role:has_flag(flag_name) then if role:has_flag(flag_name) then
return true return true
end end
@@ -493,10 +493,10 @@ end
local has_flag = Roles.player_has_flag(game.player, 'is_donator') 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) local roles = Roles.get_player_roles(player)
if not roles then return end if not roles then return end
for _,role in pairs(roles) do for _, role in pairs(roles) do
if role:is_allowed(action) then if role:is_allowed(action) then
return true return true
end end
@@ -527,31 +527,31 @@ function Roles.define_role_order(order)
_C.error_if_runtime() _C.error_if_runtime()
Roles.config.order = {} Roles.config.order = {}
local done = {} local done = {}
for _,role in ipairs(order) do for _, role in ipairs(order) do
if type(role) == 'table' and role.name then if type(role) == 'table' and role.name then
done[role.name] = true done[role.name] = true
table.insert(Roles.config.order,role.name) table.insert(Roles.config.order, role.name)
else else
done[role] = true done[role] = true
table.insert(Roles.config.order,role) table.insert(Roles.config.order, role)
end end
end end
-- Check no roles were missed -- 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 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
end end
-- Re-links roles to they parents as this is called at the end of the config -- 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] local role = Roles.config.roles[role_name]
if not role then 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 end
role.index = index role.index = index
local parent = Roles.config.roles[role.parent] local parent = Roles.config.roles[role.parent]
if parent then if parent then
setmetatable(role.allowed_actions,{__index=parent.allowed_actions}) setmetatable(role.allowed_actions, {__index=parent.allowed_actions})
end end
end end
end end
@@ -566,7 +566,7 @@ Roles.define_flag_trigger('is_donator', function(player, state)
end) end)
]] ]]
function Roles.define_flag_trigger(name,callback) function Roles.define_flag_trigger(name, callback)
_C.error_if_runtime() _C.error_if_runtime()
Roles.config.flags[name] = Async.register(callback) Roles.config.flags[name] = Async.register(callback)
end end
@@ -607,7 +607,7 @@ end
local role = Roles.new_role('Moderator', 'Mod') 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() _C.error_if_runtime()
if Roles.config.roles[name] then return error('Role name is non unique') end if Roles.config.roles[name] then return error('Role name is non unique') end
local role = setmetatable({ local role = setmetatable({
@@ -616,7 +616,7 @@ function Roles.new_role(name,short_hand)
allowed_actions={}, allowed_actions={},
allow_all_actions=false, allow_all_actions=false,
flags={} flags={}
},{__index=Roles._prototype}) }, {__index=Roles._prototype})
Roles.config.roles[name] = role Roles.config.roles[name] = role
return role return role
end end
@@ -654,7 +654,7 @@ function Roles._prototype:allow(actions)
if type(actions) ~= 'table' then if type(actions) ~= 'table' then
actions = {actions} actions = {actions}
end end
for _,action in pairs(actions) do for _, action in pairs(actions) do
self.allowed_actions[action]=true self.allowed_actions[action]=true
end end
return self return self
@@ -675,7 +675,7 @@ function Roles._prototype:disallow(actions)
if type(actions) ~= 'table' then if type(actions) ~= 'table' then
actions = {actions} actions = {actions}
end end
for _,action in pairs(actions) do for _, action in pairs(actions) do
self.allowed_actions[action]=false self.allowed_actions[action]=false
end end
return self return self
@@ -707,13 +707,13 @@ end
role:set_flag('is_admin') 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 if value == nil then value = true end
self.flags[name] = not not value -- not not forces a boolean value self.flags[name] = not not value -- not not forces a boolean value
return self return self
end 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 @treturn Roles._prototype allows chaining
@usage-- Remove all flags from a role @usage-- Remove all flags from a role
@@ -779,10 +779,10 @@ end
role:set_permission_group('Admin') 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() _C.error_if_runtime()
if use_factorio_api then if use_factorio_api then
self.permission_group = {true,name} self.permission_group = {true, name}
else else
local group = Groups.get_group_by_name(name) local group = Groups.get_group_by_name(name)
if not group then return end if not group then return end
@@ -854,7 +854,7 @@ end
role:add_player(game.player) role:add_player(game.player)
]] ]]
function Roles._prototype:add_player(player,skip_check,skip_event) function Roles._prototype:add_player(player, skip_check, skip_event)
player = Game.get_player_from_any(player) player = Game.get_player_from_any(player)
-- Default role cant have players added or removed -- Default role cant have players added or removed
if self.name == Roles.config.internal.default then return end if self.name == Roles.config.internal.default then return end
@@ -869,16 +869,16 @@ function Roles._prototype:add_player(player,skip_check,skip_event)
-- Add the role name to the player's roles -- 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 if player_roles then
for _,role_name in pairs(player_roles) do for _, role_name in pairs(player_roles) do
if role_name == self.name then return false end if role_name == self.name then return false end
end end
table.insert(player_roles,self.name) table.insert(player_roles, self.name)
else else
Roles.config.players[player.name] = {self.name} Roles.config.players[player.name] = {self.name}
end end
-- Emits event if required -- Emits event if required
if not skip_event then if not skip_event then
emit_player_roles_updated(player,'assign',{self}) emit_player_roles_updated(player, 'assign', {self})
end end
return true return true
end end
@@ -893,7 +893,7 @@ end
role:remove_player(game.player) role:remove_player(game.player)
]] ]]
function Roles._prototype:remove_player(player,skip_check,skip_event) function Roles._prototype:remove_player(player, skip_check, skip_event)
player = Game.get_player_from_any(player) player = Game.get_player_from_any(player)
-- Default role cant have players added or removed -- Default role cant have players added or removed
if self.name == Roles.config.internal.default then return end if self.name == Roles.config.internal.default then return end
@@ -909,9 +909,9 @@ function Roles._prototype:remove_player(player,skip_check,skip_event)
local player_roles = Roles.config.players[player.name] local player_roles = Roles.config.players[player.name]
local rtn = false local rtn = false
if player_roles then if player_roles then
for index,role_name in pairs(player_roles) do for index, role_name in pairs(player_roles) do
if role_name == self.name then if role_name == self.name then
table.remove(player_roles,index) table.remove(player_roles, index)
rtn = true rtn = true
break break
end end
@@ -922,7 +922,7 @@ function Roles._prototype:remove_player(player,skip_check,skip_event)
end end
-- Emits event if required -- Emits event if required
if not skip_event then if not skip_event then
emit_player_roles_updated(player,'unassign',{self}) emit_player_roles_updated(player, 'unassign', {self})
end end
return rtn return rtn
end end
@@ -941,15 +941,15 @@ local players = role:get_players(true)
function Roles._prototype:get_players(online) function Roles._prototype:get_players(online)
local players = {} local players = {}
-- Gets all players that have this role -- Gets all players that have this role
for player_name,player_roles in pairs(Roles.config.players) do for player_name, player_roles in pairs(Roles.config.players) do
for _,role_name in pairs(player_roles) do for _, role_name in pairs(player_roles) do
if role_name == self.name then if role_name == self.name then
table.insert(players,player_name) table.insert(players, player_name)
end end
end end
end end
-- Convert the player names to LuaPlayer -- Convert the player names to LuaPlayer
for index,player_name in pairs(players) do for index, player_name in pairs(players) do
players[index] = Game.get_player_from_any(player_name) players[index] = Game.get_player_from_any(player_name)
end end
-- Filter by online if param is defined -- Filter by online if param is defined
@@ -957,9 +957,9 @@ function Roles._prototype:get_players(online)
return players return players
else else
local filtered = {} local filtered = {}
for _,player in pairs(players) do for _, player in pairs(players) do
if player.connected == online then if player.connected == online then
table.insert(filtered,player) table.insert(filtered, player)
end end
end end
return filtered return filtered
@@ -976,7 +976,7 @@ role:print('Hello, World!')
]] ]]
function Roles._prototype:print(message) function Roles._prototype:print(message)
local players = self:get_players(true) local players = self:get_players(true)
for _,player in pairs(players) do for _, player in pairs(players) do
player.print(message) player.print(message)
end end
return #players return #players
@@ -987,7 +987,7 @@ local function role_update(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
-- Updates flags given to the player -- Updates flags given to the player
for flag, async_token in pairs(Roles.config.flags) do 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) Async(async_token, player, state)
end end
-- Updates the players permission group -- Updates the players permission group
@@ -1005,22 +1005,22 @@ local function role_update(event)
end end
--- When a player joined or has a role change then the update is triggered --- 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_assigned, role_update)
Event.add(Roles.events.on_role_unassigned,role_update) Event.add(Roles.events.on_role_unassigned, role_update)
Event.add(defines.events.on_player_joined_game,role_update) Event.add(defines.events.on_player_joined_game, role_update)
-- Every 60 seconds the auto promote check is preformed -- Every 60 seconds the auto promote check is preformed
Event.on_nth_tick(3600,function() Event.on_nth_tick(3600, function()
local promotes = {} local promotes = {}
for _,player in pairs(game.connected_players) do for _, player in pairs(game.connected_players) do
for _,role in pairs(Roles.config.roles) do for _, role in pairs(Roles.config.roles) do
if role.auto_promote_condition then 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 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 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 if promotes[player.name] then
table.insert(promotes[player.name],role.name) table.insert(promotes[player.name], role.name)
else else
promotes[player.name] = {role.name} promotes[player.name] = {role.name}
end end
@@ -1029,8 +1029,8 @@ Event.on_nth_tick(3600,function()
end end
end end
end end
for player_name,roles in pairs(promotes) do for player_name, roles in pairs(promotes) do
Roles.assign_player(player_name,roles) Roles.assign_player(player_name, roles)
end end
end) end)

View File

@@ -9,13 +9,13 @@ local Store = require 'expcore.store' --- @dep expcore.store
local scenario_diffculty = Store.register() local scenario_diffculty = Store.register()
-- When the store is changed this function will trigger -- When the store is changed this function will trigger
Store.watch(scenario_diffculty,function(value) Store.watch(scenario_diffculty, function(value)
game.print('The scenario diffculty has been set to '..value) game.print('The scenario diffculty has been set to '..value)
end) end)
Store.set(scenario_diffculty,'hard') -- Set the value stored to 'hard' Store.set(scenario_diffculty, 'hard') -- Set the value stored to 'hard'
Store.get(scenario_diffculty) -- Returns 'hard' Store.get(scenario_diffculty) -- Returns 'hard'
Store.update(scenario_diffculty,function(value) -- Will set value to 'normal' if no value is present Store.update(scenario_diffculty, function(value) -- Will set value to 'normal' if no value is present
return not value and 'normal' return not value and 'normal'
end) end)
@@ -27,13 +27,13 @@ local player_scores = Store.register(function(player) -- Use player name as the
end) end)
-- When any key in the store is changed this function will trigger -- When any key in the store is changed this function will trigger
Store.watch(player_scores,function(value,key,old_value) Store.watch(player_scores, function(value, key, old_value)
game.print(key..' now has a score of '..value) game.print(key..' now has a score of '..value)
end) end)
Store.set(player_scores,game.player,10) -- Set your score to 10 Store.set(player_scores, game.player, 10) -- Set your score to 10
Store.get(scenario_diffculty,game.player) -- Returns 10 Store.get(scenario_diffculty, game.player) -- Returns 10
Store.update(scenario_diffculty,game.player,function(value) -- Add 1 to your score Store.update(scenario_diffculty, game.player, function(value) -- Add 1 to your score
return value + 1 return value + 1
end) end)
@@ -79,33 +79,33 @@ local player_scores = Store.register(function(player)
end) end)
-- player_scores is a valid store and key will be your player name -- player_scores is a valid store and key will be your player name
local key = Store.validate(player_scores,game.player) local key = Store.validate(player_scores, game.player)
]] ]]
function Store.validate(store,key,error_stack) function Store.validate(store, key, error_stack)
error_stack = error_stack or 1 error_stack = error_stack or 1
if type(store) ~= 'number' then if type(store) ~= 'number' then
-- Store is not a number and so if not valid -- 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) error('Store uid given is not a number; recived type '..type(store), error_stack+1)
elseif store > Store.uid then elseif store > Store.uid then
-- Store is a number but it is out of range, ie larger than the current highest uid -- 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) 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 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 -- 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) error('Store key is not a string and no serializer has been registered; recived '..type(key), error_stack+1)
elseif key ~= nil then elseif key ~= nil then
-- Key is present and so it is serialized and returned -- Key is present and so it is serialized and returned
local serializer = Store.serializers[store] local serializer = Store.serializers[store]
if type(key) ~= 'string' then if type(key) ~= 'string' then
local success, serialized_key = pcall(serializer,key) local success, serialized_key = pcall(serializer, key)
if not success then if not success then
-- Serializer casued an error while serializing the key -- Serializer casued an error while serializing the key
error('Store watcher casued an error:\n\t'..key,error_stack+1) error('Store watcher casued an error:\n\t'..key, error_stack+1)
elseif type(serialized_key) ~= 'string' then elseif type(serialized_key) ~= 'string' then
-- Serializer was successful but failed to return a string value -- 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) error('Store key serializer did not return a string; recived type '..type(key), error_stack+1)
end end
return serialized_key return serialized_key
@@ -161,12 +161,12 @@ end
local scenario_diffculty = Store.register() local scenario_diffculty = Store.register()
-- Register the watcher so that when we change the value the message is printed -- Register the watcher so that when we change the value the message is printed
Store.watch(scenario_diffculty,function(value) Store.watch(scenario_diffculty, function(value)
game.print('The scenario diffculty has been set to '..value) game.print('The scenario diffculty has been set to '..value)
end) end)
-- Set a new value for the diffculty and see that it has printed to the game -- Set a new value for the diffculty and see that it has printed to the game
Store.set(scenario_diffculty,'hard') Store.set(scenario_diffculty, 'hard')
@usage-- Printing the changed value to all players, with keys @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 -- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects
@@ -175,21 +175,21 @@ local player_scores = Store.register(function(player)
end) end)
-- Register the watcher so that when we change the value the message is printed -- Register the watcher so that when we change the value the message is printed
Store.watch(player_scores,function(value,key,old_value) Store.watch(player_scores, function(value, key, old_value)
game.print(key..' now has a score of '..value) game.print(key..' now has a score of '..value)
end) end)
-- Set a new value for your score and see that it has printed to the game -- Set a new value for your score and see that it has printed to the game
Store.set(player_scores,game.player,10) Store.set(player_scores, game.player, 10)
]] ]]
function Store.watch(store,watcher) function Store.watch(store, watcher)
if _LIFECYCLE ~= _STAGE.control then if _LIFECYCLE ~= _STAGE.control then
-- Only allow this function to be called during the control stage -- Only allow this function to be called during the control stage
error('Store watcher can not be registered durring runtime', 2) error('Store watcher can not be registered durring runtime', 2)
end end
Store.validate(store,nil,2) Store.validate(store, nil, 2)
-- Add the watchers table if it does not exist -- Add the watchers table if it does not exist
local watchers = Store.watchers[store] local watchers = Store.watchers[store]
@@ -224,14 +224,14 @@ local player_scores = Store.register(function(player)
end) end)
-- Get your current score -- Get your current score
local my_score = Store.get(player_scores,game.player) local my_score = Store.get(player_scores, game.player)
-- Get all scores -- Get all scores
lcoal scores = Store.get(player_scores) lcoal scores = Store.get(player_scores)
]] ]]
function Store.get(store,key) function Store.get(store, key)
key = Store.validate(store,key,2) key = Store.validate(store, key, 2)
-- Get the data from the data store -- Get the data from the data store
local data = data_store[store] local data = data_store[store]
@@ -266,14 +266,14 @@ local player_scores = Store.register(function(player)
end) end)
-- Clear your score -- Clear your score
Store.clear(player_scores,game.player) Store.clear(player_scores, game.player)
-- Clear all scores -- Clear all scores
Store.clear(player_scores) Store.clear(player_scores)
]] ]]
function Store.clear(store,key) function Store.clear(store, key)
key = Store.validate(store,key,2) key = Store.validate(store, key, 2)
local old_value local old_value
-- Check if there is a key being used -- Check if there is a key being used
@@ -288,7 +288,7 @@ function Store.clear(store,key)
end end
-- Trigger any watch functions -- Trigger any watch functions
Store.raw_trigger(store,key,nil,old_value) Store.raw_trigger(store, key, nil, old_value)
end end
--[[-- Used to set the data in a store, will trigger any watchers, key is optional depending on if you are using them --[[-- Used to set the data in a store, will trigger any watchers, key is optional depending on if you are using them
@@ -301,7 +301,7 @@ end
local scenario_diffculty = Store.register() local scenario_diffculty = Store.register()
-- Set the new scenario diffculty -- Set the new scenario diffculty
Store.set(scenario_diffculty,'hard') Store.set(scenario_diffculty, 'hard')
@usage-- Set data in a store with keys @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 -- Register the new store, we are not using player names as the keys so it would be useful to accept LuaPlayer objects
@@ -310,16 +310,16 @@ local player_scores = Store.register(function(player)
end) end)
-- Set your current score -- Set your current score
Store.set(player_scores,game.player,10) Store.set(player_scores, game.player, 10)
-- Set all scores, note this might not have much use -- Set all scores, note this might not have much use
Store.set(player_scores,{ Store.set(player_scores, {
[game.player.name] = 10, [game.player.name] = 10,
['SomeOtherPlayer'] = 0 ['SomeOtherPlayer'] = 0
}) })
]] ]]
function Store.set(store,key,value) function Store.set(store, key, value)
-- Allow for key to be optional -- Allow for key to be optional
if value == nil then if value == nil then
value = key value = key
@@ -327,7 +327,7 @@ function Store.set(store,key,value)
end end
-- Check the store is valid -- Check the store is valid
key = Store.validate(store,key,2) key = Store.validate(store, key, 2)
local old_value local old_value
-- If there is a key being used then the store must be a able -- If there is a key being used then the store must be a able
@@ -343,7 +343,7 @@ function Store.set(store,key,value)
end end
-- Trigger any watchers -- Trigger any watchers
Store.raw_trigger(store,key,value,old_value) Store.raw_trigger(store, key, value, old_value)
end 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 --[[-- 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
@@ -356,10 +356,10 @@ end
local game_score = Store.register() local game_score = Store.register()
-- Setting a default value -- Setting a default value
Store.set(game_score,0) 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 -- 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) Store.update(game_score, function(value)
return value + 1 return value + 1
end) end)
@@ -370,7 +370,7 @@ local player_data = Store.register(function(player)
end) end)
-- Setting a default value for your player, used to show the table structure -- Setting a default value for your player, used to show the table structure
Store.set(player_data,game.player,{ Store.set(player_data, game.player, {
group = 'Admin', group = 'Admin',
role = 'Owner', role = 'Owner',
show_group_config = false show_group_config = false
@@ -378,12 +378,12 @@ Store.set(player_data,game.player,{
-- Updating the show_group_config key in your player data, note that it would be harder to call set every time -- 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 -- 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) Store.update(player_data, game.player, function(data)
data.show_group_config = not data.show_group_config data.show_group_config = not data.show_group_config
end) end)
]] ]]
function Store.update(store,key,updater) function Store.update(store, key, updater)
-- Allow for key to be nil -- Allow for key to be nil
if updater == nil then if updater == nil then
updater = key updater = key
@@ -391,7 +391,7 @@ function Store.update(store,key,updater)
end end
-- Check the store is valid -- Check the store is valid
key = Store.validate(store,key,2) key = Store.validate(store, key, 2)
local value, old_value local value, old_value
-- If a key is used then the store must be a table -- If a key is used then the store must be a table
@@ -420,7 +420,7 @@ function Store.update(store,key,updater)
end end
-- Trigger any watchers -- Trigger any watchers
Store.raw_trigger(store,key,value,old_value) Store.raw_trigger(store, key, value, old_value)
end 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 --[[-- 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
@@ -434,7 +434,7 @@ local player_data = Store.register(function(player)
end) end)
-- Setting a default value for your player, used to show the table structure -- Setting a default value for your player, used to show the table structure
Store.set(player_data,game.player,{ Store.set(player_data, game.player, {
group = 'Admin', group = 'Admin',
role = 'Owner', role = 'Owner',
show_group_config = false show_group_config = false
@@ -443,13 +443,13 @@ Store.set(player_data,game.player,{
-- Updating the show_group_config key for all players, note that it would be harder to call set every time -- 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 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 -- We also have access to the current key being updated if needed
Store.map(player_data,function(data,key) Store.map(player_data, function(data, key)
data.show_group_config = not data.show_group_config data.show_group_config = not data.show_group_config
end) end)
]] ]]
function Store.map(store,updater) function Store.map(store, updater)
Store.validate(store,nil,2) Store.validate(store, nil, 2)
-- Get all that data in the store and check its a table -- Get all that data in the store and check its a table
local data = data_store[store] local data = data_store[store]
@@ -458,12 +458,12 @@ function Store.map(store,updater)
end end
-- Loop over all the keys and call the updater, setting value if returned, and calling watcher functions -- Loop over all the keys and call the updater, setting value if returned, and calling watcher functions
for key,value in pairs(data) do for key, value in pairs(data) do
local rtn = updater(value,key) local rtn = updater(value, key)
if rtn then if rtn then
data[key] = rtn data[key] = rtn
end end
Store.raw_trigger(store,key,data[key],value) Store.raw_trigger(store, key, data[key], value)
end end
end end
@@ -478,16 +478,16 @@ local scenario_diffculty = Store.register()
Store.trigger(scenario_diffculty) Store.trigger(scenario_diffculty)
]] ]]
function Store.trigger(store,key) function Store.trigger(store, key)
key = Store.validate(store,key,2) key = Store.validate(store, key, 2)
-- Get the data from the data store -- Get the data from the data store
local data = data_store[store] local data = data_store[store]
if key then if key then
data = data[key] data = data[key]
Store.raw_trigger(store,key,data,data) Store.raw_trigger(store, key, data, data)
else else
Store.raw_trigger(store,key,data,data) Store.raw_trigger(store, key, data, data)
end end
end end
@@ -503,16 +503,16 @@ local scenario_diffculty = Store.register()
-- Trigger the watchers with a fake change of diffculty -- Trigger the watchers with a fake change of diffculty
-- This is mostly used internally but it can be useful in other cases -- This is mostly used internally but it can be useful in other cases
Store.raw_trigger(scenario_diffculty,nil,'normal','normal') Store.raw_trigger(scenario_diffculty, nil, 'normal', 'normal')
]] ]]
function Store.raw_trigger(store,key,value,old_value) function Store.raw_trigger(store, key, value, old_value)
key = Store.validate(store,key,2) key = Store.validate(store, key, 2)
-- Get the watchers and then loop over them -- Get the watchers and then loop over them
local watchers = Store.watchers[store] or {} local watchers = Store.watchers[store] or {}
for _,watcher in pairs(watchers) do for _, watcher in pairs(watchers) do
local success, err = pcall(watcher,value,key,old_value) local success, err = pcall(watcher, value, key, old_value)
if not success then if not success then
error('Store watcher casued an error:\n\t'..err) error('Store watcher casued an error:\n\t'..err)
end end

View File

@@ -17,31 +17,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}}) player.force.chart(player.surface, {{p.x-r, p.y-r}, {p.x+r, p.y+r}})
end end
-- spawn items -- spawn items
for item,callback in pairs(items) do for item, callback in pairs(items) do
if type(callback) == 'function' then if type(callback) == 'function' then
local stats = player.force.item_production_statistics local stats = player.force.item_production_statistics
local made = stats.get_input_count(item) 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) count = math.floor(count)
if success and count > 0 then if success and count > 0 then
player.insert{name=item,count=count} player.insert{name=item, count=count}
end end
end end
end end
end) end)
Event.on_init(function() Event.on_init(function()
remote.call('freeplay','set_created_items',{}) remote.call('freeplay', 'set_created_items', {})
remote.call('freeplay','set_chart_distance',0) remote.call('freeplay', 'set_chart_distance', 0)
remote.call('freeplay','set_skip_intro',config.skip_intro) remote.call('freeplay', 'set_skip_intro', config.skip_intro)
if config.research_queue_from_start then 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 force.research_queue_enabled = true
end end
end end
if not config.disable_base_game_silo_script then if not config.disable_base_game_silo_script then
if config.skip_victory 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 end
end) end)

View File

@@ -8,7 +8,7 @@ local config = require 'config.popup_messages' --- @dep config.popup_messages
local send_text = Game.print_player_floating_text -- (player_index, text, color) 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 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.get_player_by_index(event.player_index)
@@ -18,7 +18,7 @@ Event.add(defines.events.on_console_chat,function(event)
-- Sends the message as text above them -- Sends the message as text above them
if config.show_player_messages then 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 end
if not config.show_player_mentions then return 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+", "") local search_string = event.message:lower():gsub("%s+", "")
-- Loops over online players to see if they name is included -- 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 mentioned_player.index ~= player.index then
if search_string:match(mentioned_player.name:lower(), 1, true) 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) send_text(mentioned_player.index, {'chat-popup.ping', player.name}, player.chat_color)
end end
end end
end end

View File

@@ -6,17 +6,17 @@ local Game = require 'utils.game' --- @dep utils.game
local Roles = require 'expcore.roles' --- @dep expcore.roles local Roles = require 'expcore.roles' --- @dep expcore.roles
local config = require 'config.chat_reply' --- @dep config.chat_reply 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 local player_index = event.player_index
if not player_index or player_index < 1 then return end if not player_index or player_index < 1 then return end
local player = Game.get_player_by_index(player_index) local player = Game.get_player_by_index(player_index)
local message = event.message:lower():gsub("%s+", "") local message = event.message:lower():gsub("%s+", "")
local allowed = true local allowed = true
if config.command_admin_only and not player.admin then allowed = false end 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 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 if message:find(key_word) then
if type(reply) == 'function' then if type(reply) == 'function' then
reply = reply(player) reply = reply(player)
@@ -24,29 +24,29 @@ Event.add(defines.events.on_console_chat,function(event)
if message:find(prefix..key_word) then if message:find(prefix..key_word) then
if allowed then if allowed then
game.print{'chat-bot.reply',reply} game.print{'chat-bot.reply', reply}
else else
player.print{'chat-bot.disallow'} player.print{'chat-bot.disallow'}
end end
elseif not allowed then elseif not allowed then
player.print{'chat-bot.reply',reply} player.print{'chat-bot.reply', reply}
end end
end end
end end
if not allowed then return 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 message:find(prefix..key_word) then
if type(reply) == 'function' then if type(reply) == 'function' then
reply = reply(player) reply = reply(player)
if reply then if reply then
game.print{'chat-bot.reply',reply} game.print{'chat-bot.reply', reply}
end end
else else
game.print{'chat-bot.reply',reply} game.print{'chat-bot.reply', reply}
end end
end end

View File

@@ -18,7 +18,7 @@ local Public = {
Global.register({ Global.register({
compilatrons = Public.compilatrons, compilatrons = Public.compilatrons,
current_messages = Public.current_messages current_messages = Public.current_messages
},function(tbl) }, function(tbl)
Public.compilatrons = tbl.compilatrons Public.compilatrons = tbl.compilatrons
Public.current_messages = tbl.current_messages Public.current_messages = tbl.current_messages
end) end)
@@ -42,7 +42,7 @@ local callback =
local function circle_messages() local function circle_messages()
for name, ent in pairs(Public.compilatrons) do for name, ent in pairs(Public.compilatrons) do
if not ent.valid then if not ent.valid then
Public.spawn_compilatron(game.players[1].surface,name) Public.spawn_compilatron(game.players[1].surface, name)
end end
local current_message = Public.current_messages[name] local current_message = Public.current_messages[name]
local msg_number local msg_number
@@ -66,7 +66,7 @@ Event.on_nth_tick(config.message_cycle, circle_messages)
--- This will add a compilatron to the global and start his message cycle --- This will add a compilatron to the global and start his message cycle
-- @tparam LuaEntity entity the compilatron entity that moves around -- @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) function Public.add_compilatron(entity, name)
if not entity and not entity.valid then if not entity and not entity.valid then
return return
@@ -85,19 +85,19 @@ end
--- This spawns a new compilatron on a surface with the given location tag (not a position) --- 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 LuaSurface surface the surface to spawn the compilatron on
-- @tparam string location the location tag that is in the config file -- @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 position = locations[location]
local pos = surface.find_non_colliding_position('compilatron', position, 1.5, 0.5) 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} local compi = surface.create_entity {name='compilatron', position=pos, force=game.forces.neutral}
Public.add_compilatron(compi,location) Public.add_compilatron(compi, location)
end end
-- When the first player is created this will create all compilatrons that are resisted in the config -- 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 if event.player_index ~= 1 then return end
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
for location,pos in pairs(locations) do for location in pairs(locations) do
Public.spawn_compilatron(player.surface,location) Public.spawn_compilatron(player.surface, location)
end end
end) end)

View File

@@ -12,21 +12,21 @@ Event.add(defines.events.on_entity_damaged, function(event)
local damage = math.floor(event.original_damage_amount) local damage = math.floor(event.original_damage_amount)
local health = math.floor(entity.health) local health = math.floor(entity.health)
local health_percentage = entity.get_health_ratio() 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 -- Gets the location of the text
local size = entity.get_radius() local size = entity.get_radius()
if size < 1 then size = 1 end if size < 1 then size = 1 end
local r = (math.random()-0.5)*size*config.damage_location_variance local r = (math.random()-0.5)*size*config.damage_location_variance
local p = entity.position 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 -- Sets the message
local message local message
if entity.name == 'character' and config.show_player_health then 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 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 end
-- Outputs the message as floating text -- Outputs the message as floating text

View File

@@ -5,13 +5,13 @@ local Event = require 'utils.event' --- @dep utils.event
local Game = require 'utils.game' --- @dep utils.game local Game = require 'utils.game' --- @dep utils.game
local Global = require 'utils.global' --- @dep utils.global local Global = require 'utils.global' --- @dep utils.global
local config = require 'config.death_logger' --- @dep config.death_logger 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 = { local deaths = {
archive={} -- deaths moved here after body is gone 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 deaths = tbl
end) end)
@@ -20,10 +20,10 @@ local function create_map_tag(death)
local player = Game.get_player_from_any(death.player_name) local player = Game.get_player_from_any(death.player_name)
local message = player.name..' died' local message = player.name..' died'
if config.include_time_of_death then 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 message = message..' at '..time
end end
death.tag = player.force.add_chart_tag(player.surface,{ death.tag = player.force.add_chart_tag(player.surface, {
position=death.position, position=death.position,
icon=config.map_icon, icon=config.map_icon,
text=message text=message
@@ -33,7 +33,7 @@ end
--- Checks that all map tags are present and valid --- Checks that all map tags are present and valid
-- adds missing ones, deletes expired ones -- adds missing ones, deletes expired ones
local function check_map_tags() 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 map_tag = death.tag
local corpse = death.corpse local corpse = death.corpse
-- Check the corpse is valid -- Check the corpse is valid
@@ -51,19 +51,19 @@ local function check_map_tags()
-- Move the death to the archive -- Move the death to the archive
death.corpse = nil death.corpse = nil
death.tag = nil death.tag = nil
table.insert(deaths.archive,death) table.insert(deaths.archive, death)
table.remove(deaths,index) table.remove(deaths, index)
end end
end end
end end
-- when a player dies a new death is added to the records and a map marker is made -- 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) Event.add(defines.events.on_player_died, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local corpse = player.surface.find_entity('character-corpse',player.position) local corpse = player.surface.find_entity('character-corpse', player.position)
if config.use_chests_as_bodies then if config.use_chests_as_bodies then
local items = corpse.get_inventory(defines.inventory.character_corpse).get_contents() 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 chest.destructible = false
corpse.destroy() corpse.destroy()
corpse = chest corpse = chest
@@ -77,22 +77,22 @@ Event.add(defines.events.on_player_died,function(event)
if config.show_map_markers then if config.show_map_markers then
create_map_tag(death) create_map_tag(death)
end end
table.insert(deaths,death) table.insert(deaths, death)
end) end)
-- every 5 min all bodies are checked for valid map tags -- every 5 min all bodies are checked for valid map tags
if config.show_map_markers then if config.show_map_markers then
local check_period = 60*60*5 -- five minutes 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() check_map_tags()
end) end)
end end
if config.auto_collect_bodies then 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 corpse = event.corpse
local items = corpse.get_inventory(defines.inventory.character_corpse).get_contents() 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)
end end

View File

@@ -4,7 +4,7 @@
local Event = require 'utils.event' --- @dep utils.event local Event = require 'utils.event' --- @dep utils.event
local Game = require 'utils.game' --- @dep utils.game local Game = require 'utils.game' --- @dep utils.game
local Colors = require 'utils.color_presets' --- @dep utils.color_presets 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 config = require 'config.discord_alerts' --- @dep config.discord_alerts
local function get_player_name(event) local function get_player_name(event)
@@ -16,8 +16,8 @@ local function to_hex(color)
local hex_digits = '0123456789ABCDEF' local hex_digits = '0123456789ABCDEF'
local function hex(bit) local function hex(bit)
local major, minor = math.modf(bit/16) local major, minor = math.modf(bit/16)
major,minor = major+1,minor*16+1 major, minor = major+1, minor*16+1
return hex_digits:sub(major,major)..hex_digits:sub(minor,minor) return hex_digits:sub(major, major)..hex_digits:sub(minor, minor)
end end
return '0x'..hex(color.r)..hex(color.g)..hex(color.b) return '0x'..hex(color.r)..hex(color.g)..hex(color.b)
@@ -33,24 +33,24 @@ local function emit_event(args)
end end
local tick = args.tick or 0 local tick = args.tick or 0
local tick_formated = format_time(tick,{hours = true,minutes = true,string = true,long = true}) local tick_formated = format_time(tick, {hours = true, minutes = true, string = true, long = true})
local players_online = 0 local players_online = 0
local admins_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 players_online = players_online+1
if player.admin then if player.admin then
admins_online = admins_online + 1 admins_online = admins_online + 1
end end
end end
local done = {title=true,color=true,description=true} local done = {title=true, color=true, description=true}
local fields = {{ local fields = {{
name='Server Details', 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 name: ${serverName} Players: %d Admins: %d Time: %s', players_online, admins_online, tick_formated)
}} }}
for key,value in pairs(args) do for key, value in pairs(args) do
if not done[key] then if not done[key] then
done[key] = true done[key] = true
local field = { local field = {
@@ -59,17 +59,17 @@ local function emit_event(args)
inline=false inline=false
} }
local new_value, inline = value:gsub('<inline>','',1) local new_value, inline = value:gsub('<inline>', '', 1)
if inline then if inline then
field.value = new_value field.value = new_value
field.inline = true field.inline = true
end end
table.insert(fields,field) table.insert(fields, field)
end end
end end
write_json('log/discord.log',{ write_json('log/discord.log', {
title=title, title=title,
description=description, description=description,
color=color, color=color,
@@ -80,8 +80,8 @@ end
--- Reports added and removed --- Reports added and removed
if config.player_reports then if config.player_reports then
local Reports = require 'modules.control.reports' --- @dep modules.control.reports local Reports = require 'modules.control.reports' --- @dep modules.control.reports
Event.add(Reports.events.on_player_reported,function(event) Event.add(Reports.events.on_player_reported, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Report', title='Report',
description='A player was reported', description='A player was reported',
@@ -91,7 +91,7 @@ if config.player_reports then
['Reason:']=event.reason ['Reason:']=event.reason
} }
end) end)
Event.add(Reports.events.on_report_removed,function(event) Event.add(Reports.events.on_report_removed, function(event)
local player_name = get_player_name(event) local player_name = get_player_name(event)
emit_event{ emit_event{
title='Report Removed', title='Report Removed',
@@ -106,8 +106,8 @@ end
--- Warnings added and removed --- Warnings added and removed
if config.player_warnings then if config.player_warnings then
local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings
Event.add(Warnings.events.on_warning_added,function(event) Event.add(Warnings.events.on_warning_added, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Warning', title='Warning',
description='A player has been given a warning', description='A player has been given a warning',
@@ -117,8 +117,8 @@ if config.player_warnings then
['Reason:']=event.reason ['Reason:']=event.reason
} }
end) end)
Event.add(Warnings.events.on_warning_removed,function(event) Event.add(Warnings.events.on_warning_removed, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Warning Removed', title='Warning Removed',
description='A player has a warning removed', description='A player has a warning removed',
@@ -132,8 +132,8 @@ end
--- When a player is jailed or unjailed --- When a player is jailed or unjailed
if config.player_jail then if config.player_jail then
local Jail = require 'modules.control.jail' local Jail = require 'modules.control.jail'
Event.add(Jail.events.on_player_jailed,function(event) Event.add(Jail.events.on_player_jailed, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Jail', title='Jail',
description='A player has been jailed', description='A player has been jailed',
@@ -143,8 +143,8 @@ if config.player_jail then
['Reason:']=event.reason ['Reason:']=event.reason
} }
end) end)
Event.add(Jail.events.on_player_unjailed,function(event) Event.add(Jail.events.on_player_unjailed, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Unjail', title='Unjail',
description='A player has been unjailed', description='A player has been unjailed',
@@ -158,8 +158,8 @@ end
--- When a player is tempbanned --- When a player is tempbanned
if config.player_temp_ban then if config.player_temp_ban then
local Jail = require 'modules.control.jail' local Jail = require 'modules.control.jail'
Event.add(Jail.events.on_player_temp_banned,function(event) Event.add(Jail.events.on_player_temp_banned, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Temp Ban', title='Temp Ban',
description='A player has been temp banned', description='A player has been temp banned',
@@ -169,8 +169,8 @@ if config.player_temp_ban then
['Reason:']=event.reason ['Reason:']=event.reason
} }
end) end)
Event.add(Jail.events.on_player_untemp_banned,function(event) Event.add(Jail.events.on_player_untemp_banned, function(event)
local player_name,by_player_name = get_player_name(event) local player_name, by_player_name = get_player_name(event)
emit_event{ emit_event{
title='Temp Ban Removed', title='Temp Ban Removed',
description='A player has been untemp banned', description='A player has been untemp banned',
@@ -183,7 +183,7 @@ end
--- Ban and unban --- Ban and unban
if config.player_bans then 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 if event.by_player then
local by_player = Game.get_player_by_index(event.by_player) local by_player = Game.get_player_by_index(event.by_player)
emit_event{ emit_event{
@@ -196,7 +196,7 @@ if config.player_bans then
} }
end end
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 if event.by_player then
local by_player = Game.get_player_by_index(event.by_player) local by_player = Game.get_player_by_index(event.by_player)
emit_event{ emit_event{
@@ -212,7 +212,7 @@ end
--- Mute and unmute --- Mute and unmute
if config.player_mutes then 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) local player_name = get_player_name(event)
emit_event{ emit_event{
title='Muted', title='Muted',
@@ -221,7 +221,7 @@ if config.player_mutes then
['Player:']='<inline>'..player_name ['Player:']='<inline>'..player_name
} }
end) 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) local player_name = get_player_name(event)
emit_event{ emit_event{
title='Un-Muted', title='Un-Muted',
@@ -234,7 +234,7 @@ end
--- Kick --- Kick
if config.player_kicks then 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 if event.by_player then
local player_name = get_player_name(event) local player_name = get_player_name(event)
local by_player = Game.get_player_by_index(event.by_player) local by_player = Game.get_player_by_index(event.by_player)
@@ -252,7 +252,7 @@ end
--- Promote and demote --- Promote and demote
if config.player_promotes then 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) local player_name = get_player_name(event)
emit_event{ emit_event{
title='Promote', title='Promote',
@@ -261,7 +261,7 @@ if config.player_promotes then
['Player:']='<inline>'..player_name ['Player:']='<inline>'..player_name
} }
end) 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) local player_name = get_player_name(event)
emit_event{ emit_event{
title='Demote', title='Demote',
@@ -273,12 +273,12 @@ if config.player_promotes then
end end
--- Other commands --- 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 if event.player_index then
local player_name = get_player_name(event) local player_name = get_player_name(event)
if config[event.command] then if config[event.command] then
emit_event{ emit_event{
title=event.command:gsub('^%l',string.upper), title=event.command:gsub('^%l', string.upper),
description='/'..event.command..' was used', description='/'..event.command..' was used',
color=Colors.grey, color=Colors.grey,
['By:']='<inline>'..player_name, ['By:']='<inline>'..player_name,

View File

@@ -7,7 +7,7 @@ local config = require 'config.join_messages' --- @dep config.join_messages
local Global = require 'utils.global' --- @dep utils.global local Global = require 'utils.global' --- @dep utils.global
require 'overrides.table' require 'overrides.table'
Global.register(config,function(tbl) Global.register(config, function(tbl)
config = tbl config = tbl
end) end)
@@ -16,9 +16,9 @@ function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local custom_message = config[player.name] local custom_message = config[player.name]
if custom_message then if custom_message then
game.print(custom_message,player.color) game.print(custom_message, player.color)
else else
player.print{'greetings.greet',{'links.discord'}} player.print{'greetings.greet', {'links.discord'}}
end end
end end

View File

@@ -5,7 +5,7 @@ local Event = require 'utils.event' --- @dep utils.event
local config = require 'config.pollution_grading' --- @dep config.pollution_grading local config = require 'config.pollution_grading' --- @dep config.pollution_grading
local delay = config.update_delay * 3600 -- convert from minutes to ticks 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 surface = game.surfaces[1]
local true_max = surface.get_pollution(config.reference_point) local true_max = surface.get_pollution(config.reference_point)
local max = true_max*config.max_scalar local max = true_max*config.max_scalar

View File

@@ -8,22 +8,22 @@ local config = require 'config.preset_player_colours' --- @dep config.preset_pla
local Global = require 'utils.global' --- @dep utils.global local Global = require 'utils.global' --- @dep utils.global
require 'overrides.table' require 'overrides.table'
Global.register(config,function(tbl) Global.register(config, function(tbl)
config = tbl config = tbl
end) end)
Event.add(defines.events.on_player_created,function(event) Event.add(defines.events.on_player_created, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local color = 'white' local color = 'white'
if config.players[player.name] then if config.players[player.name] then
color = config.players[player.name] color = config.players[player.name]
else else
while config.disallow[color] do while config.disallow[color] do
color = table.get_random_dictionary_entry(Colours,true) color = table.get_random_dictionary_entry(Colours, true)
end end
color = Colours[color] color = Colours[color]
end end
color = {r=color.r/255,g=color.g/255,b=color.b/255,a=0.5} color = {r=color.r/255, g=color.g/255, b=color.b/255, a=0.5}
player.color = color player.color = color
player.chat_color = color player.chat_color = color
end) end)

View File

@@ -9,7 +9,7 @@ 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 -- Loops over the config and finds the wile which has the highest value for strength
local max_strength = 0 local max_strength = 0
for _,strength in pairs(config.strengths) do for _, strength in pairs(config.strengths) do
if strength > max_strength then if strength > max_strength then
max_strength = strength max_strength = strength
end end
@@ -22,12 +22,12 @@ Global.register(debug_players, function(tbl)
end) end)
-- Will degrade a tile down to the next tile when called -- 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 = surface.get_tile(position)
local tile_name = tile.name local tile_name = tile.name
local degrade_tile_name = config.degrade_order[tile_name] local degrade_tile_name = config.degrade_order[tile_name]
if not degrade_tile_name then return end 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 end
-- Same as degrade but will degrade all tiles that are under an entity -- Same as degrade but will degrade all tiles that are under an entity
@@ -42,12 +42,12 @@ local function degrade_entity(entity)
for x = lt.x, rb.x do -- x loop for x = lt.x, rb.x do -- x loop
local px = position.x+x local px = position.x+x
for y = lt.y, rb.y do -- y loop 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 = surface.get_tile(p)
local tile_name = tile.name local tile_name = tile.name
local degrade_tile_name = config.degrade_order[tile_name] local degrade_tile_name = config.degrade_order[tile_name]
if not degrade_tile_name then return end 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
end end
surface.set_tiles(tiles) surface.set_tiles(tiles)
@@ -62,15 +62,15 @@ local function get_probability(strength)
end end
-- Gets the mean of the strengths around a tile to give the strength at that position -- 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 = surface.get_tile(position)
local tile_name = tile.name local tile_name = tile.name
local strength = config.strengths[tile_name] local strength = config.strengths[tile_name]
if not strength then return end 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 local px = position.x + x
for y = -1,1 do -- y loop for y = -1, 1 do -- y loop
local check_tile = surface.get_tile{x=px,y=position.y+y} local check_tile = surface.get_tile{x=px, y=position.y+y}
local check_tile_name = check_tile.name local check_tile_name = check_tile.name
local check_strength = config.strengths[check_tile_name] or 0 local check_strength = config.strengths[check_tile_name] or 0
strength = strength + check_strength strength = strength + check_strength
@@ -80,12 +80,12 @@ local function get_tile_strength(surface,position)
end end
-- Same as get_tile_strength but returns to a in game text rather than as a value -- 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) local function debug_get_tile_strength(surface, position)
for x = -3,3 do -- x loop for x = -3, 3 do -- x loop
local px = position.x+x local px = position.x+x
for y = -3,3 do -- y loop for y = -3, 3 do -- y loop
local p = {x=px,y=position.y+y} local p = {x=px, y=position.y+y}
local strength = get_tile_strength(surface,p) or 0 local strength = get_tile_strength(surface, p) or 0
local tile = surface.get_tile(p) local tile = surface.get_tile(p)
print_grid_value(get_probability(strength)*config.weakness_value, surface, tile.position) print_grid_value(get_probability(strength)*config.weakness_value, surface, tile.position)
end end
@@ -97,13 +97,13 @@ Event.add(defines.events.on_player_changed_position, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local surface = player.surface local surface = player.surface
local position = player.position 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 not strength then return end
if get_probability(strength) > math.random() then if get_probability(strength) > math.random() then
degrade(surface,position) degrade(surface, position)
end end
if debug_players[player.name] then if debug_players[player.name] then
debug_get_tile_strength(surface,position) debug_get_tile_strength(surface, position)
end end
end) end)
@@ -112,7 +112,7 @@ Event.add(defines.events.on_built_entity, function(event)
local entity = event.created_entity local entity = event.created_entity
local surface = entity.surface local surface = entity.surface
local position = entity.position 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 not strength then return end
if get_probability(strength)*config.weakness_value > math.random() then if get_probability(strength)*config.weakness_value > math.random() then
degrade_entity(entity) degrade_entity(entity)
@@ -124,7 +124,7 @@ Event.add(defines.events.on_robot_built_entity, function(event)
local entity = event.created_entity local entity = event.created_entity
local surface = entity.surface local surface = entity.surface
local position = entity.position 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 not strength then return end
if get_probability(strength)*config.weakness_value > math.random() then if get_probability(strength)*config.weakness_value > math.random() then
degrade_entity(entity) degrade_entity(entity)
@@ -132,7 +132,7 @@ Event.add(defines.events.on_robot_built_entity, function(event)
end) end)
-- Used as a way to access the global table -- Used as a way to access the global table
return function(player_name,state) return function(player_name, state)
local player = Game.get_player_from_any(player_name) local player = Game.get_player_from_any(player_name)
clear_flying_text(player.surface) clear_flying_text(player.surface)
debug_players[player_name] = state debug_players[player_name] = state

View File

@@ -10,7 +10,7 @@ local entities = config.entities
local belts = config.afk_belts.locations local belts = config.afk_belts.locations
local turrets = config.infinite_ammo_turrets.locations local turrets = config.infinite_ammo_turrets.locations
Global.register(turrets,function(tbl) Global.register(turrets, function(tbl)
turrets = tbl turrets = tbl
end) end)
@@ -19,13 +19,13 @@ local function get_spawn_force()
local force = game.forces['Spawn'] local force = game.forces['Spawn']
if force and force.valid then return force end if force and force.valid then return force end
force = game.create_force('Spawn') force = game.create_force('Spawn')
force.set_cease_fire('player',true) force.set_cease_fire('player', true)
game.forces['player'].set_cease_fire('Spawn',true) game.forces['player'].set_cease_fire('Spawn', true)
return force return force
end end
-- protects and entity so players cant do anything to it -- 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 if entity and entity.valid then
entity.destructible = false entity.destructible = false
entity.minable = false entity.minable = false
@@ -39,40 +39,40 @@ end
-- handles the infinite ammo turrets -- handles the infinite ammo turrets
local function spawn_turrets() local function spawn_turrets()
if config.infinite_ammo_turrets.enabled then 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 surface = game.surfaces[turret_pos.surface]
local pos = turret_pos.position 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 -- Makes a new turret if it is not found
if not turret or not turret.valid then if not turret or not turret.valid then
turret = surface.create_entity{name='gun-turret',position=pos,force='Spawn'} turret = surface.create_entity{name='gun-turret', position=pos, force='Spawn'}
protect_entity(turret,true) protect_entity(turret, true)
end end
-- adds ammo to the turret -- adds ammo to the turret
local inv = turret.get_inventory(defines.inventory.turret_ammo) local inv = turret.get_inventory(defines.inventory.turret_ammo)
if inv.can_insert{name=config.infinite_ammo_turrets.ammo_type,count=10} then 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} inv.insert{name=config.infinite_ammo_turrets.ammo_type, count=10}
end end
end end
end end
end end
-- makes a 2x2 afk belt where set in config -- makes a 2x2 afk belt where set in config
local function spawn_belts(surface,position) 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 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 for _, belt_set in pairs(belts) do
local o = position local o = position
local p = belt_set local p = belt_set
for _,belt in pairs(belt_details) do for _, belt in pairs(belt_details) do
local pos = {x=o.x+p.x+belt[1],y=o.y+p.y+belt[2]} 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]} local belt_entity = surface.create_entity{name='transport-belt', position=pos, force='neutral', direction=belt[3]}
protect_entity(belt_entity) protect_entity(belt_entity)
end end
end end
end end
-- generates an area with no water and removes entities in the decon area -- 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 dr = config.corrections.deconstruction_radius
local dr2 = dr^2 local dr2 = dr^2
local dtile = config.corrections.deconstruction_tile local dtile = config.corrections.deconstruction_tile
@@ -86,17 +86,17 @@ local function spawn_base(surface,position)
for y = -pr, pr do -- loop over y for y = -pr, pr do -- loop over y
local y2 = y^2 local y2 = y^2
local prod = x2+y2 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 prod < dr2 then
-- if it is inside the decon radius -- if it is inside the decon radius
table.insert(tiles_to_make,{name=dtile,position=p}) 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}}} 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 for _, entity in pairs(entities_to_remove) do
if entity.name ~= 'character' then entity.destroy() end if entity.name ~= 'character' then entity.destroy() end
end end
elseif prod < pr2 then elseif prod < pr2 then
-- if it is inside the pattern radius -- 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 end
end end
@@ -104,30 +104,30 @@ local function spawn_base(surface,position)
end end
-- generates the pattern that is in the config -- 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 tiles_to_make = {}
local ptile = config.corrections.pattern_tile local ptile = config.corrections.pattern_tile
local o = config.corrections.offset local o = config.corrections.offset
local p = {x=position.x+o.x,y=position.y+o.y} local p = {x=position.x+o.x, y=position.y+o.y}
for _,tile in pairs(tiles) do for _, tile in pairs(tiles) do
table.insert(tiles_to_make,{name=ptile,position={tile[1]+p.x,tile[2]+p.y}}) table.insert(tiles_to_make, {name=ptile, position={tile[1]+p.x, tile[2]+p.y}})
end end
surface.set_tiles(tiles_to_make) surface.set_tiles(tiles_to_make)
end end
-- generates the entities that are in the config -- 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 o = config.corrections.offset
local p = {x=position.x+o.x,y=position.y+o.y} local p = {x=position.x+o.x, y=position.y+o.y}
for _,entity in pairs(entities) do for _, entity in pairs(entities) do
entity = surface.create_entity{name=entity[1],position={entity[2]+p.x,entity[3]+p.y},force='neutral'} entity = surface.create_entity{name=entity[1], position={entity[2]+p.x, entity[3]+p.y}, force='neutral'}
protect_entity(entity) protect_entity(entity)
entity.operable = true entity.operable = true
end end
end end
local refill_time = 60*60*5 -- 5 minutes 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 if game.tick < 10 then return end
spawn_turrets() spawn_turrets()
end) end)
@@ -135,15 +135,15 @@ end)
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 if event.player_index ~= 1 then return end
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local p = {x=0,y=0} local p = {x=0, y=0}
local s = player.surface local s = player.surface
spawn_base(s,p) spawn_base(s, p)
spawn_pattern(s,p) spawn_pattern(s, p)
get_spawn_force() get_spawn_force()
spawn_entities(s,p) spawn_entities(s, p)
spawn_belts(s,p) spawn_belts(s, p)
spawn_turrets() spawn_turrets()
player.teleport(p,s) player.teleport(p, s)
end) end)
-- Way to access global table -- Way to access global table

View File

@@ -1,54 +1,7 @@
---LuaPlayerBuiltEntityEventFilters ---LuaPlayerBuiltEntityEventFilters
---Events.set_event_filter(defines.events.on_built_entity, {{filter = "name", name = "fast-inserter"}}) ---Events.set_event_filter(defines.events.on_built_entity, {{filter = "name", name = "fast-inserter"}})
local Event = require 'utils.event' --- @dep utils.event 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
-- 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 closest_distance
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
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_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 ))
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. --Credit to Cooldude2606 for using his lua magic to make this function.
local directions = { local directions = {
['W'] = -0.875, ['W'] = -0.875,
@@ -60,12 +13,58 @@ local directions = {
['S'] = 0.625, ['S'] = 0.625,
['SW'] = 0.875 ['SW'] = 0.875
} }
function Angle( enetety )
local angle = math.atan2(enetety.position.y,enetety.position.x)/math.pi local function Angle(entity)
for direction, requiredAngle in pairs(directions) do local angle = math.atan2(entity.position.y, entity.position.x)/math.pi
if angle < requiredAngle then for direction, requiredAngle in pairs(directions) do
return direction if angle < requiredAngle then
end return direction
end end
end
end end
local function station_name_changer(event)
local entity = event.created_entity
local name = entity.name
if name == "train-stop" then --only do the event if its a train stop
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 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 recourse_closed
--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_ore_fluid = "item"
if item_name == "crude-oil" then
Item_ore_fluid = "fluid"
end
--Final string:
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 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)

View File

@@ -57,7 +57,7 @@ Event.add(defines.events.on_tick, function()
local max_remove = math.floor(head/100)+1 local max_remove = math.floor(head/100)+1
local remove_count = math.random(0, max_remove) local remove_count = math.random(0, max_remove)
while remove_count > 0 and head > 0 do 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] local entity = tree_queue[remove_index]
tree_queue[remove_index] = tree_queue[head] tree_queue[remove_index] = tree_queue[head]
head = head - 1 head = head - 1
@@ -71,7 +71,7 @@ end)
-- Clear the chache -- Clear the chache
Event.on_nth_tick(300, function() Event.on_nth_tick(300, function()
for key,_ in pairs(chache) do for key, _ in pairs(chache) do
chache[key] = nil chache[key] = nil
end end
end) end)

View File

@@ -10,16 +10,16 @@ require 'config.expcore.command_general_parse'
--- Sends a message in chat that only admins can see --- Sends a message in chat that only admins can see
-- @command admin-chat -- @command admin-chat
-- @tparam string message the message to send in the 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.') Commands.new_command('admin-chat', 'Sends a message in chat that only admins can see.')
:add_param('message',false) :add_param('message', false)
:enable_auto_concat() :enable_auto_concat()
:set_flag('admin_only') :set_flag('admin_only')
:add_alias('ac') :add_alias('ac')
:register(function(player,message,raw) :register(function(player, message)
local player_name_colour = format_chat_player_name(player) 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 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
end end
return Commands.success -- prevents command complete message from showing return Commands.success -- prevents command complete message from showing

View File

@@ -17,9 +17,9 @@ local bonus_store = Store.register(function(player)
end) end)
-- Apply a bonus amount to a player -- Apply a bonus amount to a player
local function apply_bonus(player,amount) local function apply_bonus(player, amount)
if not amount then return end if not amount then return end
for bonus,min_max in pairs(config) do for bonus, min_max in pairs(config) do
local increase = min_max[2]*amount local increase = min_max[2]*amount
player[bonus] = min_max[1]+increase player[bonus] = min_max[1]+increase
end end
@@ -28,32 +28,32 @@ end
--- Changes the amount of bonus you receive --- Changes the amount of bonus you receive
-- @command bonus -- @command bonus
-- @tparam number amount range 0-50 the percent increase for your bonus -- @tparam number amount range 0-50 the percent increase for your bonus
Commands.new_command('bonus','Changes the amount of bonus you receive') Commands.new_command('bonus', 'Changes the amount of bonus you receive')
:add_param('amount','integer-range',0,50) :add_param('amount', 'integer-range', 0,50)
:register(function(player,amount) :register(function(player, amount)
local percent = amount/100 local percent = amount/100
Store.set(bonus_store,player,percent) Store.set(bonus_store, player, percent)
Commands.print{'expcom-bonus.set',amount} Commands.print{'expcom-bonus.set', amount}
Commands.print({'expcom-bonus.wip'},'orange') Commands.print({'expcom-bonus.wip'}, 'orange')
end) end)
-- When store is updated apply new bonus to the player -- When store is updated apply new bonus to the player
Store.watch(bonus_store,function(value,category) Store.watch(bonus_store, function(value, category)
local player = Game.get_player_from_any(category) local player = Game.get_player_from_any(category)
apply_bonus(player,value) apply_bonus(player, value)
end) end)
-- When a player respawns re-apply bonus -- When a player respawns re-apply bonus
Event.add(defines.events.on_player_respawned,function(event) Event.add(defines.events.on_player_respawned, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local value = Store.get(bonus_store,player) local value = Store.get(bonus_store, player)
apply_bonus(player,value) apply_bonus(player, value)
end) end)
-- When a player dies allow them to have instant respawn -- When a player dies allow them to have instant respawn
Event.add(defines.events.on_player_died,function(event) Event.add(defines.events.on_player_died, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
if Roles.player_has_flag(player,'instance-respawn') then if Roles.player_has_flag(player, 'instance-respawn') then
player.ticks_to_respawn = 120 player.ticks_to_respawn = 120
end end
end) end)
@@ -61,12 +61,12 @@ end)
-- Remove bonus if a player no longer has access to the command -- Remove bonus if a player no longer has access to the command
local function role_update(event) local function role_update(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
if not Roles.player_allowed(player,'command/bonus') then if not Roles.player_allowed(player, 'command/bonus') then
Store.clear(bonus_store,player) Store.clear(bonus_store, player)
end end
end end
Event.add(Roles.events.on_role_assigned,role_update) Event.add(Roles.events.on_role_assigned, role_update)
Event.add(Roles.events.on_role_unassigned,role_update) Event.add(Roles.events.on_role_unassigned, role_update)
return bonus_store return bonus_store

View File

@@ -9,12 +9,12 @@ require 'config.expcore.command_general_parse'
--- Toggles cheat mode for your player, or another player. --- Toggles cheat mode for your player, or another player.
-- @command toggle-cheat-mode -- @command toggle-cheat-mode
-- @tparam[opt=self] LuaPlayer player player to toggle chest mode of, can be nil for self -- @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.') Commands.new_command('toggle-cheat-mode', 'Toggles cheat mode for your player, or another player.')
:add_param('player',true,'player') :add_param('player', true, 'player')
:set_defaults{player=function(player) :set_defaults{player=function(player)
return player -- default is the user using the command return player -- default is the user using the command
end} end}
:set_flag('admin_only') :set_flag('admin_only')
:register(function(player,action_player,raw) :register(function(_, player)
action_player.cheat_mode = not action_player.cheat_mode player.cheat_mode = not player.cheat_mode
end) end)

View File

@@ -10,11 +10,11 @@ require 'config.expcore.command_role_parse'
--- Clears a players inventory --- Clears a players inventory
-- @command clear-inventory -- @command clear-inventory
-- @tparam LuaPlayer player the player to clear the inventory of -- @tparam LuaPlayer player the player to clear the inventory of
Commands.new_command('clear-inventory','Clears a players inventory') Commands.new_command('clear-inventory', 'Clears a players inventory')
:add_param('player',false,'player-role-alive') :add_param('player', false, 'player-role-alive')
:add_alias('clear-inv','move-inventory','move-inv') :add_alias('clear-inv', 'move-inventory', 'move-inv')
:register(function(player,action_player) :register(function(_, player)
local inv = action_player.get_main_inventory() local inv = player.get_main_inventory()
move_items(inv.get_contents()) move_items(inv.get_contents())
inv.clear() inv.clear()
end) end)

View File

@@ -8,7 +8,7 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands
--- Opens the debug pannel for viewing tables. --- Opens the debug pannel for viewing tables.
-- @command debug -- @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) :register(function(player)
DebugView.open_dubug(player) DebugView.open_dubug(player)
end) end)

View File

@@ -9,11 +9,11 @@ require 'config.expcore.command_general_parse'
--- Find a player on your map. --- Find a player on your map.
-- @command find-on-map -- @command find-on-map
-- @tparam LuaPlayer the player to find on the map -- @tparam LuaPlayer the player to find on the map
Commands.new_command('find-on-map','Find a player on your map.') Commands.new_command('find-on-map', 'Find a player on your map.')
:add_param('player',false,'player-online') :add_param('player', false, 'player-online')
:add_alias('find','zoom-to') :add_alias('find', 'zoom-to')
:register(function(player,action_player,raw) :register(function(player, action_player)
local position = action_player.position 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 return Commands.success -- prevents command complete message from showing
end) end)

View File

@@ -10,7 +10,7 @@ require 'config.expcore.command_general_parse'
local results_per_page = 5 local results_per_page = 5
local search_cache = {} local search_cache = {}
Global.register(search_cache,function(tbl) Global.register(search_cache, function(tbl)
search_cache = tbl search_cache = tbl
end) end)
@@ -18,12 +18,12 @@ end)
-- @command chelp -- @command chelp
-- @tparam string keyword the keyword that will be looked for -- @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 -- @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.') Commands.new_command('search-help', 'Searches for a keyword in all commands you are allowed to use.')
:add_alias('chelp','shelp','commands') :add_alias('chelp', 'shelp', 'commands')
:add_param('keyword',true) :add_param('keyword', true)
:add_param('page',true,'integer') :add_param('page', true, 'integer')
:set_defaults{keyword='',page=1} :set_defaults{keyword='', page=1}
:register(function(player,keyword,page,raw) :register(function(player, keyword, page)
local player_index = player and player.index or 0 local player_index = player and player.index or 0
-- if keyword is a number then treat it as page number -- if keyword is a number then treat it as page number
if tonumber(keyword) then if tonumber(keyword) then
@@ -40,20 +40,20 @@ Commands.new_command('search-help','Searches for a keyword in all commands you a
pages = {{}} pages = {{}}
local current_page = 1 local current_page = 1
local page_count = 0 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 -- 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 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 if page_count >= results_per_page then
page_count = 0 page_count = 0
current_page = current_page + 1 current_page = current_page + 1
table.insert(pages,{}) table.insert(pages, {})
end end
-- adds the new command to the page -- adds the new command to the page
page_count = page_count + 1 page_count = page_count + 1
found = found + 1 found = found + 1
local alias_format = #command_data.aliases > 0 and {'expcom-chelp.alias',table.concat(command_data.aliases,', ')} or '' local alias_format = #command_data.aliases > 0 and {'expcom-chelp.alias', table.concat(command_data.aliases, ', ')} or ''
table.insert(pages[current_page],{ table.insert(pages[current_page], {
'expcom-chelp.format', 'expcom-chelp.format',
command_data.name, command_data.name,
command_data.description, command_data.description,
@@ -70,15 +70,15 @@ Commands.new_command('search-help','Searches for a keyword in all commands you a
end end
-- print the requested page -- print the requested page
keyword = keyword == '' and '<all>' or keyword keyword = keyword == '' and '<all>' or keyword
Commands.print({'expcom-chelp.title',keyword},'cyan') Commands.print({'expcom-chelp.title', keyword}, 'cyan')
if pages[page] then if pages[page] then
for _,command in pairs(pages[page]) do for _, command in pairs(pages[page]) do
Commands.print(command) Commands.print(command)
end end
Commands.print({'expcom-chelp.footer',found,page,#pages},'cyan') Commands.print({'expcom-chelp.footer', found, page, #pages}, 'cyan')
else else
Commands.print({'expcom-chelp.footer',found,page,#pages},'cyan') Commands.print({'expcom-chelp.footer', found, page, #pages}, 'cyan')
return Commands.error{'expcom-chelp.out-of-range',page} return Commands.error{'expcom-chelp.out-of-range', page}
end end
-- blocks command complete message -- blocks command complete message
return Commands.success return Commands.success

View File

@@ -8,16 +8,16 @@ local Global = require 'utils.global' --- @dep utils.global
require 'config.expcore.command_general_parse' require 'config.expcore.command_general_parse'
local homes = {} local homes = {}
Global.register(homes,function(tbl) Global.register(homes, function(tbl)
homes = tbl homes = tbl
end) end)
local function teleport(player,position) local function teleport(player, position)
local surface = player.surface 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 not position then return false end
if player.driving then player.driving = false end -- kicks a player out a vehicle if in one 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 return true
end end
@@ -30,22 +30,22 @@ end
--- Teleports you to your home location --- Teleports you to your home location
-- @command home -- @command home
Commands.new_command('home','Teleports you to your home location') Commands.new_command('home', 'Teleports you to your home location')
:register(function(player,raw) :register(function(player)
local home = homes[player.index] local home = homes[player.index]
if not home or not home[1] then if not home or not home[1] then
return Commands.error{'expcom-home.no-home'} return Commands.error{'expcom-home.no-home'}
end end
local rtn = floor_pos(player.position) local rtn = floor_pos(player.position)
teleport(player,home[1]) teleport(player, home[1])
home[2] = rtn home[2] = rtn
Commands.print{'expcom-home.return-set',rtn.x,rtn.y} Commands.print{'expcom-home.return-set', rtn.x, rtn.y}
end) end)
--- Sets your home location to your current position --- Sets your home location to your current position
-- @command home-set -- @command home-set
Commands.new_command('home-set','Sets your home location to your current position') Commands.new_command('home-set', 'Sets your home location to your current position')
:register(function(player,raw) :register(function(player)
local home = homes[player.index] local home = homes[player.index]
if not home then if not home then
home = {} home = {}
@@ -53,31 +53,31 @@ Commands.new_command('home-set','Sets your home location to your current positio
end end
local pos = floor_pos(player.position) local pos = floor_pos(player.position)
home[1] = pos home[1] = pos
Commands.print{'expcom-home.home-set',pos.x,pos.y} Commands.print{'expcom-home.home-set', pos.x, pos.y}
end) end)
--- Returns your current home location --- Returns your current home location
-- @command home-get -- @command home-get
Commands.new_command('home-get','Returns your current home location') Commands.new_command('home-get', 'Returns your current home location')
:register(function(player,raw) :register(function(player)
local home = homes[player.index] local home = homes[player.index]
if not home or not home[1] then if not home or not home[1] then
return Commands.error{'expcom-home.no-home'} return Commands.error{'expcom-home.no-home'}
end end
local pos = home[1] 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) end)
--- Teleports you to previous location --- Teleports you to previous location
-- @command return -- @command return
Commands.new_command('return','Teleports you to previous location') Commands.new_command('return', 'Teleports you to previous location')
:register(function(player,raw) :register(function(player)
local home = homes[player.index] local home = homes[player.index]
if not home or not home[2] then if not home or not home[2] then
return Commands.error{'expcom-home.no-return'} return Commands.error{'expcom-home.no-return'}
end end
local rtn = floor_pos(player.position) local rtn = floor_pos(player.position)
teleport(player,home[2]) teleport(player, home[2])
home[2] = rtn home[2] = rtn
Commands.print{'expcom-home.return-set',rtn.x,rtn.y} Commands.print{'expcom-home.return-set', rtn.x, rtn.y}
end) end)

View File

@@ -21,7 +21,7 @@ local interface_modules = {
} }
-- loads all the modules given in the above table -- 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 if type(value) == 'string' then
interface_modules[key] = Common.opt_require(value) interface_modules[key] = Common.opt_require(value)
end end
@@ -29,7 +29,7 @@ end
local interface_env = {} -- used as a persistent sandbox for interface commands local interface_env = {} -- used as a persistent sandbox for interface commands
local interface_callbacks = {} -- saves callbacks which can load new values per use 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 interface_env = tbl
end) end)
@@ -38,14 +38,14 @@ end)
-- @tparam string name the name that the value is loaded under, cant use upvalues -- @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 -- @tparam function callback the function that will run whent he command is used
-- callback param - player: LuaPlayer - the player who used the command -- callback param - player: LuaPlayer - the player who used the command
local function add_interface_callback(name,callback) local function add_interface_callback(name, callback)
if type(callback) == 'function' then if type(callback) == 'function' then
interface_callbacks[name] = callback interface_callbacks[name] = callback
end end
end end
-- this is a meta function for __index when self[key] is nil -- this is a meta function for __index when self[key] is nil
local function get_index(self,key) local function get_index(_, key)
if interface_env[key] then if interface_env[key] then
return interface_env[key] return interface_env[key]
elseif interface_modules[key] then elseif interface_modules[key] then
@@ -56,36 +56,36 @@ end
--- Sends an innovation to be ran and returns the result. --- Sends an innovation to be ran and returns the result.
-- @command interface -- @command interface
-- @tparam string innovation the command that will be run -- @tparam string innovation the command that will be run
Commands.new_command('interface','Sends an innovation to be ran and returns the result.') Commands.new_command('interface', 'Sends an innovation to be ran and returns the result.')
:add_param('innovation',false) :add_param('innovation', false)
:enable_auto_concat() :enable_auto_concat()
:set_flag('admin_only') :set_flag('admin_only')
:register(function(player,innovation,raw) :register(function(player, innovation)
if not innovation:find('%s') and not innovation:find('return') then 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 -- if there are no spaces and return is not present then return is appended to the start
innovation='return '..innovation innovation='return '..innovation
end end
-- temp_env will index to interface_env and interface_modules if value not found -- temp_env will index to interface_env and interface_modules if value not found
local temp_env = setmetatable({},{__index=get_index}) local temp_env = setmetatable({}, {__index=get_index})
if player then -- player can be nil when it is the server if player then -- player can be nil when it is the server
for name,callback in pairs(interface_callbacks) do for name, callback in pairs(interface_callbacks) do
-- loops over callbacks and loads the values returned -- loops over callbacks and loads the values returned
local success, rtn = pcall(callback,player) local _, rtn = pcall(callback, player)
temp_env[name]=rtn temp_env[name]=rtn
end end
end end
-- sets the global metatable to prevent new values being made -- sets the global metatable to prevent new values being made
-- global will index to temp_env and new indexs saved to interface_sandbox -- global will index to temp_env and new indexes saved to interface_sandbox
local old_mt = getmetatable(_G) local old_mt = getmetatable(_G)
setmetatable(_G,{__index=temp_env,__newindex=interface_env}) setmetatable(_G, {__index=temp_env, __newindex=interface_env})
-- runs the innovation and returns values to the player -- runs the innovation and returns values to the player
innovation = loadstring(innovation) innovation = loadstring(innovation)
local success, rtn = pcall(innovation) local success, rtn = pcall(innovation)
setmetatable(_G,old_mt) setmetatable(_G, old_mt)
if not success then if not success then
if type(rtn) == 'string' then if type(rtn) == 'string' then
-- there may be stack trace that must be removed to avoid desyncs -- there may be stack trace that must be removed to avoid desyncs
rtn = rtn:gsub('%.%.%..-/temp/currently%-playing','') rtn = rtn:gsub('%.%.%..-/temp/currently%-playing', '')
end end
return Commands.error(rtn) return Commands.error(rtn)
else else
@@ -94,16 +94,16 @@ Commands.new_command('interface','Sends an innovation to be ran and returns the
end) end)
-- adds some basic callbacks for the interface -- adds some basic callbacks for the interface
add_interface_callback('player',function(player) return player end) add_interface_callback('player', function(player) return player end)
add_interface_callback('surface',function(player) return player.surface end) add_interface_callback('surface', function(player) return player.surface end)
add_interface_callback('force',function(player) return player.force end) add_interface_callback('force', function(player) return player.force end)
add_interface_callback('position',function(player) return player.position end) add_interface_callback('position', function(player) return player.position end)
add_interface_callback('entity',function(player) return player.selected 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) add_interface_callback('tile', function(player) return player.surface.get_tile(player.position) end)
return { return {
add_interface_callback=add_interface_callback, add_interface_callback=add_interface_callback,
interface_env=interface_env, interface_env=interface_env,
interface_callbacks=interface_callbacks, interface_callbacks=interface_callbacks,
clean_stack_trace=function(str) return str:gsub('%.%.%..-/temp/currently%-playing','') end clean_stack_trace=function(str) return str:gsub('%.%.%..-/temp/currently%-playing', '') end
} }

View File

@@ -12,37 +12,37 @@ require 'config.expcore.command_role_parse'
-- @command jail -- @command jail
-- @tparam LuaPlayer player the player that will be jailed -- @tparam LuaPlayer player the player that will be jailed
-- @tparam[opt] string reason the reason why the player is being 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.') Commands.new_command('jail', 'Puts a player into jail and removes all other roles.')
:add_param('player',false,'player-role') :add_param('player', false, 'player-role')
:add_param('reason',true) :add_param('reason', true)
:enable_auto_concat() :enable_auto_concat()
:register(function(player,action_player,reason,raw) :register(function(player, action_player, reason)
reason = reason or 'Non Given.' reason = reason or 'Non Given.'
local action_player_name_color = format_chat_player_name(action_player) local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player) local by_player_name_color = format_chat_player_name(player)
local player_name = player and player.name or '<server>' local player_name = player and player.name or '<server>'
if Jail.jail_player(action_player, player_name, reason) then 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 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
end) end)
--- Removes a player from jail. --- Removes a player from jail.
-- @command unjail -- @command unjail
-- @tparam LuaPlayer the player that will be unjailed -- @tparam LuaPlayer the player that will be unjailed
Commands.new_command('unjail','Removes a player from jail.') Commands.new_command('unjail', 'Removes a player from jail.')
:add_param('player',false,'player-role') :add_param('player', false, 'player-role')
:add_alias('clear-jail','remove-jail') :add_alias('clear-jail', 'remove-jail')
:enable_auto_concat() :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 action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player) local by_player_name_color = format_chat_player_name(player)
local player_name = player and player.name or '<server>' local player_name = player and player.name or '<server>'
if Jail.unjail_player(action_player, player_name) then 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 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
end) end)
@@ -50,33 +50,33 @@ end)
-- @command temp-ban -- @command temp-ban
-- @tparam LuaPlayer player the player that will be temp banned -- @tparam LuaPlayer player the player that will be temp banned
-- @tparam string reason the reason that the player is being 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.') 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('player', false, 'player-role')
:add_param('reason',false) :add_param('reason', false)
:enable_auto_concat() :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 action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player) local by_player_name_color = format_chat_player_name(player)
if Jail.temp_ban_player(action_player,player.name,reason) then 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} game.print{'expcom-jail.temp-ban', action_player_name_color, by_player_name_color, reason}
else 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
end) end)
--- Removes temp ban from a player; this will not restore their items. --- Removes temp ban from a player; this will not restore their items.
-- @command clear-temp-ban -- @command clear-temp-ban
-- @tparam LuaPlayer player the player to revoke the temp ban from -- @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.') 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_param('player', false, 'player-role')
:add_alias('untemp-ban','remove-temp-ban') :add_alias('untemp-ban', 'remove-temp-ban')
:enable_auto_concat() :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 action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player) local by_player_name_color = format_chat_player_name(player)
if Jail.untemp_ban_player(action_player,player.name) then 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} game.print{'expcom-jail.temp-ban-clear', action_player_name_color, by_player_name_color}
else 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
end) end)

View File

@@ -11,22 +11,22 @@ require 'config.expcore.command_role_parse'
--- Kills yourself or another player. --- Kills yourself or another player.
-- @command kill -- @command kill
-- @tparam[opt=self] LuaPlayer player the player to kill, must be alive to be valid -- @tparam[opt=self] LuaPlayer player the player to kill, must be alive to be valid
Commands.new_command('kill','Kills yourself or another player.') Commands.new_command('kill', 'Kills yourself or another player.')
:add_param('player',true,'player-role-alive') :add_param('player', true, 'player-role-alive')
:set_defaults{player=function(player) :set_defaults{player=function(player)
-- default is the player unless they are dead -- default is the player unless they are dead
if player.character and player.character.health > 0 then if player.character and player.character.health > 0 then
return player return player
end end
end} end}
:register(function(player,action_player,raw) :register(function(player, action_player)
if not action_player then if not action_player then
-- can only be nil if no player given and the user is dead -- can only be nil if no player given and the user is dead
return Commands.error{'expcom-kill.already-dead'} return Commands.error{'expcom-kill.already-dead'}
end end
if player == action_player then if player == action_player then
action_player.character.die() 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() action_player.character.die()
else else
return Commands.error{'expcore-commands.unauthorized'} return Commands.error{'expcore-commands.unauthorized'}

View File

@@ -8,10 +8,10 @@ local Commands = require 'expcore.commands' --- @dep expcore.commands
--- Sends an action message in the chat --- Sends an action message in the chat
-- @command me -- @command me
-- @tparam string action the action that follows your name in chat -- @tparam string action the action that follows your name in chat
Commands.new_command('me','Sends an action message in the chat') Commands.new_command('me', 'Sends an action message in the chat')
:add_param('action',false) :add_param('action', false)
:enable_auto_concat() :enable_auto_concat()
:register(function(player,action,raw) :register(function(player, action)
local player_name = player and player.name or '<Server>' local player_name = player and player.name or '<Server>'
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) end)

View File

@@ -4,14 +4,11 @@
]] ]]
local Commands = require 'expcore.commands' --- @dep expcore.commands local Commands = require 'expcore.commands' --- @dep expcore.commands
local Roles = require 'expcore.roles' --- @dep expcore.roles
local Game = require 'utils.game' --- @dep utils.game
local config = require 'config.preset_player_quickbar' --- @dep config.preset_player_quickbar local config = require 'config.preset_player_quickbar' --- @dep config.preset_player_quickbar
--- Loads your quickbar preset --- Loads your quickbar preset
-- @command load-quickbar -- @command load-quickbar
Commands.new_command('load-quickbar','Loads your preset Quickbar items') Commands.new_command('load-quickbar', 'Loads your preset Quickbar items')
:add_alias('load-toolbar') :add_alias('load-toolbar')
:register(function(player) :register(function(player)
if config[player.name] then if config[player.name] then
@@ -28,7 +25,7 @@ end)
--- Saves your quickbar preset to the script-output folder --- Saves your quickbar preset to the script-output folder
-- @command save-quickbar -- @command save-quickbar
Commands.new_command('save-quickbar','Saves your Quickbar preset items to file') Commands.new_command('save-quickbar', 'Saves your Quickbar preset items to file')
:add_alias('save-toolbar') :add_alias('save-toolbar')
:register(function(player) :register(function(player)
local quickbar_names = {} local quickbar_names = {}

View File

@@ -6,27 +6,27 @@
local Commands = require 'expcore.commands' --- @dep expcore.commands local Commands = require 'expcore.commands' --- @dep expcore.commands
local format_chat_colour = _C.format_chat_colour --- @dep expcore.common 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 if c1 < 0 then
return 0,c2+c1 return 0, c2+c1
elseif c1 > 1 then elseif c1 > 1 then
return 1,c2-c1+1 return 1, c2-c1+1
else else
return c1,c2 return c1, c2
end end
end end
local function step_color(color) local function step_color(color)
color.r,color.g = step_component(color.r,color.g) color.r, color.g = step_component(color.r, color.g)
color.g,color.b = step_component(color.g,color.b) color.g, color.b = step_component(color.g, color.b)
color.b,color.r = step_component(color.b,color.r) color.b, color.r = step_component(color.b, color.r)
color.r = step_component(color.r,0) color.r = step_component(color.r, 0)
return color return color
end end
local function next_color(color,step) local function next_color(color, step)
step = step or 0.1 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 if color.b == 0 and color.r ~= 0 then
new_color.r = color.r-step new_color.r = color.r-step
new_color.g = color.g+step new_color.g = color.g+step
@@ -43,19 +43,19 @@ end
--- Sends an rainbow message in the chat --- Sends an rainbow message in the chat
-- @command rainbow -- @command rainbow
-- @tparam string message the message that will be printed in chat -- @tparam string message the message that will be printed in chat
Commands.new_command('rainbow','Sends an rainbow message in the chat') Commands.new_command('rainbow', 'Sends an rainbow message in the chat')
:add_param('message',false) :add_param('message', false)
:enable_auto_concat() :enable_auto_concat()
:register(function(player,message,raw) :register(function(player, message)
local player_name = player and player.name or '<Server>' local player_name = player and player.name or '<Server>'
local player_color = player and player.color or nil local player_color = player and player.color or nil
local color_step = 3/message:len() local color_step = 3/message:len()
if color_step > 1 then color_step = 1 end if color_step > 1 then color_step = 1 end
local current_color = {r=1,g=0,b=0} local current_color = {r=1, g=0, b=0}
local output = format_chat_colour(player_name..': ',player_color) local output = format_chat_colour(player_name..': ', player_color)
output = output..message:gsub('%S',function(letter) output = output..message:gsub('%S', function(letter)
local rtn = format_chat_colour(letter,current_color) local rtn = format_chat_colour(letter, current_color)
current_color = next_color(current_color,color_step) current_color = next_color(current_color, color_step)
return rtn return rtn
end) end)
game.print(output) game.print(output)

View File

@@ -2,33 +2,46 @@
local Commands = require 'expcore.commands' 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.') local multi = effect1*4+effect2*6+effect3*10
:add_param('itemsPerSecond',true,'number') return multi/100+1
:register(function(player,itemsPerSecond,raw) 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 local machine = player.selected -- selected machine
if not machine then --nil check if not machine then --nil check
return Commands.error{'expcom-ratio.notSelecting'} return Commands.error{'expcom-ratio.notSelecting'}
end end
if machine.type ~= "assembling-machine" and machine.type ~= "furnace" then if machine.type ~= "assembling-machine" and machine.type ~= "furnace" then
return Commands.error{'expcom-ratio.notSelecting'} return Commands.error{'expcom-ratio.notSelecting'}
end 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'} return Commands.error{'expcom-ratio.notSelecting'}
end end
local items = recpie.ingredients -- items in that recpie local items = recipe.ingredients -- items in that recipe
local product = recpie.products -- output items local products = recipe.products -- output items
local amountOfMachines local amountOfMachines
local moduleInvetory = machine.get_module_inventory()--the module Invetory of the machine local moduleInventory = machine.get_module_inventory()--the module Inventory of the machine
local mult = Modules(moduleInvetory) --function for the productivety moduals local multi = Modules(moduleInventory) --function for the productively modals
if itemsPerSecond then 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 end
if not amountOfMachines then if not amountOfMachines then
amountOfMachines = 1 --set to 1 to make it not nil 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 else
sprite = 'expcom-ratio.fluid-in' sprite = 'expcom-ratio.fluid-in'
end end
local ips = item.amount/recipe.energy*machine.crafting_speed*amountOfMachines --math on the items/fluids per second
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
Commands.print {sprite,math.round(ips,3),item.name}-- full string
end end
----------------------------products---------------------------- ----------------------------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 local sprite -- string to make the icon work either fluid ore item
if product.type == "item" then 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' sprite = 'expcom-ratio.fluid-out'
end end
local output = 1/recpie.energy*machine.crafting_speed*product.amount*mult --math on the outputs per second 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 Commands.print {sprite, math.round(output*amountOfMachines, 3), product.name} -- full string
end end
if amountOfMachines ~= 1 then if amountOfMachines ~= 1 then
Commands.print{'expcom-ratio.machines',amountOfMachines} Commands.print{'expcom-ratio.machines', amountOfMachines}
end end
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

View File

@@ -11,18 +11,18 @@ local max_time_to_live = 4294967295 -- unit32 max
--- Repairs entities on your force around you --- Repairs entities on your force around you
-- @command repair -- @command repair
-- @tparam number range the range to repair stuff in, there is a max limit to this -- @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') Commands.new_command('repair', 'Repairs entities on your force around you')
:add_param('range',false,'integer-range',1,config.max_range) :add_param('range', false, 'integer-range', 1,config.max_range)
:register(function(player,range,raw) :register(function(player, range)
local revive_count = 0 local revive_count = 0
local heal_count = 0 local heal_count = 0
local range2 = range^2 local range2 = range^2
local surface = player.surface local surface = player.surface
local center = player.position 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 if config.allow_ghost_revive then
local ghosts = surface.find_entities_filtered({area=area,type='entity-ghost',force=player.force}) local ghosts = surface.find_entities_filtered({area=area, type='entity-ghost', force=player.force})
for _,ghost in pairs(ghosts) do for _, ghost in pairs(ghosts) do
if ghost.valid then if ghost.valid then
local x = ghost.position.x-center.x local x = ghost.position.x-center.x
local y = ghost.position.y-center.y local y = ghost.position.y-center.y
@@ -36,8 +36,8 @@ Commands.new_command('repair','Repairs entities on your force around you')
end end
end end
if config.allow_heal_entities then if config.allow_heal_entities then
local entities = surface.find_entities_filtered({area=area,force=player.force}) local entities = surface.find_entities_filtered({area=area, force=player.force})
for _,entity in pairs(entities) do for _, entity in pairs(entities) do
if entity.valid then if entity.valid then
local x = entity.position.x-center.x local x = entity.position.x-center.x
local y = entity.position.y-center.y 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 end
end end
return Commands.success{'expcom-repair.result',revive_count,heal_count} return Commands.success{'expcom-repair.result', revive_count, heal_count}
end) end)

View File

@@ -13,25 +13,25 @@ require 'config.expcore.command_general_parse'
-- @command report -- @command report
-- @tparam LuaPlayer player the player to report, some players are immune -- @tparam LuaPlayer player the player to report, some players are immune
-- @tparam string reason the reason the player is being reported -- @tparam string reason the reason the player is being reported
Commands.new_command('report','Reports a player and notifies moderators') Commands.new_command('report', 'Reports a player and notifies moderators')
:add_param('player',false,function(input,player,reject) :add_param('player', false, function(input, player, reject)
input = Commands.parse('player',input,player,reject) input = Commands.parse('player', input, player, reject)
if not input then return end 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'} return reject{'expcom-report.player-immune'}
else else
return input return input
end end
end) end)
:add_param('reason',false) :add_param('reason', false)
:add_alias('report-player') :add_alias('report-player')
:enable_auto_concat() :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 action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(player) local by_player_name_color = format_chat_player_name(player)
if Reports.report_player(action_player,player.name,reason) then if Reports.report_player(action_player, player.name, reason) then
game.print{'expcom-report.non-admin',action_player_name_color,reason} 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}) Roles.print_to_roles_higher('Trainee', {'expcom-report.admin', action_player_name_color, by_player_name_color, reason})
else else
return Commands.error{'expcom-report.already-reported'} return Commands.error{'expcom-report.already-reported'}
end 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. --- 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 -- @command get-reports
-- @tparam LuaPlayer player the player to get the report for -- @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.') 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_param('player', true, 'player')
:add_alias('reports','list-reports') :add_alias('reports', 'list-reports')
:register(function(player,action_player,raw) :register(function(_, player)
if action_player then if player then
local reports = Reports.get_reports(action_player) local reports = Reports.get_reports(player)
local action_player_name_color = format_chat_player_name(action_player) local player_name_color = format_chat_player_name(player)
Commands.print{'expcom-report.player-report-title',action_player_name_color} Commands.print{'expcom-report.player-report-title', player_name_color}
for player_name,reason in pairs(reports) do for player_name, reason in pairs(reports) do
local by_player_name_color = format_chat_player_name(player_name) 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 end
else else
local user_reports = Reports.user_reports local user_reports = Reports.user_reports
Commands.print{'expcom-report.player-count-title'} 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 player_name_color = format_chat_player_name(player_name)
local report_count = Reports.count_reports(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 end
end) end)
@@ -67,20 +67,20 @@ end)
-- @command clear-reports -- @command clear-reports
-- @tparam LuaPlayer player the player to clear the report(s) from -- @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 -- @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.') 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('player', false, 'player')
:add_param('from-player',true,'player') :add_param('from-player', true, 'player')
:register(function(player,action_player,from_player,raw) :register(function(player, action_player, from_player)
if from_player then 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'} return Commands.error{'expcom-report.not-reported'}
end end
else 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'} return Commands.error{'expcom-report.not-reported'}
end end
end end
local action_player_name_color = format_chat_player_name(action_player) local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(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) end)

View File

@@ -12,15 +12,15 @@ local format_chat_player_name, format_chat_colour_localized = _C.format_chat_pla
-- @command assign-role -- @command assign-role
-- @tparam LuaPlayer player the player to assign the role to -- @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 -- @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') Commands.new_command('assign-role', 'Assigns a role to a player')
:add_param('player',false,'player-role') :add_param('player', false, 'player-role')
:add_param('role',false,'role') :add_param('role', false, 'role')
:set_flag('admin-only') :set_flag('admin-only')
:add_alias('rpromote','assign','role','add-role') :add_alias('rpromote', 'assign', 'role', 'add-role')
:register(function(player,action_player,role,raw) :register(function(player, action_player, role)
local player_highest = Roles.get_player_highest_role(player) local player_highest = Roles.get_player_highest_role(player)
if player_highest.index < role.index then if player_highest.index < role.index then
Roles.assign_player(action_player,role,player.name) Roles.assign_player(action_player, role, player.name)
else else
return Commands.error{'expcom-roles.higher-role'} return Commands.error{'expcom-roles.higher-role'}
end end
@@ -30,15 +30,15 @@ end)
-- @command unassign-role -- @command unassign-role
-- @tparam LuaPlayer player the player to unassign the role from -- @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 -- @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') Commands.new_command('unassign-role', 'Unassigns a role from a player')
:add_param('player',false,'player-role') :add_param('player', false, 'player-role')
:add_param('role',false,'role') :add_param('role', false, 'role')
:set_flag('admin-only') :set_flag('admin-only')
:add_alias('rdemote','unassign','rerole','remove-role') :add_alias('rdemote', 'unassign', 'rerole', 'remove-role')
:register(function(player,action_player,role,raw) :register(function(player, action_player, role)
local player_highest = Roles.get_player_highest_role(player) local player_highest = Roles.get_player_highest_role(player)
if player_highest.index < role.index then if player_highest.index < role.index then
Roles.unassign_player(action_player,role,player.name) Roles.unassign_player(action_player, role, player.name)
else else
return Commands.error{'expcom-roles.higher-role'} return Commands.error{'expcom-roles.higher-role'}
end end
@@ -47,27 +47,27 @@ end)
--- Lists all roles in they correct order --- Lists all roles in they correct order
-- @command list-roles -- @command list-roles
-- @tparam[opt=all] LuaPlayer player list only the roles which this player has -- @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') Commands.new_command('list-roles', 'Lists all roles in they correct order')
:add_param('player',true,'player') :add_param('player', true, 'player')
:add_alias('lsroles','roles') :add_alias('lsroles', 'roles')
:register(function(player,action_player,raw) :register(function(_, player)
local roles = Roles.config.order local roles = Roles.config.order
local message = {'expcom-roles.list'} local message = {'expcom-roles.list'}
if action_player then if player then
roles = Roles.get_player_roles(action_player) roles = Roles.get_player_roles(player)
end end
for index,role in pairs(roles) do for index, role in pairs(roles) do
role = Roles.get_role_from_any(role) role = Roles.get_role_from_any(role)
local colour = role.custom_color or Colours.white 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 if index == 1 then
message = {'expcom-roles.list',role_name} message = {'expcom-roles.list', role_name}
if action_player then if player then
local player_name_colour = format_chat_player_name(action_player) local player_name_colour = format_chat_player_name(player)
message = {'expcom-roles.list-player',player_name_colour,role_name} message = {'expcom-roles.list-player', player_name_colour, role_name}
end end
else else
message = {'expcom-roles.list-element',message,role_name} message = {'expcom-roles.list-element', message, role_name}
end end
end end
return Commands.success(message) return Commands.success(message)

View File

@@ -9,18 +9,18 @@ local Roles = require 'expcore.roles' --- @dep expcore.roles
local function teleport(player) local function teleport(player)
local surface = player.surface local surface = player.surface
local spawn = player.force.get_spawn_position(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 not position then return false end
if player.driving then player.driving = false end -- kicks a player out a vehicle if in one 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 return true
end end
--- Teleport to spawn --- Teleport to spawn
-- @command go-to-spawn -- @command go-to-spawn
-- @tparam[opt=self] LuaPlayer player the player to teleport to their spawn point -- @tparam[opt=self] LuaPlayer player the player to teleport to their spawn point
Commands.new_command('go-to-spawn','Teleport to spawn') Commands.new_command('go-to-spawn', 'Teleport to spawn')
:add_param('player',true,'player-role-alive') :add_param('player', true, 'player-role-alive')
:set_defaults{ :set_defaults{
player=function(player) player=function(player)
if player.connected and player.character and player.character.health > 0 then 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
end end
} }
:add_alias('spawn','tp-spawn') :add_alias('spawn', 'tp-spawn')
:register(function(player,action_player) :register(function(player, action_player)
if not action_player then if not action_player then
return Commands.error{'expcom-spawn.unavailable'} return Commands.error{'expcom-spawn.unavailable'}
elseif action_player == player then elseif action_player == player then
if not teleport(player) then if not teleport(player) then
return Commands.error{'expcom-spawn.unavailable'} return Commands.error{'expcom-spawn.unavailable'}
end 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 if not teleport(action_player) then
return Commands.error{'expcom-spawn.unavailable'} return Commands.error{'expcom-spawn.unavailable'}
end end

View File

@@ -11,26 +11,26 @@ require 'config.expcore.command_role_parse'
--- Sets your player tag. --- Sets your player tag.
-- @command tag -- @command tag
-- @tparam string tag the tag that will be after the name, there is a max length -- @tparam string tag the tag that will be after the name, there is a max length
Commands.new_command('tag','Sets your player tag.') Commands.new_command('tag', 'Sets your player tag.')
:add_param('tag',false,'string-max-length',20) :add_param('tag', false, 'string-max-length', 20)
:enable_auto_concat() :enable_auto_concat()
:register(function(player,tag,raw) :register(function(player, tag)
player.tag = '- '..tag player.tag = '- '..tag
end) end)
--- Clears your tag. Or another player if you are admin. --- Clears your tag. Or another player if you are admin.
-- @command tag-clear -- @command tag-clear
-- @tparam[opt=self] LuaPlayer player the player to remove the tag from, nil will apply to self -- @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.') Commands.new_command('tag-clear', 'Clears your tag. Or another player if you are admin.')
:add_param('player',true,'player-role') :add_param('player', true, 'player-role')
:set_defaults{player=function(player) :set_defaults{player=function(player)
return player -- default is the user using the command return player -- default is the user using the command
end} end}
:register(function(player,action_player,raw) :register(function(player, action_player)
if action_player.index == player.index then if action_player.index == player.index then
-- no player given so removes your tag -- no player given so removes your tag
action_player.tag = '' action_player.tag = ''
elseif Roles.player_allowed(player,'command/clear-tag/always') then elseif Roles.player_allowed(player, 'command/clear-tag/always') then
-- player given and user is admin so clears that player's tag -- player given and user is admin so clears that player's tag
action_player.tag = '' action_player.tag = ''
else else

View File

@@ -6,12 +6,12 @@
local Commands = require 'expcore.commands' --- @dep expcore.commands local Commands = require 'expcore.commands' --- @dep expcore.commands
require 'config.expcore.command_general_parse' 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 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 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 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 return true
end end
@@ -19,17 +19,17 @@ end
-- @command teleport -- @command teleport
-- @tparam LuaPlayer from_player the player that will be teleported, must be alive -- @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) -- @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.') Commands.new_command('teleport', 'Teleports a player to another player.')
:add_param('from_player',false,'player-alive') :add_param('from_player', false, 'player-alive')
:add_param('to_player',false,'player-online') :add_param('to_player', false, 'player-online')
:add_alias('tp') :add_alias('tp')
:set_flag('admin_only') :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 if from_player.index == to_player.index then
-- return if attempting to teleport to self -- return if attempting to teleport to self
return Commands.error{'expcom-tp.to-self'} return Commands.error{'expcom-tp.to-self'}
end end
if not teleport(from_player,to_player) then if not teleport(from_player, to_player) then
-- return if the teleport failed -- return if the teleport failed
return Commands.error{'expcom-tp.no-position-found'} return Commands.error{'expcom-tp.no-position-found'}
end end
@@ -38,15 +38,15 @@ end)
--- Teleports a player to you. --- Teleports a player to you.
-- @command bring -- @command bring
-- @tparam LuaPlayer player the player that will be teleported, must be alive -- @tparam LuaPlayer player the player that will be teleported, must be alive
Commands.new_command('bring','Teleports a player to you.') Commands.new_command('bring', 'Teleports a player to you.')
:add_param('player',false,'player-alive') :add_param('player', false, 'player-alive')
:set_flag('admin_only') :set_flag('admin_only')
:register(function(player,from_player,raw) :register(function(player, from_player)
if from_player.index == player.index then if from_player.index == player.index then
-- return if attempting to teleport to self -- return if attempting to teleport to self
return Commands.error{'expcom-tp.to-self'} return Commands.error{'expcom-tp.to-self'}
end end
if not teleport(from_player,player) then if not teleport(from_player, player) then
-- return if the teleport failed -- return if the teleport failed
return Commands.error{'expcom-tp.no-position-found'} return Commands.error{'expcom-tp.no-position-found'}
end end
@@ -55,16 +55,16 @@ end)
--- Teleports you to a player. --- Teleports you to a player.
-- @command goto -- @command goto
-- @tparam LuaPlayer player the player to teleport to, must be online (if dead goes to where they died) -- @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.') Commands.new_command('goto', 'Teleports you to a player.')
:add_param('player',false,'player-online') :add_param('player', false, 'player-online')
:add_alias('tp-me','tpme') :add_alias('tp-me', 'tpme')
:set_flag('admin_only') :set_flag('admin_only')
:register(function(player,to_player,raw) :register(function(player, to_player)
if to_player.index == player.index then if to_player.index == player.index then
-- return if attempting to teleport to self -- return if attempting to teleport to self
return Commands.error{'expcom-tp.to-self'} return Commands.error{'expcom-tp.to-self'}
end end
if not teleport(player,to_player) then if not teleport(player, to_player) then
-- return if the teleport failed -- return if the teleport failed
return Commands.error{'expcom-tp.no-position-found'} return Commands.error{'expcom-tp.no-position-found'}
end end

View File

@@ -13,47 +13,47 @@ require 'config.expcore.command_role_parse'
-- @command give-warning -- @command give-warning
-- @tparam LuaPlayer player the player the will recive a warning -- @tparam LuaPlayer player the player the will recive a warning
-- @tparam string reason the reason the player is being given 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.') 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('player', false, 'player-role')
:add_param('reason',false) :add_param('reason', false)
:add_alias('warn') :add_alias('warn')
:enable_auto_concat() :enable_auto_concat()
:register(function(player,action_player,reason,raw) :register(function(player, action_player, reason)
Warnings.add_warning(action_player,player.name,reason) Warnings.add_warning(action_player, player.name, reason)
local action_player_name_color = format_chat_player_name(action_player) local action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(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) end)
--- Gets the number of warnings a player has. If no player then lists all players and the number of warnings they have. --- 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 -- @command get-warnings
-- @tparam[opt=list] LuaPlayer player the player to get the warning for, if nil all players are listed -- @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.') 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_param('player', true, 'player')
:add_alias('warnings','list-warnings') :add_alias('warnings', 'list-warnings')
:register(function(player,action_player,raw) :register(function(_, player)
if action_player then if player then
local warnings = Warnings.get_warnings(action_player) local warnings = Warnings.get_warnings(player)
local script_warnings = Warnings.get_script_warnings(action_player) local script_warnings = Warnings.get_script_warnings(player)
local action_player_name_color = format_chat_player_name(action_player) local player_name_color = format_chat_player_name(player)
Commands.print{'expcom-warnings.player',action_player_name_color,warnings,script_warnings,config.temp_warning_limit} Commands.print{'expcom-warnings.player', player_name_color, warnings, script_warnings, config.temp_warning_limit}
else else
local rtn = {} local rtn = {}
local user_warnings = Warnings.user_warnings local user_warnings = Warnings.user_warnings
local user_script_warnings = Warnings.user_script_warnings local user_script_warnings = Warnings.user_script_warnings
for player_name,warnings in pairs(user_warnings) do for player_name, warnings in pairs(user_warnings) do
rtn[player_name] = {#warnings,0} rtn[player_name] = {#warnings, 0}
end 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 if not rtn[player_name] then
rtn[player_name] = {0,0} rtn[player_name] = {0, 0}
end end
rtn[player_name][2] = #warnings rtn[player_name][2] = #warnings
end end
Commands.print{'expcom-warnings.list-tilte'} Commands.print{'expcom-warnings.list-tilte'}
for player_name,warnings in pairs(rtn) do for player_name, warnings in pairs(rtn) do
local player_name_color = format_chat_player_name(player_name) 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 end
end) end)
@@ -61,12 +61,12 @@ end)
--- Clears all warnings (and script warnings) from a player --- Clears all warnings (and script warnings) from a player
-- @command clear-warnings -- @command clear-warnings
-- @tparam LuaPlayer player the player to clear the warnings from -- @tparam LuaPlayer player the player to clear the warnings from
Commands.new_command('clear-warnings','Clears all warnings (and script warnings) from a player') Commands.new_command('clear-warnings', 'Clears all warnings (and script warnings) from a player')
:add_param('player',false,'player') :add_param('player', false, 'player')
:register(function(player,action_player,raw) :register(function(player, action_player)
Warnings.clear_warnings(action_player,player.name) Warnings.clear_warnings(action_player, player.name)
Warnings.clear_script_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 action_player_name_color = format_chat_player_name(action_player)
local by_player_name_color = format_chat_player_name(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) end)

View File

@@ -9,15 +9,15 @@
-- This will move 'MrBiter' to the jail role and remove all other roles from them -- 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 -- 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 -- 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 -- 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 -- 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 -- 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 local Roles = require 'expcore.roles' --- @dep expcore.roles
@@ -65,7 +65,7 @@ local temp_bans = Jail.temp_bans
Global.register({ Global.register({
old_roles = old_roles, old_roles = old_roles,
temp_bans = temp_bans temp_bans = temp_bans
},function(tbl) }, function(tbl)
Jail.old_roles = tbl.old_roles Jail.old_roles = tbl.old_roles
Jail.temp_bans = tbl.temp_bans Jail.temp_bans = tbl.temp_bans
old_roles = Jail.old_roles old_roles = Jail.old_roles
@@ -77,8 +77,8 @@ end)
-- @tparam LuaPlayer player the player who is being acted on -- @tparam LuaPlayer player the player who is being acted on
-- @tparam string by_player_name the player who is doing the action -- @tparam string by_player_name the player who is doing the action
-- @tparam string reason the reason for the action (jail and tempban only) -- @tparam string reason the reason for the action (jail and tempban only)
local function event_emit(event,player,by_player_name,reason) local function event_emit(event, player, by_player_name, reason)
script.raise_event(event,{ script.raise_event(event, {
name=event, name=event,
tick=game.tick, tick=game.tick,
player_index=player.index, player_index=player.index,
@@ -95,7 +95,7 @@ end
-- @tparam LuaPlayer player the player to check if they are in jail -- @tparam LuaPlayer player the player to check if they are in jail
-- @treturn boolean whether the player is currently in jail -- @treturn boolean whether the player is currently in jail
function Jail.is_jailed(player) function Jail.is_jailed(player)
return has_role(player,'Jail') return has_role(player, 'Jail')
end end
--- Moves a player to jail and removes all other roles --- 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 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 -- @tparam[opt='Non given.'] string reason the reason that the player is being jailed
-- @treturn boolean wheather the user was jailed successfully -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name then return end if not by_player_name then return end
reason = reason or 'Non given.' 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) local roles = get_roles(player)
old_roles[player.name] = roles old_roles[player.name] = roles
@@ -126,12 +126,12 @@ end
-- @tparam LuaPlayer player the player that will be unjailed -- @tparam LuaPlayer player the player that will be unjailed
-- @tparam string by_player_name the name of the player that is doing the unjail -- @tparam string by_player_name the name of the player that is doing the unjail
-- @treturn boolean whether the player was unjailed successfully -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name 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 {} local roles = old_roles[player.name] or {}
assign_roles(player, roles, by_player_name, nil, true) 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 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 -- @tparam[opt='Non given.'] string reason the reason that the player is being temp banned
-- @treturn boolean whether the player was successfully 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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name 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.' reason = reason or 'Non given.'
if temp_bans[player.name] then return end 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) local roles = get_roles(player)
old_roles[player.name] = roles old_roles[player.name] = roles
@@ -182,7 +182,7 @@ function Jail.temp_ban_player(player,by_player_name,reason)
move_items(inv.get_contents()) move_items(inv.get_contents())
inv.clear() 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 return true
end end
@@ -191,7 +191,7 @@ end
-- @tparam LuaPlayer player the player who is being removed from temp ban -- @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 -- @tparam string by_player_name the name of the player who is doing the untemp ban
-- @treturn boolean whether the player was successfully removed -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name 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 if not temp_bans[player.name] then return end
temp_bans[player.name] = nil temp_bans[player.name] = nil
if has_role(player,'Jail') then if has_role(player, 'Jail') then
local roles = old_roles[player.name] local roles = old_roles[player.name]
assign_roles(player, roles, by_player_name, nil, true) assign_roles(player, roles, by_player_name, nil, true)
unassign_roles(player, 'Jail', by_player_name, nil, true) unassign_roles(player, 'Jail', by_player_name, nil, true)
end 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 return true
end end

View File

@@ -14,21 +14,21 @@
-- The get production function is used to get production, consumion and net -- 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 -- 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 -- 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 -- 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 -- 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 -- 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) -- 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 -- 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 -- 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 -- 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) 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] defines.flow_precision_index the next precision value
-- @treturn[1] number the multiplicive difference between the values -- @treturn[1] number the multiplicive difference between the values
function Production.precision_up(precision) function Production.precision_up(precision)
if precision == precision_index.one_second then return precision_index.one_minute,60 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.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.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.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.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.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 elseif precision == precision_index.two_hundred_fifty_hours then return precision_index.one_thousand_hours, 4
end end
end end
@@ -62,13 +62,13 @@ end
-- @treturn[1] defines.flow_precision_index the next precision value -- @treturn[1] defines.flow_precision_index the next precision value
-- @treturn[1] number the multiplicive difference between the values -- @treturn[1] number the multiplicive difference between the values
function Production.precision_down(precision) function Production.precision_down(precision)
if precision == precision_index.one_minute then return precision_index.one_second,60 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.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.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.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.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.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 elseif precision == precision_index.one_thousand_hours then return precision_index.two_hundred_fifty_hours, 4
end end
end end
@@ -95,7 +95,7 @@ end
-- @tparam LuaForce force the force to get the data for -- @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 -- @tparam string item_name the name of the item that you want the data about
-- @treturn table contains total made, used and net -- @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 stats = force.item_production_statistics
local made = stats.get_input_count(item_name) or 0 local made = stats.get_input_count(item_name) or 0
local used = stats.get_output_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 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 -- @tparam defines.flow_precision_index precision the precision that you want the data given to
-- @treturn table contains made, used and net -- @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 stats = force.item_production_statistics.get_flow_count
local made = stats{name=item_name,input=true,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 local used = stats{name=item_name, input=false, precision_index=precision} or 0
return { return {
made=made, made=made,
@@ -131,10 +131,10 @@ end
-- @tparam string item_name the name of the item that you want the data about -- @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 -- @tparam defines.flow_precision_index precision the precision that you want the data given to
-- @treturn table contains made, used and net -- @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 percision_up = Production.precision_up(precision)
local current = Production.get_production(force,item_name,precision) local current = Production.get_production(force, item_name, precision)
local previous = Production.get_production(force,item_name,percision_up) local previous = Production.get_production(force, item_name, percision_up)
return { return {
made=(current.made/previous.made)-1, 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 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 -- @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 -- @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 required = required or 1000
local ticks = Production.precision_ticks(precision) 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 return production.made == 0 and -1 or ticks*required/production.made
end end
@@ -163,10 +163,10 @@ end
-- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @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 -- @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 -- @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 required = required or 1000
local ticks = Production.precision_ticks(precision) 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 return production.used == 0 and -1 or ticks*required/production.used
end end
@@ -176,10 +176,10 @@ end
-- @tparam defines.flow_precision_index precision the precision that you want the data given to -- @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 -- @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 -- @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 required = required or 1000
local ticks = Production.precision_ticks(precision) 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 return production.net == 0 and -1 or ticks*required/production.net
end end
@@ -191,8 +191,8 @@ end
-- @tparam number clamp value which seperates the different colours -- @tparam number clamp value which seperates the different colours
-- @tparam number active_value first value tested, tested against clamp -- @tparam number active_value first value tested, tested against clamp
-- @tparam number passive_value second value tested, tested against 0 -- @tparam number passive_value second value tested, tested against 0
-- @treturn table contains r,g,b keys -- @treturn table contains r, g,b keys
function Production.get_color(clamp,active_value,passive_value) function Production.get_color(clamp, active_value, passive_value)
if active_value > clamp then if active_value > clamp then
return Colors.light_green return Colors.light_green
elseif active_value < -clamp then elseif active_value < -clamp then
@@ -213,19 +213,19 @@ end
-- @treturn[1] string the sign for the number -- @treturn[1] string the sign for the number
-- @treturn[1] string the surfix for any unit used -- @treturn[1] string the surfix for any unit used
function Production.format_number(value) 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) local surfix = rtn:sub(-1)
if value > 0 then if value > 0 then
rtn = '+'..rtn rtn = '+'..rtn
elseif value == 0 and rtn:sub(1,1) == '-' then elseif value == 0 and rtn:sub(1, 1) == '-' then
rtn = rtn:sub(2) rtn = rtn:sub(2)
end end
if not tonumber(surfix) then if not tonumber(surfix) then
return surfix,rtn:sub(1,-2) return surfix, rtn:sub(1, -2)
else else
return '',rtn return '', rtn
end end
end end

View File

@@ -10,13 +10,13 @@
-- This will place a report on "MrBiter" (must be a valid player) the report will have been made -- 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 -- by "Cooldude2606" (must be the player name) with the reason 'Liking biters too much' this can be
-- seen by using Reports.get_report. -- 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. -- 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'. -- 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 -- This will remove all the report that have been made against 'MrBiter'. Note that the remove event will
-- be triggered once per report issused. -- be triggered once per report issused.
@@ -48,7 +48,7 @@ local Reports = {
} }
local user_reports = Reports.user_reports local user_reports = Reports.user_reports
Global.register(user_reports,function(tbl) Global.register(user_reports, function(tbl)
Reports.user_reports = tbl Reports.user_reports = tbl
user_reports = Reports.user_reports user_reports = Reports.user_reports
end) end)
@@ -71,7 +71,7 @@ end
-- @tparam LuaPlayer player the player to get the report for -- @tparam LuaPlayer player the player to get the report for
-- @tparam string by_player_name the name of the player who made the report -- @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 -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name then return end if not by_player_name then return end
@@ -84,7 +84,7 @@ end
-- @tparam LuaPlayer player the player to check if reported -- @tparam LuaPlayer player the player to check if reported
-- @tparam[opt] string by_player_name when given will check if reported by this player -- @tparam[opt] string by_player_name when given will check if reported by this player
-- @treturn boolean if the player has been reported -- @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) player = valid_player(player)
if not player then return end if not player then return end
@@ -100,15 +100,15 @@ end
-- @tparam LuaPlayer player the player to count the reports for -- @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 -- @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 -- @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) player = valid_player(player)
if not player then return end if not player then return end
local reports = user_reports[player.name] or {} local reports = user_reports[player.name] or {}
if custom_count then if custom_count then
local ctn = 0 local ctn = 0
for by_player_name,reason in pairs(reports) do for by_player_name, reason in pairs(reports) do
ctn = ctn + custom_count(player,by_player_name,reason) ctn = ctn + custom_count(player, by_player_name, reason)
end end
return ctn return ctn
else else
@@ -125,7 +125,7 @@ end
-- @tparam string by_player_name the name of the player that is making the report -- @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 -- @tparam[opt='Non given.'] string reason the reason that the player is being reported
-- @treturn boolean whether the report was added successfully -- @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) player = valid_player(player)
if not player then return end if not player then return end
local player_name = player.name local player_name = player.name
@@ -144,7 +144,7 @@ function Reports.report_player(player,by_player_name,reason)
reports[by_player_name] = reason reports[by_player_name] = reason
end end
script.raise_event(Reports.events.on_player_reported,{ script.raise_event(Reports.events.on_player_reported, {
name = Reports.events.on_player_reported, name = Reports.events.on_player_reported,
tick = game.tick, tick = game.tick,
player_index = player.index, player_index = player.index,
@@ -159,8 +159,8 @@ end
-- @tparam LuaPlayer player the player who is having the report removed from them -- @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 reported_by_name the player who had the report
-- @tparam string removed_by_name the player who is clearing 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) local function report_removed_event(player, reported_by_name, removed_by_name)
script.raise_event(Reports.events.on_report_removed,{ script.raise_event(Reports.events.on_report_removed, {
name = Reports.events.on_report_removed, name = Reports.events.on_report_removed,
tick = game.tick, tick = game.tick,
player_index = player.index, player_index = player.index,
@@ -174,7 +174,7 @@ end
-- @tparam string reported_by_name the name of the player that made the report -- @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 -- @tparam string removed_by_name the name of the player who removed the report
-- @treturn boolean whether the report was removed successfully -- @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) player = valid_player(player)
if not player then return end if not player then return end
@@ -188,7 +188,7 @@ function Reports.remove_report(player,reported_by_name,removed_by_name)
return false return false
end 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 reports[reported_by_name] = nil
return true return true
@@ -198,7 +198,7 @@ end
-- @tparam LuaPlayer player the player to remove the reports from -- @tparam LuaPlayer player the player to remove the reports from
-- @tparam string removed_by_name the name of the player who removed the report -- @tparam string removed_by_name the name of the player who removed the report
-- @treturn boolean whether the reports were removed successfully -- @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) player = valid_player(player)
if not player then return end if not player then return end
@@ -207,8 +207,8 @@ function Reports.remove_all(player,removed_by_name)
return false return false
end end
for reported_by_name,_ in pairs(reports) do for reported_by_name, _ in pairs(reports) do
report_removed_event(player,reported_by_name,removed_by_name) report_removed_event(player, reported_by_name, removed_by_name)
end end
user_reports[player.name] = nil user_reports[player.name] = nil

View File

@@ -18,10 +18,10 @@
Rockets.get_silos('player') Rockets.get_silos('player')
-- You can get the launch time for a rocket, meaning what game tick the 50th rocket was launched -- 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 -- 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 config = require 'config.gui.rockets' --- @dep config.rockets
local largest_rolling_avg = 0 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 if avg_over > largest_rolling_avg then
largest_rolling_avg = avg_over largest_rolling_avg = avg_over
end end
@@ -49,7 +49,7 @@ Global.register({
rocket_times = rocket_times, rocket_times = rocket_times,
rocket_stats = rocket_stats, rocket_stats = rocket_stats,
rocket_silos = rocket_silos rocket_silos = rocket_silos
},function(tbl) }, function(tbl)
Rockets.times = tbl.rocket_times Rockets.times = tbl.rocket_times
Rockets.stats = tbl.rocket_stats Rockets.stats = tbl.rocket_stats
Rockets.silos = tbl.rocket_silos Rockets.silos = tbl.rocket_silos
@@ -94,9 +94,9 @@ end
-- @treturn table an array of silo data that all belong to this force -- @treturn table an array of silo data that all belong to this force
function Rockets.get_silos(force_name) function Rockets.get_silos(force_name)
local rtn = {} 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 if silo_data.force == force_name then
table.insert(rtn,silo_data) table.insert(rtn, silo_data)
end end
end end
return rtn return rtn
@@ -106,7 +106,7 @@ end
-- @tparam string force_name the name of the force to get the count for -- @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 -- @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 -- @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 return rocket_times[force_name] and rocket_times[force_name][rocket_number] or nil
end end
@@ -122,7 +122,7 @@ end
-- @treturn number the total number of rockets launched this game -- @treturn number the total number of rockets launched this game
function Rockets.get_game_rocket_count() function Rockets.get_game_rocket_count()
local rtn = 0 local rtn = 0
for _,force in pairs(game.forces) do for _, force in pairs(game.forces) do
rtn = rtn + force.rockets_launched rtn = rtn + force.rockets_launched
end end
return rtn return rtn
@@ -132,7 +132,7 @@ end
-- @tparam string force_name the name of the force to get the average for -- @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 -- @tparam number count the distance to get the rolling average over
-- @treturn number the number of ticks required to launch one rocket -- @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 force = game.forces[force_name]
local rocket_count = force.rockets_launched local rocket_count = force.rockets_launched
if rocket_count == 0 then return 0 end if rocket_count == 0 then return 0 end
@@ -146,7 +146,7 @@ function Rockets.get_rolling_average(force_name,count)
end end
--- Event used to update the stats and the hui when a rocket is launched --- 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 entity = event.rocket_silo
local silo_data = Rockets.get_silo_data(entity) local silo_data = Rockets.get_silo_data(entity)
local force = event.rocket_silo.force 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 rocket_times[force_name][rockets_launched] = event.tick
local remove_rocket = rockets_launched-largest_rolling_avg 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 rocket_times[force_name][remove_rocket] = nil
end end
@@ -186,7 +186,7 @@ Event.add(defines.events.on_rocket_launched,function(event)
end) end)
--- When a launch is reiggered it will await reset --- 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 entity = event.rocket_silo
local silo_data = Rockets.get_silo_data(entity) local silo_data = Rockets.get_silo_data(entity)
silo_data.awaiting_reset = true silo_data.awaiting_reset = true
@@ -212,7 +212,7 @@ local function on_built(event)
end end
end end
Event.add(defines.events.on_built_entity,on_built) Event.add(defines.events.on_built_entity, on_built)
Event.add(defines.events.on_robot_built_entity,on_built) Event.add(defines.events.on_robot_built_entity, on_built)
return Rockets return Rockets

View File

@@ -4,9 +4,9 @@
@alias Tasks @alias Tasks
@usage-- Making and then editing a new task @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)
]] ]]
@@ -18,7 +18,7 @@ local Tasks = {}
-- Global lookup table for force name to task ids -- Global lookup table for force name to task ids
local force_tasks = {} local force_tasks = {}
Global.register(force_tasks,function(tbl) Global.register(force_tasks, function(tbl)
force_tasks = tbl force_tasks = tbl
end) end)
@@ -38,10 +38,10 @@ Tasks.store = task_store
@treturn string the uid of the task which was created @treturn string the uid of the task which was created
@usage-- Adding a new task for your force @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 -- Get a new task id
local task_id = tostring(Token.uid()) local task_id = tostring(Token.uid())
task_message = task_message or 'New Task' task_message = task_message or 'New Task'
@@ -55,9 +55,9 @@ function Tasks.add_task(force_name,task_number,player_name,task_message)
-- Insert the task id into the forces tasks -- Insert the task id into the forces tasks
if task_number then if task_number then
table.insert(tasks,task_number,task_id) table.insert(tasks, task_number, task_id)
else else
table.insert(tasks,task_id) table.insert(tasks, task_id)
end end
-- Create the editing table -- Create the editing table
@@ -67,7 +67,7 @@ function Tasks.add_task(force_name,task_number,player_name,task_message)
end end
-- Add the new task to the store -- Add the new task to the store
Store.set(task_store,task_id,{ Store.set(task_store, task_id, {
task_id = task_id, task_id = task_id,
force_name = force_name, force_name = force_name,
message = task_message, message = task_message,
@@ -87,10 +87,10 @@ Tasks.remove_task(task_id)
]] ]]
function Tasks.remove_task(task_id) function Tasks.remove_task(task_id)
local task = Store.get(task_store,task_id) local task = Store.get(task_store, task_id)
local force_name = task.force_name local force_name = task.force_name
table.remove_element(force_tasks[force_name],task_id) table.remove_element(force_tasks[force_name], task_id)
Store.clear(task_store,task_id) Store.clear(task_store, task_id)
end end
--[[-- Update the message and last edited information for a task --[[-- 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 @tparam[opt='server'] string player_name the name of the player who made the edit
@usage-- Updating the message for on a task @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) function Tasks.update_task(task_id, new_message, player_name)
Store.update(task_store,task_id,function(task) Store.update(task_store, task_id, function(task)
task.last_edit_name = player_name or '<server>' task.last_edit_name = player_name or '<server>'
task.last_edit_time = game.tick task.last_edit_time = game.tick
task.message = new_message task.message = new_message
@@ -116,11 +116,11 @@ end
@tparam boolean state the new state to set editing to @tparam boolean state the new state to set editing to
@usage-- Setting your editing state to true @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) function Tasks.set_editing(task_id, player_name, state)
Store.update(task_store,task_id,function(task) Store.update(task_store, task_id, function(task)
task.curently_editing[player_name] = state task.curently_editing[player_name] = state
end) end)
end end
@@ -135,7 +135,7 @@ end)
]] ]]
function Tasks.on_update(handler) function Tasks.on_update(handler)
Store.watch(task_store,handler) Store.watch(task_store, handler)
end end
--- Getters. --- Getters.
@@ -151,7 +151,7 @@ local task = Tasks.get_task(task_id)
]] ]]
function Tasks.get_task(task_id) function Tasks.get_task(task_id)
return Store.get(task_store,task_id) return Store.get(task_store, task_id)
end end
--[[-- Gets all the task ids that a force has --[[-- Gets all the task ids that a force has
@@ -172,11 +172,11 @@ end
@treturn boolean weather the player is currently editing this task @treturn boolean weather the player is currently editing this task
@usage-- Check if a player is editing a task or not @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) function Tasks.get_editing(task_id, player_name)
local task = Store.get(task_store,task_id) local task = Store.get(task_store, task_id)
return task.curently_editing[player_name] return task.curently_editing[player_name]
end end

View File

@@ -8,17 +8,17 @@
local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings local Warnings = require 'modules.control.warnings' --- @dep modules.control.warnings
-- This will add a warning to the player -- 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 -- 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 -- 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 -- 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 -- 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 local Event = require 'utils.event' --- @dep utils.event
@@ -65,7 +65,7 @@ local user_script_warnings = Warnings.user_script_warnings
Global.register({ Global.register({
user_warnings = user_warnings, user_warnings = user_warnings,
user_script_warnings = user_script_warnings user_script_warnings = user_script_warnings
},function(tbl) }, function(tbl)
Warnings.user_warnings = tbl.user_warnings Warnings.user_warnings = tbl.user_warnings
Warnings.user_script_warnings = tbl.user_script_warnings Warnings.user_script_warnings = tbl.user_script_warnings
user_warnings = Warnings.user_warnings user_warnings = Warnings.user_warnings
@@ -92,7 +92,7 @@ end
-- @tparam string by_player_name the name of the player who is doing the action -- @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 -- @tparam[opt='Non given.'] string reason the reason that the player is being warned
-- @treturn number the number of warnings that the player has -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name then return end if not by_player_name then return end
@@ -105,7 +105,7 @@ function Warnings.add_warning(player,by_player_name,reason)
user_warnings[player.name] = warnings user_warnings[player.name] = warnings
end end
table.insert(warnings,{ table.insert(warnings, {
tick = game.tick, tick = game.tick,
by_player_name = by_player_name, by_player_name = by_player_name,
reason = reason reason = reason
@@ -113,7 +113,7 @@ function Warnings.add_warning(player,by_player_name,reason)
local warning_count = #warnings local warning_count = #warnings
script.raise_event(Warnings.events.on_warning_added,{ script.raise_event(Warnings.events.on_warning_added, {
name = Warnings.events.on_warning_added, name = Warnings.events.on_warning_added,
tick = game.tick, tick = game.tick,
player_index = player.index, player_index = player.index,
@@ -126,11 +126,11 @@ function Warnings.add_warning(player,by_player_name,reason)
if action then if action then
local _type = type(action) local _type = type(action)
if _type == 'function' then if _type == 'function' then
action(player,by_player_name,warning_count) action(player, by_player_name, warning_count)
elseif _type == 'table' then elseif _type == 'table' then
local current = table.deepcopy(action) local current = table.deepcopy(action)
table.insert(current,2,by_player_name) table.insert(current, 2,by_player_name)
table.insert(current,3,warning_count) table.insert(current, 3,warning_count)
player.print(current) player.print(current)
elseif type(action) == 'string' then elseif type(action) == 'string' then
player.print(action) player.print(action)
@@ -145,8 +145,8 @@ end
-- @tparam string warning_by_name the name of the player who made the warning -- @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 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 -- @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) local function warning_removed_event(player, warning_by_name, removed_by_name, warning_count)
script.raise_event(Warnings.events.on_warning_removed,{ script.raise_event(Warnings.events.on_warning_removed, {
name = Warnings.events.on_warning_removed, name = Warnings.events.on_warning_removed,
tick = game.tick, tick = game.tick,
player_index = player.index, player_index = player.index,
@@ -160,7 +160,7 @@ end
-- @tparam LuaPlayer player the player to remove a warning from -- @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 -- @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 -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name then return end if not by_player_name then return end
@@ -168,9 +168,9 @@ function Warnings.remove_warning(player,by_player_name)
local warnings = user_warnings[player.name] local warnings = user_warnings[player.name]
if not warnings then return end if not warnings then return end
local warning = table.remove(warnings,1) local warning = table.remove(warnings, 1)
warning_removed_event(player,warning.by_player_name,by_player_name,#warnings) warning_removed_event(player, warning.by_player_name, by_player_name, #warnings)
return #warnings return #warnings
end end
@@ -179,7 +179,7 @@ end
-- @tparam LuaPlayer player the player to clear the warnings from -- @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 -- @tparam string by_player_name the name of the player who is doing the action
-- @treturn boolean true when warnings were cleared succesfully -- @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) player = valid_player(player)
if not player then return end if not player then return end
if not by_player_name then return end if not by_player_name then return end
@@ -188,8 +188,8 @@ function Warnings.clear_warnings(player,by_player_name)
if not warnings then return end if not warnings then return end
local warning_count = #warnings local warning_count = #warnings
for n,warning in pairs(warnings) do for n, warning in pairs(warnings) do
warning_removed_event(player,warning.by_player_name,by_player_name,warning_count-n) warning_removed_event(player, warning.by_player_name, by_player_name, warning_count-n)
end end
user_warnings[player.name] = nil user_warnings[player.name] = nil
@@ -215,7 +215,7 @@ end
-- @tparam LuaPlayer player the player to add a script warning to -- @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 -- @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 -- @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) player = valid_player(player)
if not player then return end if not player then return end
@@ -227,14 +227,14 @@ function Warnings.add_script_warning(player,reason)
user_script_warnings[player.name] = warnings user_script_warnings[player.name] = warnings
end end
table.insert(warnings,{ table.insert(warnings, {
tick = game.tick, tick = game.tick,
reason = reason reason = reason
}) })
local warning_count = #warnings 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, name = Warnings.events.on_script_warning_added,
tick = game.tick, tick = game.tick,
player_index = player.index, player_index = player.index,
@@ -243,7 +243,7 @@ function Warnings.add_script_warning(player,reason)
}) })
if warning_count > config.script_warning_limit then if warning_count > config.script_warning_limit then
Warnings.add_warning(player,'<server>',reason) Warnings.add_warning(player, '<server>', reason)
end end
return warning_count return warning_count
@@ -252,8 +252,8 @@ end
--- Script warning removed event tigger due to it being looped in clear script warnings --- Script warning removed event tigger due to it being looped in clear script warnings
-- @tparam LuaPlayer player the player who is having a script warning removed -- @tparam LuaPlayer player the player who is having a script warning removed
-- @tparam number warning_count the number of warning that the player has -- @tparam number warning_count the number of warning that the player has
local function script_warning_removed_event(player,warning_count) local function script_warning_removed_event(player, warning_count)
script.raise_event(Warnings.events.on_script_warning_removed,{ script.raise_event(Warnings.events.on_script_warning_removed, {
name = Warnings.events.on_script_warning_removed, name = Warnings.events.on_script_warning_removed,
tick = game.tick, tick = game.tick,
player_index = player.index, player_index = player.index,
@@ -271,7 +271,7 @@ function Warnings.remove_script_warning(player)
local warnings = user_script_warnings[player.name] local warnings = user_script_warnings[player.name]
if not warnings then return end if not warnings then return end
table.remove(warnings,1) table.remove(warnings, 1)
script_warning_removed_event(player) script_warning_removed_event(player)
@@ -288,8 +288,8 @@ function Warnings.clear_script_warnings(player)
if not warnings then return end if not warnings then return end
local warning_count = #warnings local warning_count = #warnings
for n,_ in pairs(warnings) do for n, _ in pairs(warnings) do
script_warning_removed_event(player,warning_count-n) script_warning_removed_event(player, warning_count-n)
end end
user_script_warnings[player.name] = nil user_script_warnings[player.name] = nil
@@ -298,11 +298,11 @@ end
-- script warnings are removed after a certain amount of time to make them even more lienient -- 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 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 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 if #script_warnings > 0 then
for _,warning in pairs(script_warnings) do for _, warning in pairs(script_warnings) do
if warning.tick < cutoff then if warning.tick < cutoff then
Warnings.remove_script_warning(player_name) Warnings.remove_script_warning(player_name)
end end

View File

@@ -6,7 +6,7 @@
@usage-- Making a new spawn warp @usage-- Making a new spawn warp
local player = game.player local player = game.player
local force = player.force 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.set_spawn_warp(spawn_id, force)
Warps.make_warp_tag(spawn_id) Warps.make_warp_tag(spawn_id)
@@ -14,7 +14,7 @@ Warps.make_warp_tag(spawn_id)
@usage-- Making a new warp with a warp area @usage-- Making a new warp with a warp area
local player = game.player local player = game.player
local force = player.force 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_area(warp_id)
Warps.make_warp_tag(warp_id) Warps.make_warp_tag(warp_id)
@@ -30,7 +30,7 @@ local Warps = {}
-- Global lookup table for force name to task ids -- Global lookup table for force name to task ids
local force_warps = {} local force_warps = {}
Global.register(force_warps,function(tbl) Global.register(force_warps, function(tbl)
force_warps = tbl force_warps = tbl
end) end)
@@ -39,7 +39,7 @@ local warp_store = Store.register()
Warps.store = warp_store Warps.store = warp_store
-- When a warp is updated change its chat tag and resort the warp order -- When a warp is updated change its chat tag and resort the warp order
Store.watch(warp_store,function(warp,warp_id) Store.watch(warp_store, function(warp, warp_id)
if warp then if warp then
-- Update the map chart tag if there is one -- Update the map chart tag if there is one
if warp.tag then if warp.tag then
@@ -55,8 +55,8 @@ Store.watch(warp_store,function(warp,warp_id)
local spawn_id = warp_ids.spawn local spawn_id = warp_ids.spawn
local warp_names = {} local warp_names = {}
for _,next_warp_id in pairs(warp_ids) do for _, next_warp_id in pairs(warp_ids) do
local next_warp = Store.get(warp_store,next_warp_id) local next_warp = Store.get(warp_store, next_warp_id)
if next_warp_id ~= spawn_id then if next_warp_id ~= spawn_id then
warp_names[next_warp.name..next_warp_id] = next_warp_id warp_names[next_warp.name..next_warp_id] = next_warp_id
end end
@@ -64,7 +64,7 @@ Store.watch(warp_store,function(warp,warp_id)
-- Sort the warp names in alphabetical order -- Sort the warp names in alphabetical order
local new_warp_ids = table.get_values(table.keysort(warp_names)) 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 new_warp_ids.spawn = spawn_id
force_warps[force_name] = new_warp_ids force_warps[force_name] = new_warp_ids
end end
@@ -83,7 +83,7 @@ local tag_added = Warps.make_warp_tag(warp_id)
]] ]]
function Warps.make_warp_tag(warp_id) function Warps.make_warp_tag(warp_id)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
local name = warp.name local name = warp.name
local icon = warp.icon local icon = warp.icon
@@ -91,7 +91,7 @@ function Warps.make_warp_tag(warp_id)
local tag = warp.tag local tag = warp.tag
if tag and tag.valid then if tag and tag.valid then
tag.text = 'Warp: '..name tag.text = 'Warp: '..name
tag.icon = {type='item',name=icon} tag.icon = {type='item', name=icon}
return false return false
end end
@@ -100,10 +100,10 @@ function Warps.make_warp_tag(warp_id)
local surface = warp.surface local surface = warp.surface
local position = warp.position local position = warp.position
tag = force.add_chart_tag(surface,{ tag = force.add_chart_tag(surface, {
position = {position.x+0.5,position.y+0.5}, position = {position.x+0.5, position.y+0.5},
text = 'Warp: '..name, 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 -- Add the tag to this warp, store.update not needed as we dont want it to trigger
@@ -120,7 +120,7 @@ local removed = Warps.remove_warp_tag(warp_id)
]] ]]
function Warps.remove_warp_tag(warp_id) function Warps.remove_warp_tag(warp_id)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
-- Check there is a tag to remove -- Check there is a tag to remove
local tag = warp.tag local tag = warp.tag
@@ -144,7 +144,7 @@ Warps.make_warp_area(warp_id)
]] ]]
function Warps.make_warp_area(warp_id) function Warps.make_warp_area(warp_id)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
local surface = warp.surface local surface = warp.surface
local position = warp.position local position = warp.position
local posx = position.x local posx = position.x
@@ -164,7 +164,7 @@ function Warps.make_warp_area(warp_id)
for y = -radius, radius do for y = -radius, radius do
local y2 = y^2 local y2 = y^2
if x2+y2 < radius2 then 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 end
end end
@@ -172,16 +172,16 @@ function Warps.make_warp_area(warp_id)
-- Add a tile patern ontop of the base -- Add a tile patern ontop of the base
local tiles = {} local tiles = {}
for _,pos in pairs(config.tiles) do for _, pos in pairs(config.tiles) do
table.insert(tiles,{name=base_tile,position={pos[1]+posx,pos[2]+posy}}) table.insert(tiles, {name=base_tile, position={pos[1]+posx, pos[2]+posy}})
end end
surface.set_tiles(tiles) surface.set_tiles(tiles)
-- Add entities to the warp structure -- Add entities to the warp structure
for _,entity in pairs(config.entities) do for _, entity in pairs(config.entities) do
entity = surface.create_entity{ entity = surface.create_entity{
name=entity[1], name=entity[1],
position={entity[2]+posx,entity[3]+posy}, position={entity[2]+posx, entity[3]+posy},
force='neutral' force='neutral'
} }
entity.destructible = false entity.destructible = false
@@ -199,7 +199,7 @@ Warps.remove_warp_area(warp_id)
]] ]]
function Warps.remove_warp_area(warp_id) function Warps.remove_warp_area(warp_id)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
local position = warp.position local position = warp.position
local surface = warp.surface local surface = warp.surface
local radius = config.standard_proximity_radius local radius = config.standard_proximity_radius
@@ -216,7 +216,7 @@ function Warps.remove_warp_area(warp_id)
for y = -radius, radius do for y = -radius, radius do
local y2 = y^2 local y2 = y^2
if x2+y2 < radius2 then 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 end
end end
@@ -226,11 +226,11 @@ function Warps.remove_warp_area(warp_id)
local entities = surface.find_entities_filtered{ local entities = surface.find_entities_filtered{
force='neutral', force='neutral',
area={ 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.name ~= 'player' then entity.destroy() end end
end end
--[[-- Set a warp to be the spawn point for a force, force must own this warp --[[-- Set a warp to be the spawn point for a force, force must own this warp
@@ -238,12 +238,12 @@ end
@tparam LuaForce force the force that you want to set the spawn for @tparam LuaForce force the force that you want to set the spawn for
@usage-- Set your forces spawn to a warp @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 -- Check the force owns this warp
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
if warp.force_name ~= force.name then return end if warp.force_name ~= force.name then return end
-- Set this warp as the spawn -- Set this warp as the spawn
@@ -263,11 +263,11 @@ end
@tparam LuaPlayer player the player to teleport to the warp @tparam LuaPlayer player the player to teleport to the warp
@usage-- Teleport yourself to a warp point @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) function Warps.teleport_player(warp_id, player)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
local surface = warp.surface local surface = warp.surface
local position = { local position = {
x=warp.position.x+0.5, x=warp.position.x+0.5,
@@ -275,9 +275,9 @@ function Warps.teleport_player(warp_id,player)
} }
-- Teleport the 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 if player.driving then player.driving = false end
player.teleport(goto_position,surface) player.teleport(goto_position, surface)
end end
--- Setters. --- Setters.
@@ -294,10 +294,10 @@ end
@usage-- Adding a new warp for your force at your position @usage-- Adding a new warp for your force at your position
local player = game.player 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 -- Get new warp id
local warp_id = tostring(Token.uid()) local warp_id = tostring(Token.uid())
warp_name = warp_name or 'New warp' warp_name = warp_name or 'New warp'
@@ -310,7 +310,7 @@ function Warps.add_warp(force_name,surface,position,player_name,warp_name)
end end
-- Insert the warp id into the force warps -- Insert the warp id into the force warps
table.insert(warp_ids,warp_id) table.insert(warp_ids, warp_id)
-- Create the editing table -- Create the editing table
local editing = {} local editing = {}
@@ -319,7 +319,7 @@ function Warps.add_warp(force_name,surface,position,player_name,warp_name)
end end
-- Add the new warp to the store -- Add the new warp to the store
Store.set(warp_store,warp_id,{ Store.set(warp_store, warp_id, {
warp_id = warp_id, warp_id = warp_id,
force_name = force_name, force_name = force_name,
name = warp_name, name = warp_name,
@@ -345,12 +345,12 @@ Warps.remove_warp(warp_id)
]] ]]
function Warps.remove_warp(warp_id) function Warps.remove_warp(warp_id)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
local force_name = warp.force_name local force_name = warp.force_name
Warps.remove_warp_tag(warp_id) Warps.remove_warp_tag(warp_id)
Warps.remove_warp_area(warp_id) Warps.remove_warp_area(warp_id)
Store.clear(warp_store,warp_id) Store.clear(warp_store, warp_id)
table.remove_element(force_warps[force_name],warp_id) table.remove_element(force_warps[force_name], warp_id)
end end
--[[-- Update the name and icon for a warp --[[-- Update the name and icon for a warp
@@ -360,11 +360,11 @@ end
@tparam[opt='server'] string player_name the name of the player that made the edit @tparam[opt='server'] string player_name the name of the player that made the edit
@usage-- Changing the name and icon for a warp @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) function Warps.update_warp(warp_id, new_name, new_icon, player_name)
Store.update(warp_store,warp_id,function(warp) Store.update(warp_store, warp_id, function(warp)
warp.last_edit_name = player_name or '<server>' warp.last_edit_name = player_name or '<server>'
warp.last_edit_time = game.tick warp.last_edit_time = game.tick
warp.old_name = warp.name warp.old_name = warp.name
@@ -379,11 +379,11 @@ end
@tparam boolean state the new state to set editing to @tparam boolean state the new state to set editing to
@usage-- Setting your editing state to true @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) function Warps.set_editing(warp_id, player_name, state)
Store.update(warp_store,warp_id,function(warp) Store.update(warp_store, warp_id, function(warp)
warp.currently_editing[player_name] = state warp.currently_editing[player_name] = state
end) end)
end end
@@ -398,7 +398,7 @@ end)
]] ]]
function Warps.on_update(handler) function Warps.on_update(handler)
Store.watch(warp_store,handler) Store.watch(warp_store, handler)
end end
--- Getters. --- Getters.
@@ -414,7 +414,7 @@ local warp = Warps.get_warp(warp_id)
]] ]]
function Warps.get_warp(warp_id) function Warps.get_warp(warp_id)
return Store.get(warp_store,warp_id) return Store.get(warp_store, warp_id)
end end
--[[-- Gets all the warp ids that a force has --[[-- Gets all the warp ids that a force has
@@ -448,11 +448,11 @@ end
@treturn boolean weather the player is currently editing this warp @treturn boolean weather the player is currently editing this warp
@usage-- Check if a player is editing a warp or not @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) function Warps.get_editing(warp_id, player_name)
local warp = Store.get(warp_store,warp_id) local warp = Store.get(warp_store, warp_id)
return warp.currently_editing[player_name] return warp.currently_editing[player_name]
end end

View File

@@ -10,7 +10,7 @@ if use_silo_script then
end end
local global = {} local global = {}
Global.register(global,function(tbl) Global.register(global, function(tbl)
global = tbl global = tbl
end) end)
@@ -35,7 +35,7 @@ local respawn_items = function()
end end
if use_silo_script then 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) Event.add(k, v)
end end
end end

View File

@@ -4,6 +4,7 @@
@alias player_list @alias player_list
]] ]]
-- luacheck:ignore 211/Colors
local Gui = require 'expcore.gui' --- @dep expcore.gui local Gui = require 'expcore.gui' --- @dep expcore.gui
local Roles = require 'expcore.roles' --- @dep expcore.roles local Roles = require 'expcore.roles' --- @dep expcore.roles
local Store = require 'expcore.store' --- @dep expcore.store local Store = require 'expcore.store' --- @dep expcore.store
@@ -24,7 +25,7 @@ local selected_action_store = Store.register(function(player)
end) end)
-- Set the config to use these stores -- Set the config to use these stores
config.set_store_uids(selected_player_store,selected_action_store) config.set_store_uids(selected_player_store, selected_action_store)
--- Button used to open the action bar --- Button used to open the action bar
-- @element open_action_bar -- @element open_action_bar
@@ -40,13 +41,13 @@ Gui.element{
width = 8, width = 8,
height = 14 height = 14
} }
:on_click(function(player,element,_) :on_click(function(player, element, _)
local selected_player_name = element.parent.name local selected_player_name = element.parent.name
local old_selected_player_name = Store.get(selected_player_store,player) local old_selected_player_name = Store.get(selected_player_store, player)
if selected_player_name == old_selected_player_name then if selected_player_name == old_selected_player_name then
Store.clear(selected_player_store,player) Store.clear(selected_player_store, player)
else else
Store.set(selected_player_store,player,selected_player_name) Store.set(selected_player_store, player, selected_player_name)
end end
end) end)
@@ -59,10 +60,10 @@ Gui.element{
tooltip = {'player-list.close-action-bar'}, tooltip = {'player-list.close-action-bar'},
style = 'shortcut_bar_button_red' style = 'shortcut_bar_button_red'
} }
:style(Gui.sprite_style(30,-1,{ top_margin = -1, right_margin = -1 })) :style(Gui.sprite_style(30, -1, { top_margin = -1, right_margin = -1 }))
:on_click(function(player,_) :on_click(function(player, _)
Store.clear(selected_player_store,player) Store.clear(selected_player_store, player)
Store.clear(selected_action_store,player) Store.clear(selected_action_store, player)
end) end)
--- Button used to confirm a reason --- Button used to confirm a reason
@@ -74,21 +75,21 @@ Gui.element{
tooltip = {'player-list.reason-confirm'}, tooltip = {'player-list.reason-confirm'},
style = 'shortcut_bar_button_green' style = 'shortcut_bar_button_green'
} }
:style(Gui.sprite_style(30,-1,{ left_margin = -2, right_margin = -1 })) :style(Gui.sprite_style(30, -1, { left_margin = -2, right_margin = -1 }))
:on_click(function(player,element) :on_click(function(player, element)
local reason = element.parent.entry.text or 'Non Given' local reason = element.parent.entry.text or 'Non Given'
local action_name = Store.get(selected_action_store,player) local action_name = Store.get(selected_action_store, player)
local reason_callback = config.buttons[action_name].reason_callback local reason_callback = config.buttons[action_name].reason_callback
reason_callback(player,reason) reason_callback(player, reason)
Store.clear(selected_player_store,player) Store.clear(selected_player_store, player)
Store.clear(selected_action_store,player) Store.clear(selected_action_store, player)
element.parent.entry.text = '' element.parent.entry.text = ''
end) end)
--- Set of elements that are used to make up a row of the player table --- Set of elements that are used to make up a row of the player table
-- @element add_player_base -- @element add_player_base
local 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 -- Add the button to open the action bar
local toggle_action_bar_flow = parent.add{ type = 'flow', name = player_data.name } local toggle_action_bar_flow = parent.add{ type = 'flow', name = player_data.name }
open_action_bar(toggle_action_bar_flow) open_action_bar(toggle_action_bar_flow)
@@ -99,13 +100,13 @@ Gui.element(function(event_trigger,parent,player_data)
type = 'label', type = 'label',
name = event_trigger, name = event_trigger,
caption = player_data.name, 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 player_name.style.font_color = player_data.chat_color
-- Add the time played label -- 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{ local time_label = alignment.add{
name = 'label', name = 'label',
type = 'label', type = 'label',
@@ -116,34 +117,34 @@ Gui.element(function(event_trigger,parent,player_data)
return time_label return time_label
end) end)
:on_click(function(player,element,event) :on_click(function(player, element, event)
local selected_player_name = element.caption local selected_player_name = element.caption
local selected_player = Game.get_player_from_any(selected_player_name) local selected_player = Game.get_player_from_any(selected_player_name)
if event.button == defines.mouse_button_type.left then if event.button == defines.mouse_button_type.left then
-- LMB will open the map to the selected player -- LMB will open the map to the selected player
local position = selected_player.position local position = selected_player.position
event.player.zoom_to_world(position,1.75) event.player.zoom_to_world(position, 1.75)
else else
-- RMB will toggle the settings -- RMB will toggle the settings
local old_selected_player_name = Store.get(selected_player_store,player) local old_selected_player_name = Store.get(selected_player_store, player)
if selected_player_name == old_selected_player_name then if selected_player_name == old_selected_player_name then
Store.clear(selected_player_store,player) Store.clear(selected_player_store, player)
Store.clear(selected_action_store,player) Store.clear(selected_action_store, player)
else else
Store.set(selected_player_store,player,selected_player_name) Store.set(selected_player_store, player, selected_player_name)
end end
end end
end) end)
-- Removes the three elements that are added as part of the base -- 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])
Gui.destroy_if_valid(parent['player-name-'..player.index]) Gui.destroy_if_valid(parent['player-name-'..player.index])
Gui.destroy_if_valid(parent['player-time-'..player.index]) Gui.destroy_if_valid(parent['player-time-'..player.index])
end end
-- Update the time label for a player using there player time data -- 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] local time_element = parent[player_time.element_name]
if time_element and time_element.valid then if time_element and time_element.valid then
time_element.label.caption = player_time.caption time_element.label.caption = player_time.caption
@@ -154,15 +155,15 @@ end
--- Adds all the buttons and flows that make up the action bar --- Adds all the buttons and flows that make up the action bar
-- @element add_action_bar -- @element add_action_bar
local add_action_bar_buttons = local add_action_bar_buttons =
Gui.element(function(_,parent) Gui.element(function(_, parent)
close_action_bar(parent) close_action_bar(parent)
-- Loop over all the buttons in the config -- 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 -- Added the permission flow
local permission_flow = parent.add{ type = 'flow', name = action_name } local permission_flow = parent.add{ type = 'flow', name = action_name }
permission_flow.visible = false permission_flow.visible = false
-- Add the buttons under that permission -- Add the buttons under that permission
for _,button in ipairs(button_data) do for _, button in ipairs(button_data) do
button(permission_flow) button(permission_flow)
end end
end end
@@ -173,7 +174,7 @@ end)
--- Updates the visible state of the action bar buttons --- Updates the visible state of the action bar buttons
local function update_action_bar(element) local function update_action_bar(element)
local player = Gui.get_player_from_element(element) local player = Gui.get_player_from_element(element)
local selected_player_name = Store.get(selected_player_store,player) local selected_player_name = Store.get(selected_player_store, player)
if not selected_player_name then if not selected_player_name then
-- Hide the action bar when no player is selected -- Hide the action bar when no player is selected
@@ -184,16 +185,16 @@ local function update_action_bar(element)
if not selected_player.connected then if not selected_player.connected then
-- If the player is offline then reest stores -- If the player is offline then reest stores
element.visible = false element.visible = false
Store.clear(selected_player_store,player) Store.clear(selected_player_store, player)
Store.clear(selected_action_store,player) Store.clear(selected_action_store, player)
else else
-- Otherwise check what actions the player is allowed to use -- Otherwise check what actions the player is allowed to use
element.visible = true element.visible = true
for action_name,buttons in pairs(config.buttons) do for action_name, buttons in pairs(config.buttons) do
if buttons.auth and not buttons.auth(player,selected_player) then if buttons.auth and not buttons.auth(player, selected_player) then
element[action_name].visible = false 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 element[action_name].visible = true
end end
end end
@@ -205,36 +206,36 @@ end
--- Main player list container for the left flow --- Main player list container for the left flow
-- @element player_list_container -- @element player_list_container
local player_list_container = local player_list_container =
Gui.element(function(event_trigger,parent) Gui.element(function(event_trigger, parent)
-- Draw the internal container -- 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 -- 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 -- Change the style of the scroll table
local scroll_table_style = scroll_table.style 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 -- 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 -- Change the style of the action bar
local action_bar_style = action_bar.style local action_bar_style = action_bar.style
action_bar_style.height = 35 action_bar_style.height = 35
action_bar_style.padding = {1,3} action_bar_style.padding = {1, 3}
action_bar.visible = false action_bar.visible = false
-- Add the buttons to the action bar -- Add the buttons to the action bar
add_action_bar_buttons(action_bar) add_action_bar_buttons(action_bar)
-- Add the reason 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 -- Change the style of the reason bar
local reason_bar_style = reason_bar.style local reason_bar_style = reason_bar.style
reason_bar_style.height = 35 reason_bar_style.height = 35
reason_bar_style.padding = {-1,3} reason_bar_style.padding = {-1, 3}
reason_bar.visible = false reason_bar.visible = false
-- Add the text entry for the reason bar -- Add the text entry for the reason bar
@@ -263,15 +264,15 @@ end)
--- Button on the top flow used to toggle the player list container --- Button on the top flow used to toggle the player list container
-- @element toggle_left_element -- @element toggle_left_element
Gui.left_toolbar_button('entity/character', {'player-list.main-tooltip'}, player_list_container, function(player) 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) end)
-- Get caption and tooltip format for a player -- 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 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 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 return caption, tooltip
end end
@@ -297,20 +298,20 @@ end
local function get_player_list_order() local function get_player_list_order()
-- Sort all the online players into roles -- Sort all the online players into roles
local players = {} 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) local highest_role = Roles.get_player_highest_role(player)
if not players[highest_role.name] then if not players[highest_role.name] then
players[highest_role.name] = {} players[highest_role.name] = {}
end end
table.insert(players[highest_role.name],player) table.insert(players[highest_role.name], player)
end end
-- Sort the players from roles into a set order -- Sort the players from roles into a set order
local ctn = 0 local ctn = 0
local player_list_order = {} 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 if players[role_name] then
for _,player in pairs(players[role_name]) do for _, player in pairs(players[role_name]) do
ctn = ctn + 1 ctn = ctn + 1
-- Add the player data to the array -- Add the player data to the array
local caption, tooltip = get_time_formats(player.online_time, player.afk_time) local caption, tooltip = get_time_formats(player.online_time, player.afk_time)
@@ -329,8 +330,8 @@ local function get_player_list_order()
--[[Adds fake players to the player list --[[Adds fake players to the player list
for i = 1, 10 do for i = 1, 10 do
local online_time = math.random(1,tick) local online_time = math.random(1, tick)
local afk_time = math.random(online_time-(tick/10),tick) local afk_time = math.random(online_time-(tick/10), tick)
local caption, tooltip = get_time_formats(online_time, afk_time) local caption, tooltip = get_time_formats(online_time, afk_time)
player_list_order[ctn+i] = { player_list_order[ctn+i] = {
name='Player '..i, name='Player '..i,
@@ -347,29 +348,29 @@ local function get_player_list_order()
end end
--- Update the play times every 30 sections --- 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() local player_times = get_player_times()
for _,player in pairs(game.connected_players) do for _, player in pairs(game.connected_players) do
local frame = Gui.get_left_element(player,player_list_container) local frame = Gui.get_left_element(player, player_list_container)
local scroll_table = frame.container.scroll.table local scroll_table = frame.container.scroll.table
for _,player_time in pairs(player_times) do for _, player_time in pairs(player_times) do
update_player_base(scroll_table,player_time) update_player_base(scroll_table, player_time)
end end
end end
end) end)
--- When a player leaves only remove they entry --- When a player leaves only remove they entry
Event.add(defines.events.on_player_left_game,function(event) Event.add(defines.events.on_player_left_game, function(event)
local remove_player = Game.get_player_by_index(event.player_index) local remove_player = Game.get_player_by_index(event.player_index)
for _,player in pairs(game.connected_players) do for _, player in pairs(game.connected_players) do
local frame = Gui.get_left_element(player,player_list_container) local frame = Gui.get_left_element(player, player_list_container)
local scroll_table = frame.container.scroll.table 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 = Store.get(selected_player_store, player)
if selected_player_name == remove_player.name then if selected_player_name == remove_player.name then
Store.clear(selected_player_store,player) Store.clear(selected_player_store, player)
Store.clear(selected_action_store,player) Store.clear(selected_action_store, player)
end end
end end
end) end)
@@ -377,27 +378,27 @@ end)
--- All other events require a full redraw of the table --- All other events require a full redraw of the table
local function redraw_player_list() local function redraw_player_list()
local player_list_order = get_player_list_order() local player_list_order = get_player_list_order()
for _,player in pairs(game.connected_players) do for _, player in pairs(game.connected_players) do
local frame = Gui.get_left_element(player,player_list_container) local frame = Gui.get_left_element(player, player_list_container)
local scroll_table = frame.container.scroll.table local scroll_table = frame.container.scroll.table
scroll_table.clear() scroll_table.clear()
for _,next_player_data in ipairs(player_list_order) do for _, next_player_data in ipairs(player_list_order) do
add_player_base(scroll_table,next_player_data) add_player_base(scroll_table, next_player_data)
end end
end end
end end
Event.add(defines.events.on_player_joined_game,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_assigned, redraw_player_list)
Event.add(Roles.events.on_role_unassigned,redraw_player_list) Event.add(Roles.events.on_role_unassigned, redraw_player_list)
--- When the action player is changed the action bar will update --- When the action player is changed the action bar will update
Store.watch(selected_player_store,function(value,player_name) Store.watch(selected_player_store, function(value, player_name)
local player = Game.get_player_from_any(player_name) local player = Game.get_player_from_any(player_name)
local frame = Gui.get_left_element(player,player_list_container) local frame = Gui.get_left_element(player, player_list_container)
local scroll_table = frame.container.scroll.table local scroll_table = frame.container.scroll.table
update_action_bar(frame.container.action_bar) 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 element = scroll_table[next_player.name][open_action_bar.name]
local style = 'frame_button' local style = 'frame_button'
if next_player.name == value then if next_player.name == value then
@@ -412,20 +413,20 @@ Store.watch(selected_player_store,function(value,player_name)
end) end)
--- When the action name is changed the reason input will update --- When the action name is changed the reason input will update
Store.watch(selected_action_store,function(value,player_name) Store.watch(selected_action_store, function(value, player_name)
local player = Game.get_player_from_any(player_name) local player = Game.get_player_from_any(player_name)
local frame = Gui.get_left_element(player,player_list_container) local frame = Gui.get_left_element(player, player_list_container)
local element = frame.container.reason_bar local element = frame.container.reason_bar
if value then if value then
-- if there is a new value then check the player is still online -- 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_name = Store.get(selected_player_store, player_name)
local selected_player = Game.get_player_from_any(selected_player_name) local selected_player = Game.get_player_from_any(selected_player_name)
if selected_player.connected then if selected_player.connected then
element.visible = true element.visible = true
else else
-- Clear if the player is offline -- Clear if the player is offline
Store.clear(selected_player_store,player_name) Store.clear(selected_player_store, player_name)
Store.clear(selected_action_store,player_name) Store.clear(selected_action_store, player_name)
end end
else else

View File

@@ -12,7 +12,7 @@ local Game = require 'utils.game' --- @dep utils.game
local format_time = _C.format_time --- @dep expcore.common local format_time = _C.format_time --- @dep expcore.common
local tabs = {} local tabs = {}
local function Tab(caption,tooltip,element_define) local function Tab(caption, tooltip, element_define)
tabs[#tabs+1] = {caption, tooltip, element_define} tabs[#tabs+1] = {caption, tooltip, element_define}
end end
@@ -23,7 +23,7 @@ local scroll_hieght = 275 -- controls the height of the scrolls
--- Sub content area used within the content areas --- Sub content area used within the content areas
-- @element sub_content -- @element sub_content
local sub_content = local sub_content =
Gui.element(function(_,parent) Gui.element(function(_, parent)
return parent.add{ return parent.add{
type = 'frame', type = 'frame',
direction = 'vertical', direction = 'vertical',
@@ -38,7 +38,7 @@ end)
--- Table which has a title above it above it --- Table which has a title above it above it
-- @element title_table -- @element title_table
local 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) Gui.title_label(parent, bar_size, caption)
return parent.add{ return parent.add{
@@ -65,15 +65,15 @@ Gui.element{
style = 'scroll_pane_under_subheader' style = 'scroll_pane_under_subheader'
} }
:style{ :style{
padding = {1,3}, padding = {1, 3},
maximal_height = scroll_hieght, maximal_height = scroll_hieght,
horizontally_stretchable = true, horizontally_stretchable = true,
} }
--- Content area for the welcome tab --- Content area for the welcome tab
-- @element welcome_content -- @element welcome_content
Tab({'readme.welcome-tab'},{'readme.welcome-tooltip'}, Tab({'readme.welcome-tab'}, {'readme.welcome-tooltip'},
Gui.element(function(_,parent) 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'} 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'}
local container = parent.add{ type='flow', direction='vertical' } local container = parent.add{ type='flow', direction='vertical' }
local player = Gui.get_player_from_element(parent) local player = Gui.get_player_from_element(parent)
@@ -93,15 +93,15 @@ Gui.element(function(_,parent)
-- Get the names of the roles the player has -- Get the names of the roles the player has
local player_roles = Roles.get_player_roles(player) local player_roles = Roles.get_player_roles(player)
local role_names = {} local role_names = {}
for i,role in ipairs(player_roles) do for i, role in ipairs(player_roles) do
role_names[i] = role.name role_names[i] = role.name
end end
-- Add the other information to the gui -- Add the other information to the gui
container.add{ type='flow' }.style.height = 4 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-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'}) Gui.centered_label(sub_content(container), frame_width, {'readme.welcome-chat'})
return container return container
@@ -109,8 +109,8 @@ end))
--- Content area for the rules tab --- Content area for the rules tab
-- @element rules_content -- @element rules_content
Tab({'readme.rules-tab'},{'readme.rules-tooltip'}, Tab({'readme.rules-tab'}, {'readme.rules-tooltip'},
Gui.element(function(_,parent) Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' } local container = parent.add{ type='flow', direction='vertical' }
-- Add the title and description to the content -- Add the title and description to the content
@@ -125,7 +125,7 @@ Gui.element(function(_,parent)
rules.style.cell_padding = 4 rules.style.cell_padding = 4
-- Add the rules to the table -- Add the rules to the table
for i = 1,15 do for i = 1, 15 do
Gui.centered_label(rules, 565, {'readme.rules-'..i}) Gui.centered_label(rules, 565, {'readme.rules-'..i})
end end
@@ -134,8 +134,8 @@ end))
--- Content area for the commands tab --- Content area for the commands tab
-- @element commands_content -- @element commands_content
Tab({'readme.commands-tab'},{'readme.commands-tooltip'}, Tab({'readme.commands-tab'}, {'readme.commands-tooltip'},
Gui.element(function(_,parent) Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' } local container = parent.add{ type='flow', direction='vertical' }
local player = Gui.get_player_from_element(parent) local player = Gui.get_player_from_element(parent)
@@ -151,7 +151,7 @@ Gui.element(function(_,parent)
commands.style.cell_padding = 0 commands.style.cell_padding = 0
-- Add the rules to the table -- 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, 120, name)
Gui.centered_label(commands, 450, command.help) Gui.centered_label(commands, 450, command.help)
end end
@@ -161,8 +161,8 @@ end))
--- Content area for the servers tab --- Content area for the servers tab
-- @element servers_content -- @element servers_content
Tab({'readme.servers-tab'},{'readme.servers-tooltip'}, Tab({'readme.servers-tab'}, {'readme.servers-tooltip'},
Gui.element(function(_,parent) Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' } local container = parent.add{ type='flow', direction='vertical' }
-- Add the title and description to the content -- Add the title and description to the content
@@ -177,14 +177,14 @@ Gui.element(function(_,parent)
-- Add the factorio servers -- Add the factorio servers
local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 2) local factorio_servers = title_table(scroll_pane, 225, {'readme.servers-factorio'}, 2)
for i = 1,8 do for i = 1, 8 do
Gui.centered_label(factorio_servers, 110, {'readme.servers-'..i}) Gui.centered_label(factorio_servers, 110, {'readme.servers-'..i})
Gui.centered_label(factorio_servers, 460, {'readme.servers-d'..i}) Gui.centered_label(factorio_servers, 460, {'readme.servers-d'..i})
end end
-- Add the external links -- Add the external links
local external_links = title_table(scroll_pane, 235, {'readme.servers-external'}, 2) 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
Gui.centered_label(external_links, 110, key:gsub("^%l", string.upper)) Gui.centered_label(external_links, 110, key:gsub("^%l", string.upper))
Gui.centered_label(external_links, 460, {'links.'..key}, {'readme.servers-open-in-browser'}) Gui.centered_label(external_links, 460, {'links.'..key}, {'readme.servers-open-in-browser'})
end end
@@ -194,8 +194,8 @@ end))
--- Content area for the servers tab --- Content area for the servers tab
-- @element backers_content -- @element backers_content
Tab({'readme.backers-tab'},{'readme.backers-tooltip'}, Tab({'readme.backers-tab'}, {'readme.backers-tooltip'},
Gui.element(function(_,parent) Gui.element(function(_, parent)
local container = parent.add{ type='flow', direction='vertical' } local container = parent.add{ type='flow', direction='vertical' }
-- Add the title and description to the content -- Add the title and description to the content
@@ -207,10 +207,10 @@ Gui.element(function(_,parent)
-- Find which players will go where -- Find which players will go where
local done = {} local done = {}
local groups = { local groups = {
{ _roles={'Senior Administrator','Administrator'}, _title={'readme.backers-management'}, _width=230 }, { _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={'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={'Sponsor', 'Supporter'}, _title={'readme.backers-backers'}, _width=196 }, -- change to backer
{ _roles={'Moderator','Trainee'}, _title={'readme.backers-staff'}, _width=235 }, { _roles={'Moderator', 'Trainee'}, _title={'readme.backers-staff'}, _width=235 },
{ _roles={}, _time=3*3600*60, _title={'readme.backers-active'}, _width=235 }, { _roles={}, _time=3*3600*60, _title={'readme.backers-active'}, _width=235 },
} }
@@ -242,12 +242,12 @@ Gui.element(function(_,parent)
local scroll_pane = title_table_scroll(container) local scroll_pane = title_table_scroll(container)
for _, players in ipairs(groups) do for _, players in ipairs(groups) do
local table = title_table(scroll_pane, players._width, players._title, 4) 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) Gui.centered_label(table, 140, player_name)
end end
if #players < 4 then if #players < 4 then
for i = 1,4-#players do for i = 1, 4-#players do
Gui.centered_label(table, 140) Gui.centered_label(table, 140)
end end
end end
@@ -260,7 +260,7 @@ end))
-- @element readme -- @element readme
local readme_toggle local readme_toggle
local readme = local readme =
Gui.element(function(event_trigger,parent) Gui.element(function(event_trigger, parent)
local container = parent.add{ local container = parent.add{
name = event_trigger, name = event_trigger,
type = 'frame', type = 'frame',
@@ -269,7 +269,7 @@ Gui.element(function(event_trigger,parent)
-- Add the left hand side of the frame back, removed because of frame_tabbed_pane style -- 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') 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 = local left_side =
left_alignment.add{ left_alignment.add{
@@ -288,7 +288,7 @@ Gui.element(function(event_trigger,parent)
} }
-- Add the different content areas -- 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] } 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)) tab_pane.add_tab(tab, tab_details[3](tab_pane))
end end
@@ -299,7 +299,7 @@ end)
local toggle_button = Gui.get_top_element(player, readme_toggle) local toggle_button = Gui.get_top_element(player, readme_toggle)
Gui.toolbar_button_style(toggle_button, true) Gui.toolbar_button_style(toggle_button, true)
end) end)
:on_close(function(player,element) :on_close(function(player, element)
local toggle_button = Gui.get_top_element(player, readme_toggle) local toggle_button = Gui.get_top_element(player, readme_toggle)
Gui.toolbar_button_style(toggle_button, false) Gui.toolbar_button_style(toggle_button, false)
Gui.destroy_if_valid(element) Gui.destroy_if_valid(element)
@@ -308,10 +308,10 @@ end)
--- Toggle button for the readme gui --- Toggle button for the readme gui
-- @element readme_toggle -- @element readme_toggle
readme_toggle = readme_toggle =
Gui.toolbar_button('virtual-signal/signal-info',{'readme.main-tooltip'},function(player) Gui.toolbar_button('virtual-signal/signal-info', {'readme.main-tooltip'}, function(player)
return Roles.player_allowed(player,'gui/readme') return Roles.player_allowed(player, 'gui/readme')
end) end)
:on_click(function(player,_) :on_click(function(player, _)
local center = player.gui.center local center = player.gui.center
if center[readme.name] then if center[readme.name] then
player.opened = nil player.opened = nil
@@ -321,7 +321,7 @@ end)
end) end)
--- When a player joins the game for the first time show this gui --- When a player joins the game for the first time show this gui
Event.add(defines.events.on_player_created,function(event) Event.add(defines.events.on_player_created, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local element = readme(player.gui.center) local element = readme(player.gui.center)
element.pane.selected_tab_index = 1 element.pane.selected_tab_index = 1
@@ -329,7 +329,7 @@ Event.add(defines.events.on_player_created,function(event)
end) end)
--- When a player joins clear center unless the player has something open --- When a player joins clear center unless the player has something open
Event.add(defines.events.on_player_joined_game,function(event) Event.add(defines.events.on_player_joined_game, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
if not player.opened then if not player.opened then
player.gui.center.clear() player.gui.center.clear()
@@ -337,7 +337,7 @@ Event.add(defines.events.on_player_joined_game,function(event)
end) end)
--- When a player respawns clear center unless the player has something open --- When a player respawns clear center unless the player has something open
Event.add(defines.events.on_player_respawned,function(event) Event.add(defines.events.on_player_respawned, function(event)
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
if not player.opened then if not player.opened then
player.gui.center.clear() player.gui.center.clear()

View File

@@ -20,7 +20,7 @@ local time_formats = {
} }
--- Check if a player is allowed to use certain interactions --- 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 if not config.progress['allow_'..action] then
return false return false
end end
@@ -30,7 +30,7 @@ local function check_player_permissions(player,action)
end end
if config.progress[action..'_role_permission'] 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 return false
end end
@@ -46,7 +46,7 @@ Gui.element{
tooltip = {'rocket-info.toggle-rocket-tooltip'} tooltip = {'rocket-info.toggle-rocket-tooltip'}
} }
:style(Gui.sprite_style(16)) :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_name = element.parent.name:sub(8)
local rocket_silo = Rockets.get_silo_entity(rocket_silo_name) local rocket_silo = Rockets.get_silo_entity(rocket_silo_name)
if rocket_silo.auto_launch then if rocket_silo.auto_launch then
@@ -68,21 +68,21 @@ Gui.element{
sprite = 'utility/center', sprite = 'utility/center',
tooltip = {'rocket-info.launch-tooltip'} tooltip = {'rocket-info.launch-tooltip'}
} }
:style(Gui.sprite_style(16,-1)) :style(Gui.sprite_style(16, -1))
:on_click(function(player,element,_) :on_click(function(player, element, _)
local rocket_silo_name = element.parent.name:sub(8) local rocket_silo_name = element.parent.name:sub(8)
local silo_data = Rockets.get_silo_data_by_name(rocket_silo_name) local silo_data = Rockets.get_silo_data_by_name(rocket_silo_name)
if silo_data.entity.launch_rocket() then if silo_data.entity.launch_rocket() then
element.enabled = false element.enabled = false
else else
player.print({'rocket-info.launch-failed'},Colors.orange_red) player.print({'rocket-info.launch-failed'}, Colors.orange_red)
end end
end) end)
--- XY cords that allow zoom to map when pressed --- XY cords that allow zoom to map when pressed
-- @element silo_cords -- @element silo_cords
local 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 silo_name = silo_data.silo_name
local pos = silo_data.position local pos = silo_data.position
local name = config.progress.allow_zoom_to_map and event_trigger or nil 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, name = 'label-x-'..silo_name,
caption = 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 -- Add the x cord label
flow_x.add{ flow_x.add{
type = 'label', type = 'label',
name = name, name = name,
caption = {'rocket-info.progress-x-pos',pos.x}, caption = {'rocket-info.progress-x-pos', pos.x},
tooltip = tooltip tooltip = tooltip
} }
@@ -110,32 +110,32 @@ Gui.element(function(event_trigger,parent,silo_data)
name = 'label-y-'..silo_name, name = 'label-y-'..silo_name,
caption = 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 -- Add the y cord label
flow_y.add{ flow_y.add{
type = 'label', type = 'label',
name = name, name = name,
caption = {'rocket-info.progress-y-pos',pos.y}, caption = {'rocket-info.progress-y-pos', pos.y},
tooltip = tooltip tooltip = tooltip
} }
end) end)
:on_click(function(player,element,_) :on_click(function(player, element, _)
local rocket_silo_name = element.parent.caption local rocket_silo_name = element.parent.caption
local rocket_silo = Rockets.get_silo_entity(rocket_silo_name) 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) end)
--- Base element for each rocket in the progress list --- Base element for each rocket in the progress list
-- @element rocket_entry -- @element rocket_entry
local 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 silo_name = silo_data.silo_name
local player = Gui.get_player_from_element(parent) local player = Gui.get_player_from_element(parent)
-- Add the toggle auto launch if the player is allowed it -- 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 flow = parent.add{ type = 'flow', name = 'toggle-'..silo_name}
local button = toggle_launch(flow) local button = toggle_launch(flow)
button.tooltip = silo_data.toggle_tooltip button.tooltip = silo_data.toggle_tooltip
@@ -143,17 +143,17 @@ Gui.element(function(_,parent,silo_data)
end end
-- Add the remote launch if the player is allowed it -- 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 flow = parent.add{ type = 'flow', name = 'launch-'..silo_name}
local button = launch_rocket(flow) local button = launch_rocket(flow)
button.enabled = silo_data.allow_launch button.enabled = silo_data.allow_launch
end end
-- Draw the silo cords element -- Draw the silo cords element
silo_cords(parent,silo_data) silo_cords(parent, silo_data)
-- Add a progress label -- Add a progress label
local alignment = Gui.alignment(parent,silo_name) local alignment = Gui.alignment(parent, silo_name)
local element = local element =
alignment.add{ alignment.add{
type = 'label', type = 'label',
@@ -169,7 +169,7 @@ end)
--- Data label which contains a name and a value label pair --- Data label which contains a name and a value label pair
-- @element data_label -- @element data_label
local 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_name = label_data.name
local data_subname = label_data.subname local data_subname = label_data.subname
local data_fullname = data_subname and data_name..data_subname or data_name 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{ local name_label = parent.add{
type = 'label', type = 'label',
name = data_fullname..'-label', name = data_fullname..'-label',
caption = {'rocket-info.data-caption-'..data_name,data_subname}, caption = {'rocket-info.data-caption-'..data_name, data_subname},
tooltip = {'rocket-info.data-tooltip-'..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 --- Right aligned label to store the data
local alignment = Gui.alignment(parent,data_fullname) local alignment = Gui.alignment(parent, data_fullname)
local element = local element =
alignment.add{ alignment.add{
type = 'label', type = 'label',
@@ -192,17 +192,17 @@ Gui.element(function(_,parent,label_data)
caption = label_data.value, caption = label_data.value,
tooltip = label_data.tooltip tooltip = label_data.tooltip
} }
element.style.padding = {0,2} element.style.padding = {0, 2}
return element return element
end) end)
-- Used to update the captions and tooltips on the data labels -- 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 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 local data_name = label_data.subname and label_data.name..label_data.subname or label_data.name
if not parent[data_name] then if not parent[data_name] then
data_label(parent,label_data) data_label(parent, label_data)
else else
local data_label_element = parent[data_name].label local data_label_element = parent[data_name].label
data_label_element.tooltip = label_data.tooltip 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 if not rocket_silo or not rocket_silo.valid then
-- Remove from list if not valid -- Remove from list if not valid
force_silos[silo_data.name] = nil force_silos[silo_data.name] = nil
table.insert(progress_data,{ table.insert(progress_data, {
silo_name = silo_data.name, silo_name = silo_data.name,
remove = true remove = true
}) })
@@ -228,14 +228,14 @@ local function get_progress_data(force_name)
else else
-- Get the progress caption and tooltip -- Get the progress caption and tooltip
local progress_color = Colors.white local progress_color = Colors.white
local progress_caption = {'rocket-info.progress-caption',rocket_silo.rocket_parts} 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_tooltip = {'rocket-info.progress-tooltip', silo_data.launched or 0}
local status = rocket_silo.status == defines.entity_status.waiting_to_launch_rocket local status = rocket_silo.status == defines.entity_status.waiting_to_launch_rocket
if status and silo_data.awaiting_reset then if status and silo_data.awaiting_reset then
progress_caption = {'rocket-info.progress-launched'} progress_caption = {'rocket-info.progress-launched'}
progress_color = Colors.green progress_color = Colors.green
elseif status then elseif status then
progress_caption = {'rocket-info.progress-caption',100} progress_caption = {'rocket-info.progress-caption', 100}
progress_color = Colors.cyan progress_color = Colors.cyan
else else
silo_data.awaiting_reset = false silo_data.awaiting_reset = false
@@ -250,7 +250,7 @@ local function get_progress_data(force_name)
end end
-- Insert the gui data -- Insert the gui data
table.insert(progress_data,{ table.insert(progress_data, {
silo_name = silo_data.name, silo_name = silo_data.name,
position = rocket_silo.position, position = rocket_silo.position,
allow_launch = not silo_data.awaiting_reset and status or false, allow_launch = not silo_data.awaiting_reset and status or false,
@@ -267,7 +267,7 @@ local function get_progress_data(force_name)
end end
--- Update the build progress section --- 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 local show_message = true
for _, silo_data in ipairs(progress_data) do for _, silo_data in ipairs(progress_data) do
parent.parent.no_silos.visible = false parent.parent.no_silos.visible = false
@@ -285,7 +285,7 @@ local function update_build_progress(parent,progress_data)
elseif not progress_label then elseif not progress_label then
-- Add the rocket to the list -- Add the rocket to the list
show_message = false show_message = false
rocket_entry(parent,silo_data) rocket_entry(parent, silo_data)
else else
show_message = false show_message = false
@@ -323,7 +323,7 @@ local function get_stats_data(force_name)
-- Format the first launch data -- Format the first launch data
if config.stats.show_first_rocket then if config.stats.show_first_rocket then
local value = stats.first_launch or 0 local value = stats.first_launch or 0
table.insert(stats_data,{ table.insert(stats_data, {
name = 'first-launch', name = 'first-launch',
value = time_formats.caption_hours(value), value = time_formats.caption_hours(value),
tooltip = time_formats.tooltip_hours(value) tooltip = time_formats.tooltip_hours(value)
@@ -333,7 +333,7 @@ local function get_stats_data(force_name)
-- Format the last launch data -- Format the last launch data
if config.stats.show_last_rocket then if config.stats.show_last_rocket then
local value = stats.last_launch or 0 local value = stats.last_launch or 0
table.insert(stats_data,{ table.insert(stats_data, {
name = 'last-launch', name = 'last-launch',
value = time_formats.caption_hours(value), value = time_formats.caption_hours(value),
tooltip = time_formats.tooltip_hours(value) tooltip = time_formats.tooltip_hours(value)
@@ -343,7 +343,7 @@ local function get_stats_data(force_name)
-- Format fastest launch data -- Format fastest launch data
if config.stats.show_fastest_rocket then if config.stats.show_fastest_rocket then
local value = stats.fastest_launch or 0 local value = stats.fastest_launch or 0
table.insert(stats_data,{ table.insert(stats_data, {
name = 'fastest-launch', name = 'fastest-launch',
value = time_formats.caption_hours(value), value = time_formats.caption_hours(value),
tooltip = time_formats.tooltip_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 if config.stats.show_total_rockets then
local total_rockets = Rockets.get_game_rocket_count() local total_rockets = Rockets.get_game_rocket_count()
total_rockets = total_rockets == 0 and 1 or total_rockets total_rockets = total_rockets == 0 and 1 or total_rockets
local percentage = math.round(force_rockets/total_rockets,3)*100 local percentage = math.round(force_rockets/total_rockets, 3)*100
table.insert(stats_data,{ table.insert(stats_data, {
name = 'total-rockets', name = 'total-rockets',
value = force_rockets, value = force_rockets,
tooltip = {'rocket-info.value-tooltip-total-rockets',percentage} tooltip = {'rocket-info.value-tooltip-total-rockets', percentage}
}) })
end end
-- Format game avg data -- Format game avg data
if config.stats.show_game_avg then if config.stats.show_game_avg then
local avg = force_rockets > 0 and math.floor(game.tick/force_rockets) or 0 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', name = 'avg-launch',
value = time_formats.caption(avg), value = time_formats.caption(avg),
tooltip = time_formats.tooltip(avg) tooltip = time_formats.tooltip(avg)
@@ -373,9 +373,9 @@ local function get_stats_data(force_name)
end end
-- Format rolling avg data -- Format rolling avg data
for _,avg_over in pairs(config.stats.rolling_avg) do for _, avg_over in pairs(config.stats.rolling_avg) do
local avg = Rockets.get_rolling_average(force_name,avg_over) local avg = Rockets.get_rolling_average(force_name, avg_over)
table.insert(stats_data,{ table.insert(stats_data, {
name = 'avg-launch-n', name = 'avg-launch-n',
subname = avg_over, subname = avg_over,
value = time_formats.caption(avg), 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 force_rockets = Rockets.get_rocket_count(force_name)
local milestone_data = {} local milestone_data = {}
for _,milestone in ipairs(config.milestones) do for _, milestone in ipairs(config.milestones) do
if milestone <= force_rockets then if milestone <= force_rockets then
local time = Rockets.get_rocket_time(force_name,milestone) local time = Rockets.get_rocket_time(force_name, milestone)
table.insert(milestone_data,{ table.insert(milestone_data, {
name = 'milestone-n', name = 'milestone-n',
subname = milestone, subname = milestone,
value = time_formats.caption_hours(time), value = time_formats.caption_hours(time),
tooltip = time_formats.tooltip_hours(time) tooltip = time_formats.tooltip_hours(time)
}) })
else else
table.insert(milestone_data,{ table.insert(milestone_data, {
name = 'milestone-n', name = 'milestone-n',
subname = milestone, subname = milestone,
value = {'rocket-info.data-caption-milestone-next'}, value = {'rocket-info.data-caption-milestone-next'},
@@ -425,7 +425,7 @@ Gui.element{
tooltip = {'rocket-info.toggle-section-tooltip'} tooltip = {'rocket-info.toggle-section-tooltip'}
} }
:style(Gui.sprite_style(20)) :style(Gui.sprite_style(20))
:on_click(function(_,element,_) :on_click(function(_, element, _)
local header_flow = element.parent local header_flow = element.parent
local flow_name = header_flow.caption local flow_name = header_flow.caption
local flow = header_flow.parent.parent[flow_name] local flow = header_flow.parent.parent[flow_name]
@@ -443,7 +443,7 @@ end)
-- Draw a section header and main scroll -- Draw a section header and main scroll
-- @element rocket_list_container -- @element rocket_list_container
local section = local section =
Gui.element(function(_,parent,section_name,table_size) Gui.element(function(_, parent, section_name, table_size)
-- Draw the header for the section -- Draw the header for the section
local header = Gui.header( local header = Gui.header(
parent, parent,
@@ -458,7 +458,7 @@ Gui.element(function(_,parent,section_name,table_size)
toggle_section(header) toggle_section(header)
-- Table used to store the data -- 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 scroll_table.parent.visible = false
-- Return the flow table -- Return the flow table
@@ -468,9 +468,9 @@ end)
--- Main gui container for the left flow --- Main gui container for the left flow
-- @element rocket_list_container -- @element rocket_list_container
local rocket_list_container = local rocket_list_container =
Gui.element(function(event_trigger,parent) Gui.element(function(event_trigger, parent)
-- Draw the internal container -- Draw the internal container
local container = Gui.container(parent,event_trigger,200) local container = Gui.container(parent, event_trigger, 200)
-- Set the container style -- Set the container style
local style = container.style local style = container.style
@@ -480,27 +480,27 @@ Gui.element(function(event_trigger,parent)
local force_name = player.force.name local force_name = player.force.name
-- Draw stats section -- Draw stats section
if config.stats.show_stats then 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 end
-- Draw milestones section -- Draw milestones section
if config.milestones.show_milestones then 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 end
-- Draw build progress list -- Draw build progress list
if config.progress.show_progress then if config.progress.show_progress then
local col_count = 3 local col_count = 3
if check_player_permissions(player,'remote_launch') 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 if check_player_permissions(player, 'toggle_active') then col_count = col_count+1 end
local progress = section(container,'progress',col_count) local progress = section(container, 'progress', col_count)
-- Label used when there are no active silos -- Label used when there are no active silos
local no_silos = progress.parent.add{ local no_silos = progress.parent.add{
type = 'label', type = 'label',
name = 'no_silos', name = 'no_silos',
caption = {'rocket-info.progress-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)) update_build_progress(progress, get_progress_data(force_name))
end end
@@ -508,13 +508,13 @@ Gui.element(function(event_trigger,parent)
return container.parent return container.parent
end) end)
:add_to_left_flow(function(player) :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) end)
--- Button on the top flow used to toggle the container --- Button on the top flow used to toggle the container
-- @element toggle_left_element -- @element toggle_left_element
Gui.left_toolbar_button('entity/rocket-silo', {'rocket-info.main-tooltip'}, rocket_list_container, function(player) Gui.left_toolbar_button('entity/rocket-silo', {'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) end)
--- Update the gui for all players on a force --- Update the gui for all players on a force
@@ -522,21 +522,21 @@ local function update_rocket_gui_all(force_name)
local stats = get_stats_data(force_name) local stats = get_stats_data(force_name)
local milestones = get_milestone_data(force_name) local milestones = get_milestone_data(force_name)
local progress = get_progress_data(force_name) local progress = get_progress_data(force_name)
for _,player in pairs(game.forces[force_name].players) do for _, player in pairs(game.forces[force_name].players) do
local frame = Gui.get_left_element(player,rocket_list_container) local frame = Gui.get_left_element(player, rocket_list_container)
local container = frame.container local container = frame.container
update_data_labels(container.stats.table,stats) update_data_labels(container.stats.table, stats)
update_data_labels(container.milestones.table,milestones) update_data_labels(container.milestones.table, milestones)
update_build_progress(container.progress.table,progress) update_build_progress(container.progress.table, progress)
end end
end end
--- Event used to update the stats when a rocket is launched --- 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 local force = event.rocket_silo.force
update_rocket_gui_all(force.name) update_rocket_gui_all(force.name)
if force.rockets_launched == 1 then if force.rockets_launched == 1 then
for _,player in pairs(force.players) do for _, player in pairs(force.players) do
Gui.update_top_flow(player) Gui.update_top_flow(player)
end end
end end
@@ -545,23 +545,23 @@ end)
--- Update only the progress gui for a force --- Update only the progress gui for a force
local function update_rocket_gui_progress(force_name) local function update_rocket_gui_progress(force_name)
local progress = get_progress_data(force_name) local progress = get_progress_data(force_name)
for _,player in pairs(game.forces[force_name].players) do for _, player in pairs(game.forces[force_name].players) do
local frame = Gui.get_left_element(player,rocket_list_container) local frame = Gui.get_left_element(player, rocket_list_container)
local container = frame.container local container = frame.container
update_build_progress(container.progress.table,progress) update_build_progress(container.progress.table, progress)
end end
end end
--- Event used to set a rocket silo to be awaiting reset --- 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 = event.rocket_silo
local silo_data = Rockets.get_silo_data(silo) local silo_data = Rockets.get_silo_data(silo)
silo_data.awaiting_reset = true silo_data.awaiting_reset = true
update_rocket_gui_progress(silo.force.name) update_rocket_gui_progress(silo.force.name)
end) end)
Event.on_nth_tick(150,function() Event.on_nth_tick(150, function()
for _,force in pairs(game.forces) do for _, force in pairs(game.forces) do
if #Rockets.get_silos(force.name) > 0 then if #Rockets.get_silos(force.name) > 0 then
update_rocket_gui_progress(force.name) update_rocket_gui_progress(force.name)
end end
@@ -576,20 +576,20 @@ local function on_built(event)
end end
end end
Event.add(defines.events.on_built_entity,on_built) Event.add(defines.events.on_built_entity, on_built)
Event.add(defines.events.on_robot_built_entity,on_built) Event.add(defines.events.on_robot_built_entity, on_built)
--- Redraw the progress section on role change --- Redraw the progress section on role change
local function role_update_event(event) local function role_update_event(event)
if not config.progress.show_progress then return end if not config.progress.show_progress then return end
local player = game.players[event.player_index] 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 local progress_scroll = container.progress
Gui.destroy_if_valid(progress_scroll.table) Gui.destroy_if_valid(progress_scroll.table)
local col_count = 3 local col_count = 3
if check_player_permissions(player,'remote_launch') 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 if check_player_permissions(player, 'toggle_active') then col_count = col_count+1 end
local progress = progress_scroll.add{ local progress = progress_scroll.add{
type = 'table', type = 'table',
name = 'table', name = 'table',
@@ -599,7 +599,7 @@ local function role_update_event(event)
update_build_progress(progress, get_progress_data(player.force.name)) update_build_progress(progress, get_progress_data(player.force.name))
end end
Event.add(Roles.events.on_role_assigned,role_update_event) 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_unassigned, role_update_event)
return rocket_list_container return rocket_list_container

View File

@@ -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 Production = require 'modules.control.production' --- @dep modules.control.production
local format_time = _C.format_time --- @dep expcore.common 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_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_long = format_time(0, {hours=true, minutes=true, seconds=true, long=true, null=true})
--- Data label that contains the value and the surfix --- Data label that contains the value and the surfix
-- @element production_label -- @element production_label
local 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 name = production_label_data.name
local tooltip = production_label_data.tooltip local tooltip = production_label_data.tooltip
local color = production_label_data.color local color = production_label_data.color
-- Add an alignment for the number -- Add an alignment for the number
local alignment = Gui.alignment(parent,name) local alignment = Gui.alignment(parent, name)
-- Add the main value label -- Add the main value label
local element = local element =
@@ -42,7 +42,7 @@ Gui.element(function(_,parent,production_label_data)
parent.add{ parent.add{
name = 'surfix-'..name, name = 'surfix-'..name,
type = 'label', type = 'label',
caption = {'science-info.unit',production_label_data.surfix}, caption = {'science-info.unit', production_label_data.surfix},
tooltip = tooltip tooltip = tooltip
} }
@@ -56,9 +56,9 @@ Gui.element(function(_,parent,production_label_data)
end) end)
-- Get the data that is used with the production label -- Get the data that is used with the production label
local function get_production_label_data(name,tooltip,value,secondary) local function get_production_label_data(name, tooltip, value, secondary)
local data_colour = Production.get_color(config.color_clamp, value, secondary) local data_colour = Production.get_color(config.color_clamp, value, secondary)
local surfix,caption = Production.format_number(value) local surfix, caption = Production.format_number(value)
return { return {
name = name, name = name,
@@ -70,20 +70,20 @@ local function get_production_label_data(name,tooltip,value,secondary)
end end
-- Updates a prodution label to match the current data -- 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 name = production_label_data.name
local tooltip = production_label_data.tooltip local tooltip = production_label_data.tooltip
local color = production_label_data.color local color = production_label_data.color
-- Update the production label -- 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.caption = production_label_data.caption
production_label_element.tooltip = production_label_data.tooltip production_label_element.tooltip = production_label_data.tooltip
production_label_element.style.font_color = color production_label_element.style.font_color = color
-- Update the surfix label -- Update the surfix label
local surfix_element = parent['surfix-'..name] 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.tooltip = tooltip
surfix_element.style.font_color = color surfix_element.style.font_color = color
@@ -92,7 +92,7 @@ end
--- Adds 4 elements that show the data for a science pack --- Adds 4 elements that show the data for a science pack
-- @element science_pack_base -- @element science_pack_base
local 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 local science_pack = science_pack_data.science_pack
-- Draw the icon for the science pack -- Draw the icon for the science pack
@@ -110,7 +110,7 @@ Gui.element(function(_,parent,science_pack_data)
local pack_icon_style = pack_icon.style local pack_icon_style = pack_icon.style
pack_icon_style.height = 55 pack_icon_style.height = 55
if icon_style == 'quick_bar_slot_button' then if icon_style == 'quick_bar_slot_button' then
pack_icon_style.padding = {0,-2} pack_icon_style.padding = {0, -2}
pack_icon_style.width = 36 pack_icon_style.width = 36
end end
@@ -121,7 +121,7 @@ Gui.element(function(_,parent,science_pack_data)
type = 'frame', type = 'frame',
style = 'bordered_frame' style = 'bordered_frame'
} }
delta_flow.style.padding = {0,3} delta_flow.style.padding = {0, 3}
-- Draw the delta flow table -- Draw the delta flow table
local delta_table = local delta_table =
@@ -133,15 +133,15 @@ Gui.element(function(_,parent,science_pack_data)
delta_table.style.padding = 0 delta_table.style.padding = 0
-- Draw the production labels -- Draw the production labels
update_production_label(delta_table,science_pack_data.positive) update_production_label(delta_table, science_pack_data.positive)
update_production_label(delta_table,science_pack_data.negative) update_production_label(delta_table, science_pack_data.negative)
update_production_label(parent,science_pack_data.net) update_production_label(parent, science_pack_data.net)
-- Return the pack icon -- Return the pack icon
return pack_icon return pack_icon
end) end)
local function get_science_pack_data(player,science_pack) local function get_science_pack_data(player, science_pack)
local force = player.force local force = player.force
-- Check that some packs have been made -- Check that some packs have been made
@@ -186,28 +186,28 @@ local function get_science_pack_data(player,science_pack)
end 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 if not science_pack_data then return end
local science_pack = science_pack_data.science_pack local science_pack = science_pack_data.science_pack
pack_table.parent.non_made.visible = false pack_table.parent.non_made.visible = false
-- Update the icon -- 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 local icon_style = science_pack_data.icon_style
pack_icon.style = icon_style pack_icon.style = icon_style
local pack_icon_style = pack_icon.style local pack_icon_style = pack_icon.style
pack_icon_style.height = 55 pack_icon_style.height = 55
if icon_style == 'quick_bar_slot_button' then if icon_style == 'quick_bar_slot_button' then
pack_icon_style.padding = {0,-2} pack_icon_style.padding = {0, -2}
pack_icon_style.width = 36 pack_icon_style.width = 36
end end
-- Update the production labels -- Update the production labels
local delta_table = pack_table['delta-'..science_pack].table 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.positive)
update_production_label(delta_table,science_pack_data.negative) update_production_label(delta_table, science_pack_data.negative)
update_production_label(pack_table,science_pack_data.net) update_production_label(pack_table, science_pack_data.net)
end end
@@ -226,7 +226,7 @@ local function get_eta_label_data(player)
local remaining = research.research_unit_count*(1-progress) local remaining = research.research_unit_count*(1-progress)
-- Check for the limiting science pack -- 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 pack_name = ingredient.name
local required = ingredient.amount * remaining local required = ingredient.amount * remaining
local time = Production.get_consumsion_eta(force, pack_name, defines.flow_precision_index.one_minute, required) 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 the caption and tooltip
return limit and limit > 0 and { return limit and limit > 0 and {
research = true, research = true,
caption = format_time(limit,{hours=true,minutes=true,seconds=true,time=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}) tooltip = format_time(limit, {hours=true, minutes=true, seconds=true, long=true})
} or { research = false } } or { research = false }
end end
-- Updates the eta label -- 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 no research selected show null
if not eta_label_data.research then if not eta_label_data.research then
element.caption = null_time_short element.caption = null_time_short
@@ -254,24 +254,24 @@ local function update_eta_label(element,eta_label_data)
end end
-- Update the element -- 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 element.tooltip = eta_label_data.tooltip
end end
--- Main task list container for the left flow --- Main task list container for the left flow
-- @element task_list_container -- @element task_list_container
local science_info_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) local player = Gui.get_player_from_element(parent)
-- Draw the internal container -- Draw the internal container
local container = Gui.container(parent,event_trigger,200) local container = Gui.container(parent, event_trigger, 200)
-- Draw the header -- Draw the header
Gui.header(container, {'science-info.main-caption'}, {'science-info.main-tooltip'}) Gui.header(container, {'science-info.main-caption'}, {'science-info.main-tooltip'})
-- Draw the scroll table for the tasks -- 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 -- Draw the no packs label
local 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 -- Change the style of the no packs label
local no_packs_style = no_packs_label.style 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.single_line = false
no_packs_style.width = 200 no_packs_style.width = 200
@@ -303,13 +303,13 @@ Gui.element(function(event_trigger,parent)
} }
-- Update the eta -- Update the eta
update_eta_label(eta_label,get_eta_label_data(player)) update_eta_label(eta_label, get_eta_label_data(player))
end end
-- Add packs which have been made -- Add packs which have been made
for _,science_pack in ipairs(config) do for _, science_pack in ipairs(config) do
update_science_pack(scroll_table,get_science_pack_data(player,science_pack)) update_science_pack(scroll_table, get_science_pack_data(player, science_pack))
end end
-- Return the exteral container -- Return the exteral container
@@ -320,16 +320,16 @@ end)
--- Button on the top flow used to toggle the task list container --- Button on the top flow used to toggle the task list container
-- @element toggle_left_element -- @element toggle_left_element
Gui.left_toolbar_button('entity/lab', {'science-info.main-tooltip'}, science_info_container, function(player) 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) end)
--- Updates the gui every 1 second --- Updates the gui every 1 second
Event.on_nth_tick(60,function() Event.on_nth_tick(60, function()
local force_pack_data = {} local force_pack_data = {}
local force_eta_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 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 local container = frame.container
-- Update the science packs -- Update the science packs
@@ -339,16 +339,16 @@ Event.on_nth_tick(60,function()
-- No data in chache so it needs to be generated -- No data in chache so it needs to be generated
pack_data = {} pack_data = {}
force_pack_data[force_name] = pack_data force_pack_data[force_name] = pack_data
for _,science_pack in ipairs(config) do for _, science_pack in ipairs(config) do
local next_data = get_science_pack_data(player,science_pack) local next_data = get_science_pack_data(player, science_pack)
pack_data[science_pack] = next_data pack_data[science_pack] = next_data
update_science_pack(scroll_table,next_data) update_science_pack(scroll_table, next_data)
end end
else else
-- Data found in chache is no need to generate it -- Data found in chache is no need to generate it
for _,next_data in ipairs(pack_data) do for _, next_data in ipairs(pack_data) do
update_science_pack(scroll_table,next_data) update_science_pack(scroll_table, next_data)
end end
end end
@@ -361,11 +361,11 @@ Event.on_nth_tick(60,function()
-- No data in chache so it needs to be generated -- No data in chache so it needs to be generated
eta_data = get_eta_label_data(player) eta_data = get_eta_label_data(player)
force_eta_data[force_name] = eta_data force_eta_data[force_name] = eta_data
update_eta_label(eta_label,eta_data) update_eta_label(eta_label, eta_data)
else else
-- Data found in chache is no need to generate it -- Data found in chache is no need to generate it
update_eta_label(eta_label,eta_data) update_eta_label(eta_label, eta_data)
end end

View File

@@ -21,8 +21,8 @@ Gui.element{
--- Toggles if the server ups is visbile --- Toggles if the server ups is visbile
-- @command server-ups -- @command server-ups
Commands.new_command('server-ups','Toggle the server ups display') Commands.new_command('server-ups', 'Toggle the server ups display')
:add_alias('sups','ups') :add_alias('sups', 'ups')
:register(function(player) :register(function(player)
local label = player.gui.screen[server_ups.name] local label = player.gui.screen[server_ups.name]
if not global.ext or not global.ext.server_ups then if not global.ext or not global.ext.server_ups then
@@ -42,7 +42,7 @@ local function set_location(event)
end end
-- Draw the label when the player joins -- 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 player = game.players[event.player_index]
local label = server_ups(player.gui.screen) local label = server_ups(player.gui.screen)
label.visible = false label.visible = false
@@ -50,15 +50,15 @@ Event.add(defines.events.on_player_created,function(event)
end) end)
-- Update the caption for all online players -- Update the caption for all online players
Event.on_nth_tick(60,function() Event.on_nth_tick(60, function()
if global.ext and global.ext.server_ups then if global.ext and global.ext.server_ups then
local caption = 'SUPS = '..global.ext.server_ups local caption = 'SUPS = '..global.ext.server_ups
for _,player in pairs(game.connected_players) do for _, player in pairs(game.connected_players) do
player.gui.screen[server_ups.name].caption = caption player.gui.screen[server_ups.name].caption = caption
end end
end end
end) end)
-- Update when res or ui scale changes -- 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_resolution_changed, set_location)
Event.add(defines.events.on_player_display_scale_changed,set_location) Event.add(defines.events.on_player_display_scale_changed, set_location)

View File

@@ -18,7 +18,7 @@ local Styles = {
} }
--- If a player is allowed to use the edit buttons --- 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 if task then
-- When a task is given check if the player can edit it -- When a task is given check if the player can edit it
local allow_edit_task = config.allow_edit_task 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 elseif allow_edit_task == 'admin' then
return player.admin return player.admin
elseif allow_edit_task == 'expcore.roles' then 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 end
-- Return false as all other condidtions have not been met -- 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 elseif allow_add_task == 'admin' then
return player.admin return player.admin
elseif allow_add_task == 'expcore.roles' then 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 end
-- Return false as all other condidtions have not been met -- Return false as all other condidtions have not been met
@@ -67,8 +67,8 @@ Gui.element{
style = 'tool_button' style = 'tool_button'
} }
:style(Styles.sprite20) :style(Styles.sprite20)
:on_click(function(player,_,_) :on_click(function(player, _,_)
Tasks.add_task(player.force.name,nil,player.name) Tasks.add_task(player.force.name, nil, player.name)
end) end)
--- Button displayed next to tasks which the user is can edit, used to start editing a task --- 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 = 'tool_button'
} }
:style(Styles.sprite20) :style(Styles.sprite20)
:on_click(function(player,element,_) :on_click(function(player, element, _)
local task_id = element.parent.name:sub(6) 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) end)
--- Button displayed next to tasks which the user is can edit, used to delete a task from the list --- 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 = 'tool_button'
} }
:style(Styles.sprite20) :style(Styles.sprite20)
:on_click(function(_,element,_) :on_click(function(_, element, _)
local task_id = element.parent.name:sub(6) local task_id = element.parent.name:sub(6)
Tasks.remove_task(task_id) Tasks.remove_task(task_id)
end) end)
@@ -104,7 +104,7 @@ end)
--- Set of three elements which make up each row of the task table --- Set of three elements which make up each row of the task table
-- @element add_task_base -- @element add_task_base
local add_task_base = local add_task_base =
Gui.element(function(_,parent,task_id) Gui.element(function(_, parent, task_id)
-- Add the task number label -- Add the task number label
local task_number = parent.add{ local task_number = parent.add{
name = 'count-'..task_id, name = 'count-'..task_id,
@@ -118,7 +118,7 @@ Gui.element(function(_,parent,task_id)
task_flow.style.padding = 0 task_flow.style.padding = 0
-- Add the two edit buttons outside the task flow -- 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) edit_task(edit_flow)
discard_task(edit_flow) discard_task(edit_flow)
@@ -127,7 +127,7 @@ Gui.element(function(_,parent,task_id)
end) end)
-- Removes the three elements that are added as part of the task base -- 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['count-'..task_id])
Gui.destroy_if_valid(parent['edit-'..task_id]) Gui.destroy_if_valid(parent['edit-'..task_id])
Gui.destroy_if_valid(parent[task_id]) Gui.destroy_if_valid(parent[task_id])
@@ -144,11 +144,11 @@ Gui.element{
style = 'shortcut_bar_button_green' style = 'shortcut_bar_button_green'
} }
:style(Styles.sprite22) :style(Styles.sprite22)
:on_click(function(player,element,_) :on_click(function(player, element, _)
local task_id = element.parent.name local task_id = element.parent.name
local new_message = element.parent[task_editing.name].text local new_message = element.parent[task_editing.name].text
Tasks.set_editing(task_id,player.name) Tasks.set_editing(task_id, player.name)
Tasks.update_task(task_id,new_message,player.name) Tasks.update_task(task_id, new_message, player.name)
end) end)
--- Button displayed next to tasks which the user is currently editing, used to discard changes --- 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 = 'shortcut_bar_button_red'
} }
:style(Styles.sprite22) :style(Styles.sprite22)
:on_click(function(player,element,_) :on_click(function(player, element, _)
local task_id = element.parent.name local task_id = element.parent.name
Tasks.set_editing(task_id,player.name) Tasks.set_editing(task_id, player.name)
end) end)
--- Editing state for a task, contrins a text field and the two edit buttons --- Editing state for a task, contrins a text field and the two edit buttons
-- @element task_editing -- @element task_editing
task_editing = task_editing =
Gui.element(function(event_trigger,parent,task) Gui.element(function(event_trigger, parent, task)
local message = task.message local message = task.message
-- Draw the element -- Draw the element
@@ -192,17 +192,17 @@ end)
maximal_width = 110, maximal_width = 110,
height = 20 height = 20
} }
:on_confirmed(function(player,element,_) :on_confirmed(function(player, element, _)
local task_id = element.parent.name local task_id = element.parent.name
local new_message = element.text local new_message = element.text
Tasks.set_editing(task_id,player.name) Tasks.set_editing(task_id, player.name)
Tasks.update_task(task_id,new_message,player.name) Tasks.update_task(task_id, new_message, player.name)
end) end)
--- Default state for a task, contains only a label with the task message --- Default state for a task, contains only a label with the task message
-- @element task_label -- @element task_label
local task_label = local task_label =
Gui.element(function(_,parent,task) Gui.element(function(_, parent, task)
local message = task.message local message = task.message
local last_edit_name = task.last_edit_name local last_edit_name = task.last_edit_name
local last_edit_time = task.last_edit_time local last_edit_time = task.last_edit_time
@@ -220,7 +220,7 @@ end)
} }
--- Updates a task for a player --- 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 = Tasks.get_task(task_id)
local task_ids = Tasks.get_force_task_ids(player.force.name) local task_ids = Tasks.get_force_task_ids(player.force.name)
local task_number = table.get_index(task_ids, task_id) local task_number = table.get_index(task_ids, task_id)
@@ -228,18 +228,18 @@ local function update_task(player,task_table,task_id)
-- Task no longer exists so should be removed from the list -- Task no longer exists so should be removed from the list
if not task then if not task then
task_table.parent.no_tasks.visible = #task_ids == 0 task_table.parent.no_tasks.visible = #task_ids == 0
remove_task_base(task_table,task_id) remove_task_base(task_table, task_id)
return return
end end
-- Get the task flow for this task -- 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.parent.no_tasks.visible = false
task_table['count-'..task_id].caption = task_number..')' task_table['count-'..task_id].caption = task_number..')'
-- Update the edit flow -- Update the edit flow
local edit_flow = task_table['edit-'..task_id] local edit_flow = task_table['edit-'..task_id]
local player_allowed_edit = check_player_permissions(player,task) local player_allowed_edit = check_player_permissions(player, task)
local players_editing = table.get_keys(task.curently_editing) local players_editing = table.get_keys(task.curently_editing)
local edit_task_element = edit_flow[edit_task.name] local edit_task_element = edit_flow[edit_task.name]
local discard_task_element = edit_flow[discard_task.name] local discard_task_element = edit_flow[discard_task.name]
@@ -248,14 +248,14 @@ local function update_task(player,task_table,task_id)
discard_task_element.visible = player_allowed_edit discard_task_element.visible = player_allowed_edit
if #players_editing > 0 then if #players_editing > 0 then
edit_task_element.hovered_sprite = 'utility/warning_icon' 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 else
edit_task_element.hovered_sprite = edit_task_element.sprite edit_task_element.hovered_sprite = edit_task_element.sprite
edit_task_element.tooltip = {'task-list.edit-tooltip-none'} edit_task_element.tooltip = {'task-list.edit-tooltip-none'}
end end
-- Check if the player is was editing and/or currently editing -- 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_was_editing = task_entry.type == 'textfield'
local player_is_editing = task.curently_editing[player.name] local player_is_editing = task.curently_editing[player.name]
@@ -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 -- Player was editing but is no longer, remove text field and add label
edit_task_element.enabled = true edit_task_element.enabled = true
task_flow.clear() task_flow.clear()
task_label(task_flow,task) task_label(task_flow, task)
elseif not player_was_editing and player_is_editing then elseif not player_was_editing and player_is_editing then
-- Player was not editing but now is, remove label and add text field -- Player was not editing but now is, remove label and add text field
edit_task_element.enabled = false edit_task_element.enabled = false
task_flow.clear() task_flow.clear()
task_editing(task_flow,task).focus() task_editing(task_flow, task).focus()
task_table.parent.scroll_to_element(task_flow,'top-third') task_table.parent.scroll_to_element(task_flow, 'top-third')
end end
end end
-- Update all the tasks for a player -- 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) local task_ids = Tasks.get_force_task_ids(player.force.name)
if #task_ids > 0 then if #task_ids > 0 then
for _,task_id in ipairs(task_ids) do for _, task_id in ipairs(task_ids) do
update_task(player,scroll_table,task_id) update_task(player, scroll_table, task_id)
end end
end end
end end
@@ -297,9 +297,9 @@ end
--- Main task list container for the left flow --- Main task list container for the left flow
-- @element task_list_container -- @element task_list_container
local task_list_container = local task_list_container =
Gui.element(function(event_trigger,parent) Gui.element(function(event_trigger, parent)
-- Draw the internal container -- Draw the internal container
local container = Gui.container(parent,event_trigger,200) local container = Gui.container(parent, event_trigger, 200)
-- Draw the header -- Draw the header
local header = Gui.header( local header = Gui.header(
@@ -315,7 +315,7 @@ Gui.element(function(event_trigger,parent)
add_new_task_element.visible = check_player_permissions(player) add_new_task_element.visible = check_player_permissions(player)
-- Draw the scroll table for the tasks -- 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.draw_horizontal_lines = true
scroll_table.vertical_centering = false scroll_table.vertical_centering = false
@@ -334,7 +334,7 @@ Gui.element(function(event_trigger,parent)
-- Change the style of the no tasks label -- Change the style of the no tasks label
local no_tasks_style = no_tasks_label.style 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.single_line = false
no_tasks_style.width = 200 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) local task_ids = Tasks.get_force_task_ids(player.force.name)
if #task_ids > 0 then if #task_ids > 0 then
no_tasks_label.visible = false no_tasks_label.visible = false
for _,task_id in ipairs(task_ids) do for _, task_id in ipairs(task_ids) do
update_task(player,scroll_table,task_id) update_task(player, scroll_table, task_id)
end end
end end
@@ -358,11 +358,11 @@ end)
--- Button on the top flow used to toggle the task list container --- Button on the top flow used to toggle the task list container
-- @element toggle_left_element -- @element toggle_left_element
Gui.left_toolbar_button('utility/not_enough_repair_packs_icon', {'task-list.main-tooltip'}, task_list_container, function(player) 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) end)
--- When a new task is added it will udpate the task list for everyone on that force --- 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) Tasks.on_update(function(task, task_id, removed_task)
-- Get the force to update, task is nil when removed -- Get the force to update, task is nil when removed
local force local force
if task then if task then
@@ -373,12 +373,12 @@ Tasks.on_update(function(task,task_id,removed_task)
-- Update the task for all the players on the force -- Update the task for all the players on the force
local task_ids = Tasks.get_force_task_ids(force.name) local task_ids = Tasks.get_force_task_ids(force.name)
for _,player in pairs(force.connected_players) do for _, player in pairs(force.connected_players) do
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 local scroll_table = frame.container.scroll.table
-- Update the task that was changed -- 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 -- Update the numbering of the other tasks if the task was removed
if not task then if not task then
@@ -391,26 +391,26 @@ Tasks.on_update(function(task,task_id,removed_task)
end) end)
--- Update the tasks when the player joins --- 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 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 local scroll_table = frame.container.scroll.table
update_all_tasks(player,scroll_table) update_all_tasks(player, scroll_table)
end) end)
--- Makes sure the right buttons are present when roles change --- Makes sure the right buttons are present when roles change
local function role_update_event(event) local function role_update_event(event)
local player = game.players[event.player_index] 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 -- Update the tasks, incase the user can now edit them
local scroll_table = container.scroll.table 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 -- Update the new task button incase the user can now add them
local add_new_task_element = container.header.alignment[add_new_task.name] local add_new_task_element = container.header.alignment[add_new_task.name]
add_new_task_element.visible = check_player_permissions(player) add_new_task_element.visible = check_player_permissions(player)
end end
Event.add(Roles.events.on_role_assigned,role_update_event) 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_unassigned, role_update_event)

View File

@@ -27,7 +27,7 @@ end)
-- 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 = {} local keep_gui_open = {}
Global.register(keep_gui_open,function(tbl) Global.register(keep_gui_open, function(tbl)
keep_gui_open = tbl keep_gui_open = tbl
end) end)
@@ -40,7 +40,7 @@ local Styles = {
--- Returns if a player is allowed to edit the given warp --- Returns if a player is allowed to edit the given warp
--- If a player is allowed to use the edit buttons --- 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 -- Check if the action is allow edit and then check bypass settings
if action == 'allow_edit_warp' then if action == 'allow_edit_warp' then
-- Check if the warp is the spawn then it cant be edited -- Check if the warp is the spawn then it cant be edited
@@ -62,7 +62,7 @@ local function check_player_permissions(player,action,warp)
elseif action_config == 'admin' then elseif action_config == 'admin' then
return player.admin return player.admin
elseif action_config == 'expcore.roles' then 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 end
-- Return false as all other condidtions have not been met -- Return false as all other condidtions have not been met
@@ -79,12 +79,12 @@ Gui.element{
style = 'tool_button' style = 'tool_button'
} }
:style(Styles.sprite20) :style(Styles.sprite20)
:on_click(function(player,_) :on_click(function(player, _)
-- Add the new warp -- Add the new warp
local force_name = player.force.name local force_name = player.force.name
local surface = player.surface local surface = player.surface
local position = player.position 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_tag(warp_id)
Warps.make_warp_area(warp_id) Warps.make_warp_area(warp_id)
end) end)
@@ -99,7 +99,7 @@ Gui.element{
style = 'tool_button' style = 'tool_button'
} }
:style(Styles.sprite20) :style(Styles.sprite20)
:on_click(function(_,element) :on_click(function(_, element)
local warp_id = element.parent.name:sub(6) local warp_id = element.parent.name:sub(6)
Warps.remove_warp(warp_id) Warps.remove_warp(warp_id)
end) end)
@@ -114,15 +114,15 @@ Gui.element{
style = 'tool_button' style = 'tool_button'
} }
:style(Styles.sprite20) :style(Styles.sprite20)
:on_click(function(player,element) :on_click(function(player, element)
local warp_id = element.parent.name:sub(6) 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) end)
--- Set of three elements which make up each row of the warp table --- Set of three elements which make up each row of the warp table
-- @element add_warp_base -- @element add_warp_base
local add_warp_base = local add_warp_base =
Gui.element(function(_,parent,warp_id) Gui.element(function(_, parent, warp_id)
-- Add the icon flow -- Add the icon flow
local icon_flow = local icon_flow =
parent.add{ parent.add{
@@ -137,7 +137,7 @@ Gui.element(function(_,parent,warp_id)
warp_flow.style.padding = 0 warp_flow.style.padding = 0
-- Add the two edit buttons outside the warp flow -- 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) edit_warp(edit_flow)
discard_warp(edit_flow) discard_warp(edit_flow)
@@ -146,7 +146,7 @@ Gui.element(function(_,parent,warp_id)
end) end)
-- Removes the three elements that are added as part of the warp base -- 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['icon-'..warp_id])
Gui.destroy_if_valid(parent['edit-'..warp_id]) Gui.destroy_if_valid(parent['edit-'..warp_id])
Gui.destroy_if_valid(parent[warp_id]) Gui.destroy_if_valid(parent[warp_id])
@@ -164,12 +164,12 @@ Gui.element{
style = 'shortcut_bar_button_green' style = 'shortcut_bar_button_green'
} }
:style(Styles.sprite22) :style(Styles.sprite22)
:on_click(function(player,element) :on_click(function(player, element)
local warp_id = element.parent.name local warp_id = element.parent.name
local warp_name = element.parent[warp_editing.name].text local warp_name = element.parent[warp_editing.name].text
local warp_icon = element.parent.parent['icon-'..warp_id][warp_icon_button.name].elem_value local warp_icon = element.parent.parent['icon-'..warp_id][warp_icon_button.name].elem_value
Warps.set_editing(warp_id,player.name) Warps.set_editing(warp_id, player.name)
Warps.update_warp(warp_id,warp_name,warp_icon,player.name) Warps.update_warp(warp_id, warp_name, warp_icon, player.name)
end) end)
--- Cancels the editing changes of the selected warp name or icon --- Cancels the editing changes of the selected warp name or icon
@@ -182,15 +182,15 @@ Gui.element{
style = 'shortcut_bar_button_red' style = 'shortcut_bar_button_red'
} }
:style(Styles.sprite22) :style(Styles.sprite22)
:on_click(function(player,element) :on_click(function(player, element)
local warp_id = element.parent.name local warp_id = element.parent.name
Warps.set_editing(warp_id,player.name) Warps.set_editing(warp_id, player.name)
end) end)
--- Editing state for a warp, contrins a text field and the two edit buttons --- Editing state for a warp, contrins a text field and the two edit buttons
-- @element warp_editing -- @element warp_editing
warp_editing = warp_editing =
Gui.element(function(event_trigger,parent,warp) Gui.element(function(event_trigger, parent, warp)
local name = warp.name local name = warp.name
-- Draw the element -- Draw the element
@@ -213,18 +213,18 @@ end)
maximal_width = 110, maximal_width = 110,
height = 20 height = 20
} }
:on_confirmed(function(player,element,_) :on_confirmed(function(player, element, _)
local warp_id = element.parent.name local warp_id = element.parent.name
local warp_name = element.text local warp_name = element.text
local warp_icon = element.parent.parent['icon-'..warp_id][warp_icon_button.name].elem_value local warp_icon = element.parent.parent['icon-'..warp_id][warp_icon_button.name].elem_value
Warps.set_editing(warp_id,player.name) Warps.set_editing(warp_id, player.name)
Warps.update_warp(warp_id,warp_name,warp_icon,player.name) Warps.update_warp(warp_id, warp_name, warp_icon, player.name)
end) end)
--- Default state for a warp, contains only a label with the warp name --- Default state for a warp, contains only a label with the warp name
-- @element warp_label -- @element warp_label
local 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_name = warp.last_edit_name
local last_edit_time = warp.last_edit_time local last_edit_time = warp.last_edit_time
-- Draw the element -- Draw the element
@@ -232,52 +232,52 @@ Gui.element(function(event_trigger,parent,warp)
name = event_trigger, name = event_trigger,
type = 'label', type = 'label',
caption = warp.name, 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) end)
:style{ :style{
single_line = false, single_line = false,
maximal_width = 150 maximal_width = 150
} }
:on_click(function(player,element,_) :on_click(function(player, element, _)
local warp_id = element.parent.name local warp_id = element.parent.name
local warp = Warps.get_warp(warp_id) local warp = Warps.get_warp(warp_id)
local position = warp.position local position = warp.position
player.zoom_to_world(position,1.5) player.zoom_to_world(position, 1.5)
end) end)
--- Default state for the warp icon, when pressed teleports the player --- Default state for the warp icon, when pressed teleports the player
-- @element warp_icon_button -- @element warp_icon_button
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 local warp_position = warp.position
-- Draw the element -- Draw the element
return parent.add{ return parent.add{
name = event_trigger, name = event_trigger,
type = 'sprite-button', type = 'sprite-button',
sprite = 'item/'..warp.icon, 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 = 'quick_bar_slot_button' style = 'quick_bar_slot_button'
} }
end) end)
:style(Styles.sprite32) :style(Styles.sprite32)
:on_click(function(player,element,_) :on_click(function(player, element, _)
if element.type == 'choose-elem-button' then return end if element.type == 'choose-elem-button' then return end
local warp_id = element.parent.caption 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 -- Reset the warp cooldown if the player does not have unlimited warps
if not check_player_permissions(player,'bypass_warp_cooldown') then if not check_player_permissions(player, 'bypass_warp_cooldown') then
Store.set(player_warp_cooldown_store,player,config.cooldown_duraction) Store.set(player_warp_cooldown_store, player, config.cooldown_duraction)
Store.trigger(player_in_range_store,player) Store.trigger(player_in_range_store, player)
end end
end) end)
--- Editing state for the warp icon, chose elem used to chosse icon --- Editing state for the warp icon, chose elem used to chosse icon
-- @element warp_icon_editing -- @element warp_icon_editing
local warp_icon_editing = local warp_icon_editing =
Gui.element(function(_,parent,warp) Gui.element(function(_, parent, warp)
return parent.add{ return parent.add{
name = warp_icon_button.name, name = warp_icon_button.name,
type = 'choose-elem-button', type = 'choose-elem-button',
@@ -293,7 +293,7 @@ end)
local warp_timer = local warp_timer =
Gui.element{ Gui.element{
type = 'progressbar', type = 'progressbar',
tooltip = {'warp-list.timer-tooltip',config.cooldown_duraction}, tooltip = {'warp-list.timer-tooltip', config.cooldown_duraction},
minimum_value = 0, minimum_value = 0,
maximum_value = config.cooldown_duraction*config.update_smoothing maximum_value = config.cooldown_duraction*config.update_smoothing
} }
@@ -303,22 +303,22 @@ Gui.element{
} }
--- Updates a warp for a player --- 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) local warp = Warps.get_warp(warp_id)
-- Warp no longer exists so should be removed from the list -- Warp no longer exists so should be removed from the list
if not warp then if not warp then
remove_warp_base(warp_table,warp_id) remove_warp_base(warp_table, warp_id)
return return
end end
-- Get the warp flow for this warp -- 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] local icon_flow = warp_table['icon-'..warp_id]
-- Update the edit flow -- Update the edit flow
local edit_flow = warp_table['edit-'..warp_id] 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 players_editing = table.get_keys(warp.currently_editing)
local edit_warp_element = edit_flow[edit_warp.name] local edit_warp_element = edit_flow[edit_warp.name]
local discard_warp_element = edit_flow[discard_warp.name] local discard_warp_element = edit_flow[discard_warp.name]
@@ -327,15 +327,15 @@ local function update_warp(player,warp_table,warp_id)
discard_warp_element.visible = player_allowed_edit discard_warp_element.visible = player_allowed_edit
if #players_editing > 0 then if #players_editing > 0 then
edit_warp_element.hovered_sprite = 'utility/warning_icon' 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 else
edit_warp_element.hovered_sprite = edit_warp_element.sprite edit_warp_element.hovered_sprite = edit_warp_element.sprite
edit_warp_element.tooltip = {'warp-list.edit-tooltip-none'} edit_warp_element.tooltip = {'warp-list.edit-tooltip-none'}
end end
-- Check if the player is was editing and/or currently editing -- 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 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 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_was_editing = icon_entry.type == 'choose-elem-button'
local player_is_editing = warp.currently_editing[player.name] local player_is_editing = warp.currently_editing[player.name]
@@ -347,20 +347,20 @@ local function update_warp(player,warp_table,warp_id)
local last_edit_name = warp.last_edit_name local last_edit_name = warp.last_edit_name
local last_edit_time = warp.last_edit_time local last_edit_time = warp.last_edit_time
warp_label_element.caption = warp_name 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 icon_entry.sprite = 'item/'..warp_icon
elseif player_was_editing and not player_is_editing then elseif player_was_editing and not player_is_editing then
-- Player was editing but is no longer, remove text field and add label -- Player was editing but is no longer, remove text field and add label
edit_warp_element.enabled = true edit_warp_element.enabled = true
warp_flow.clear() warp_flow.clear()
warp_label(warp_flow,warp) warp_label(warp_flow, warp)
icon_flow.clear() icon_flow.clear()
local warp_icon_element = warp_icon_button(icon_flow,warp) local warp_icon_element = warp_icon_button(icon_flow, warp)
local timer = Store.get(player_warp_cooldown_store,player) local timer = Store.get(player_warp_cooldown_store, player)
local in_range = Store.get(player_in_range_store,player) local in_range = Store.get(player_in_range_store, player)
local apply_proximity = not check_player_permissions(player,'bypass_warp_proximity') local apply_proximity = not check_player_permissions(player, 'bypass_warp_proximity')
if (timer and timer > 0) or (apply_proximity and not in_range) then if (timer and timer > 0) or (apply_proximity and not in_range) then
warp_icon_element.enabled = false warp_icon_element.enabled = false
warp_icon_element.tooltip = {'warp-list.goto-disabled'} warp_icon_element.tooltip = {'warp-list.goto-disabled'}
@@ -370,20 +370,20 @@ local function update_warp(player,warp_table,warp_id)
-- Player was not editing but now is, remove label and add text field -- Player was not editing but now is, remove label and add text field
edit_warp_element.enabled = false edit_warp_element.enabled = false
warp_flow.clear() warp_flow.clear()
warp_editing(warp_flow,warp).focus() warp_editing(warp_flow, warp).focus()
warp_table.parent.scroll_to_element(warp_flow,'top-third') warp_table.parent.scroll_to_element(warp_flow, 'top-third')
icon_flow.clear() icon_flow.clear()
warp_icon_editing(icon_flow,warp) warp_icon_editing(icon_flow, warp)
end end
end end
-- Update all the warps for a player -- 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) local warp_ids = Warps.get_force_warp_ids(player.force.name)
if #warp_ids > 0 then if #warp_ids > 0 then
for _,warp_id in ipairs(warp_ids) do for _, warp_id in ipairs(warp_ids) do
update_warp(player,warp_table,warp_id) update_warp(player, warp_table, warp_id)
end end
end end
end end
@@ -391,9 +391,9 @@ end
--- Main warp list container for the left flow --- Main warp list container for the left flow
-- @element warp_list_container -- @element warp_list_container
local warp_list_container = local warp_list_container =
Gui.element(function(event_trigger,parent) Gui.element(function(event_trigger, parent)
-- Draw the internal container -- Draw the internal container
local container = Gui.container(parent,event_trigger,200) local container = Gui.container(parent, event_trigger, 200)
-- Draw the header -- Draw the header
local header = Gui.header( local header = Gui.header(
@@ -406,10 +406,10 @@ Gui.element(function(event_trigger,parent)
-- Draw the new warp button -- Draw the new warp button
local player = Gui.get_player_from_element(parent) local player = Gui.get_player_from_element(parent)
local add_new_warp_element = add_new_warp(header) 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 -- 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 -- Change the style of the scroll table
local scroll_table_style = scroll_table.style local scroll_table_style = scroll_table.style
@@ -421,14 +421,14 @@ Gui.element(function(event_trigger,parent)
-- Change the progress of the warp timer -- Change the progress of the warp timer
local progress = 1 local progress = 1
local timer = Store.get(player_warp_cooldown_store,player) local timer = Store.get(player_warp_cooldown_store, player)
if timer and timer > 0 then if timer and timer > 0 then
progress = 1 - (timer/config.cooldown_duraction) progress = 1 - (timer/config.cooldown_duraction)
end end
warp_timer_element.value = progress warp_timer_element.value = progress
-- Add any existing warps -- Add any existing warps
update_all_warps(player,scroll_table) update_all_warps(player, scroll_table)
-- Return the exteral container -- Return the exteral container
return container.parent return container.parent
@@ -437,16 +437,16 @@ end)
--- Button on the top flow used to toggle the warp list container --- Button on the top flow used to toggle the warp list container
-- @element warp_list_toggle -- @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) 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') return Roles.player_allowed(player, 'gui/warp-list')
end) 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 -- Set gui keep open state for player that clicked the button: true if visible, false if invisible
keep_gui_open[player.name] = event.state keep_gui_open[player.name] = event.state
end) end)
--- When the name of a warp is updated this is triggered --- When the name of a warp is updated this is triggered
Warps.on_update(function(warp,_,removed_warp) Warps.on_update(function(warp, _,removed_warp)
-- Get the force to update, warp is nil when removed -- Get the force to update, warp is nil when removed
local force local force
if warp then if warp then
@@ -457,69 +457,69 @@ Warps.on_update(function(warp,_,removed_warp)
-- Update the gui for selected players -- Update the gui for selected players
local warp_ids = Warps.get_force_warp_ids(force.name) local warp_ids = Warps.get_force_warp_ids(force.name)
for _,player in pairs(force.connected_players) do for _, player in pairs(force.connected_players) do
local frame = Gui.get_left_element(player,warp_list_container) local frame = Gui.get_left_element(player, warp_list_container)
local scroll_table = frame.container.scroll.table local scroll_table = frame.container.scroll.table
-- Update the gui -- Update the gui
scroll_table.clear() scroll_table.clear()
for _,next_warp_id in ipairs(warp_ids) do for _, next_warp_id in ipairs(warp_ids) do
update_warp(player,scroll_table,next_warp_id) update_warp(player, scroll_table, next_warp_id)
end end
end end
end) end)
--- Update the warps when the player joins --- Update the warps 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 player = game.players[event.player_index]
local frame = Gui.get_left_element(player,warp_list_container) local frame = Gui.get_left_element(player, warp_list_container)
local scroll_table = frame.container.scroll.table local scroll_table = frame.container.scroll.table
update_all_warps(player,scroll_table) update_all_warps(player, scroll_table)
end) end)
--- Makes sure the right buttons are present when roles change --- Makes sure the right buttons are present when roles change
local function role_update_event(event) local function role_update_event(event)
local player = game.players[event.player_index] local player = game.players[event.player_index]
local container = Gui.get_left_element(player,warp_list_container).container local container = Gui.get_left_element(player, warp_list_container).container
-- Update the warps, incase the user can now edit them -- Update the warps, incase the user can now edit them
local scroll_table = container.scroll.table local scroll_table = container.scroll.table
update_all_warps(player,scroll_table) update_all_warps(player, scroll_table)
-- Update the new warp button incase the user can now add them -- Update the new warp button incase the user can now add them
local add_new_warp_element = container.header.alignment[add_new_warp.name] local add_new_warp_element = container.header.alignment[add_new_warp.name]
add_new_warp_element.visible = check_player_permissions(player,'allow_add_warp') add_new_warp_element.visible = check_player_permissions(player, 'allow_add_warp')
end end
Event.add(Roles.events.on_role_assigned,role_update_event) 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_unassigned, role_update_event)
--- When the player leaves or enters range of a warp this is triggered --- When the player leaves or enters range of a warp this is triggered
Store.watch(player_in_range_store,function(value,player_name) Store.watch(player_in_range_store, function(value, player_name)
local player = game.players[player_name] local player = game.players[player_name]
local force = player.force local force = player.force
-- Change if the frame is visible based on if the player is in range -- Change if the frame is visible based on if the player is in range
if not keep_gui_open[player.name] then 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, value)
end end
-- Check if the player requires proximity -- Check if the player requires proximity
if check_player_permissions(player,'bypass_warp_proximity') then if check_player_permissions(player, 'bypass_warp_proximity') then
return return
end end
-- Get the warp table -- Get the warp table
local frame = Gui.get_left_element(player,warp_list_container) local frame = Gui.get_left_element(player, warp_list_container)
local scroll_table = frame.container.scroll.table local scroll_table = frame.container.scroll.table
-- Check if the buttons should be active -- Check if the buttons should be active
local timer = Store.get(player_warp_cooldown_store,player) local timer = Store.get(player_warp_cooldown_store, player)
local button_disabled = timer and timer > 0 or not value local button_disabled = timer and timer > 0 or not value
-- Change the enabled state of the warp buttons -- Change the enabled state of the warp buttons
local warp_ids = Warps.get_force_warp_ids(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 element = scroll_table['icon-'..warp_id][warp_icon_button.name] local element = scroll_table['icon-'..warp_id][warp_icon_button.name]
if element and element.valid then if element and element.valid then
element.enabled = not button_disabled element.enabled = not button_disabled
@@ -527,23 +527,23 @@ Store.watch(player_in_range_store,function(value,player_name)
element.tooltip = {'warp-list.goto-disabled'} element.tooltip = {'warp-list.goto-disabled'}
else else
local position = Warps.get_warp(warp_id).position local position = Warps.get_warp(warp_id).position
element.tooltip = {'warp-list.goto-tooltip',position.x,position.y} element.tooltip = {'warp-list.goto-tooltip', position.x, position.y}
end end
end end
end end
end) end)
--- Update the warp cooldown progress bars to match the store --- Update the warp cooldown progress bars to match the store
Store.watch(player_warp_cooldown_store,function(value,player_name,old_value) Store.watch(player_warp_cooldown_store, function(value, player_name, old_value)
if value == old_value then return end if value == old_value then return end
-- Get the progress bar element -- Get the progress bar element
local player = game.players[player_name] 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] local warp_timer_element = frame.container[warp_timer.name]
-- Set the progress -- Set the progress
local progress = 1 local progress = 1
local timer = Store.get(player_warp_cooldown_store,player) local timer = Store.get(player_warp_cooldown_store, player)
if timer and timer > 0 then if timer and timer > 0 then
progress = 1 - (timer/config.cooldown_duraction) progress = 1 - (timer/config.cooldown_duraction)
end end
@@ -551,7 +551,7 @@ Store.watch(player_warp_cooldown_store,function(value,player_name,old_value)
-- Trigger update of buttons if cooldown is now 0 -- Trigger update of buttons if cooldown is now 0
if value == 0 then if value == 0 then
Store.trigger(player_in_range_store,player_name) Store.trigger(player_in_range_store, player_name)
end end
end) end)
@@ -559,8 +559,8 @@ end)
local r2 = config.standard_proximity_radius^2 local r2 = config.standard_proximity_radius^2
local rs2 = config.spawn_proximity_radius^2 local rs2 = config.spawn_proximity_radius^2
local mr2 = config.minimum_distance^2 local mr2 = config.minimum_distance^2
Event.on_nth_tick(math.floor(60/config.update_smoothing),function() Event.on_nth_tick(math.floor(60/config.update_smoothing), function()
Store.map(player_warp_cooldown_store,function(value) Store.map(player_warp_cooldown_store, function(value)
if value > 0 then if value > 0 then
return value - 1 return value - 1
end end
@@ -568,8 +568,8 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function()
local force_warps = {} local force_warps = {}
local warps = {} local warps = {}
for _,player in pairs(game.connected_players) do for _, player in pairs(game.connected_players) do
local was_in_range = Store.get(player_in_range_store,player) local was_in_range = Store.get(player_in_range_store, player)
-- Get the ids of all the warps on the players force -- Get the ids of all the warps on the players force
local force_name = player.force.name local force_name = player.force.name
@@ -585,10 +585,10 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function()
if #warp_ids > 0 then if #warp_ids > 0 then
local surface = player.surface local surface = player.surface
local pos = player.position local pos = player.position
local px,py = pos.x,pos.y local px, py = pos.x, pos.y
-- Loop over each warp -- Loop over each warp
for _,warp_id in ipairs(warp_ids) do for _, warp_id in ipairs(warp_ids) do
-- Check if warp id is chached -- Check if warp id is chached
local warp = warps[warp_id] local warp = warps[warp_id]
if not warp then if not warp then
@@ -612,13 +612,13 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function()
-- Check the dist to the closest warp -- 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 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 if was_in_range and not in_range then
Store.set(player_in_range_store,player,false) Store.set(player_in_range_store, player, false)
elseif not was_in_range and in_range then elseif not was_in_range and in_range then
Store.set(player_in_range_store,player,true) Store.set(player_in_range_store, player, true)
end end
-- Change the enabled state of the add warp button -- 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 add_warp_element = frame.container.header.alignment[add_new_warp.name]
local was_able_to_make_warp = add_warp_element.enabled local was_able_to_make_warp = add_warp_element.enabled
local can_make_warp = closest_distance > mr2 local can_make_warp = closest_distance > mr2
@@ -627,7 +627,7 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function()
add_warp_element.tooltip = {'warp-list.add-tooltip'} add_warp_element.tooltip = {'warp-list.add-tooltip'}
elseif not can_make_warp and was_able_to_make_warp then elseif not can_make_warp and was_able_to_make_warp then
add_warp_element.enabled = false 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
end end
@@ -637,16 +637,16 @@ Event.on_nth_tick(math.floor(60/config.update_smoothing),function()
end) end)
--- When a player is created make sure that there is a spawn warp created --- 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 -- If the force has no spawn then make a spawn warp
local player = Game.get_player_by_index(event.player_index) local player = Game.get_player_by_index(event.player_index)
local force = player.force local force = player.force
local spawn_id = Warps.get_spawn_warp_id(force.name) local spawn_id = Warps.get_spawn_warp_id(force.name)
if not spawn_id then if not spawn_id then
local spawn_position = force.get_spawn_position(player.surface) local spawn_position = force.get_spawn_position(player.surface)
spawn_id = Warps.add_warp(force.name,player.surface,spawn_position,nil,'Spawn') spawn_id = Warps.add_warp(force.name, player.surface, spawn_position, nil, 'Spawn')
Warps.set_spawn_warp(spawn_id,force) Warps.set_spawn_warp(spawn_id, force)
Store.trigger(Warps.store,spawn_id) Store.trigger(Warps.store, spawn_id)
Warps.make_warp_tag(spawn_id) Warps.make_warp_tag(spawn_id)
end end
end) end)
@@ -657,7 +657,7 @@ local function maintain_tag(event)
local tag = event.tag local tag = event.tag
local force_name = event.force.name local force_name = event.force.name
local warp_ids = Warps.get_force_warp_ids(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 warp = Warps.get_warp(warp_id)
local wtag = warp.tag local wtag = warp.tag
if not wtag or not wtag.valid or wtag == tag then if not wtag or not wtag.valid or wtag == tag then
@@ -669,5 +669,5 @@ local function maintain_tag(event)
end end
end end
Event.add(defines.events.on_chart_tag_modified,maintain_tag) Event.add(defines.events.on_chart_tag_modified, maintain_tag)
Event.add(defines.events.on_chart_tag_removed,maintain_tag) Event.add(defines.events.on_chart_tag_removed, maintain_tag)

View File

@@ -99,10 +99,10 @@ end
-- tables aren't pure sequences. So we implement our own # operator. -- tables aren't pure sequences. So we implement our own # operator.
local function getSequenceLength(t) local function getSequenceLength(t)
local len = 1 local len = 1
local v = rawget(t,len) local v = rawget(t, len)
while v ~= nil do while v ~= nil do
len = len + 1 len = len + 1
v = rawget(t,len) v = rawget(t, len)
end end
return len - 1 return len - 1
end end
@@ -110,7 +110,7 @@ end
local function getNonSequentialKeys(t) local function getNonSequentialKeys(t)
local keys = {} local keys = {}
local sequenceLength = getSequenceLength(t) 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 if not isSequenceKey(k, sequenceLength) then table.insert(keys, k) end
end end
table.sort(keys, sortKeys) table.sort(keys, sortKeys)
@@ -133,7 +133,7 @@ local function countTableAppearances(t, tableAppearances)
if type(t) == 'table' then if type(t) == 'table' then
if not tableAppearances[t] then if not tableAppearances[t] then
tableAppearances[t] = 1 tableAppearances[t] = 1
for k,v in pairs(t) do for k, v in pairs(t) do
countTableAppearances(k, tableAppearances) countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances) countTableAppearances(v, tableAppearances)
end end
@@ -172,7 +172,7 @@ local function processRecursive(process, item, path, visited)
visited[item] = processedCopy visited[item] = processedCopy
local processedKey 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) processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY), visited)
if processedKey ~= nil then if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited) processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey), visited)
@@ -258,14 +258,14 @@ function Inspector:putTable(t)
local count = 0 local count = 0
for i=1, sequenceLength do for i=1, sequenceLength do
if count > 0 then self:puts(',') end if count > 0 then self:puts(', ') end
self:puts(' ') self:puts(' ')
self:putValue(t[i]) self:putValue(t[i])
count = count + 1 count = count + 1
end end
for _,k in ipairs(nonSequentialKeys) do for _, k in ipairs(nonSequentialKeys) do
if count > 0 then self:puts(',') end if count > 0 then self:puts(', ') end
self:tabify() self:tabify()
self:putKey(k) self:putKey(k)
self:puts(' = ') self:puts(' = ')
@@ -274,7 +274,7 @@ function Inspector:putTable(t)
end end
if mt then if mt then
if count > 0 then self:puts(',') end if count > 0 then self:puts(', ') end
self:tabify() self:tabify()
self:puts('<metatable> = ') self:puts('<metatable> = ')
self:putValue(mt) self:putValue(mt)
@@ -302,7 +302,7 @@ function Inspector:putValue(v)
elseif tv == 'table' then elseif tv == 'table' then
self:putTable(v) self:putTable(v)
else else
self:puts('<',tv,' ',self:getId(v),'>') self:puts('<', tv, ' ', self:getId(v), '>')
end end
end end

View File

@@ -1,4 +1,3 @@
--luacheck:ignore global require
local loaded = package.loaded local loaded = package.loaded
local raw_require = require local raw_require = require

View File

@@ -54,10 +54,10 @@ end
@usage-- Adding 1000 values into the middle of the array @usage-- Adding 1000 values into the middle of the array
local tbl = {} local tbl = {}
local values = {} local values = {}
for i = 1,1000 do tbl[i] = i values[i] = i end for i = 1, 1000 do tbl[i] = i values[i] = i end
table.array_insert(tbl,500,values) -- around 0.4ms 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 if not values then
values = start_index values = start_index
start_index = nil start_index = nil
@@ -90,16 +90,16 @@ end
@usage-- Merging two tables @usage-- Merging two tables
local tbl = {} local tbl = {}
local tbl2 = {} local tbl2 = {}
for i = 1,100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end for i = 1, 100 do tbl[i] = i tbl['_'..i] = i tbl2[i] = i tbl2['__'..i] = i end
table.table_insert(tbl,50,tbl2) 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 if not tbl2 then
tbl2 = start_index tbl2 = start_index
start_index = nil start_index = nil
end end
table.array_insert(tbl,start_index,tbl2) table.array_insert(tbl, start_index, tbl2)
for key, value in pairs(tbl2) do for key, value in pairs(tbl2) do
if not tonumber(key) then if not tonumber(key) then
tbl[key] = value tbl[key] = value
@@ -152,14 +152,14 @@ function table.array_contains(t, e)
end end
--- Extracts certain keys from a table --- 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 table tbl table the which contains the keys
-- @tparam string ... the names of the keys you want extracted -- @tparam string ... the names of the keys you want extracted
-- @return the keys in the order given -- @return the keys in the order given
function table.extract_keys(tbl,...) function table.extract_keys(tbl, ...)
local values = {} local values = {}
for _,key in pairs({...}) do for _, key in pairs({...}) do
table.insert(values,tbl[key]) table.insert(values, tbl[key])
end end
return unpack(values) return unpack(values)
end end
@@ -302,7 +302,7 @@ function table.get_values(tbl, sorted, as_string)
end end
end end
if sorted then if sorted then
table.sort(valueset,sortFunc) table.sort(valueset, sortFunc)
end end
return valueset return valueset
end end
@@ -328,7 +328,7 @@ function table.get_keys(tbl, sorted, as_string)
end end
end end
if sorted then if sorted then
table.sort(keyset,sortFunc) table.sort(keyset, sortFunc)
end end
return keyset return keyset
end end
@@ -340,11 +340,11 @@ function table.alphanumsort(tbl)
local o = table.get_keys(tbl) local o = table.get_keys(tbl)
local function padnum(d) local dec, n = string.match(d, "(%.?)0*(.+)") 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 return #dec > 0 and ("%.12f"):format(d) or ("%s%03d%s"):format(dec, #n, n) end
table.sort(o, function(a,b) table.sort(o, function(a, b)
return tostring(a):gsub("%.?%d+",padnum)..("%3d"):format(#b) return tostring(a):gsub("%.?%d+", padnum)..("%3d"):format(#b)
< tostring(b):gsub("%.?%d+",padnum)..("%3d"):format(#a) end) < tostring(b):gsub("%.?%d+", padnum)..("%3d"):format(#a) end)
local _tbl = {} 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 return _tbl
end end
@@ -352,9 +352,9 @@ end
-- @tparam table tbl the table to be sorted -- @tparam table tbl the table to be sorted
-- @treturn table the sorted table -- @treturn table the sorted table
function table.keysort(tbl) function table.keysort(tbl)
local o = table.get_keys(tbl,true) local o = table.get_keys(tbl, true)
local _tbl = {} 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 return _tbl
end end
@@ -365,7 +365,7 @@ end
t must be a list in ascending order for the return value to be valid. t must be a list in ascending order for the return value to be valid.
Usage example: Usage example:
local t = {1,3,5,7,9} local t = {1, 3,5, 7,9}
local x = 5 local x = 5
local index = table.binary_search(t, x) local index = table.binary_search(t, x)
if index < 0 then if index < 0 then

View File

@@ -72,7 +72,7 @@ local function handler_factory(event_name)
return function(element_name, handler) return function(element_name, handler)
local element = ExpGui.defines[element_name] local element = ExpGui.defines[element_name]
if not element then return end if not element then return end
element[event_name](element,function(_,_,event) element[event_name](element, function(_, _,event)
handler(event) handler(event)
end) end)
end end