repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
jkeywo/KFactorioMods
k-ruins_0.1.1/prototypes/world-tree.lua
1
6388
-- add data for entities local _tree_cluster = table.deepcopy( data.raw["tree"]["tree-01"] ) _tree_cluster.name = "tree-cluster" data:extend( { _tree_cluster, { type = "item", name = "fertiliser", icon = "__base__/graphics/icons/green-bush-mini.png", flags = {"goes-to-main-inventory"}, subgroup = "intermediate-product", order = "z[fertiliser]", stack_size = 100 }, { type = "recipe", name = "fertiliser", enabled = true, ingredients = { {type="fluid", name="petroleum-gas", amount=1}, { "stone", 1 } }, result = "fertiliser", category = "chemistry", }, { type = "recipe-category", name = "restore-world-tree", }, { type = "item", name = "restored-world-tree", icon = "__base__/graphics/icons/tree-05.png", flags = {"goes-to-main-inventory"}, subgroup = "ruins", order = "b[restored-world-tree]", stack_size = 1 }, { type = "recipe", name = "restore-world-tree", enabled = true, ingredients = { { "fertiliser", 1000 } }, result = "restored-world-tree", category = "restore-world-tree" }, { type = "assembling-machine", name = "world-tree-dead", icon = "__base__/graphics/icons/tree-05.png", flags = { "placeable-neutral" }, max_health = 250, corpse = "big-remnants", dying_explosion = "medium-explosion", resistances = { { type = "fire", percent = 70 } }, order = "a-b-a", collision_box = {{-1.2, -1.2}, {1.2, 1.2}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, vehicle_impact_sound = { filename = "__base__/sound/car-wood-impact.ogg", volume = 0.65 }, working_sound = { sound = { { filename = "__base__/sound/assembling-machine-t2-1.ogg", volume = 0.8 }, { filename = "__base__/sound/assembling-machine-t2-2.ogg", volume = 0.8 }, }, idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 }, apparent_volume = 1.5, }, animation = { filename = "__k-ruins__/graphics/world_tree_dead.png", priority = "high", width = 464, height = 384, frame_count = 1, line_length = 1, shift = {-0.0, -4.5} }, open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.85 }, close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.75 }, energy_source = { type = "electric", usage_priority = "secondary-input" }, energy_usage = "1kW", crafting_categories = { "restore-world-tree" }, crafting_speed = 1.0, ingredient_count = 1, }, { type = "item-subgroup", name = "capsules", group = "monuments", order = "d-b", }, { type = "capsule", name = "seed-pod", icon = "__base__/graphics/icons/tree-01.png", flags = {"goes-to-quickbar"}, capsule_action = { type = "throw", attack_parameters = { type = "projectile", ammo_category = "capsule", cooldown = 60, projectile_creation_distance = 0.6, range = 20, ammo_type = { category = "capsule", target_type = "position", action = { type = "direct", action_delivery = { type = "projectile", projectile = "tree-seed", starting_speed = 0.3 } } } } }, subgroup = "capsules", order = "a[grenade]-a[seed-pod]", stack_size = 100 }, { type = "projectile", name = "tree-seed", flags = {"not-on-map"}, acceleration = 0.005, action = { type = "direct", action_delivery = { type = "instant", target_effects = { type = "create-entity", entity_name = "tree-cluster", trigger_created_entity = true, offsets = {{0, 0}} } } }, light = {intensity = 0.1, size = 1}, animation = { filename = "__base__/graphics/entity/acid-projectile-purple/acid-projectile-purple.png", frame_count = 33, line_length = 5, width = 16, height = 18, priority = "high" }, shadow = { filename = "__base__/graphics/entity/acid-projectile-purple/acid-projectile-purple-shadow.png", frame_count = 33, line_length = 5, width = 28, height = 16, priority = "high" }, smoke = capsule_smoke }, { type = "recipe-category", name = "air-filter" }, { type = "recipe", name = "filter-air", icon = "__base__/graphics/icons/tree-05.png", category = "air-filter", subgroup = "ruins-products", order = "a[filter-air]", energy_required = 25, ingredients = { {"fertiliser", 1} }, results = { {type = "item", name = "seed-pod", amount = 1 }, }, }, { type = "furnace", name = "world-tree", icon = "__base__/graphics/icons/tree-05.png", flags = {"placeable-neutral"}, max_health = 1500, corpse = "big-remnants", collision_box = {{-1.2, -1.2}, {1.2, 1.2}}, selection_box = {{-1.5, -1.5}, {1.5, 1.5}}, vehicle_impact_sound = { filename = "__base__/sound/car-wood-impact.ogg", volume = 0.65 }, order = "a-b-a", animation = { filename = "__k-ruins__/graphics/world_tree.png", priority = "high", width = 464, height = 384, frame_count = 1, line_length = 1, shift = {-0.0, -4.5} }, open_sound = { filename = "__base__/sound/wooden-chest-open.ogg", volume = 0.85 }, close_sound = { filename = "__base__/sound/wooden-chest-close.ogg", volume = 0.75 }, working_sound = { sound = { { filename = "__base__/sound/electric-furnace.ogg", volume = 0.7 } }, idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 }, apparent_volume = 1.5, }, crafting_categories = {"air-filter"}, source_inventory_size = 1, result_inventory_size = 1, crafting_speed = 1.0, energy_source = { type = "electric", usage_priority = "secondary-input", emissions = -10.0 }, energy_usage = "1kW", ingredient_count = 1, module_slots = 0 } })
mit
vvw/waifu2x
lib/minibatch_adam.lua
35
1780
require 'optim' require 'cutorch' require 'xlua' local function minibatch_adam(model, criterion, train_x, config, transformer, input_size, target_size) local parameters, gradParameters = model:getParameters() config = config or {} local sum_loss = 0 local count_loss = 0 local batch_size = config.xBatchSize or 32 local shuffle = torch.randperm(#train_x) local c = 1 local inputs = torch.Tensor(batch_size, input_size[1], input_size[2], input_size[3]):cuda() local targets = torch.Tensor(batch_size, target_size[1] * target_size[2] * target_size[3]):cuda() local inputs_tmp = torch.Tensor(batch_size, input_size[1], input_size[2], input_size[3]) local targets_tmp = torch.Tensor(batch_size, target_size[1] * target_size[2] * target_size[3]) for t = 1, #train_x, batch_size do if t + batch_size > #train_x then break end xlua.progress(t, #train_x) for i = 1, batch_size do local x, y = transformer(train_x[shuffle[t + i - 1]]) inputs_tmp[i]:copy(x) targets_tmp[i]:copy(y) end inputs:copy(inputs_tmp) targets:copy(targets_tmp) local feval = function(x) if x ~= parameters then parameters:copy(x) end gradParameters:zero() local output = model:forward(inputs) local f = criterion:forward(output, targets) sum_loss = sum_loss + f count_loss = count_loss + 1 model:backward(inputs, criterion:backward(output, targets)) return f, gradParameters end optim.adam(feval, parameters, config) c = c + 1 if c % 10 == 0 then collectgarbage() end end xlua.progress(#train_x, #train_x) return { mse = sum_loss / count_loss} end return minibatch_adam
mit
jazzyb/lambdatk
sequence.lua
1
4255
-- Define Sequence class and methods Sequence = {} local function _init_seq_methods (seq) seq.concat = Sequence.concat seq.copy = Sequence.copy seq.filter = Sequence.filter seq.map = Sequence.map seq.prepend = Sequence.prepend seq.reduce = Sequence.reduce seq.reverse = Sequence.reverse seq.size = Sequence.size seq.split = Sequence.split seq.subseq = Sequence.subseq end -- Define table.pack() if using old Lua local pack = table.pack if not pack then pack = function (...) local arg = {...} arg.n = select('#', ...) return arg end end -- Sequence.new can take arguments in two ways: -- (1) Sequence.new(vargs...) -- (2) Sequence.new(count, func) -- In the first, any number and kind of items can be provided. A new Sequence -- will be constructed with those items in the order given. -- In the second, the second argument is a function that takes a single number -- as argument (the index). This function will be called 'count' times and -- will return the next item for the sequence. function Sequence.new (...) local args = pack(...) if args.n == 2 and type(args[1]) == 'number' and type(args[2]) == 'function' then local ret, count, f = {}, args[1], args[2] for i = 1, count do ret[i] = f(i) end ret.n = count args = ret end _init_seq_methods(args) return args end -- Return the size of the Sequence. Since we want these functions to work on -- any table sequence, not just Sequence instances -- if there is no length -- variable, then return #table. function Sequence.size (self) return self.n or #self end -- Returns a new Sequence generated by calling 'f' for each item in 'self' function Sequence.map (self, f) return Sequence.new(Sequence.size(self), function (i) return f(self[i]) end) end -- Returns a "reduced value" for the Sequence. May be called in two different -- ways: -- (1) Sequence.reduce(self, acc, func) -- (2) Sequence.reduce(self, func) -- In the first, 'func' is a function which takes two arguments: The first is -- an item from 'self', and the second is an "accumulator". The function will -- return the next accumulator. -- The second manner of calling the function is the same as the first except -- the first item in 'self' will be treated as the first accumulator variable. function Sequence.reduce (self, ...) local args = pack(...) local start, acc, f if args.n == 1 and type(args[1]) == 'function' then start, acc, f = 2, self[1], args[1] elseif args.n == 2 and type(args[2]) == 'function' then start, acc, f = 1, args[1], args[2] end for i = start, Sequence.size(self) do acc = f(self[i], acc) end return acc end -- Returns a new Sequence limited to the items in 'self' for which 'f' returns -- true function Sequence.filter (self, f) local ret = {} local count = 0 for i = 1, Sequence.size(self) do if f(self[i], i) then ret[count + 1] = self[i] count = count + 1 end end ret.n = count _init_seq_methods(ret) return ret end -- Returns a subsequence of 'self' from indices start to finish, inclusive function Sequence.subseq (self, start, finish) if finish == nil or finish == -1 then finish = Sequence.size(self) end return Sequence.filter(self, function (_, idx) return (idx >= start and idx <= finish) end) end -- Returns a copy of 'self' function Sequence.copy (self) return Sequence.subseq(self, 1) end -- Returns two values: the first item in 'self' and the rest of 'self' function Sequence.split (self) return self[1], Sequence.subseq(self, 2) end -- Returns a new Sequence with 'head' prepended to 'self' function Sequence.prepend (self, head) return Sequence.new(Sequence.size(self) + 1, function (i) if i == 1 then return head else return self[i - 1] end end) end -- Returns 'seq' concatenated to the end of 'self' function Sequence.concat (self, seq) local ret = Sequence.copy(self) for i = 1, Sequence.size(seq) do ret[ret.n + 1] = seq[i] ret.n = ret.n + 1 end return ret end -- Returns 'self' reversed function Sequence.reverse (self) local size = Sequence.size(self) return Sequence.new(size, function (i) return self[size - i + 1] end) end
mit
KlonZK/Zero-K
gamedata/modularcomms/weapons/aalaser.lua
5
1227
local name = "commweapon_aalaser" local weaponDef = { name = [[Anti-Air Laser]], areaOfEffect = 12, beamDecay = 0.736, beamTime = 0.01, beamttl = 15, canattackground = false, coreThickness = 0.5, craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { slot = [[5]], }, damage = { default = 1.88, planes = 18.8, subs = 1, }, explosionGenerator = [[custom:flash_teal7]], fireStarter = 100, impactOnly = true, impulseFactor = 0, interceptedByShieldType = 1, laserFlareSize = 3.25, minIntensity = 1, noSelfDamage = true, pitchtolerance = 8192, range = 800, reloadtime = 0.1, rgbColor = [[0 1 1]], soundStart = [[weapon/laser/rapid_laser]], soundStartVolume = 4, thickness = 2.1650635094611, tolerance = 8192, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 2200, } return name, weaponDef
gpl-2.0
EntranceJew/Simple-Tiled-Implementation
init.lua
9
1323
--- Simple and fast Tiled map loader and renderer. -- @module sti -- @author Landon Manning -- @copyright 2015 -- @license MIT/X11 local STI = { _LICENSE = "MIT/X11", _URL = "https://github.com/karai17/Simple-Tiled-Implementation", _VERSION = "0.14.1.12", _DESCRIPTION = "Simple Tiled Implementation is a Tiled Map Editor library designed for the *awesome* LÖVE framework.", cache = {} } local path = (...):gsub('%.init$', '') .. "." local Map = require(path .. "map") --- Instance a new map. -- @param path Path to the map file. -- @param plugins A list of plugins to load. -- @param ox Offset of map on the X axis (in pixels) -- @param oy Offset of map on the Y axis (in pixels) -- @return table The loaded Map. function STI.new(map, plugins, ox, oy) -- Check for valid map type local ext = map:sub(-4, -1) assert(ext == ".lua", string.format( "Invalid file type: %s. File must be of type: lua.", ext )) -- Get path to map local path = map:reverse():find("[/\\]") or "" if path ~= "" then path = map:sub(1, 1 + (#map - path)) end -- Load map map = love.filesystem.load(map) setfenv(map, {}) map = setmetatable(map(), {__index = Map}) map:init(STI, path, plugins, ox, oy) return map end --- Flush image cache. function STI:flush() self.cache = {} end return STI
mit
tunneff/tef
deps/lzmq/examples/utils.lua
16
1150
local zmq = require "lzmq" io.stdout:setvbuf"no" function printf(...) return print(string.format(...)) end function print_msg(title, data, err, ...) print(title) if data then -- data if type(data) == 'table' then for _, msg in ipairs(data) do printf("[%.4d] %s", #msg, msg) end elseif type(data) == 'userdata' then printf("[%.4d] %s", data:size(), data:data()) else printf("[%.4d] %s", #data, data) end else --error if type(err) == 'string' then printf("Error: %s", err) elseif type(err) == 'number' then local msg = zmq.error(err):msg() local mnemo = zmq.errors[err] or 'UNKNOWN' printf("Error: [%s] %s (%d)", mnemo, msg, err) elseif type(err) == 'userdata' then printf("Error: [%s] %s (%d)", err:mnemo(), err:msg(), err:no()) else printf("Error: %s", tostring(err)) end end print("-------------------------------------") return data, err, ... end function print_version(zmq) local version = zmq.version() printf("zmq version: %d.%d.%d", version[1], version[2], version[3]) end
lgpl-3.0
KlonZK/Zero-K
ModOptions.lua
1
18655
-- $Id: ModOptions.lua 4642 2009-05-22 05:32:36Z carrepairer $ -- Custom Options Definition Table format -- NOTES: -- - using an enumerated table lets you specify the options order -- -- These keywords must be lowercase for LuaParser to read them. -- -- key: the string used in the script.txt -- name: the displayed name -- desc: the description (could be used as a tooltip) -- type: the option type ('list','string','number','bool') -- def: the default value -- min: minimum value for number options -- max: maximum value for number options -- step: quantization step, aligned to the def value -- maxlen: the maximum string length for string options -- items: array of item strings for list options -- section: so lobbies can order options in categories/panels -- scope: 'all', 'player', 'team', 'allyteam' <<< not supported yet >>> -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Example ModOptions.lua -- local options = { -- do deployment and tactics even work? { key = 'a_important', name = 'Important', desc = 'Commonly used options.', type = 'section', }, { key = 'silly', -- lava, fun, zombies name = 'Silly', desc = 'Silly options for trolling.', type = 'section', }, { key = 'zkmode', name = 'Game Mode', desc = 'Change the game mode.', type = 'list', section= 'silly', def = 'normal', items = { { key = 'normal', name = 'Normal', desc = 'Normal game mode', }, { key = 'lavarise', name = 'Lava Rising', desc = 'Endlessly rising lava! Fiery fun for the whole family!', }, }, }, { key = 'commends', name = 'Team Commander Ends', desc = 'Causes an allyteam to lose if they have no commanders left on their team', type = 'bool', def = false, section= 'modifiers', }, { key = "noelo", name = "No Elo", desc = "Prevent battle from affecting Elo rankings", type = "bool", section= 'a_important', def = false, }, { key = 'mutespec', name = 'Mute Spectators', desc = 'Determines whether spectators can talk to players.', type = 'list', section = 'a_important', def = 'autodetect', items = { { key='mute', name = "Mute", desc = 'Mutes spectators.' }, { key='autodetect', name = "Autodetect", desc = 'Mutes spectators in FFA (more than two teams).' }, { key='nomute', name = "No Mute", desc = 'Does not mute spectators.' }, }, }, { key = 'mutelobby', name = 'Mute Lobby', desc = 'Determines whether chat in the lobby is visible ingame.', type = 'list', section = 'a_important', def = 'autodetect', items = { { key='mute', name = "Mute", desc = 'Mutes the lobby.' }, { key='autodetect', name = "Autodetect", desc = 'Mutes the lobby in FFA (more than two teams).' }, { key='nomute', name = "No Mute", desc = 'Does not mute the lobby.' }, }, }, { key='lavarisecycles', name='Number of cycles', desc='Set how many cycles before map floods completely. The more cycles, the slower the map floods. ', type='number', def=7, min=1, max=2000, step=1.0, section='silly', }, { key='lavariseperiod', name='Length of lava cycle', desc='How long each rise will wait for the next in seconds. ', type='number', def=120, min=1, max=6000, step=1, section='silly', }, { key = 'zombies', name = 'Enable zombies', desc = "All features self-resurrect.", type = 'bool', section= 'silly', def = false, }, { key = 'zombies_delay', name = 'Zombie min spawn time', desc = "In seconds, unit will resurrection no faster than this.", type = 'number', section= 'silly', def=10, min=1, max=600, step=1, }, { key = 'zombies_rezspeed', name = 'Zombie resurrection speed', desc = "In metal per second.", type = 'number', section= 'silly', def=12, min=1, max=10000, step=1, }, { key = 'zombies_permaslow', name = 'Zombie permaslow modifier', desc = "If more than 0 zombies are permaslowed to half of that amount, so 1 means 50% slow.", type = 'number', section= 'silly', def=1, min=0, max=1, step=0.01, }, { key = "forcejunior", name = "Force Junior", desc = "Choose whether everyone gets a standard Junior Comm chassis.", type = "bool", section= 'startconds', def = false, }, { key = "disabledunits", name = "Disable units", desc = "Prevents specified units from being built ingame. Specify multiple units by using + ", section = 'startconds', type = "string", def = nil, }, { key = "noair", name = "Disable air", desc = "Disables plane and gunship factories", section = 'startconds', type = "bool", def = false, }, { key = "nodef", name = "Disable defences", desc = "Disables all defences from Defence tab", section = 'startconds', type = "bool", def = false, }, { key = "overdrivesharingscheme", name = "Overdrive Resource Distribution Scheme", desc = "Different scheme designed for distributing overdrive share.", type = "list", section= 'a_important', def = "investmentreturn", items = { { key = "investmentreturn", name = "Investment Return", desc = "Extra income is given to active players who built economy structure until the cost of the structure is paid.", }, { key = "investmentreturn_od", name = "Overdrive Return", desc = "Extra overdrive is given to active players who built energy structure until the cost of the structure is paid.", }, { key = "investmentreturn_base", name = "Extractor Return", desc = "Extra income is given to active players who built metal extractor until the cost of the structure is paid.", }, { key = "communism", name = "Equal Sharing", desc = "All overdrive is shared equally among active players at all time.", }, }, }, { key = "allyreclaim", name = "Reclaimable allies", desc = "Allows reclaiming allied units and structures", type = "bool", section = "modifiers", def = false, }, { key = "shuffle", name = "Shuffle Start Boxes", desc = "Shuffles start boxes.", type = "list", section= 'startconds', def = "off", items = { { key = "off", name = "Off", desc = "Do nothing.", }, { key = "shuffle", name = "Shuffle", desc = "Shuffle among boxes that would be used.", }, { key = "allshuffle", name = "All Shuffle", desc = "Shuffle all present boxes.", }, }, }, { key = 'noceasefire', name = 'Disable ceasefire panel', desc = 'Disable ceasefire control panel (When "Fixed ingame alliances" is off).', type = 'bool', section = 'diplomacy', def = false, }, { key = 'sharemode', name = 'Share Mode', desc = 'Determines to which teams you may share units.', type = 'list', section = 'diplomacy', def = 'teammates', items = { { key='teammates', name="Teammates Only", desc='Share only to teammates.' }, { key='ceasefire', name="Teammates and Ceasefired", desc='May also share to temporary ceasefired allies.' }, { key='anyone', name="Anyone", desc='Share to anyone, including enemies.' }, }, }, { key='typemapsetting', name='Terrain Speed Boost', desc='Choose which map Speed Boost to use', type='list', section= 'mapsettings', def='auto', items = { { key='auto', name="Automatic", desc='Use one of the other options based on a mod-defined list, defaulting to Keep Equal' }, { key='mapdefault', name="Map Default", desc='Use map speed boost' }, { key='average', name="Average", desc='Each terrain types speed boost is averaged' }, { key='keepequal', name="Keep Equal", desc='Non-equal speedboost removed' }, { key='onlyimpassable', name="Only Impassable", desc='Override all speedboost except impassable terrain' }, { key='alloff', name="All Off", desc='Disable all speed boost' }, }, }, { key = 'waterlevel', name = 'Water Level', desc = 'Adjusts the water level of the map', type = 'number', section= 'mapsettings', def = 0, min = -2000, max = 2000, step = 1, }, { key = 'metalmult', name = 'Metal Extraction Multiplier', desc = 'Multiplies metal extraction rate. For use in large team games when there are fewer mexes per player.', type = 'number', section= 'mapsettings', def = 1, min = 0, max = 100, step = 0.05, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, { key = 'energymult', name = 'Energy Production Multiplier', desc = 'Useful for speed games without relying on map units.', type = 'number', section= 'mapsettings', def = 1, min = 0, max = 100, step = 0.05, -- quantization is aligned to the def value -- (step <= 0) means that there is no quantization }, { key = 'experimental', name = 'Experimental Settings', desc = 'Experimental settings.', type = 'section', }, { key = 'marketandbounty', name = 'Enable MarketPlace and Bounties (dysfunctional)', desc = 'Adds option to sell your units, buy units from allies (including temporary allies). Also allows you to place a bounty on a unit.', type = 'bool', section= 'experimental', def = false, }, { key = 'terracostmult', name = 'Terraform Cost Multiplier', desc = 'Multiplies the cost of terraform.', type = 'number', section= 'experimental', def = 1, min = 0.01, max = 100, step = 0.01, }, { key = 'terrarestoreonly', name = 'Terraform Restore Only', desc = 'Restore is the only terraform option available.', type = 'bool', section= 'experimental', def = false, }, --[[ { key = 'damagemult', name = 'Damage Multiplier', desc = 'Multiplies the damage dealt by all weapons, except for D-guns; autoheal; repair; and capture.', type = 'number', section= 'experimental', def = 1, min = 0.01, max = 10, step = 0.01, }, { key = 'unitspeedmult', name = 'Unit Speed Multiplier', desc = 'Multiplies the speed, acceleration, and turn rate of all units.', type = 'number', section= 'experimental', def = 1, min = 0.01, max = 10, step = 0.01, }, ]]-- { key = 'cratermult', name = 'Cratering Multiplier', desc = 'Multiplies the depth of craters.', type = 'number', section= 'experimental', def = 1, min = 0, max = 1000, step = 0.01, }, { key = 'defeatmode', name = 'Defeat Mode', desc = "Method of handling defeated alliances", type = 'list', section= 'experimental', def = 'destroy', items = { { key='debug', name="Debug", desc='Does nothing; game is endless.' }, { key='destroy', name="Destroy Alliance", desc='Destroys the alliance if they are defeated"' }, { key='losecontrol', name="Lose Control", desc='Alliance loses control of their units if they are defeated.' }, }, }, --[[ { key = 'easymetal', name = 'Easy Metal', desc = 'Metal extractors are restricted to metal spots in the same way geo plants are. Spots are pre-analyzed but certain maps will provide strange results, such as Azure or Speedmetal.', type = 'bool', section= 'experimental', def = false, }, --]] --[[ { key = 'terratex', name = 'Terraform Texture', desc = 'Adds a texture to terraformed ground.', type = 'bool', section= 'experimental', def = true, }, --]] --[[ { key = 'specialpower', name = 'Special Advanced Powerplants', desc = 'Rather than explode like a nuke, Adv Fusions create a massive implosion.', type = 'bool', section= 'experimental', def = false, }, --]] { key = 'specialdecloak', name = 'Special Decloak Behavior (buggy)', desc = 'Overrides engine\'s decloak. Shows cloaked units only to team that reveals them, also fixes cloak behavior in FFA games with ceasefires.', type = 'bool', section= 'experimental', def = false, }, { key = 'xmas', name = 'Enable festive units', desc = "Zero K units get into the spirit of the season with a festive new look.", type = 'bool', section= 'silly', def = false, }, { key = 'iwinbutton', name = 'Enable giant expensive "I Win" button', desc = "For speed games. Race to build it!", type = 'bool', section= 'silly', def = false, }, { key = "disablefeatures", name = "Disable Features", desc = "Disable features (no wreackages).", type = "bool", section= "mapsettings", def = false, }, { key = 'factorycostmult', name = 'Factory Cost Multiplier', desc = 'Multiplies the cost of factories.', type = 'number', section= 'experimental', def = 1, min = 0.01, max = 100, step = 0.01, }, { key = 'wreckagemult', name = 'Wreckage Metal Multiplier', desc = 'Multiplies the metal of wreckages and debris.', type = 'number', section= 'experimental', def = 1, min = 0.01, max = 100, step = 0.01, }, { key = "coop", name = "Cooperation Mode", desc = "Cooperation Mode", type = "bool", section= "startconds", def = false, }, --{ -- key = "enableunlocks", -- name = "Enable unlock system", -- desc = "Enables the unlock system (disabling will enable all units by default)", -- type = "bool", -- def = true, -- section = "experimental", --}, { key = "impulsejump", name = "Impulses Jump", desc = "Allow jumps that is effected by Newton and can jump anywhere (no restriction). Compatible for Spring 93.2 and above", type = "bool", def = false, section = "experimental", }, { key = "pathfinder", name = "Pathfinder type", desc = "Sets the pathfinding system used by units.", type = "list", def = "standard", section = "experimental", items = { { key = 'standard', name = 'Standard', desc = 'Standard pathfinder', }, { key = 'qtpfs', name = 'QTPFS', desc = 'New Quadtree Pathfinding System (experimental)', }, -- { -- key = 'classic', -- name = 'Classic', -- desc = 'An older pathfinding system without turninplace or reverse', -- } }, }, { key = 'chicken', name = 'Chicken', desc = 'Settings for Chicken: Custom', type = 'section', }, { key = "playerchickens", name = "Players as chickens", desc = "Shared chickens with players, take commanders away", type = "bool", def = false, section = 'chicken', }, { key = "eggs", name = "Chicken Eggs", desc = "Enables eggs mode (applies to all chicken difficulties); metal extractors are disabled but chickens drop twice as many eggs", type = "bool", def = false, section = 'chicken', }, { key = "speedchicken", name = "Speed Chicken", desc = "Game lasts half as long; no miniqueens (applies to all chicken difficulties)", type = "bool", def = false, section = 'chicken', }, { key = 'chickenspawnrate', name = 'Chicken Spawn Rate', desc = 'Sets the frequency of chicken waves in seconds.', type = 'number', section= 'chicken', def = 50, min = 20, max = 200, step = 1, }, { key = 'burrowspawnrate', name = 'Burrow Spawn Rate', desc = 'Sets the frequency of burrow spawns in seconds (modified by playercount and number of existing burrows).', type = 'number', section= 'chicken', def = 45, min = 20, max = 200, step = 1, }, { key = 'queentime', name = 'Queen Time', desc = 'How soon the queen appears on her own, minutes.', type = 'number', section= 'chicken', def = 60, min = 1, max = 200, step = 1, }, { key = 'graceperiod', name = 'Grace Period', desc = 'Delay before the first wave appears, minutes.', type = 'number', section= 'chicken', def = 2.5, min = 0, max = 120, step = 0.5, }, { key = 'miniqueentime', name = 'Dragon Time', desc = 'Time when the White Dragons appear, as a proportion of queen time. 0 disables.', type = 'number', section= 'chicken', def = 0.6, min = 0, max = 1, step = 0.05, }, { key = 'techtimemult', name = 'Tech Time Mult', desc = 'Multiplier for the appearance times of advanced chickens.', type = 'number', section= 'chicken', def = 1, min = 0, max = 5, step = 0.05, }, --[[ { key = 'burrowtechtime', name = 'Burrow Tech Time', desc = 'How much time each burrow shaves off chicken appearance times per wave (divided by playercount), seconds', type = 'number', section= 'chicken', def = 12, min = 0, max = 60, step = 1, }, ]]-- { key = 'burrowqueentime', name = 'Burrow Queen Time', desc = 'How much time each burrow death subtracts from queen appearance time, seconds', type = 'number', section= 'chicken', def = 15, min = 0, max = 120, step = 1, }, } --// add key-name to the description (so you can easier manage modoptions in springie) for i=1,#options do local opt = options[i] opt.desc = opt.desc .. '\nkey: ' .. opt.key end return options
gpl-2.0
KlonZK/Zero-K
LuaUI/Configs/marking_menu_menu_armcom.lua
6
3784
local menu_armcom = { items = { { angle = 0, unit = "cormex", label = "Economy", items = { { angle = 45, unit = "cafus" }, { angle= 90, unit = "armfus", }, { angle= 135, unit = "geo", }, --{ -- angle = -45, -- unit = "cortide", --}, { angle = -45, unit = "armnanotc", }, { angle= -90, unit = "armsolar", }, { angle= -135, unit = "armwin", }, } }, { angle = -45, unit = "factoryplane", label = "Air/Sea Facs", items = { { angle = 90, unit = "factorygunship" }, { angle = -90, unit = "armcsa" }, { angle = -135, unit = "factoryamph" }, { angle = 180, unit = "factoryship" }, { angle = 0, unit = "armasp" }, } }, { angle = -90, unit = "factorycloak", label = "Land Facs", items = { { angle = 0, unit = "factoryshield" }, { angle = 45, unit = "factoryjump" }, { angle = -45, unit = "factoryspider" }, { angle = 180, unit = "factoryveh" }, { angle = 135, unit = "factorytank" }, { angle = -135, unit = "factoryhover" }, } }, { angle = 180, unit = "corllt", label = "Defense", items = { { angle = 45, unit = "corrl" }, -- { -- angle = 90, -- unit = "corpre" -- }, { angle = 90, unit = "corhlt" }, { angle = 135, unit = "corgrav" }, { angle = -90, unit = "armdeva" }, { angle = -135, unit = "armartic" }, { angle = -45, unit = "armpb" } } }, { angle = 135, unit = "corrl", label = "AA/AS", items = { { angle = 0, unit = "screamer" }, { angle = -90, unit = "corrazor" }, { angle = 45, unit = "corflak" }, { angle = -135, unit = "missiletower" }, { angle = 90, unit = "armcir" }, { angle = 180, unit = "turrettorp" } } }, { angle = 90, unit = "corrad", label = "Support", items = { { angle = 0, unit = "armarad" }, { angle = -180, unit = "corjamt" }, { angle = 135, unit = "armjamt" }, { angle = 45, unit = "armsonar" }, { angle = -45, unit = "armestor" }, { angle = -135, unit = "armmstor" }, } }, { angle = -135, unit = "armamd", label = "Super", items = { { angle = 0, unit = "corsilo" }, { angle = 90, unit = "missilesilo" }, { angle = 135, unit = "armanni" }, { angle = 180, unit = "cordoom" }, { angle = -45, unit = "corbhmth" }, { angle = -90, unit = "armbrtha" } } }, { angle = 45, unit = "mahlazer", label = "Costly", items = { { angle = 315, unit = "striderhub" }, { angle = 180, unit = "raveparty" }, { angle = 135, unit = "iwin" }, { angle = 0, unit = "zenith" }, }, }, }, } return menu_armcom
gpl-2.0
ms2008/lor
lib/lor/lib/middleware/session.lua
2
6231
local type, xpcall = type, xpcall local traceback = debug.traceback local string_sub = string.sub local string_len = string.len local http_time = ngx.http_time local ngx_time = ngx.time local ck = require("resty.cookie") local utils = require("lor.lib.utils.utils") local aes = require("lor.lib.utils.aes") local base64 = require("lor.lib.utils.base64") local function decode_data(field, aes_key, ase_secret) if not field or field == "" then return {} end local payload = base64.decode(field) local data = {} local cipher = aes.new() local decrypt_str = cipher:decrypt(payload, aes_key, ase_secret) local decode_obj = utils.json_decode(decrypt_str) return decode_obj or data end local function encode_data(obj, aes_key, ase_secret) local default = "{}" local str = utils.json_encode(obj) or default local cipher = aes.new() local encrypt_str = cipher:encrypt(str, aes_key, ase_secret) local encode_encrypt_str = base64.encode(encrypt_str) return encode_encrypt_str end local function parse_session(field, aes_key, ase_secret) if not field then return end return decode_data(field, aes_key, ase_secret) end --- no much secure & performance consideration --- TODO: optimization & security issues local session_middleware = function(config) config = config or {} config.session_key = config.session_key or "_app_" if config.refresh_cookie ~= false then config.refresh_cookie = true end if not config.timeout or type(config.timeout) ~= "number" then config.timeout = 3600 -- default session timeout is 3600 seconds end local err_tip = "session_aes_key should be set for session middleware" -- backward compatibility for lor < v0.3.2 config.session_aes_key = config.session_aes_key or "custom_session_aes_key" if not config.session_aes_key then ngx.log(ngx.ERR, err_tip) end local session_key = config.session_key local session_aes_key = config.session_aes_key local refresh_cookie = config.refresh_cookie local timeout = config.timeout -- session_aes_secret must be 8 charactors to respect lua-resty-string v0.10+ local session_aes_secret = config.session_aes_secret or config.secret or "12345678" if string_len(session_aes_secret) < 8 then for i=1,8-string_len(session_aes_secret),1 do session_aes_secret = session_aes_secret .. "0" end end session_aes_secret = string_sub(session_aes_secret, 1, 8) ngx.log(ngx.INFO, "session middleware initialized") return function(req, res, next) if not session_aes_key then return next(err_tip) end local cookie, err = ck:new() if not cookie then ngx.log(ngx.ERR, "cookie is nil:", err) end local current_session local session_data, err = cookie:get(session_key) if err then ngx.log(ngx.ERR, "cannot get session_data:", err) else if session_data then current_session = parse_session(session_data, session_aes_key, session_aes_secret) end end current_session = current_session or {} req.session = { set = function(...) local p = ... if type(p) == "table" then for i, v in pairs(p) do current_session[i] = v end else local params = { ... } if type(params[2]) == "table" then -- set("k", {1, 2, 3}) current_session[params[1]] = params[2] else -- set("k", "123") current_session[params[1]] = params[2] or "" end end local value = encode_data(current_session, session_aes_key, session_aes_secret) local expires = http_time(ngx_time() + timeout) local max_age = timeout local ok, err = cookie:set({ key = session_key, value = value or "", expires = expires, max_age = max_age, path = "/" }) ngx.log(ngx.INFO, "session.set: ", value) if err or not ok then return ngx.log(ngx.ERR, "session.set error:", err) end end, refresh = function() if session_data and session_data ~= "" then local expires = http_time(ngx_time() + timeout) local max_age = timeout local ok, err = cookie:set({ key = session_key, value = session_data or "", expires = expires, max_age = max_age, path = "/" }) if err or not ok then return ngx.log(ngx.ERR, "session.refresh error:", err) end end end, get = function(key) return current_session[key] end, destroy = function() local expires = "Thu, 01 Jan 1970 00:00:01 GMT" local max_age = 0 local ok, err = cookie:set({ key = session_key, value = "", expires = expires, max_age = max_age, path = "/" }) if err or not ok then ngx.log(ngx.ERR, "session.destroy error:", err) return false end return true end } if refresh_cookie then local e, ok ok = xpcall(function() req.session.refresh() end, function() e = traceback() end) if not ok then ngx.log(ngx.ERR, "refresh cookie error:", e) end end next() end end return session_middleware
mit
ds4ww/lurs
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
annulen/premake-dev-rgeary
tests/base/test_path.lua
2
6951
-- -- tests/base/test_path.lua -- Automated test suite for the action list. -- Copyright (c) 2008-2010 Jason Perkins and the Premake project -- T.path = { } local suite = T.path -- -- path.getabsolute() tests -- function suite.getabsolute_ReturnsCorrectPath_OnMissingSubdir() local expected = path.translate(os.getcwd(), "/") .. "/a/b/c" test.isequal(expected, path.getabsolute("a/b/c")) end function suite.getabsolute_RemovesDotDots_OnWindowsAbsolute() test.isequal("c:/ProjectB/bin", path.getabsolute("c:/ProjectA/../ProjectB/bin")) end function suite.getabsolute_RemovesDotDots_OnPosixAbsolute() test.isequal("/ProjectB/bin", path.getabsolute("/ProjectA/../ProjectB/bin")) end function suite.getabsolute_OnTrailingSlash() local expected = path.translate(os.getcwd(), "/") .. "/a/b/c" test.isequal(expected, path.getabsolute("a/b/c/")) end function suite.getabsolute_OnLeadingEnvVar() test.isequal("$(HOME)/user", path.getabsolute("$(HOME)/user")) end function suite.getabsolute_OnMultipleEnvVar() test.isequal("$(HOME)/$(USER)", path.getabsolute("$(HOME)/$(USER)")) end function suite.getabsolute_OnTrailingEnvVar() local expected = path.translate(os.getcwd(), "/") .. "/home/$(USER)" test.isequal(expected, path.getabsolute("home/$(USER)")) end function suite.getabsolute_OnLeadingEnvVarQuoted() test.isequal('"$(HOME)/user"', path.getabsolute('"$(HOME)/user"')) end -- -- path.getbasename() tests -- function suite.getbasename_ReturnsCorrectName_OnDirAndExtension() test.isequal("filename", path.getbasename("folder/filename.ext")) end -- -- path.getdirectory() tests -- function suite.getdirectory_ReturnsEmptyString_OnNoDirectory() test.isequal(".", path.getdirectory("filename.ext")) end function suite.getdirectory_ReturnsDirectory_OnSingleLevelPath() test.isequal("dir0", path.getdirectory("dir0/filename.ext")) end function suite.getdirectory_ReturnsDirectory_OnMultiLeveLPath() test.isequal("dir0/dir1/dir2", path.getdirectory("dir0/dir1/dir2/filename.ext")) end function suite.getdirectory_ReturnsRootPath_OnRootPathOnly() test.isequal("/", path.getdirectory("/filename.ext")) end -- -- path.getdrive() tests -- function suite.getdrive_ReturnsNil_OnNotWindows() test.isnil(path.getdrive("/hello")) end function suite.getdrive_ReturnsLetter_OnWindowsAbsolute() test.isequal("x", path.getdrive("x:/hello")) end -- -- path.getextension() tests -- function suite.getextension_ReturnsEmptyString_OnNoExtension() test.isequal("", path.getextension("filename")) end function suite.getextension_ReturnsExtension() test.isequal(".txt", path.getextension("filename.txt")) end function suite.getextension_OnMultipleDots() test.isequal(".txt", path.getextension("filename.mod.txt")) end function suite.getextension_OnLeadingNumeric() test.isequal(".7z", path.getextension("filename.7z")) end function suite.getextension_OnUnderscore() test.isequal(".a_c", path.getextension("filename.a_c")) end function suite.getextension_OnHyphen() test.isequal(".a-c", path.getextension("filename.a-c")) end -- -- path.getrelative() tests -- function suite.getrelative_ReturnsDot_OnMatchingPaths() test.isequal(".", path.getrelative("/a/b/c", "/a/b/c")) end function suite.getrelative_ReturnsDoubleDot_OnChildToParent() test.isequal("..", path.getrelative("/a/b/c", "/a/b")) end function suite.getrelative_ReturnsDoubleDot_OnSiblingToSibling() test.isequal("../d", path.getrelative("/a/b/c", "/a/b/d")) end function suite.getrelative_ReturnsChildPath_OnParentToChild() test.isequal("d", path.getrelative("/a/b/c", "/a/b/c/d")) end function suite.getrelative_ReturnsChildPath_OnWindowsAbsolute() test.isequal("obj/debug", path.getrelative("C:/Code/Premake4", "C:/Code/Premake4/obj/debug")) end function suite.getrelative_ReturnsAbsPath_OnDifferentDriveLetters() test.isequal("D:/Files", path.getrelative("C:/Code/Premake4", "D:/Files")) end function suite.getrelative_ReturnsAbsPath_OnDollarMacro() test.isequal("$(SDK_HOME)/include", path.getrelative("C:/Code/Premake4", "$(SDK_HOME)/include")) end function suite.getrelative_ReturnsAbsPath_OnRootedPath() test.isequal("/opt/include", path.getrelative("/home/me/src/project", "/opt/include")) end -- -- path.isabsolute() tests -- function suite.isabsolute_ReturnsTrue_OnAbsolutePosixPath() test.istrue(path.isabsolute("/a/b/c")) end function suite.isabsolute_ReturnsTrue_OnAbsoluteWindowsPathWithDrive() test.istrue(path.isabsolute("C:/a/b/c")) end function suite.isabsolute_ReturnsFalse_OnRelativePath() test.isfalse(path.isabsolute("a/b/c")) end function suite.isabsolute_ReturnsTrue_OnDollarSign() test.istrue(path.isabsolute("$(SDK_HOME)/include")) end -- -- path.join() tests -- function suite.join_OnValidParts() test.isequal("p1/p2", path.join("p1", "p2")) end function suite.join_OnAbsoluteUnixPath() test.isequal("/p2", path.join("p1", "/p2")) end function suite.join_OnAbsoluteWindowsPath() test.isequal("C:/p2", path.join("p1", "C:/p2")) end function suite.join_OnCurrentDirectory() test.isequal("p2", path.join(".", "p2")) end function suite.join_OnNilSecondPart() test.isequal("p1", path.join("p1", nil)) end function suite.join_onMoreThanTwoParts() test.isequal("p1/p2/p3", path.join("p1", "p2", "p3")) end function suite.join_removesExtraInternalSlashes() test.isequal("p1/p2", path.join("p1/", "p2")) end function suite.join_removesTrailingSlash() test.isequal("p1/p2", path.join("p1", "p2/")) end function suite.join_ignoresNilParts() test.isequal("p2", path.join(nil, "p2", nil)) end function suite.join_ignoresEmptyParts() test.isequal("p2", path.join("", "p2", "")) end -- -- path.rebase() tests -- function suite.rebase_WithEndingSlashOnPath() local cwd = os.getcwd() test.isequal("src", path.rebase("../src/", cwd, path.getdirectory(cwd))) end -- -- path.translate() tests -- function suite.translate_ReturnsTranslatedPath_OnValidPath() test.isequal("dir/dir/file", path.translate("dir\\dir\\file", "/")) end function suite.translate_returnsCorrectSeparator_onMixedPath() local actual = path.translate("dir\\dir/file", "/") test.isequal("dir/dir/file", actual) end -- -- path.wildcards tests -- function suite.wildcards_MatchesTrailingStar() local p = path.wildcards("**/xcode/*") test.isequal(".*/xcode/[^/]*", p) end function suite.wildcards_MatchPlusSign() local patt = path.wildcards("file+name.*") local name = "file+name.c" test.isequal(name, name:match(patt)) end function suite.wildcards_escapeSpecialChars() test.isequal("%.%-", path.wildcards(".-")) end function suite.wildcards_escapeStar() test.isequal("vs[^/]*", path.wildcards("vs*")) end function suite.wildcards_escapeStarStar() test.isequal("Images/.*%.bmp", path.wildcards("Images/**.bmp")) end
bsd-3-clause
Black-Nine/anti-spbot
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
turanszkij/WickedEngine
Tests/test_script.lua
1
2228
-- Wicked Engine Test Framework lua script backlog_post("Begin script: test_script.lua"); -- Load a model: local parent = LoadModel("../Content/models/teapot.wiscene"); LoadModel("../Content/models/cameras.wiscene"); -- Load camera sample script: dofile("../Content/scripts/camera_animation_repeat.lua"); ToggleCameraAnimation(); -- Load an image: local sprite = Sprite("../Content/logo_small.png"); sprite.SetParams(ImageParams(100,100,128,128)); -- Set this image as renderable to the active component: local component = main.GetActivePath(); component.AddSprite(sprite); -- Start a background task to rotate the model and update the sprite: runProcess(function() local velocity = Vector((math.random() * 2 - 1) * 4, (math.random() * 2 - 1) * 4); -- starting velocity for our sprite local screenW = GetScreenWidth(); local screenH = GetScreenHeight(); local scene = GetScene(); -- This shows how to handle attachments: -- -- Create parent transform, this will be rotated: -- local parent = CreateEntity(); -- scene.Component_CreateTransform(parent); -- -- -- Retrieve teapot base and lid entity IDs: -- local teapot_base = scene.Entity_FindByName("Base"); -- local teapot_top = scene.Entity_FindByName("Top"); -- -- -- Attach base to parent, lid to base: -- scene.Component_Attach(teapot_base, parent); -- scene.Component_Attach(teapot_top, teapot_base); while(true) do -- Bounce our sprite across the screen: local fx = sprite.GetParams(); local pos = fx.GetPos(); local size = fx.GetSize(); -- if it hits a wall, reverse velocity: if(pos.GetX()+size.GetX() >= screenW) then velocity.SetX(velocity.GetX() * -1); end if(pos.GetY()+size.GetY() >= screenH) then velocity.SetY(velocity.GetY() * -1); end if(pos.GetX() <= 0) then velocity.SetX(velocity.GetX() * -1); end if(pos.GetY() < 0) then velocity.SetY(velocity.GetY() * -1); end pos = vector.Add(pos, velocity); fx.SetPos(pos); sprite.SetParams(fx); -- Rotate teapot by parent transform: local transform = scene.Component_GetTransform(parent); transform.Rotate(Vector(0, 0, 0.01)); fixedupdate(); -- wait for new frame end end); backlog_post("Script complete.");
mit
KlonZK/Zero-K
LuaUI/camain.lua
7
4795
-- $Id: camain.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: main.lua -- brief: the entry point from gui.lua, relays call-ins to the widget manager -- author: Dave Rodgers -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- 0.75b2 compatibilty -- if (Spring.GetTeamColor == nil) then local getTeamInfo = Spring.GetTeamInfo Spring.GetTeamColor = function(teamID) local _,_,_,_,_,_,r,g,b,a = getTeamInfo(teamID) return r, g, b, a end Spring.GetTeamInfo = function(teamID) local id, leader, active, isDead, isAi, side, r, g, b, a, allyTeam = getTeamInfo(teamID) return id, leader, active, isDead, isAi, side, allyTeam end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- Spring.SendCommands({"ctrlpanel " .. LUAUI_DIRNAME .. "ctrlpanel.txt"}) VFS.Include(LUAUI_DIRNAME .. 'utils.lua', utilFile) include("setupdefs.lua") include("savetable.lua") include("debug.lua") include("modfonts.lua") include("layout.lua") -- contains a simple LayoutButtons() include("cawidgets.lua") -- the widget handler -------------------------------------------------------------------------------- -- -- print the header -- if (RestartCount == nil) then RestartCount = 0 else RestartCount = RestartCount + 1 end do local restartStr = "" if (RestartCount > 0) then restartStr = " (" .. RestartCount .. " Restarts)" end Spring.SendCommands({"echo " .. LUAUI_VERSION .. restartStr}) end -------------------------------------------------------------------------------- local gl = Spring.Draw -- easier to use ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- -- A few helper functions -- function Say(msg) Spring.SendCommands({'say ' .. msg}) end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- -- Update() -- called every frame -- activePage = 0 forceLayout = true function Update() local currentPage = Spring.GetActivePage() if (forceLayout or (currentPage ~= activePage)) then Spring.ForceLayoutUpdate() -- for the page number indicator forceLayout = false end activePage = currentPage fontHandler.Update() widgetHandler:Update() return end ------------------------------------------------------------------------------- ------------------------------------------------------------------------------- -- -- WidgetHandler fixed calls -- function Shutdown() return widgetHandler:Shutdown() end function ConfigureLayout(command) return widgetHandler:ConfigureLayout(command) end function CommandNotify(id, params, options) return widgetHandler:CommandNotify(id, params, options) end function DrawScreen(vsx, vsy) return widgetHandler:DrawScreen() end function KeyPress(key, mods, isRepeat) return widgetHandler:KeyPress(key, mods, isRepeat) end function KeyRelease(key, mods) return widgetHandler:KeyRelease(key, mods) end function TextInput(utf8, ...) return widgetHandler:TextInput(utf8, ...) end function MouseMove(x, y, dx, dy, button) return widgetHandler:MouseMove(x, y, dx, dy, button) end function MousePress(x, y, button) return widgetHandler:MousePress(x, y, button) end function MouseRelease(x, y, button) return widgetHandler:MouseRelease(x, y, button) end function IsAbove(x, y) return widgetHandler:IsAbove(x, y) end function GetTooltip(x, y) return widgetHandler:GetTooltip(x, y) end function AddConsoleLine(msg, priority) return widgetHandler:AddConsoleLine(msg, priority) end function GroupChanged(groupID) return widgetHandler:GroupChanged(groupID) end local allModOptions = Spring.GetModOptions() function Spring.GetModOption(s,bool,default) if (bool) then local modOption = allModOptions[s] if (modOption==nil) then modOption = (default and "1") end return (modOption=="1") else local modOption = allModOptions[s] if (modOption==nil) then modOption = default end return modOption end end -- -- The unit (and some of the Draw) call-ins are handled -- differently (see LuaUI/widgets.lua / UpdateCallIns()) -- --------------------------------------------------------------------------------
gpl-2.0
KlonZK/Zero-K
features/corpses/chicken_eggs.lua
17
4627
-- $Id$ local eggDefs = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local defaultEgg = { description = [[Egg]], blocking = false, damage = 10000, reclaimable = true, energy = 0, footprintx = 1, footprintz = 1, customParams = { mod = true, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local type = type local pairs = pairs local function CopyTable(outtable,intable) for i,v in pairs(intable) do if (type(v)=='table') then if (type(outtable[i])~='table') then outtable[i] = {} end CopyTable(outtable[i],v) else outtable[i] = v end end end local function MergeTable(table1,table2) local ret = {} CopyTable(ret,table2) CopyTable(ret,table1) return ret end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- eggDefs.chicken_dodo_egg = MergeTable(defaultEgg, { metal = 30, reclaimTime = 30, object = [[chickeneggcrimson.s3o]], }) eggDefs.chicken_egg = MergeTable(defaultEgg, { metal = 10, reclaimTime = 10, object = [[chickenegg.s3o]], }) eggDefs.chicken_pigeon_egg = MergeTable(defaultEgg, { metal = 15, reclaimTime = 15, object = [[chickeneggblue.s3o]], }) eggDefs.chicken_sporeshooter_egg = MergeTable(defaultEgg, { metal = 60, reclaimTime = 60, object = [[chickeneggyellow.s3o]], }) eggDefs.chickena_egg = MergeTable(defaultEgg, { metal = 100, reclaimTime = 100, object = [[chickeneggred.s3o]], }) eggDefs.chickenc_egg = MergeTable(defaultEgg, { metal = 200, reclaimTime = 200, object = [[chickeneggaqua.s3o]], }) eggDefs.chickend_egg = MergeTable(defaultEgg, { metal = 125, reclaimTime = 125, object = [[chickeneggaqua.s3o]], }) eggDefs.chickenf_egg = MergeTable(defaultEgg, { metal = 100, reclaimTime = 100, object = [[chickeneggyellow.s3o]], }) eggDefs.chickenr_egg = MergeTable(defaultEgg, { metal = 80, reclaimTime = 80, object = [[chickeneggblue.s3o]], }) eggDefs.chickens_egg = MergeTable(defaultEgg, { metal = 30, reclaimTime = 30, object = [[chickenegggreen.s3o]], }) eggDefs.chicken_leaper_egg = MergeTable(defaultEgg, { metal = 20, reclaimTime = 20, object = [[chickeneggbrown.s3o]], }) eggDefs.chickenspire_egg = MergeTable(defaultEgg, { metal = 300, reclaimTime = 300, object = [[chickenegggreen_big.s3o]], }) eggDefs.chicken_blimpy_egg = MergeTable(defaultEgg, { metal = 150, reclaimTime = 150, object = [[chickeneggaqua.s3o]], }) eggDefs.chickenblobber_egg = MergeTable(defaultEgg, { metal = 200, reclaimTime = 200, object = [[chickeneggblue.s3o]], }) eggDefs.chickenwurm_egg = MergeTable(defaultEgg, { metal = 150, reclaimTime = 150, object = [[chickeneggbrown.s3o]], }) eggDefs.chicken_roc_egg = MergeTable(defaultEgg, { metal = 175, reclaimTime = 175, object = [[chickenegggreen.s3o]], }) eggDefs.chicken_shield_egg = MergeTable(defaultEgg, { metal = 150, reclaimTime = 150, object = [[chickenegggreen_big.s3o]], }) eggDefs.chicken_tiamat_egg = MergeTable(defaultEgg, { metal = 300, reclaimTime = 300, object = [[chickeneggwhite.s3o]], }) eggDefs.chicken_spidermonkey_egg = MergeTable(defaultEgg, { metal = 150, reclaimTime = 150, object = [[chickenegg.s3o]], }) eggDefs.chicken_rafflesia_egg = MergeTable(defaultEgg, { metal = 150, reclaimTime = 150, object = [[chickenegg.s3o]], }) eggDefs.chicken_dragon_egg = MergeTable(defaultEgg, { metal = 1000, reclaimTime = 1000, object = [[chickeneggblue_huge.s3o]], }) -- specify origin unit (for tooltip/contextmenu) for name,data in pairs(eggDefs) do local unitname = name local truncate = unitname:find("_egg") unitname = unitname:sub(1, truncate) data.customParams.unit = unitname end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- return lowerkeys( eggDefs ) -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
findstr/mmorpg-demo
server/scene-src/aoi.lua
1
1778
local c = require "aoi.c" local const = require "const" local M = {} local AOI local USER_X = {} local USER_Z = {} local USER_FILTER = {} local npc_watch = {} local function update_user(id, x, z, enter, leave) local e, l = c.update(AOI, id, x, z, enter, leave) for i = 1, e do local x = enter[i] if x >= const.UIDSTART then USER_FILTER[id][x] = true USER_FILTER[x][id] = true else USER_FILTER[x][id] = true npc_watch(x, id, "enter") end end for i = 1, l do local x = leave[i] if x >= const.UIDSTART then USER_FILTER[x][id] = nil USER_FILTER[id][x] = nil else npc_watch(x, id, "leave") end end return e > 0 or l > 0 end local function update_npc(id, x, z, enter, leave) local e, l = c.update(AOI, id, x, z, enter, leave) for i = 1, e do local x = enter[i] if x >= const.UIDSTART then USER_FILTER[x][id] = true USER_FILTER[id][x] = true npc_watch(id, x, "enter") end end for i = 1, l do local x = leave[i] leave[i] = nil if x >= const.UIDSTART then USER_FILTER[x][id] = nil USER_FILTER[id][x] = nil npc_watch(id, x, "leave") end end return e > 0 or l > 0 end local function enter_by(update) return function(id, x, z, enter) USER_X[id] = x USER_Z[id] = z USER_FILTER[id] = {} --because first enter can't be leave --so pass nil of 'leave' param is harmless update(id, x, z, enter) end end function M.start(x, z) AOI = c.start(x, z) end function M.leave(id) USER_X[id] = nil USER_Z[id] = nil USER_FILTER[id] = nil c.leave(AOI, id) end function M.filter(id) return USER_FILTER[id] end function M.npcwatch(func) npc_watch = func end M.enter = enter_by(update_user) M.npcenter = enter_by(update_npc) M.move = update_user M.npcmove = update_npc M.npcleave = M.leave return M
mit
iamgreaser/seabase
pkg/base/lib/timer.lua
1
1104
--[[ Copyright (C) 2013 Ben "GreaseMonkey" Russell & contributors This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]] function timer_new(fn, sec_base, interval) return function(sec) sec_base = sec_base or sec while sec > sec_base do fn(sec_base) sec_base = sec_base + interval end end end
gpl-2.0
complynx/nodemcu-IoT
lua_modules/base64/base64.lua
60
1224
-- Lua 5.1+ base64 v3.0 (c) 2009 by Alex Kloss <alexthkloss@web.de> -- licensed under the terms of the LGPL2 local moduleName = ... local M = {} _G[moduleName] = M -- character table string local b='ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -- encoding function M.enc(data) return ((data:gsub('.', function(x) local r,b='',x:byte() for i=8,1,-1 do r=r..(b%2^i-b%2^(i-1)>0 and '1' or '0') end return r; end)..'0000'):gsub('%d%d%d?%d?%d?%d?', function(x) if (#x < 6) then return '' end local c=0 for i=1,6 do c=c+(x:sub(i,i)=='1' and 2^(6-i) or 0) end return b:sub(c+1,c+1) end)..({ '', '==', '=' })[#data%3+1]) end -- decoding function M.dec(data) data = string.gsub(data, '[^'..b..'=]', '') return (data:gsub('.', function(x) if (x == '=') then return '' end local r,f='',(b:find(x)-1) for i=6,1,-1 do r=r..(f%2^i-f%2^(i-1)>0 and '1' or '0') end return r; end):gsub('%d%d%d?%d?%d?%d?%d?%d?', function(x) if (#x ~= 8) then return '' end local c=0 for i=1,8 do c=c+(x:sub(i,i)=='1' and 2^(7-i) or 0) end return string.char(c) end)) end return M
mit
annulen/premake
src/base/_foundation.lua
1
5004
--- -- Base definitions required by all the other scripts. -- @copyright 2002-2013 Jason Perkins and the Premake project --- premake = {} premake.modules = {} premake.tools = {} premake.extensions = premake.modules -- Keep track of warnings that have been shown, so they don't get shown twice local _warnings = {} -- -- Define some commonly used symbols, for future-proofing. -- premake.C = "C" premake.C7 = "c7" premake.CLANG = "clang" premake.CONSOLEAPP = "ConsoleApp" premake.CPP = "C++" premake.CSHARP = "C#" premake.GCC = "gcc" premake.HAIKU = "haiku" premake.LINUX = "linux" premake.MACOSX = "macosx" premake.MAKEFILE = "Makefile" premake.NONE = "None" premake.OFF = "Off" premake.POSIX = "posix" premake.PS3 = "ps3" premake.SHAREDLIB = "SharedLib" premake.STATICLIB = "StaticLib" premake.UNIVERSAL = "universal" premake.UTILITY = "Utility" premake.WINDOWEDAPP = "WindowedApp" premake.WINDOWS = "windows" premake.X32 = "x32" premake.X64 = "x64" premake.XBOX360 = "xbox360" --- -- Call a list of functions. -- -- @param funcs -- The list of functions to be called, or a function that can be called -- to build and return the list. If this is a function, it will be called -- with all of the additional arguments (below). -- @param ... -- An optional set of arguments to be passed to each of the functions as -- as they are called. --- function premake.callArray(funcs, ...) if type(funcs) == "function" then funcs = funcs(...) end for i = 1, #funcs do funcs[i](...) end end -- TODO: THIS IMPLEMENTATION IS GOING AWAY function premake.callarray(namespace, array, ...) local n = #array for i = 1, n do local fn = namespace[array[i]] if not fn then error(string.format("Unable to find function '%s'", array[i])) end fn(...) end end --- -- Clears the list of already fired warning messages, allowing them -- to be fired again. --- function premake.clearWarnings() _warnings = {} end -- -- Raise an error, with a formatted message built from the provided -- arguments. -- -- @param message -- The error message, which may contain string formatting tokens. -- @param ... -- Values to fill in the string formatting tokens. -- function premake.error(message, ...) error(string.format("** Error: " .. message, ...), 0) end --- -- "Immediate If" - returns one of the two values depending on the value -- of the provided condition. Note that both the true and false expressions -- will be evaluated regardless of the condition, even if only one result -- is returned. -- -- @param condition -- A boolean condition, determining which value gets returned. -- @param trueValue -- The value to return if the condition is true. -- @param falseValue -- The value to return if the condition is false. -- @return -- One of trueValue or falseValue. --- function iif(condition, trueValue, falseValue) if condition then return trueValue else return falseValue end end --- -- Override an existing function with a new implementation; the original -- function is passed as the first argument to the replacement when called. -- -- @param scope -- The table containing the function to be overridden. Use _G for -- global functions. -- @param name -- The name of the function to override (a string value). -- @param repl -- The replacement function. The first argument to the function -- will be the original implementation, followed by the arguments -- passed to the original call. --- function premake.override(scope, name, repl) local original = scope[name] if not original then error("unable to override '" .. name .. "'; no such function", 2) end scope[name] = function(...) return repl(original, ...) end end -- -- Display a warning, with a formatted message built from the provided -- arguments. -- -- @param message -- The warning message, which may contain string formatting tokens. -- @param ... -- Values to fill in the string formatting tokens. -- function premake.warn(message, ...) message = string.format(message, ...) if _OPTIONS.fatal then error(message) else io.stderr:write(string.format("** Warning: " .. message .. "\n", ...)) end end -- -- Displays a warning just once per run. -- -- @param key -- A unique key to identify this warning. Subsequent warnings messages -- using the same key will not be shown. -- @param message -- The warning message, which may contain string formatting tokens. -- @param ... -- Values to fill in the string formatting tokens. -- function premake.warnOnce(key, message, ...) if not _warnings[key] then _warnings[key] = true premake.warn(message, ...) end end -- -- A shortcut for printing formatted output. -- function printf(msg, ...) print(string.format(msg, unpack(arg))) end
bsd-3-clause
ArthurF5/tfs1.0
data/migrations/14.lua
55
1362
function onUpdateDatabase() print("> Updating database to version 15 (moving groups to data/XML/groups.xml)") db.query("ALTER TABLE players DROP FOREIGN KEY players_ibfk_2") db.query("DROP INDEX group_id ON players") db.query("ALTER TABLE accounts DROP FOREIGN KEY accounts_ibfk_1") db.query("DROP INDEX group_id ON accounts") db.query("ALTER TABLE `accounts` DROP `group_id`") local groupsFile = io.open("data/XML/groups.xml", "w") if groupsFile ~= nil then groupsFile:write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n") groupsFile:write("<groups>\r\n") local resultId = db.storeQuery("SELECT `id`, `name`, `flags`, `access`, `maxdepotitems`, `maxviplist` FROM `groups` ORDER BY `id` ASC") if resultId ~= false then repeat groupsFile:write("\t<group id=\"" .. result.getDataInt(resultId, "id") .. "\" name=\"" .. result.getDataString(resultId, "name") .. "\" flags=\"" .. string.format("%u", result.getDataLong(resultId, "flags")) .. "\" access=\"" .. result.getDataInt(resultId, "access") .. "\" maxdepotitems=\"" .. result.getDataInt(resultId, "maxdepotitems") .. "\" maxvipentries=\"" .. result.getDataInt(resultId, "maxviplist") .. "\" />\r\n") until not result.next(resultId) result.free(resultId) end groupsFile:write("</groups>\r\n") groupsFile:close() db.query("DROP TABLE `groups`") end return true end
gpl-2.0
m2q1n9/lua
tests/calls.lua
4
9359
-- $Id: calls.lua,v 1.57 2015/03/04 13:09:38 roberto Exp $ print("testing functions and calls") local debug = require "debug" -- get the opportunity to test 'type' too ;) assert(type(1<2) == 'boolean') assert(type(true) == 'boolean' and type(false) == 'boolean') assert(type(nil) == 'nil' and type(-3) == 'number' and type'x' == 'string' and type{} == 'table' and type(type) == 'function') assert(type(assert) == type(print)) function f (x) return a:x (x) end assert(type(f) == 'function') do -- test error in 'print' too... local tostring = _ENV.tostring _ENV.tostring = nil local st, msg = pcall(print, 1) assert(st == false and string.find(msg, "attempt to call a nil value")) _ENV.tostring = function () return {} end local st, msg = pcall(print, 1) assert(st == false and string.find(msg, "must return a string")) _ENV.tostring = tostring end -- testing local-function recursion fact = false do local res = 1 local function fact (n) if n==0 then return res else return n*fact(n-1) end end assert(fact(5) == 120) end assert(fact == false) -- testing declarations a = {i = 10} self = 20 function a:x (x) return x+self.i end function a.y (x) return x+self end assert(a:x(1)+10 == a.y(1)) a.t = {i=-100} a["t"].x = function (self, a,b) return self.i+a+b end assert(a.t:x(2,3) == -95) do local a = {x=0} function a:add (x) self.x, a.y = self.x+x, 20; return self end assert(a:add(10):add(20):add(30).x == 60 and a.y == 20) end local a = {b={c={}}} function a.b.c.f1 (x) return x+1 end function a.b.c:f2 (x,y) self[x] = y end assert(a.b.c.f1(4) == 5) a.b.c:f2('k', 12); assert(a.b.c.k == 12) print('+') t = nil -- 'declare' t function f(a,b,c) local d = 'a'; t={a,b,c,d} end f( -- this line change must be valid 1,2) assert(t[1] == 1 and t[2] == 2 and t[3] == nil and t[4] == 'a') f(1,2, -- this one too 3,4) assert(t[1] == 1 and t[2] == 2 and t[3] == 3 and t[4] == 'a') function fat(x) if x <= 1 then return 1 else return x*load("return fat(" .. x-1 .. ")", "")() end end assert(load "load 'assert(fat(6)==720)' () ")() a = load('return fat(5), 3') a,b = a() assert(a == 120 and b == 3) print('+') function err_on_n (n) if n==0 then error(); exit(1); else err_on_n (n-1); exit(1); end end do function dummy (n) if n > 0 then assert(not pcall(err_on_n, n)) dummy(n-1) end end end dummy(10) function deep (n) if n>0 then deep(n-1) end end deep(10) deep(200) -- testing tail call function deep (n) if n>0 then return deep(n-1) else return 101 end end assert(deep(30000) == 101) a = {} function a:deep (n) if n>0 then return self:deep(n-1) else return 101 end end assert(a:deep(30000) == 101) print('+') a = nil (function (x) a=x end)(23) assert(a == 23 and (function (x) return x*2 end)(20) == 40) -- testing closures -- fixed-point operator Z = function (le) local function a (f) return le(function (x) return f(f)(x) end) end return a(a) end -- non-recursive factorial F = function (f) return function (n) if n == 0 then return 1 else return n*f(n-1) end end end fat = Z(F) assert(fat(0) == 1 and fat(4) == 24 and Z(F)(5)==5*Z(F)(4)) local function g (z) local function f (a,b,c,d) return function (x,y) return a+b+c+d+a+x+y+z end end return f(z,z+1,z+2,z+3) end f = g(10) assert(f(9, 16) == 10+11+12+13+10+9+16+10) Z, F, f = nil print('+') -- testing multiple returns function unlpack (t, i) i = i or 1 if (i <= #t) then return t[i], unlpack(t, i+1) end end function equaltab (t1, t2) assert(#t1 == #t2) for i = 1, #t1 do assert(t1[i] == t2[i]) end end local pack = function (...) return (table.pack(...)) end function f() return 1,2,30,4 end function ret2 (a,b) return a,b end local a,b,c,d = unlpack{1,2,3} assert(a==1 and b==2 and c==3 and d==nil) a = {1,2,3,4,false,10,'alo',false,assert} equaltab(pack(unlpack(a)), a) equaltab(pack(unlpack(a), -1), {1,-1}) a,b,c,d = ret2(f()), ret2(f()) assert(a==1 and b==1 and c==2 and d==nil) a,b,c,d = unlpack(pack(ret2(f()), ret2(f()))) assert(a==1 and b==1 and c==2 and d==nil) a,b,c,d = unlpack(pack(ret2(f()), (ret2(f())))) assert(a==1 and b==1 and c==nil and d==nil) a = ret2{ unlpack{1,2,3}, unlpack{3,2,1}, unlpack{"a", "b"}} assert(a[1] == 1 and a[2] == 3 and a[3] == "a" and a[4] == "b") -- testing calls with 'incorrect' arguments rawget({}, "x", 1) rawset({}, "x", 1, 2) assert(math.sin(1,2) == math.sin(1)) table.sort({10,9,8,4,19,23,0,0}, function (a,b) return a<b end, "extra arg") -- test for generic load local x = "-- a comment\0\0\0\n x = 10 + \n23; \ local a = function () x = 'hi' end; \ return '\0'" function read1 (x) local i = 0 return function () collectgarbage() i=i+1 return string.sub(x, i, i) end end function cannotload (msg, a,b) assert(not a and string.find(b, msg)) end a = assert(load(read1(x), "modname", "t", _G)) assert(a() == "\0" and _G.x == 33) assert(debug.getinfo(a).source == "modname") -- cannot read text in binary mode cannotload("attempt to load a text chunk", load(read1(x), "modname", "b", {})) cannotload("attempt to load a text chunk", load(x, "modname", "b")) a = assert(load(function () return nil end)) a() -- empty chunk assert(not load(function () return true end)) -- small bug local t = {nil, "return ", "3"} f, msg = load(function () return table.remove(t, 1) end) assert(f() == nil) -- should read the empty chunk -- another small bug (in 5.2.1) f = load(string.dump(function () return 1 end), nil, "b", {}) assert(type(f) == "function" and f() == 1) x = string.dump(load("x = 1; return x")) a = assert(load(read1(x), nil, "b")) assert(a() == 1 and _G.x == 1) cannotload("attempt to load a binary chunk", load(read1(x), nil, "t")) cannotload("attempt to load a binary chunk", load(x, nil, "t")) assert(not pcall(string.dump, print)) -- no dump of C functions cannotload("unexpected symbol", load(read1("*a = 123"))) cannotload("unexpected symbol", load("*a = 123")) cannotload("hhi", load(function () error("hhi") end)) -- any value is valid for _ENV assert(load("return _ENV", nil, nil, 123)() == 123) -- load when _ENV is not first upvalue local x; XX = 123 local function h () local y=x -- use 'x', so that it becomes 1st upvalue return XX -- global name end local d = string.dump(h) x = load(d, "", "b") assert(debug.getupvalue(x, 2) == '_ENV') debug.setupvalue(x, 2, _G) assert(x() == 123) assert(assert(load("return XX + ...", nil, nil, {XX = 13}))(4) == 17) -- test generic load with nested functions x = [[ return function (x) return function (y) return function (z) return x+y+z end end end ]] a = assert(load(read1(x))) assert(a()(2)(3)(10) == 15) -- test for dump/undump with upvalues local a, b = 20, 30 x = load(string.dump(function (x) if x == "set" then a = 10+b; b = b+1 else return a end end), "", "b", nil) assert(x() == nil) assert(debug.setupvalue(x, 1, "hi") == "a") assert(x() == "hi") assert(debug.setupvalue(x, 2, 13) == "b") assert(not debug.setupvalue(x, 3, 10)) -- only 2 upvalues x("set") assert(x() == 23) x("set") assert(x() == 24) -- test for dump/undump with many upvalues do local nup = 200 -- maximum number of local variables local prog = {"local a1"} for i = 2, nup do prog[#prog + 1] = ", a" .. i end prog[#prog + 1] = " = 1" for i = 2, nup do prog[#prog + 1] = ", " .. i end local sum = 1 prog[#prog + 1] = "; return function () return a1" for i = 2, nup do prog[#prog + 1] = " + a" .. i; sum = sum + i end prog[#prog + 1] = " end" prog = table.concat(prog) local f = assert(load(prog))() assert(f() == sum) f = load(string.dump(f)) -- main chunk now has many upvalues local a = 10 local h = function () return a end for i = 1, nup do debug.upvaluejoin(f, i, h, 1) end assert(f() == 10 * nup) end -- test for bug in parameter adjustment assert((function () return nil end)(4) == nil) assert((function () local a; return a end)(4) == nil) assert((function (a) return a end)() == nil) print("testing binary chunks") do local header = string.pack("c4BBc6BBBBBj", "\27Lua", -- signature 5*16 + 3, -- version 5.3 0, -- format "\x19\x93\r\n\x1a\n", -- data string.packsize("i"), -- sizeof(int) string.packsize("T"), -- sizeof(size_t) 4, -- size of instruction string.packsize("j"), -- sizeof(lua integer) string.packsize("n"), -- sizeof(lua number) 0x5678 -- LUAC_INT -- LUAC_NUM may not have a unique binary representation (padding...) ) local c = string.dump(function () local a = 1; local b = 3; return a+b*3 end) assert(string.sub(c, 1, #header) == header) -- corrupted header for i = 1, #header do local s = string.sub(c, 1, i - 1) .. string.char(string.byte(string.sub(c, i, i)) + 1) .. string.sub(c, i + 1, -1) assert(#s == #c) assert(not load(s)) end -- loading truncated binary chunks for i = 1, #c - 1 do local st, msg = load(string.sub(c, 1, i)) assert(not st and string.find(msg, "truncated")) end assert(assert(load(c))() == 10) end print('OK') return deep
mit
aceforeverd/vimrc
lua/aceforeverd/plugins/tree.lua
1
1226
-- Copyright (C) 2022 Ace <teapot@aceforeverd.com> -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. local M = {} function M.neo_tree() require('neo-tree').setup({ filesystem = { hijack_netrw_behavior = 'disabled', window = { mappings = { ['o'] = 'open', ['g/'] = 'filter_as_you_type', ['gf'] = 'filter_on_submit', ['g?'] = 'show_help', ['/'] = 'none', ['?'] = 'none', ['f'] = 'none', }, }, }, }) require('aceforeverd.utility.map').set_map('n', '<space>e', '<cmd>Neotree toggle reveal<cr>') end return M
gpl-3.0
rockneurotiko/telegram-bot
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
ollpu/telegram-bot
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
KlonZK/Zero-K
units/factoryhover.lua
4
3816
unitDef = { unitname = [[factoryhover]], name = [[Hovercraft Platform]], description = [[Produces Hovercraft, Builds at 10 m/s]], acceleration = 0, brakeRate = 0, buildCostEnergy = 600, buildCostMetal = 600, builder = true, buildoptions = { [[corch]], [[corsh]], [[nsaclash]], [[hoverassault]], [[hoverdepthcharge]], [[hoverriot]], [[armmanni]], [[hoveraa]], }, buildPic = [[factoryhover.png]], buildTime = 600, canAttack = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[UNARMED FLOAT]], collisionVolumeTest = 1, corpse = [[DEAD]], customParams = { description_de = [[Produziert Aerogleiter, Baut mit 10 M/s]], description_pl = [[Buduje poduszkowce, moc 10 m/s]], helptext = [[The Hovercraft Platform is fast and deadly, offering the ability to cross sea and plains alike and outmaneuver the enemy. Key units: Scrubber, Halberd, Scalpel, Mace, Penetrator]], helptext_de = [[Die Hovercraft Platform ist schnell und tödlich und eröffnet dir die Möglichkeit Wasser und Boden gleichzeitig zu überqueren und somit deinen Gegner geschickt zu überlisten. Wichtigste Einheiten: Scrubber, Halberd, Scalpel, Mace, Penetrator]], helptext_pl = [[Poduszkowce sa szybkie i smiercionosne; sa w stanie poruszac sie zarowno na morzu, jak i po ladzie, co pozwala im na okrazenie lub ominiecie przeciwnika. Najwazniejsze jednostki: Scrubber, Halberd, Scalpel, Mace, Penetrator]], sortName = [[8]], aimposoffset = [[0 0 0]], midposoffset = [[0 -25 0]], modelradius = [[60]], }, energyMake = 0.3, energyUse = 0, explodeAs = [[LARGE_BUILDINGEX]], footprintX = 8, footprintZ = 8, iconType = [[fachover]], idleAutoHeal = 5, idleTime = 1800, levelGround = false, mass = 324, maxDamage = 4000, maxSlope = 15, maxVelocity = 0, metalMake = 0.3, minCloakDistance = 150, noAutoFire = false, objectName = [[ARMFHP.s3o]], seismicSignature = 4, selfDestructAs = [[LARGE_BUILDINGEX]], showNanoSpray = false, side = [[ARM]], sightDistance = 273, smoothAnim = true, TEDClass = [[PLANT]], turnRate = 0, waterline = 1, workerTime = 10, yardMap = [[xoooooox ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo xoccccox]], featureDefs = { DEAD = { description = [[Wreckage - Hovercraft Platform]], blocking = false, category = [[corpses]], damage = 4000, energy = 0, featureDead = [[HEAP]], footprintX = 8, footprintZ = 7, height = [[20]], hitdensity = [[100]], metal = 240, object = [[ARMFHP_DEAD.s3o]], reclaimable = true, reclaimTime = 240, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, HEAP = { description = [[Debris - Hovercraft Platform]], blocking = false, category = [[heaps]], damage = 4000, energy = 0, featurereclamate = [[SMUDGE01]], footprintX = 8, footprintZ = 7, hitdensity = [[100]], metal = 120, object = [[debris4x4c.s3o]], reclaimable = true, reclaimTime = 120, seqnamereclamate = [[TREE1RECLAMATE]], world = [[All Worlds]], }, }, } return lowerkeys({ factoryhover = unitDef })
gpl-2.0
XxMTxX/XxMTxX
plugins/supergroup1.lua
3
76689
--Begin supergrpup.lua --Check members #Add supergroup local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "Promote me to admin first!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "no", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', public = 'no', lock_rtl = 'no', lock_tgservice = 'yes', lock_contacts = 'no', strict = 'no' } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) local text = 'Group has been added ✅' return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'Group has been removed ✅' return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="Info for SuperGroup: ["..result.title.."]\n\n" local admin_num = "Admin count: "..result.admins_count.."\n" local user_num = "User count: "..result.participants_count.."\n" local kicked_num = "Kicked user count: "..result.kicked_count.."\n" local channel_id = "ID: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Owners only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Flood is already locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Flood has been unlocked' end end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'SuperGroup members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'SuperGroup members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup members has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked' end end local function lock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'yes' then return 'Tgservice is already locked' else data[tostring(target)]['settings']['lock_tgservice'] = 'yes' save_data(_config.moderation.data, data) return 'Tgservice has been locked' end end local function unlock_group_tgservice(msg, data, target) if not is_momod(msg) then return end local group_tgservice_lock = data[tostring(target)]['settings']['lock_tgservice'] if group_tgservice_lock == 'no' then return 'TgService Is Not Locked!' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'Tgservice has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == 'no' then return 'Settings are not strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced' end end --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Group rules set 📋📌' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules in this group 📋❌' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' rules:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only ❌" end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_tgservice'] then data[tostring(target)]['settings']['lock_tgservice'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings⚙:\n◼️Lock links : "..settings.lock_link.."\n◼️Lock flood: "..settings.flood.."\n◼️Flood sensitivity : "..NUM_MSG_MAX.."\n◼️Lock spam: "..settings.lock_spam.."\n◼️Lock Arabic: "..settings.lock_arabic.."\n◼️Lock Member: "..settings.lock_member.."\n◼️Lock RTL: "..settings.lock_rtl.."\n◼️Lock Tgservice : "..settings.lock_tgservice.."\n◼️Lock sticker: "..settings.lock_sticker.."\n◼️Public: "..settings.public.."\n◼️Strict settings: "..settings.strict return text end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator.') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'Group is not added ❌') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' is already a moderator 👤‼️') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been promoted 👤‼️') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added ❌') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' is not a moderator 👤‼️') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' has been demoted 👤‼️') end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added ' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator in this group 👤‼️' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "setadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." set as an admin" else text = "[ "..user_id.." ]set as an admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "demoteadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." has been demoted from admin" else text = "[ "..user_id.." ] has been demoted from admin" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "spromote" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] added as leader" else text = "[ "..result.from.peer_id.." ] added as leader" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id --local user = "user#id"..result.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..user_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_demote(channel_id, user, ok_cb, false) elseif get_cmd == 'mute_user' then if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end end -- End by reply actions --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "You can't demote global admins!") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] has been demoted from admin" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "demoteadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "You can't demote global admins!") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been demoted from admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been demoted from admin" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/leader/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) return end end elseif get_cmd == "setadmin" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] has been set as an admin" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) return end elseif get_cmd == 'spromote' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] added as Leader" else text = "["..v.peer_id.."] added as Leader" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] added as Leader" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then return end local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved ✅', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end --Run function local function run(msg, matches) if msg.to.type == 'chat' then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1] == 'tosuper' then if not is_admin1(msg) then return end return "Already a SuperGroup" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1] == 'add' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, 'Group is already added ✅', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1] == 'rem' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'Group is not added ❌', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if not data[tostring(msg.to.id)] then return end if matches[1] == "info" then if not is_owner(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1] == "admins" then if not is_owner(msg) and not is_support(msg.from.id) then return end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "leader" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no Leader,ask admins in support groups to set leader for your SuperGroup" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group leader is ["..group_owner..']' end if matches[1] == "modlist" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1] == "bots" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1] == "who" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1] == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1] == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1] == 'block' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'block' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") return "SuperGroup ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1] == 'kickme' then if msg.to.type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] left via kickme") channel_kick("channel#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if matches[1] == 'relink' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, 'this is not my group') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "Created a new link ✅🔗") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1] == 'setlink' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send the new group link now 🌇' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "New link set" end end if matches[1] == 'link' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "please us /relink" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link 👤🔋:\n"..group_link end if matches[1] == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1] == 'res' and is_owner(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end --[[if matches[1] == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end]] if matches[1] == 'setadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'setadmin' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'setadmin' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'setadmin' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'setadmin' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'demoteadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demoteadmin' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'demoteadmin' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'spromote' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'spromote', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'spromote' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(matches[2]) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = "[ "..matches[2].." ] added as owner" return text end]] local get_cmd = 'spromote' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1] == 'spromote' and not string.match(matches[2], '^%d+$') then local get_cmd = 'spromote' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1] == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only leader/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == 'promote' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == 'mp' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'md' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "ok" end if matches[1] == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "Only leader/support/admin can promote" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'demote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1] == "setname" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1] == "setabout" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "Description has been set.\n\nSelect the chat again to see the changes." end if matches[1] == "setusername" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1] == 'setrules' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return 'Please send the new group photo now' end if matches[1] == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "Only leader can clean" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'No moderator(s) in this SuperGroup.' end for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") return 'Modlist has been cleaned' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "Rules have not been set" end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") return 'Rules have been cleaned' end if matches[2] == 'about' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'About is not set' end data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") channel_set_about(receiver, about_text, ok_cb, false) return "About has been cleaned" end if matches[2] == 'mutelist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "Mutelist Cleaned" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end end if matches[1] == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked Tgservice Actions") return lock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[1] == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked Arabic") return unlock_group_arabic(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'tgservice' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tgservice actions") return unlock_group_tgservice(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end end if matches[1] == 'setflood' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Flood has been set to: '..matches[2] end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'photo' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'video' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'documents' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "SuperGroup mute "..msg_type.." is already on" end end if matches[2] == 'text' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." has been muted" else return "Mute "..msg_type.." is already on" end end if matches[2] == 'all' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) return "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'unmute' and is_momod(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'photo' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'video' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'documents' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'text' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute message") unmute(chat_id, msg_type) return msg_type.." has been unmuted" else return "Mute text is already off" end end if matches[2] == 'all' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) return "Mute "..msg_type.." has been disabled" else return "Mute "..msg_type.." is already disabled" end end end if matches[1] == "muteuser" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" muteuser = get_message(msg.reply_id, get_message_callback, {receiver = receiver, get_cmd = get_cmd, msg = msg}) elseif matches[1] == "muteuser" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] removed from the muted users list" elseif is_owner(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] added to the muted user list" end elseif matches[1] == "muteuser" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callbackres, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end if matches[1] == "muteslist" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "mutelist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'help' and not is_owner(msg) then text = "Message /superhelp to @Teleseed in private for SuperGroup help" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/]([Aa]dd)$", "^[#!/]([Rr]em)$", "^[#!/]([Mm]ove) (.*)$", "^[#!/]([Aa]dmins)$", "^[#!/]([Ll]eader)$", "^[#!/]([Mm]odlist)$", "^[#!/]([Bb]ots)$", "^[#!/]([Ww]ho)$", "^[#!/]([Kk]icked)$", "^[#!/]([Bb]lock) (.*)", "^[#!/]([Bb]lock)", "^[#!/]([Tt]osuper)$", "^[#!/]([Kk]ickme)$", "^[#!/]([Kk]ick) (.*)$", "^[#!/]([Rr]elink)$", "^[#!/]([Ss]etlink)$", "^[#!/]([Ll]ink)$", "^[#!/]([Rr]es) (.*)$", "^[#!/]([Ss]etadmin) (.*)$", "^[#!/]([Ss]etadmin)", "^[#!/]([Dd]emoteadmin) (.*)$", "^[#!/]([Dd]emoteadmin)", "^[#!/]([Ss]promote) (.*)$", "^[#!/]([Ss]promote)$", "^[#!/]([Pp]romote) (.*)$", "^[#!/]([Pp]romote)", "^[#!/]([Dd]emote) (.*)$", "^[#!/]([Dd]emote)", "^[#!/]([Ss]etname) (.*)$", "^[#!/]([Ss]etabout) (.*)$", "^[#!/]([Ss]etrules) (.*)$", "^[#!/]([Ss]etphoto)$", "^[#!/]([Ss]etusername) (.*)$", "^[#!/]([Dd]el)$", "^[#!/]([Ll]ock) (.*)$", "^[#!/]([Uu]nlock) (.*)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Mm]uteuser)$", "^[#!/]([Mm]uteuser) (.*)$", "^[#!/]([Pp]ublic) (.*)$", "^[#!/]([Ss]ettings)$", "^[#!/]([Rr]ules)$", "^[#!/]([Ss]etflood) (%d+)$", "^[#!/]([Cc]lean) (.*)$", "^[#!/]([Hh]elp)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Mm]utelist)$", "[#!/](mp) (.*)", "[#!/](md) (.*)", "^(https://telegram.me/joinchat/%S+)$", "msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } --End supergrpup.lua --By @Rondoozle
gpl-2.0
ids1024/naev
dat/missions/common.lua
13
4395
--[[ Common Lua Mission framework --]] -- The common function table. common = {} --[[ COMBAT TIER STUFF --]] --[[ @brief Calculates the mission combat tier. Calculations are done with ally and enemy values at the instance where they are highest. To calculate the enemy/ally ratings you use the following table: - Lone Fighter/Bomber: +1 - Fighter/Bomber Squadron: +3 - Corvette: +4 - Destroyer: +6 - Cruiser: +10 - Carrier: +12 - Small Fleet: +10 (equivalent to small fleet in fleet.xml) - Medium Fleet: +20 (equivalent to medium fleet in fleet.xml) - Large Fleet: +30 (equivalent to heavy fleet in fleet.xml) @param enemy_value Peak enemy value. @param ally_value Ally value for peak enemy value. @param must_destroy Whether or not player must destroy the enemies (default: false) @param bkg_combat Whether or not combat is in the background without player as target (default: false) @luareturn The combat tier level (also stores it internally). --]] common.calcMisnCombatTier = function( enemy_value, ally_value, must_destroy, bkg_combat ) -- Set defaults must_destroy = must_destroy or true bkg_combat = bkg_combat or false -- Calculate modifiers local mod = 0 if not must_destroy then mod = mod * 0.5 end if bkg_combat then mod = mod * 0.75 end -- Calculate rating value local rating = mod * (enemy_value - ally_value/3) -- Get Tier from rating local tier if rating <= 0 then tier = 0 elseif rating <= 2 then tier = 1 elseif rating <= 4 then tier = 2 elseif rating <= 8 then tier = 3 elseif rating <= 12 then tier = 4 elseif rating <= 17 then tier = 5 elseif rating <= 22 then tier = 6 else tier = 7 end -- Set tier common.setCombatTier( tier ) -- Return tier return tier end --[[ @brief Calculates the player combat tier @return The player's equivalent combat tier. --]] common.calcPlayerCombatTier = function () local crating = player.getRating() local tier -- Calculate based off of combat rating if crating <= 5 then tier = 0 elseif crating <= 10 then tier = 1 elseif crating <= 20 then tier = 2 elseif crating <= 40 then tier = 3 elseif crating <= 80 then tier = 4 elseif crating <= 160 then tier = 5 elseif creating <= 320 then tier = 6 else tier = 7 end return tier end --[[ @brief Sets the combat tier @param tier Tier to set mission combat tier to. --]] common.setTierCombat = function( tier ) common["__tierCombat"] = tier end --[[ @brief Gets the combat tier @return The combat tier of the mission. --]] common.getTierCombat = function () return common["__tierCombat"] end --[[ @brief Checks to see if the player meets a minum tier @param tier Tier to check for (if nil tries to use the mission tier) --]] common.checkTierCombat = function( tier ) tier = tier or common.getTierCombat() -- No tier set so it always matches if tier == nil then return true end -- Check against mission tier return common.calcPlayerCombatTier() >= tier end --[[ REWARD STUFF --]] function _calcTierReward( tier ) local low, high if tier <= 0 then low = 0 high = 0 elseif tier == 1 then low = 0 high = 50 elseif tier == 2 then low = 50 high = 100 elseif tier == 3 then low = 100 high = 150 elseif tier == 4 then low = 150 high = 200 elseif tier == 5 then low = 200 high = 250 elseif tier == 6 then low = 250 high = 275 else low = 275 high = 300 end return low, high end --[[ @brief Calculates the monetary reward based on the tiers of the mission @usage low, high = common.calcMonetaryReward() @return The amount of money the player should be paid as an interval. --]] common.calcMonetaryReward = function () local low = 0 local high = 0 local l,h local tiers = {} -- Get tiers tiers[ #tiers+1 ] = common.getTierCombat() -- Calculate money for k,v in ipairs(tiers) do l, h = _calcTierReward( v ) low = low + l high = high + h end -- Return total amount return low, high end
gpl-3.0
iamgreaser/seabase
pkg/base/widget/drawobj.lua
1
1453
--[[ Copyright (C) 2013 Ben "GreaseMonkey" Russell & contributors This software is provided 'as-is', without any express or implied warranty. In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions: 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. ]] --[[ Tile object widget. Creates a surface to draw the image for a given tile. ]] do local cfg = ... if cfg.u_obj then cfg.w, cfg.h = 16, 16 else cfg.w, cfg.h = 1, 1 end local this = widget_new(cfg) this.u_obj = cfg.u_obj function this.on_pack(maxw, maxh, expand) if this.u_obj then return 16, 16 else return 1, 1 end end function this.on_draw(img, bx, by, bw, bh, ax, ay, ...) -- TODO: sort out the APIs and whatnot if this.u_obj then this.u_obj.draw(img, nil, nil, bx, by) end end return this end
gpl-2.0
KlonZK/Zero-K
effects/missiletrail.lua
11
42654
-- missiletrailredsmall -- missiletrailred -- missiletrailyellow -- missiletrailgreen -- torptrailpurple -- missiletrailblue -- missiletrailbluebig -- moderatortrail -- chainsawtrail -- cruisetrail -- tactrail -- napalmtrail -- seismictrail -- bigemptrail -- emptrail -- disarmtrail -- raventrail -- banishertrail -- bdtrail -- voidtrail return { ["missiletrailredsmall"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.3 0.1 0.01 1 0.3 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 2, }, }, }, ["missiletrailred"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.3 0.1 0.01 1 0.3 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 3, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.8, 0.1, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 9, width = 6, }, }, }, ["missiletrailyellow"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.9 0.9 0.4 0.01 0.8 0.8 0.3 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.5, color = [[0.9, 0.9, 0.5]], dir = [[-6 r12,-6 r12,-6 r12]], length = 5, width = 3, }, }, }, ["missiletrailpurple"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.9 0.1 0.9 0.01 0.5 0.1 0.8 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.5, color = [[0.9, 0.5, 0.9]], dir = [[-6 r12,-6 r12,-6 r12]], length = 5, width = 3, }, }, }, ["missiletrailgreen"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.2 0.9 0.4 0.01 0.15 0.8 0.3 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.5, color = [[0.25, 0.9, 0.5]], dir = [[-6 r12,-6 r12,-6 r12]], length = 5, width = 3, }, }, }, ["missiletrailblue"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.5 0.2 0.9 0.01 0.6 0.2 0.4 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -9, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.3, color = [[0.6, 0.6, 0.9]], dir = [[-6 r12,-6 r12,-6 r12]], length = 4, width = 4, }, }, }, ["missiletrailbluebig"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.5 0.2 0.9 0.01 0.6 0.2 0.4 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -18, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.3, color = [[0.6, 0.6, 0.9]], dir = [[-6 r12,-6 r12,-6 r12]], length = 8, width = 8, }, }, }, ["chainsawtrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.5 0.2 0.9 0.01 0.6 0.2 0.4 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -9, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.3, color = [[0.6, 0.6, 0.9]], dir = [[-6 r12,-6 r12,-6 r12]], length = 4, width = 4, }, }, smoketrail = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.9, colormap = [[0.65 0.65 0.85 0.4 0.3 0.2 0.5 0.3 1 1 1 0.1 0 0 0 0]], directional = true, emitrot = 0, emitrotspread = 2, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 10, particlelifespread = 5, particlesize = 4, particlesizespread = 4, particlespeed = 20, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 1, sizemod = 1, texture = [[smokesmall]], }, }, }, ["moderatortrail"] = { alwaysvisible = false, usedefaultexplosions = false, smoketrail = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.9, colormap = [[1 0.67 0.9 0.2 0.45 0.3 0.405 0.2 0.4 0.3 0.36 0.125 0.3 0.3 0.3 0.05 0 0 0 0]], directional = true, emitrot = 15, emitrotspread = 30, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 28, particlelifespread = 4, particlesize = 25, particlesizespread = 11, particlespeed = 1, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = -1, sizemod = 1.04, texture = [[smoke]], }, }, }, ["screamertrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.5 0.2 0.9 0.01 0.6 0.2 0.4 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -18, sizegrowth = 0.75, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.3, color = [[0.6, 0.6, 0.9]], dir = [[-6 r12,-6 r12,-6 r12]], length = 8, width = 8, }, }, smoketrail = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.95, colormap = [[0.65 0.65 0.85 0.4 0.8 0.8 0.9 0.2 1 1 1 0.1 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.1, 0]], numparticles = 2, particlelife = 20, particlelifespread = 40, particlesize = 4, particlesizespread = 6, particlespeed = 5, particlespeedspread = 5, pos = [[r5, r5, r5]], sizegrowth = 1.6, sizemod = 1, texture = [[smoke]], }, }, }, ["cruisetrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.3 0.1 0.01 0.4 0.2 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -33, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 5, }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.8 0.4 0.1 0.4 0.3 0.3 0.3 0.6 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 20, particlelifespread = 0, particlesize = 6, particlesizespread = 2, particlespeed = 8, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.5, sizemod = 1.0, texture = [[smoke]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.8, 0.1, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 22, width = 10, }, }, }, ["tactrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.3 0.1 0.01 0.4 0.2 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -45, sidetexture = [[muzzleside]], size = -8, sizegrowth = 0.75, ttl = 8, }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.8 0.4 0.1 0.4 0.3 0.3 0.3 0.6 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 30, particlelifespread = 0, particlesize = 8, particlesizespread = 2, particlespeed = 10, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.5, sizemod = 1.0, texture = [[smoke]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.8, 0.1, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 33, width = 15, }, }, }, ["napalmtrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.6 0.1 0.01 0.6 0.4 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -45, sidetexture = [[muzzleside]], size = -8, sizegrowth = 0.75, ttl = 8, }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[1.0 0.6 0.1 0.4 0.5 0.4 0.3 0.6 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 20, particlelifespread = 0, particlesize = 8, particlesizespread = 2, particlespeed = 10, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.5, sizemod = 1.0, texture = [[smoke]], }, }, fire = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0.2 0.01 1 1 0.4 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 14, particlelifespread = 7, particlesize = 10, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 1.05, sizemod = 1.0, texture = [[fireball]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[1.0, 0.4, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 26, width = 16, }, }, }, ["seismictrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.8 1.0 0.1 0.01 0.2 0.4 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -45, sidetexture = [[muzzleside]], size = -8, sizegrowth = 0.75, ttl = 8, }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.6 0.8 0.1 0.4 0.25 0.3 0.1 0.6 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 20, particlelifespread = 0, particlesize = 8, particlesizespread = 2, particlespeed = 10, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.5, sizemod = 1.0, texture = [[smoke]], }, }, dirt = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[0.2 0.3 0.1 0.01 0.1 0.2 0.0 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[0, 1, 0]], gravity = [[0, -0.25, 0]], numparticles = 1, particlelife = 14, particlelifespread = 6, particlesize = 6, particlesizespread = 2, particlespeed = 2, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[dirt]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.7, 0.8, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 24, width = 12, }, }, }, ["bigemptrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 1 0.25 0.01 0.75 0.75 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -42, sidetexture = [[muzzleside]], size = -7, sizegrowth = 0.75, ttl = 7, }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.8 0.8 0.4 0.8 0.5 0.5 0.3 0.7 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 3, particlelife = 15, particlelifespread = 0, particlesize = 8, particlesizespread = 3, particlespeed = 8, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.02, sizemod = 1.05, texture = [[smoke]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0.2 0.01 1 1 0.4 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 2, particlelife = 17, particlelifespread = 7, particlesize = 7, particlesizespread = 0, particlespeed = 5, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[spark]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.9, 0.8, 0.4]], dir = [[-6 r12,-6 r12,-6 r12]], length = 32, width = 10, }, }, }, ["emptrail"] = { alwaysvisible = false, usedefaultexplosions = false, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.8 0.8 0.4 0.4 0.5 0.5 0.3 0.7 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 10, particlelifespread = 0, particlesize = 6, particlesizespread = 2, particlespeed = 4, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.3, sizemod = 1.0, texture = [[smoke]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 0.2 0.01 1 1 0.4 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 8, particlelifespread = 4, particlesize = 5, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[spark]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 0.75, alphadecay = 0.25, color = [[0.8, 0.7, 0.2]], dir = [[-6 r12,-6 r12,-6 r12]], length = 12, width = 5, }, }, }, ["disarmtrail"] = { alwaysvisible = false, usedefaultexplosions = false, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.9 0.9 0.9 0.4 0.5 0.5 0.5 0.7 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 10, particlelifespread = 0, particlesize = 6, particlesizespread = 2, particlespeed = 4, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.3, sizemod = 1.0, texture = [[smoke]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 1 1 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[0, 1, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 12, particlelifespread = 4, particlesize = 5, particlesizespread = 0, particlespeed = 3, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[spark]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 0.75, alphadecay = 0.25, color = [[0.8, 0.8, 0.8]], dir = [[-6 r12,-6 r12,-6 r12]], length = 12, width = 5, }, }, }, ["yellowdisarmtrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.9 0.9 0.4 0.01 0.8 0.8 0.3 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -20, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.8, ttl = 1, }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.4, color = [[0.9, 0.9, 0.7]], dir = [[-6 r12,-6 r12,-6 r12]], length = 8, width = 5, ttl = 1, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 1 1 0.01 0.0 0.0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 60, emitvector = [[1, 0, 0]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 12, particlelifespread = 4, particlesize = 4, particlesizespread = 0, particlespeed = 0, particlespeedspread = 0.5, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[spark]], }, }, }, ["raventrail"] = { alwaysvisible = false, usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.3 0.1 0.01 0.4 0.2 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -33, sidetexture = [[muzzleside]], size = -6, sizegrowth = 0.75, ttl = 5, }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.8 0.4 0.1 0.4 0.35 0.32 0.3 0.6 0.0 0.0 0.0 0.01]], directional = false, emitrot = 0, emitrotspread = 50, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 2, particlelife = 20, particlelifespread = 0, particlesize = 6, particlesizespread = 2, particlespeed = 6, particlespeedspread = -4, pos = [[0, 1, 3]], sizegrowth = 1.3, sizemod = 1.0, texture = [[smoke]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.8, 0.1, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 22, width = 10, }, }, }, ["banishertrail"] = { usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[0.9 0.9 0.4 0.01 0.8 0.8 0.3 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -25, sidetexture = [[muzzleside]], size = -4, sizegrowth = 0.75, ttl = 8, }, }, smoke_back = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[0.9 0.9 0.4 0.01 0.7 0.7 0.7 0.01 0.7 0.7 0.7 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, 0.05, 0]], numparticles = 5, particlelife = 6, particlelifespread = 5, particlesize = 1, particlesizespread = 0.5, particlespeed = -2, particlespeedspread = -12, pos = [[0, 1, 3]], sizegrowth = 0.05, sizemod = 1.0, texture = [[smoke]], }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[0.9 0.9 0.4 0.01 0.7 0.7 0.7 0.01 0.7 0.7 0.7 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 20, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 5, particlelife = 3, particlelifespread = 1, particlesize = 4, particlesizespread = 2, particlespeed = 1, particlespeedspread = -2, pos = [[0, 1, 3]], sizegrowth = 0.01, sizemod = 1.0, texture = [[smoke]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.9, 0.9, 0.5]], dir = [[-6 r12,-6 r12,-6 r12]], length = 1, width = 10, }, }, }, ["bdtrail"] = { usedefaultexplosions = false, largeflash = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, underwater = 1, water = true, properties = { colormap = [[1 0.3 0.1 0.01 1 0.3 0.1 0.01 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[muzzlefront]], length = -25, sidetexture = [[muzzleside]], size = -4, sizegrowth = 0.75, ttl = 8, }, }, smoke_back = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[1 0.3 0.1 0.01 0.1 0 0 0.01 0.1 0 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, 0.05, 0]], numparticles = 5, particlelife = 6, particlelifespread = 5, particlesize = 1, particlesizespread = 0.5, particlespeed = -2, particlespeedspread = -12, pos = [[0, 1, 3]], sizegrowth = 0.05, sizemod = 1.0, texture = [[smoke]], }, }, smoke_front = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 0.3 0.1 0.01 0.1 0 0 0.01 0.1 0 0 0.01 0 0 0 0.01]], directional = false, emitrot = 0, emitrotspread = 20, emitvector = [[dir]], gravity = [[0.05 r-0.1, 0.05 r-0.1, 0.05 r-0.1]], numparticles = 5, particlelife = 3, particlelifespread = 1, particlesize = 4, particlesizespread = 2, particlespeed = 1, particlespeedspread = -2, pos = [[0, 1, 3]], sizegrowth = 0.01, sizemod = 1.0, texture = [[smoke]], }, }, spikes = { air = true, class = [[explspike]], count = 4, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.25, color = [[0.8, 0.1, 0]], dir = [[-6 r12,-6 r12,-6 r12]], length = 1, width = 10, }, }, }, ["voidtrail"] = { alwaysvisible = false, usedefaultexplosions = false, }, }
gpl-2.0
annulen/premake-dev-rgeary
src/base/api.lua
1
48312
-- -- api.lua -- Implementation of the solution, project, and configuration APIs. -- Copyright (c) 2002-2012 Jason Perkins and the Premake project -- premake.api = {} local api = premake.api local globalContainer = premake5.globalContainer -- -- Here I define all of the getter/setter functions as metadata. The actual -- functions are built programmatically below. -- -- Note that these are deprecated in favor of the api.register() calls below, -- and will be going away as soon as I have a chance to port them. -- -- isList true if it's an list of objects (unordered, unless allowDuplicates=true) -- allowDuplicates Allow duplicate values, order dependent -- isKeyedTable Values are in a keyed table. Multiple tables with the same key will overwrite the value. -- kind Description Multiple instance behaviour Comments ------------------------------------------------------------------------------------------------ -- string A single string value overwrite -- string-list A list of strings append new elements to the list -- path A single path overwrite Paths are converted to absolute -- path-list A list of paths append new elements to the list Paths are converted to absolute -- directory-list A list of paths append new elements to the list Can contain wildcards -- file-list A list of files append new elements to the list Can contain wildcards -- key-array A keyed table overwrite -- object A table overwrite -- Modifiers : -- overwrite Multiple instances will overwrite. Used on string-list. -- uniqueValues The final list will contain only unique elements -- splitOnSpace If the field value contains a space, treat it as an array of two values. eg "aaa bbb" => { "aaa", "bbb" } -- isConfigurationKeyword The value to this field will automatically be added to the filter list when evaluating xxx in 'configuration "xxx"' statements -- expandtokens The value can contain tokens, eg. %{cfg.shortname} -- usagePropagation Possible values : StaticLinkage, SharedLinkage, always. -- When project 'B' uses project 'A', anything in project A's usage requirements will be copied to project B -- StaticLinkage This field is propagated automatically from a project 'A' to project A's usage if A has kind="StaticLib". Used for linkAsStatic -- SharedLinkage This field is propagated automatically from a project 'A' to project A's usage if A has kind="StaticLib" or kind="SharedLib". Used for linkAsShared, -- Always This field will always be propagaged to the usage requirement. Used for implicit compile dependencies -- (function) Propagates the return value of function(cfg, value), if not nil premake.fields = {} premake.propagatedFields = {} premake.fieldAliases = {} -- -- A place to store the current active objects in each project scope. -- api.scope = {} -- -- Register a new API function. See the built-in API definitions below -- for usage examples. -- function api.register(field) -- verify the name local name = field.name if not name then error("missing name", 2) end -- Create the list of aliases local names = { field.name } if field.namealiases then names = table.join(names, field.namealiases) end if field.kind:startswith("key-") then field.kind = field.kind:sub(5) field.isKeyedTable = true end if field.kind:endswith("-list") then field.kind = field.kind:sub(1, -6) field.isList = true end for _,n in ipairs(names) do if rawget(_G,n) then error('name '..n..' in use', 2) end -- add create a setter function for it _G[n] = function(value) return api.callback(field, value) end -- list values also get a removal function if field.isList and not field.isKeyedTable then _G["remove" .. n] = function(value) return api.remove(field, value) end end -- all fields get a usage function, which allows you to quickly specify usage requirements _G["usage" .. n] = function(value) -- Activate a usage project of the same name & configuration as we currently have -- then apply the callback local activePrjSln = api.scope.project or api.scope.solution local prjName = activePrjSln.name local cfgTerms = (api.scope.configuration or {}).terms local rv api.scopepush() usage(prjName) configuration(cfgTerms) rv = api.callback(field, value) api.scopepop() return rv end end -- Pre-process the allowed list in to a lower-case set if field.allowed then if type(field.allowed) ~= 'function' then local allowedSet = {} if type(field.allowed) == 'string' then local v = field.allowed allowedSet[v:lower()] = v else for k,v in pairs(field.allowed) do if type(k) == 'number' then allowedSet[v:lower()] = v else if type(v) == 'table' then -- specific options for _,v2 in ipairs(v) do allowedSet[k:lower() ..'='.. v2:lower()] = k ..'='.. v2 end else -- no options specified allowedSet[k:lower() ..'='.. v:lower()] = k ..'='.. v end end end end field.allowedList = field.allowed field.allowed = allowedSet end end -- Pre-process aliases if field.aliases then local aliases = {} for k,v in pairs(field.aliases) do -- case insensitive k = k:lower() v = v:lower() aliases[k] = v premake.fieldAliases[k] = v end field.aliases = aliases end -- make sure there is a handler available for this kind of value if not api["set" .. field.kind] then error("invalid kind '" .. kind .. "'", 2) end -- add this new field to my master list premake.fields[field.name] = field if field.usagePropagation then premake.propagatedFields[field.name] = field end end -- -- Find the right target object for a given scope. -- function api.gettarget(scope) local target if scope == "solution" then target = api.scope.solution elseif scope == "project" then target = api.scope.project or api.scope.solution else target = api.scope.configuration end if not target then error("no " .. scope .. " in scope", 4) end return target end -- -- Push the current scope on to a stack -- api.scopeStack = {} function api.scopepush() local s = { solution = api.scope.solution, project = api.scope.project, configuration = api.scope.configuration, currentContainer = premake.CurrentContainer, currentConfiguration = premake.CurrentConfiguration, } table.insert( api.scopeStack, s ) end -- -- Pop a scope from the stack -- function api.scopepop() if #api.scopeStack < 1 then error('No scope to pop') end api.scope = table.remove( api.scopeStack ) premake.CurrentContainer = api.scope.currentContainer premake.CurrentConfiguration = api.scope.currentConfiguration end -- -- Callback for all API functions; everything comes here first, and then -- parceled out to the individual set...() functions. -- function api.callback(field, value) -- right now, ignore calls with no value; later might want to -- return the current baked value if not value then return end if type(value) == 'table' and count(value)==0 then error("Can't set \"" .. field.name .. '\" with value {} - did you forget to add quotes around the value? ') end local target = api.gettarget(field.scope) -- fields with this property will allow users to customise using "configuration <value>" if field.isConfigurationKeyword then local useValue if type(value) == 'table' then -- if you have a keyed table, eg. flags, convert it in to a table in the form key = "key=value" useValue = {} for k,v in pairs(value) do v = v:lower() if premake.fieldAliases[v] then v = premake.fieldAliases[v] end if type(k) == 'number' then table.insert(useValue, tostring(v)) else k = k:lower() useValue[k] = k..'='..tostring(v) end end else if premake.fieldAliases[value] then value = premake.fieldAliases[value] end useValue = { [field.name] = value:lower() } end api.callback(premake.fields['usesconfig'], useValue) end -- Custom field setter if field.setter then field.setter(target, field.name, field, value) -- A keyed value is a table containing key-value pairs, where the -- type of the value is defined by the field. elseif field.isKeyedTable then target[field.name] = target[field.name] or {} api.setkeyvalue(target[field.name], field, value) -- Lists is an array containing values of another type elseif field.isList then api.setlist(target, field.name, field, value) -- Otherwise, it is a "simple" value defined by the field else local setter = api["set" .. field.kind] setter(target, field.name, field, value) end end -- -- The remover: adds values to be removed to the "removes" field on -- current configuration. Removes are keyed by the associated field, -- so the call `removedefines("X")` will add the entry: -- cfg.removes["defines"] = { "X" } -- function api.remove(field, value) -- right now, ignore calls with no value; later might want to -- return the current baked value if not value then return end -- hack: start a new configuration block if I can, so that the -- remove will be processed in the same context as it appears in -- the script. Can be removed when I rewrite the internals to -- be truly declarative if field.scope == "config" then api.configuration(api.scope.configuration.terms) end local target = api.gettarget(field.scope) -- start a removal list, and make it the target for my values target.removes = {} target.removes[field.name] = {} target = target.removes[field.name] -- some field kinds have a removal function to process the value local kind = field.kind local remover = api["remove" .. kind] or table.insert -- iterate the list of values and add them all to the list local function addvalue(value) -- recurse into tables if type(value) == "table" then for _, v in ipairs(value) do addvalue(v) end elseif field.splitOnSpace and type(value) == 'string' and value:contains(' ') then local v = value:split(' ') addvalue(v) -- insert simple values else if field.uniqueValues then target[value] = nil end remover(target, value) end end addvalue(value) end -- -- Check to see if a value exists in a list of values, using a -- case-insensitive match. If the value does exist, the canonical -- version contained in the list is returned, so future tests can -- use case-sensitive comparisions. -- function api.checkvalue(value, allowed, aliases) local valueL = value:lower() local errMsg if aliases then if aliases[valueL] then valueL = aliases[valueL]:lower() end end -- If allowed it set to nil, allow everything. -- But if allowed is a function and it returns nil, it's a failure if allowed then local allowedValues, errMsg if type(allowed) == "function" then allowedValues,errMsg = allowed(value) if not allowedValues then return nil, errMsg end allowedValues = toSet(allowedValues, true) if allowedValues[valueL] then return allowedValues[valueL] else for _,v in ipairs(allowedValues) do if valueL == v:lower() then return v end end end else if allowed[valueL] then return allowed[valueL] end end errMsg = "invalid value '" .. value .. "'." if allowedValues and type(allowedValues)=='table' then errMsg = errMsg..' Allowed values are {'..table.concat(allowedValues, ' ')..'}' end return nil, errMsg else return value end end -- -- Retrieve the base data kind of a field, by removing any key- prefix -- or -list suffix and returning what's left. -- function api.getbasekind(field) local kind = field.kind if kind:startswith("key-") then kind = kind:sub(5) end if kind:endswith("-list") then kind = kind:sub(1, -6) end return kind end -- -- Check the collection properties of a field. -- function api.iskeyedfield(field) --return field.kind:endswith("key-") return field.isKeyedTable end function api.islistfield(field) --return field.kind:endswith("-list") return field.isList end -- -- Set a new array value. Arrays are lists of values stored by "value", -- in that new values overwrite old ones, rather than merging like lists. -- function api.setarray(target, name, field, value) -- put simple values in an array if type(value) ~= "table" then value = { value } end -- store it, overwriting any existing value target[name] = value end -- -- Set a new file value on an API field. Unlike paths, file value can -- use wildcards (and so must always be a list). -- function api.setfile(target, name, field, value) if value:find("*") then local values = os.matchfiles(value) for _, value in ipairs(values) do api.setfile(target, name, field, value) name = name + 1 end -- Check if we need to split the string elseif (not os.isfile(value)) and value:contains(' ') then for _,v in ipairs(value:split(' ')) do api.setfile(target, name, field, v) end elseif field.expandtokens and value:startswith('%') then -- expand to absolute later, as we don't know now if we have an absolute path or not target[name] = value else local filename = path.getabsolute(value) local dir = path.getdirectory(value) if not os.isfile(filename) and not filename:match("%.pb%..*") then if not os.isdir(dir) then print("Warning : \""..dir.."\" is not a directory, can't find "..filename) else print("Warning : \""..filename.."\" is not a file") local allFiles = os.matchfiles(dir..'/*') local spell = premake.spelling.new(allFiles) local suggestions,str = spell:getSuggestions(value) print(str) end end target[name] = filename end end function api.setdirectory(target, name, field, value) if value:find("*") then local values = os.matchdirs(value) for _, value in ipairs(values) do api.setdirectory(target, name, field, value) name = name + 1 end else -- make absolute later if it starts with % value = iif( value:startswith('%'), value, path.getabsolute(value)) target[name] = value end end function api.removefile(target, value) table.insert(target, path.getabsolute(value)) end api.removedirectory = api.removefile -- -- Update a keyed value. Iterate over the keys in the new value, and use -- the corresponding values to update the target object. -- function api.setkeyvalue(target, field, values) if type(values) ~= "table" then error("value must be a table of key-value pairs", 4) end local kind = field.kind if field.isList then for key, value in pairs(values) do api.setlist(target, key, field, value) end else local setter = api["set" .. kind] for key, value in pairs(values) do setter(target, key, field, value) end end end function api.setusesconfig(target, name, field, values) target[name] = target[name] or {} target = target[name] if type(values) == 'string' then values = { values } end for k,v in pairs(values) do if type(k) == 'number' then table.insert(target, v) else target[k] = v end end end -- -- Set a new list value. Lists are arrays of values, with new values -- appended to any previous values. -- function api.setlist(target, name, field, value) -- start with the existing list, or an empty one target[name] = iif(field.overwrite, {}, target[name] or {}) target = target[name] -- find the contained data type local kind = field.kind local setter = api["set" .. kind] -- function to add values local function addvalue(value, depth) -- recurse into tables if type(value) == "table" then for _, v in ipairs(value) do addvalue(v, depth + 1) end -- insert simple values elseif field.splitOnSpace and type(value) == 'string' and value:contains(' ') then local v = value:split(' ') addvalue(v, depth + 1) else if field.uniqueValues then if target[value] then return end target[value] = true end setter(target, #target + 1, field, value) end end addvalue(value, 3) end -- -- Set a new object value on an API field. -- function api.setobject(target, name, field, value) target[name] = value end -- -- Set a new path value on an API field. -- function api.setpath(target, name, field, value) api.setstring(target, name, field, value) target[name] = path.getabsolute(target[name]) end -- -- Set a new string value on an API field. -- function api.setstring(target, name, field, value) if type(value) == "table" then error("expected string; got table", 3) end local err value, err = api.checkvalue(value, field.allowed, field.aliases) if not value then error(err, 3) end target[name] = value end -- -- Flags can contain an = in the string -- function api.setflaglist(target, name, field, value) if type(value) == 'table' then for k,v in pairs(value) do if type(k) == 'string' then v = k..'='..v end api.setflaglist(target, name, field, v) end return end local value, err = api.checkvalue(value, field.allowed, field.aliases) if err then error(err, 3) end -- Split in to key=value local key, v2 = value:match('([^=]*)=([^ ]*)') target[name] = target[name] or {} target = target[name] if key and v2 then -- eg. flags.Optimize=On target[key] = v2 else -- eg flags.Symbols = "Symbols" target[value] = value end end -- -- Register the core API functions. -- api.register { name = "architecture", scope = "config", kind = "string", allowed = { "universal", "x32", "x64", }, } api.register { name = "basedir", scope = "project", kind = "path" } api.register { name = "buildaction", scope = "config", kind = "string", allowed = { "Compile", -- Treat the file as source code; compile and link it "Copy", -- Copy the file to the target directory "Embed", -- Embed the file into the target binary as a resource "ImplicitDependency", -- Implicit dependency - Not part of the build, but rebuild the project if this file changes "None" -- do nothing with the file }, } api.register { name = "buildoptions", scope = "config", kind = "string", isList = true, expandtokens = true, namealiases = { "buildflags", "cflags" }, } -- buildrule takes a table parameter with the keys : -- command[s] Command or commands to execute -- description Short description of the command, displayed during ninja build -- outputs (optional) Output files -- language (optional) Specify a shell language to execute the command in. eg. bash, python, etc. -- stage (default) 'postbuild' runs on the project target, 'link' runs on the compile output, 'compile' runs on the compile inputs -- dependencies (optional) additional files which the tool depends on, but does not take as an input -- Use tokens to specify the input filename, eg. %{file.relpath}/%{file.name} -- also "$in" is equivalent to "%{cfg.files}", $out => %{cfg.targetdir.abspath} api.register { name = "buildrule", scope = "config", kind = "object", isList = true, expandtokens = true, setter = function(target, name, field, value) -- aliases value.commands = value.commands or value.command or value.cmd if type(value.commands) == 'string' then value.commands = { value.commands } end value.outputs = value.outputs or value.output local outputStr = Seq:new(value.outputs):select(function(p) if not p:startswith('%') then return path.getabsolute(p) else return p end end):mkstring() value.absOutput = outputStr for k,v in ipairs(value.dependencies or {}) do value.dependencies[k] = path.getabsolute(v) end for k,v in ipairs(value.commands) do value.commands[k] = v:replace('$in','%{cfg.files}'):replace('$out',outputStr) end target[name] = target[name] or {} table.insert( target[name], value ) end } -- buildwhen specifies when Premake should output the project in this configuration. Default is "always" -- always Always output the project in this configuration and build it by default -- used Only output the project in this configuration when it is used by another project -- explicit Always output the project in this configuration, but only build it when explicitly specified api.register { name = "buildwhen", scope = "config", kind = "string", allowed = { "always", "explicit", "used", } } premake.buildWhen = {} premake.buildWhen['always'] = 1 premake.buildWhen['explicit'] = 2 premake.buildWhen['used'] = 3 -- The compile implicitly depends on the specified project api.register { name = "compiledepends", scope = "config", kind = "string", isList = true, usagePropagation = "Always", } -- Wrap the compile tool with this command. The original compile command & flags will be -- appended, or substituted in place of "$CMD" api.register { name = "compilerwrapper", scope = "config", kind = "string", expandtokens = true, } api.register { name = "configmap", scope = "project", kind = "array", isKeyedTable = true, } api.register { name = "configurations", scope = "project", kind = "string", isList = true, overwrite = true, -- don't merge multiple configurations sections } -- Flags only passed to the C++ compiler api.register { name = "cxxflags", kind = "string", isList = true, scope = "config", } api.register { name = "debugargs", scope = "config", kind = "string", isList = true, expandtokens = true, } api.register { name = "debugcommand", scope = "config", kind = "path", expandtokens = true, } api.register { name = "debugdir", scope = "config", kind = "path", expandtokens = true, } api.register { name = "debugenvs", scope = "config", kind = "string", isList = true, expandtokens = true, } api.register { name = "debugformat", scope = "config", kind = "string", allowed = { "c7", }, } api.register { name = "defaultconfiguration", scope = "project", kind = "string", } api.register { name = "defines", scope = "config", kind = "string", isList = true, expandtokens = true, splitOnSpace = true, namealiases = { "define" }, } api.register { name = "deploymentoptions", scope = "config", kind = "string", isList = true, expandtokens = true, } api.register { name = "files", scope = "config", kind = "file", isList = true, expandtokens = true, } api.register { name = "flags", scope = "config", kind = "flaglist", isConfigurationKeyword = true, usagePropagation = function(cfg, flags) local rv = {} -- Propagate these flags from a project to a project's usage requirements rv.Threading = flags.Threading rv.Stdlib = flags.Stdlib return rv end, allowed = { "AddPhonyHeaderDependency", -- for Makefiles, requires CreateDependencyFile "CreateDependencyFile", "CreateDependencyFileIncludeSystem", -- include system headers in the .d file "DebugEnvsDontMerge", "DebugEnvsInherit", "EnableSSE", "EnableSSE2", "EnableSSE3", "EnableSSE41", "EnableSSE42", "EnableAVX", "FatalWarnings", Float = { "Fast", "Strict", }, Inline = { "Disabled", "ExplicitOnly", "Anything", }, "Managed", "MFC", Threading = { "Multi", -- Multithreaded system libs. Always propagated to usage. "Single", -- Single threaded system libs. Always propagated to usage. }, "NativeWChar", "No64BitChecks", "NoEditAndContinue", "NoExceptions", "NoFramePointer", "NoImportLib", "NoIncrementalLink", "NoManifest", "NoMinimalRebuild", "NoNativeWChar", "NoPCH", "NoRTTI", Optimize = { 'On', 'Off', 'Size', 'Speed' }, "Profiling", -- Enable profiling compiler flag "SEH", "StaticRuntime", Stdlib = { "Static", "Shared" }, -- Use static/shared standard libraries. Propagated to usage. "Symbols", "Unicode", "Unsafe", Warnings = { 'On', 'Off', 'Extra' }, "WholeArchive", "WinMain", }, aliases = { Optimize = 'Optimize=On', OptimizeSize = 'Optimize=Size', OptimizeSpeed = 'Optimize=Speed', OptimizeOff = 'Optimize=Off', Optimise = 'Optimize=On', OptimiseSize = 'Optimize=Size', OptimiseSpeed = 'Optimize=Speed', OptimiseOff = 'Optimize=Off', NoWarnings = 'Warnings=Off', ExtraWarnings = 'Warnings=Extra', }, } api.register { name = "framework", scope = "project", kind = "string", allowed = { "1.0", "1.1", "2.0", "3.0", "3.5", "4.0" }, } api.register { name = "imageoptions", scope = "config", kind = "string", isList = true, expandtokens = true, } api.register { name = "imagepath", scope = "config", kind = "path", expandtokens = true, } api.register { name = "implibdir", scope = "config", kind = "path", expandtokens = true, } api.register { name = "implibextension", scope = "config", kind = "string", expandtokens = true, } api.register { name = "implibname", scope = "config", kind = "string", expandtokens = true, } api.register { name = "implibprefix", scope = "config", kind = "string", expandtokens = true, } api.register { name = "implibsuffix", scope = "config", kind = "string", expandtokens = true, } api.register { name = "includedirs", scope = "config", kind = "directory", isList = true, uniqueValues = true, -- values in includedirs are unique. Duplicates are discarded expandtokens = true, namealiases = { "includedir" }, } -- includes a solution in the current solution. Use "*" to include all solutions api.register { name = "includesolution", scope = "solution", kind = "string", isList = true, uniqueValues = true, } -- Specifies the kind of project to output api.register { name = "kind", scope = "config", kind = "string", isConfigurationKeyword = true, -- use this as a keyword for configurations allowed = { "ConsoleApp", "WindowedApp", "StaticLib", "SharedLib", -- Ouput is a header or source file, usually a compile dependency for another project -- This only gets built once for one configuration, as the output files are in the source tree "SourceGen", -- Input files are script files to be executed "Command", }, aliases = { Executable = 'ConsoleApp', Exe = 'ConsoleApp', } } api.register { name = "language", scope = "project", kind = "string", allowed = { "C", "C++", "C#", "assembler", "protobuf", }, } -- Command line flags passed to both 'ar' and 'link' tools api.register { name = "ldflags", scope = "config", kind = "string", isList = true, } api.register { name = "libdirs", scope = "config", kind = "directory", isList = true, expandtokens = true, usagePropagation = "SharedLinkage", -- Propagate to usage requirement if kind="StaticLib" or kind="SharedLib" namealiases = { 'libdir' } } -- Command line flags passed to the link tool (and not 'ar') api.register { name = "linkoptions", scope = "config", kind = "string", isList = true, expandtokens = true, namealiases = { "linkflags" } } -- if the value is a static lib project, link it as a static lib & propagate if the current project is StaticLib -- if the value is a shared lib project, link it as a shared lib & propagate if the current project is StaticLib or SharedLib -- if the value is neither, link it as a shared system lib & propagate if the current project is StaticLib or SharedLib api.register { name = "links", scope = "config", kind = "string", isList = true, allowed = function(value) -- if library name contains a '/' then treat it as a path to a local file if value:find('/', nil, true) then local absPath = path.getabsolute(value) if os.isfile(absPath) then value = absPath end end return value end, expandtokens = true, -- usage propagation is dealt with by converting it to linkAsShared / linkAsStatic once it's resolved } -- Link to the shared lib version of a system library -- If the same library is also defined with linkAsStatic, then linkAsShared will override it api.register { name = "linkAsShared", scope = "config", kind = "string", isList = true, expandtokens = true, usagePropagation = "SharedLinkage", } -- Link to the static lib version of a system library -- If the same library is also defined with linkAsShared, then linkAsShared will override this api.register { name = "linkAsStatic", scope = "config", kind = "string", isList = true, expandtokens = true, usagePropagation = "StaticLinkage" } -- Wrap the linker tool with this command. The original compile command & flags will be -- appended, or substituted in place of "$CMD" api.register { name = "linkerwrapper", scope = "config", kind = "string", expandtokens = true, } api.register { name = "location", scope = "project", kind = "path", expandtokens = true, } api.register { name = "makesettings", scope = "config", kind = "string", isList = true, expandtokens = true, } -- Path to put the ninja build log api.register { name = "ninjaBuildDir", scope = "solution", kind = "string", expandtokens = true, nameAliases = { 'ninjabuilddir' } } api.register { name = "objdir", scope = "config", kind = "path", expandtokens = true, } api.register { name = "pchheader", scope = "config", kind = "string", expandtokens = true, } api.register { name = "pchsource", scope = "config", kind = "path", expandtokens = true, } api.register { name = "platforms", scope = "project", kind = "string", isList = true, } api.register { name = "postbuildcommands", scope = "config", kind = "string", isList = true, expandtokens = true, namealiases = { 'postbuildcommand' }, } api.register { name = "prebuildcommands", scope = "config", kind = "string", isList = true, expandtokens = true, namealiases = { 'prebuildcommand' }, } api.register { name = "prelinkcommands", scope = "config", kind = "string", isList = true, expandtokens = true, } -- Project full-names consist of namespace/shortname, where namespace can contain further / characters -- Projects created after this statement will have their name prefixed by this value. -- When using a project, you can refer to it by its shortname if you are in the same solution -- The default prefix is the solution name -- If the project name is equal to the prefix, the prefix is ignored. -- eg : -- solution "MySoln" -- project "prjA" -- this is equivalent to project "MySoln/prjA" -- projectprefix "base" -- project "prjA" ... -- this is equivalent to project "base/prjA" -- project "B/prjB" ... -- this is equivalent to project "base/B/prjB" -- projectprefix "MySoln/client" -- project "prjA" ... -- this is equivalent to project "MySoln/client/prjA" -- project "MySoln/client" -- special case, this is equivalent to project "MySoln/client" api.register { name = "projectprefix", scope = "solution", kind = "string", allowed = function(value) if not value:endswith("/") then return nil, "projectprefix must end with / : "..value..' in '..path.getrelative(repoRoot or '',_SCRIPT) end return value end, namealiases = { "projectPrefix", } } -- -- CPP = Directory which a protobuf project outputs C++ files to (optional) -- Directory which a protobuf project outputs Java files to (optional) api.register { name = "protobufout", scope = "config", kind = "path", isKeyedTable = true, expandtokens = true, } api.register { name = "resdefines", scope = "config", kind = "string", isList = true, expandtokens = true, } api.register { name = "resincludedirs", scope = "config", kind = "directory", isList = true, expandtokens = true, } api.register { name = "resoptions", scope = "config", kind = "string", isList = true, expandtokens = true, } -- Specify a [.so/.dll] search directory to hard-code in to the executable api.register { name = "rpath", scope = "config", kind = "path", isList = true, expandtokens = true, usagePropagation = "SharedLinkage", } api.register { name = "system", scope = "config", kind = "string", allowed = function(value) value = value:lower() if premake.systems[value] then return value else return nil, "unknown system" end end, } api.register { name = "targetdir", scope = "config", kind = "path", expandtokens = true, } api.register { name = "targetextension", scope = "config", kind = "string", expandtokens = true, } api.register { name = "targetname", scope = "config", kind = "string", expandtokens = true, } api.register { name = "targetprefix", scope = "config", kind = "string", expandtokens = true, } api.register { name = "targetsuffix", scope = "config", kind = "string", expandtokens = true, } api.register { name = "toolset", scope = "config", kind = "string", isConfigurationKeyword = true, -- use this as a keyword for configurations -- set allowed to a function so it will be evaluated later when all the toolsets have been loaded allowed = function() return getSubTableNames(premake.tools); end } -- Specifies a project/usage that this project configuration depends upon api.register { name = "uses", scope = "config", kind = "string", isList = true, namealiases = { "using", "use" }, splitOnSpace = true, -- "apple banana carrot" is equivalent to { "apple", "banana", "carrot" } } -- Like "uses", but is always propagated to all dependent projects, not just the first level real projects api.register { name = "alwaysuses", scope = "config", kind = "string", isList = true, namealiases = { "alwaysuse" }, splitOnSpace = true, -- "apple banana carrot" is equivalent to { "apple", "banana", "carrot" } usagePropagation = "Always", } -- Add a new keyword to the configuration filter -- for any project we use which defines a configuration with this keyword will have that section applied -- eg. declare the debug build of the boost libs with configuration "boostdebug" -- and add usesconfig "boostdebug" to your project -- This keeps the boost configuration name separate from your solution's configuration names api.register { name = "usesconfig", scope = "config", kind = "usesconfig", namealiases = { "useconfig" }, } api.register { name = "uuid", scope = "project", kind = "string", allowed = function(value) local ok = true if (#value ~= 36) then ok = false end for i=1,36 do local ch = value:sub(i,i) if (not ch:find("[ABCDEFabcdef0123456789-]")) then ok = false end end if (value:sub(9,9) ~= "-") then ok = false end if (value:sub(14,14) ~= "-") then ok = false end if (value:sub(19,19) ~= "-") then ok = false end if (value:sub(24,24) ~= "-") then ok = false end if (not ok) then return nil, "invalid UUID" end return value:upper() end } api.register { name = "vpaths", scope = "project", kind = "path", isKeyedTable = true, isList = true, } ----------------------------------------------------------------------------- -- Everything below this point is a candidate for deprecation ----------------------------------------------------------------------------- -- -- Retrieve the current object of a particular type from the session. The -- type may be "solution", "container" (the last activated solution or -- project), or "config" (the last activated configuration). Returns the -- requested container, or nil and an error message. -- function premake.getobject(t) local container if (t == "container" or t == "solution") then container = premake.CurrentContainer else container = premake.CurrentConfiguration end if t == "solution" then if ptype(container) == "project" then container = container.solution end if ptype(container) ~= "solution" then container = nil end end local msg if (not container) then if (t == "container") then msg = "no active solution or project" elseif (t == "solution") then msg = "no active solution" else msg = "no active solution, project, or configuration" end end return container, msg end -- -- Sets the value of an object field on the provided container. -- -- @param obj -- The object containing the field to be set. -- @param fieldname -- The name of the object field to be set. -- @param value -- The new object value for the field. -- @return -- The new value of the field. -- function premake.setobject(obj, fieldname, value) obj[fieldname] = value return value end -- -- Adds values to an array field. -- -- @param obj -- The object containing the field. -- @param fieldname -- The name of the array field to which to add. -- @param values -- The value(s) to add. May be a simple value or an array -- of values. -- @param allowed -- An optional list of allowed values for this field. -- @return -- The value of the target field, with the new value(s) added. -- function premake.setarray(obj, fieldname, value, allowed, aliases) obj[fieldname] = obj[fieldname] or {} local function add(value, depth) if type(value) == "table" then for _,v in ipairs(value) do add(v, depth + 1) end else value, err = api.checkvalue(value, allowed, aliases) if not value then error(err, depth) end obj[fieldname] = table.join(obj[fieldname], value) end end if value then add(value, 5) end return obj[fieldname] end -- -- Adds values to a key-value field of a solution/project/configuration. `ctype` -- specifies the container type (see premake.getobject) for the field. -- function premake.setkeyvalue(ctype, fieldname, values) local container, err = premake.getobject(ctype) if not container then error(err, 4) end if type(values) ~= "table" then error("invalid value; table expected", 4) end container[fieldname] = container[fieldname] or {} local field = container[fieldname] or {} for key,value in pairs(values) do field[key] = field[key] or {} table.insertflat(field[key], value) end return field end -- -- Set a new value for a string field of a solution/project/configuration. `ctype` -- specifies the container type (see premake.getobject) for the field. -- function premake.setstring(ctype, fieldname, value, allowed, aliases) -- find the container for this value local container, err = premake.getobject(ctype) if (not container) then error(err, 4) end -- if a value was provided, set it if (value) then value, err = api.checkvalue(value, allowed, aliases) if (not value) then error(err, 4) end container[fieldname] = value end return container[fieldname] end -- -- For backward compatibility, excludes() is becoming an alias for removefiles(). -- function excludes(value) removefiles(value) end -- -- Project object constructors. -- function api.configuration(terms) if not terms then return premake.CurrentConfiguration end local container, err = premake.getobject("container") if (not container) then error(err, 2) end local cfg = { } cfg.terms = table.flatten({terms}) table.insert(container.blocks, cfg) premake.CurrentConfiguration = cfg -- create a keyword list using just the indexed keyword items. This is a little -- confusing: "terms" are what the user specifies in the script, "keywords" are -- the Lua patterns that result. I'll refactor to better names. cfg.keywords = { } local aliases = premake.fields['flags'] for i, word in ipairs(cfg.terms) do -- check if the word is an alias for something else if aliases[word] then word = aliases[word] cfg.terms[i] = word end table.insert(cfg.keywords, path.wildcards(word):lower()) end local isUsageProj = container.isUsage -- this is the new place for storing scoped objects api.scope.configuration = cfg return cfg end -- Starts a usage project section -- If a real project of the same name already exists, this section defines the usage requirements for the project -- If a real project of the same name does not exist, this is a pure "usage project", a set of fields to copy to anything that uses it function api.usage(name) if (not name) then --Only return usage projects. if(ptype(premake.CurrentContainer) ~= "project") then return nil end if(premake.CurrentContainer.isUsage) then return premake.CurrentContainer else return api.usage(premake.CurrentContainer.name) end elseif type(name) ~= 'string' then error('Invalid parameter for usage, must be a string') elseif name == '_GLOBAL_CONTAINER' then return api.solution(name) end -- identify the parent solution local sln if (ptype(premake.CurrentContainer) == "project") then sln = premake.CurrentContainer.solution else sln = premake.CurrentContainer end if (ptype(sln) ~= "solution" and ptype(sln) ~= 'globalcontainer') then error("no active solution or globalcontainer", 2) end -- if this is a new project, or the project in that slot doesn't have a usage, create it local prj = premake5.project.createproject(name, sln, true) -- Set the current container premake.CurrentContainer = prj api.scope.project = premake.CurrentContainer -- add an empty, global configuration to the project configuration { } return premake.CurrentContainer end function api.project(name) if (not name) then --Only return non-usage projects if(ptype(premake.CurrentContainer) ~= "project") then return nil end if(premake.CurrentContainer.isUsage) then return nil end return premake.CurrentContainer end -- identify the parent solution local sln if (ptype(premake.CurrentContainer) == "project") then sln = premake.CurrentContainer.solution else sln = premake.CurrentContainer end if (ptype(sln) ~= "solution") then error("no active solution", 2) end -- if this is a new project, create it local prj = premake5.project.createproject(name, sln, false) -- Set the current container premake.CurrentContainer = prj api.scope.project = premake.CurrentContainer -- add an empty, global configuration to the project configuration { } return premake.CurrentContainer end -- -- Global container for configurations, applied to all solutions -- function api.global() local c = api.solution('_GLOBAL_CONTAINER') globalContainer.solution = c end function api.solution(name) if not name then if ptype(premake.CurrentContainer) == "project" then return premake.CurrentContainer.solution else return premake.CurrentContainer end end local sln if name == '_GLOBAL_CONTAINER' then sln = globalContainer.solution else sln = premake.solution.get(name) end if (not sln) then sln = premake.solution.new(name) end premake.CurrentContainer = sln -- add an empty, global configuration configuration { } -- this is the new place for storing scoped objects api.scope.solution = sln api.scope.project = nil -- set the default project prefix if name ~= '_GLOBAL_CONTAINER' then sln.projectprefix = sln.projectprefix or (name..'/') end return premake.CurrentContainer end -- -- Creates a reference to an external, non-Premake generated project. -- function external(name) -- define it like a regular project local prj = api.project(name) -- then mark it as external prj.external = true; prj.externalname = prj.name return prj end -- -- Define a new action. -- -- @param a -- The new action object. -- function newaction(a) premake.action.add(a) end -- -- Define a new option. -- -- @param opt -- The new option object. -- function newoption(opt) premake.option.add(opt) end -- -- Define a new tool -- function newtool(t) return premake.tools.newtool(t) end -- -- Defines a new toolset. -- eg. newtoolset { toolsetName = 'mytoolset', tools = { mytool_cc, mytool_cxx, mytool_link, mytool_ar }, } -- function newtoolset(t) return premake.tools.newtoolset(t) end -- -- Google protocol buffers -- Example usage in a project section : protobuf { cppRoot = "..", javaRoot = ".." } -- function api.protobuf(t) local protoPath = path.getabsolute( api.scope.solution.basedir ) -- Some alternative quick inputs. eg. protobuf "*.protobuf" or protobuf "cpp" if type(t) == 'string' then if t:contains('proto') then t = { files = t } elseif t:startswith("cpp") then t = { cppRoot = protoPath } elseif t:startswith("java") then t = { javaRoot = protoPath } elseif t:startswith("python") then t = { pythonRoot = protoPath } else error("unknown protobuf argument "..t) end end if not protoPath then error("protoPath is nil") end local inputFilePattern = toList(t.files or '*.proto') local outputs = {} -- Create a new project, append /protobuf on to the active project name or directory name local prj = api.scope.project or {} local prjName = prj.name or path.getbasename(os.getcwd()) prjName = prjName..'/protobuf' -- ** protoc's cpp/java/python_out is relative to the specified --proto_path ** outputs.protoPath = protoPath if t.cppRoot then outputs.cppRoot = t.cppRoot end if t.javaRoot then outputs.javaRoot = t.javaRoot end if t.pythonRoot then outputs.pythonRoot = t.pythonRoot end -- default to cpp output in the current directory if (not outputs.cppRoot) and (not outputs.javaRoot) and (not outputs.pythonRoot) then outputs.cppRoot = protoPath end api.scopepush() project(prjName) language("protobuf") toolset("protobuf") kind("SourceGen") files(inputFilePattern) protobufout(outputs) compiledepends(prjName) -- if you use this project, it should be propagated as a compile dependency alwaysuse("system/protobuf") -- any derived project should always include the protobuf includes -- add the protobuf project to the usage requirements for the active solution solution(api.scope.solution.name) uses(prjName) api.scopepop() end -- "export" explicitly lists which projects are included in a solution, and gives it an alias function api.export(aliasName, fullProjectName) fullProjectName = fullProjectName or aliasName local sln = api.scope.solution if not sln then error("Can't export, no active solution to export to") end if type(aliasName) ~= 'string' then error("export expected string parameter, found "..type(aliasName)) end if not aliasName:startswith(sln.name..'/') then aliasName = sln.name .. '/' ..aliasName end if not fullProjectName:startswith(sln.name..'/') then fullProjectName = sln.name .. '/' ..fullProjectName end -- set up alias if fullProjectName ~= aliasName then globalContainer.aliases[aliasName] = fullProjectName end sln.exports = sln.exports or {} sln.exports[aliasName] = fullProjectName -- solution's usage requirements include exported projects api.scopepush() usage(sln.name..'/'..sln.name) uses(aliasName) api.scopepop() end function api.explicitproject(prjName) api.project(prjName) api.explicit(prjName) end function api.explicit(prjName) local prj = premake5.project.getRealProject(prjName) if prj then prj.isExplicit = true end end
bsd-3-clause
jkeywo/KFactorioMods
k-nineworlds_0.0.0/stdlib/data/data.lua
11
2357
--- Data module -- @module Data require 'stdlib/core' require 'stdlib/string' require 'stdlib/table' Data = {} --- Selects all data values where the key matches the selector pattern. -- The selector pattern is divided into groups. The pattern should have a colon character `:` to denote the selection for each group. -- <br/>The first group is for the class of the data type (item, recipe, entity-type, etc) -- <br/>The second group is for the name of the data element, and is optional. If missing, all elements matching prior groups are returned. -- <p> For more granular selectors, see other modules, such as Recipe.select. -- @usage Data.select('recipe') -- returns a table with all recipes -- @usage Data.select('recipe:steel.*') -- returns a table with all recipes whose name matches 'steel.*' -- @param pattern to search with -- @return table containing the elements matching the selector pattern, or an empty table if there was no matches function Data.select(pattern) fail_if_missing(pattern, "missing pattern argument") local parts = string.split(pattern, ":") local category_pattern = table.first(parts) local results = {} for category, values in pairs(data.raw) do if string.match(category, category_pattern) then local element_pattern = #parts > 1 and parts[2] or '.*' -- escape the '-' in names element_pattern = string.gsub(element_pattern, "%-", "%%-") for element_name, element in pairs(values) do if string.match(element_name, element_pattern) then table.insert(results, element) end end end end setmetatable(results, Data._select_metatable.new(results)) return results end -- this metatable is set on recipes, to control access to ingredients and results Data._select_metatable = {} Data._select_metatable.new = function(selection) local self = { } self.__index = function(tbl, key) if key == 'apply' then return function(k, v) table.each(tbl, function(obj) obj[k] = v end) return tbl end end end self.__newindex = function(tbl, key, value) table.each(tbl, function(obj) obj[key] = value end) end return self end
mit
focusworld/biig
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
KlonZK/Zero-K
scripts/amphassault.lua
3
11141
include "constants.lua" local base, body, turret, torpedo = piece('base', 'body', 'turret', 'torpedo') local rbarrel1, rbarrel2, lbarrel1, lbarrel2, rflare, lflare, mflare = piece('rbarrel1', 'rbarrel2', 'lbarrel1', 'lbarrel2', 'rflare', 'lflare', 'mflare') local rfleg, rffoot, lfleg, lffoot, rbleg, rbfoot, lbleg, lbfoot = piece('rfleg', 'rffoot', 'lfleg', 'lffoot', 'rbleg', 'rbfoot', 'lbleg', 'lbfoot') local vents = {rffoot, lffoot, rbfoot, lbfoot, piece('ventf1', 'ventf2', 'ventr1', 'ventr2', 'ventr3')} local SIG_WALK = 1 local SIG_AIM = 2 local SIG_RESTORE = 4 local SIG_BOB = 8 local SIG_FLOAT = 32 -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- -- Swim functions local function Bob() Signal(SIG_BOB) SetSignalMask(SIG_BOB) Turn(rfleg, x_axis, math.rad(20),math.rad(60)) Turn(rffoot, x_axis, math.rad(-20),math.rad(60)) Turn(rbleg, x_axis, math.rad(-20),math.rad(60)) Turn(rbfoot, x_axis, math.rad(20),math.rad(60)) Move(rfleg, y_axis, 0,1) Move(rbleg, y_axis, 0,1) Turn(lfleg, x_axis, math.rad(20),math.rad(60)) Turn(lffoot, x_axis, math.rad(-20),math.rad(60)) Turn(lbleg, x_axis, math.rad(-20),math.rad(60)) Turn(lbfoot, x_axis, math.rad(20),math.rad(60)) Move(lfleg, y_axis, 0,1) Move(lbleg, y_axis, 0,1) while true do Turn(base, x_axis, math.rad(math.random(-1,1)), math.rad(math.random())) Turn(base, z_axis, math.rad(math.random(-1,1)), math.rad(math.random())) Move(base, y_axis, math.rad(math.random(0,3)), math.rad(math.random(1,2))) Sleep(2000) --[[ Doesn't workm don't know why. Turn(rfleg, x_axis, math.rad(20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(rffoot, x_axis, math.rad(-20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(rbleg, x_axis, math.rad(-20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(rbfoot, x_axis, math.rad(20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(lfleg, x_axis, math.rad(20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(lffoot, x_axis, math.rad(-20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(lbleg, x_axis, math.rad(-20 + math.random(-2,2)),math.rad(math.random(-2,2))) Turn(lbfoot, x_axis, math.rad(20 + math.random(-2,2)),math.rad(math.random(-2,2))) --]] Turn(base, x_axis, math.rad(math.random(-1,1)), math.rad(math.random())) Turn(base, z_axis, math.rad(math.random(-1,1)), math.rad(math.random())) Move(base, y_axis, math.rad(math.random(-3,0)), math.rad(math.random(1,2))) Sleep(2000) end end local function SinkBubbles() SetSignalMask(SIG_FLOAT) Turn(rfleg, x_axis, math.rad(0),math.rad(20)) Turn(rffoot, x_axis, math.rad(0),math.rad(20)) Turn(rbleg, x_axis, math.rad(0),math.rad(20)) Turn(rbfoot, x_axis, math.rad(0),math.rad(20)) Move(rfleg, y_axis, 0,1) Move(rbleg, y_axis, 0,1) Turn(lfleg, x_axis, math.rad(0),math.rad(20)) Turn(lffoot, x_axis, math.rad(0),math.rad(20)) Turn(lbleg, x_axis, math.rad(0),math.rad(20)) Turn(lbfoot, x_axis, math.rad(0),math.rad(20)) Move(lfleg, y_axis, 0,1) Move(lbleg, y_axis, 0,1) while true do for i=1,#vents do EmitSfx(vents[i], SFX.BUBBLE) end Sleep(66) end end local function dustBottom() local x,y,z = Spring.GetUnitPiecePosDir(unitID,rffoot) Spring.SpawnCEG("uw_vindiback", x, y+5, z, 0, 0, 0, 0) local x,y,z = Spring.GetUnitPiecePosDir(unitID,rbfoot) Spring.SpawnCEG("uw_vindiback", x, y+5, z, 0, 0, 0, 0) local x,y,z = Spring.GetUnitPiecePosDir(unitID,lffoot) Spring.SpawnCEG("uw_vindiback", x, y+5, z, 0, 0, 0, 0) local x,y,z = Spring.GetUnitPiecePosDir(unitID,lbfoot) Spring.SpawnCEG("uw_vindiback", x, y+5, z, 0, 0, 0, 0) end -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- -- Swim gadget callins function Float_startFromFloor() dustBottom() Signal(SIG_WALK) Signal(SIG_FLOAT) StartThread(Bob) end function Float_stopOnFloor() dustBottom() Signal(SIG_BOB) Signal(SIG_FLOAT) end function Float_rising() Signal(SIG_FLOAT) end function Float_sinking() Signal(SIG_FLOAT) Signal(SIG_BOB) StartThread(SinkBubbles) end function Float_crossWaterline(speed) --Signal(SIG_FLOAT) end function Float_stationaryOnSurface() Signal(SIG_FLOAT) end function unit_teleported(position) return GG.Floating_UnitTeleported(unitID, position) end -------------------------------------------------------------------------------------- -------------------------------------------------------------------------------------- local gunPieces = { [0] = {flare = lflare, recoil = lbarrel2}, [1] = {flare = rflare, recoil = rbarrel2}, } local gun_1 = 0 local beamCount = 0 local SPEED = 1.9 local function Walk() Signal(SIG_WALK) SetSignalMask(SIG_WALK) Turn(base, x_axis, 0, math.rad(20)) Turn(base, z_axis, 0, math.rad(20)) Move(base, y_axis, 0, 10) while true do local speedmult = (1 - (Spring.GetUnitRulesParam(unitID,"slowState") or 0))*SPEED -- right Turn(rfleg, x_axis, math.rad(40),math.rad(40)*speedmult) Turn(rffoot, x_axis, math.rad(-40),math.rad(40)*speedmult) Turn(rbleg, x_axis, math.rad(5),math.rad(10)*speedmult) Turn(rbfoot, x_axis, math.rad(-40),math.rad(80)*speedmult) Move(rfleg, y_axis, 0.6,1.2*speedmult) Move(rbleg, y_axis, 0.6,1.2*speedmult) -- left Turn(lfleg, x_axis, math.rad(-20),math.rad(120)*speedmult) Turn(lffoot, x_axis, math.rad(35),math.rad(150)*speedmult) Turn(lbleg, x_axis, math.rad(0),math.rad(45)*speedmult) Turn(lbfoot, x_axis, math.rad(0),math.rad(46)*speedmult) Move(lfleg, y_axis, 1,4.4*speedmult) Move(lbleg, y_axis, 1,2*speedmult) Move(body, y_axis, 1.5,1*speedmult) Sleep(500/speedmult) -- **************** -- right Turn(rbleg, x_axis, math.rad(-50),math.rad(110)*speedmult) Turn(rbfoot, x_axis, math.rad(50),math.rad(180)*speedmult) Move(rfleg, y_axis, 3.2,5.2*speedmult) Move(rbleg, y_axis, 2,2.8*speedmult) -- left Turn(lfleg, x_axis, math.rad(0),math.rad(40)*speedmult) Turn(lffoot, x_axis, math.rad(0),math.rad(80)*speedmult) Move(lfleg, y_axis, 0,2*speedmult) Move(lbleg, y_axis, 0,2*speedmult) Move(body, y_axis, 1,1*speedmult) Sleep(500/speedmult) -- **************** -- right Turn(rfleg, x_axis, math.rad(-20),math.rad(120)*speedmult) Turn(rffoot, x_axis, math.rad(35),math.rad(150)*speedmult) Turn(rbleg, x_axis, math.rad(0),math.rad(45)*speedmult) Turn(rbfoot, x_axis, math.rad(0),math.rad(46)*speedmult) Move(rfleg, y_axis, 1,4.4*speedmult) Move(rbleg, y_axis, 1,2*speedmult) -- left Turn(lfleg, x_axis, math.rad(40),math.rad(40)*speedmult) Turn(lffoot, x_axis, math.rad(-40),math.rad(40)*speedmult) Turn(lbleg, x_axis, math.rad(5),math.rad(10)*speedmult) Turn(lbfoot, x_axis, math.rad(-40),math.rad(80)*speedmult) Move(lfleg, y_axis, 0.6,1.2*speedmult) Move(lbleg, y_axis, 0.6,1.2*speedmult) Move(body, y_axis, 3,2*speedmult) Sleep(500/speedmult) -- **************** -- right Turn(rfleg, x_axis, math.rad(0),math.rad(40)*speedmult) Turn(rffoot, x_axis, math.rad(0),math.rad(80)*speedmult) Move(rfleg, y_axis, 0,2) Move(rbleg, y_axis, 0,2) -- left Turn(lbleg, x_axis, math.rad(-50),math.rad(110)*speedmult) Turn(lbfoot, x_axis, math.rad(50),math.rad(180)*speedmult) Move(lfleg, y_axis, 3.2,5.2*speedmult) Move(lbleg, y_axis, 2,2.8*speedmult) Move(body, y_axis, 1,1*speedmult) Sleep(500/speedmult) -- **************** end end local function Stopping() Signal(SIG_WALK) SetSignalMask(SIG_WALK) Turn(rfleg, x_axis, math.rad(0),math.rad(60)) Turn(rffoot, x_axis, math.rad(0),math.rad(60)) Turn(rbleg, x_axis, math.rad(0),math.rad(60)) Turn(rbfoot, x_axis, math.rad(0),math.rad(60)) Move(rfleg, y_axis, 0,1) Move(rbleg, y_axis, 0,1) Turn(lfleg, x_axis, math.rad(0),math.rad(60)) Turn(lffoot, x_axis, math.rad(0),math.rad(60)) Turn(lbleg, x_axis, math.rad(0),math.rad(60)) Turn(lbfoot, x_axis, math.rad(0),math.rad(60)) Move(lfleg, y_axis, 0,1) Move(lbleg, y_axis, 0,1) end function script.StartMoving() StartThread(Walk) end function script.StopMoving() StartThread(Stopping) GG.Floating_StopMoving(unitID) end function script.Create() Turn(rfleg, x_axis, math.rad(0)) Turn(rffoot, x_axis, math.rad(0)) Turn(rbleg, x_axis, math.rad(0)) Turn(rbfoot, x_axis, math.rad(0)) end function script.QueryWeapon(num) if num == 1 then if beamCount < 6 then if beamCount == 1 then Spring.SetUnitWeaponState(unitID, 1, "range", 1) elseif beamCount == 2 then Spring.SetUnitWeaponState(unitID, 1, "range", 600) end return mflare else if beamCount >= 24*5 then beamCount = 0 end return gunPieces[gun_1].flare end elseif num == 2 then return torpedo end end function script.AimFromWeapon(num) if num == 1 then return turret elseif num == 2 then return torpedo end end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(6000) Turn(turret, y_axis, 0, math.rad(90)) Turn(lbarrel1, x_axis, 0, math.rad(45)) Turn(rbarrel1, x_axis, 0, math.rad(45)) end function script.AimWeapon(num, heading, pitch) if num == 1 then Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(turret, y_axis, heading, math.rad(180)) Turn(lbarrel1, x_axis, -pitch, math.rad(90)) Turn(rbarrel1, x_axis, -pitch, math.rad(90)) WaitForTurn(turret, y_axis) WaitForTurn(rbarrel1, x_axis) WaitForTurn(lbarrel1, x_axis) StartThread(RestoreAfterDelay) return true elseif num == 2 then local reloadState = Spring.GetUnitWeaponState(unitID, 1, 'reloadState') if reloadState < 0 or reloadState - Spring.GetGameFrame() < 90 then GG.Floating_AimWeapon(unitID) end return false end end function script.Shot(num) if num == 1 then beamCount = beamCount + 1 if beamCount > 24*5 then beamCount = 0 end gun_1 = 1 - gun_1 -- for i=1,12 do -- EmitSfx(gunPieces[gun_1].flare, 1024) -- end Move(gunPieces[gun_1].recoil, z_axis, -10) Move(gunPieces[gun_1].recoil, z_axis, 0, 10) elseif num == 2 then local height = select(2, Spring.GetUnitPosition(unitID)) local px, py, pz = Spring.GetUnitPosition(unitID) if height < 18 then Spring.PlaySoundFile("sounds/weapon/torpedo.wav", 10, px, py, pz) else Spring.PlaySoundFile("sounds/weapon/torp_land.wav", 10, px, py, pz) end end end -- should also explode the leg pieces but I really cba... function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= .50 then Explode(turret, sfxNone) Explode(body, sfxNone) return 1 elseif severity <= .99 then Explode(body, sfxShatter) Explode(turret, sfxShatter) Explode(lbarrel1, sfxFall + sfxSmoke) Explode(rbarrel2, sfxFall + sfxSmoke) return 2 else Explode(body, sfxShatter) Explode(turret, sfxShatter) Explode(lbarrel1, sfxFall + sfxSmoke + sfxFire + sfxExplode) Explode(rbarrel2, sfxFall + sfxSmoke + sfxFire + sfxExplode) return 2 end end
gpl-2.0
rockneurotiko/telegram-bot
plugins/lyrics.lua
695
2113
do local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs' local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5' local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect' local function getInfo(query) print('Getting info of ' .. query) local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY ..'&q='..URL.escape(query) local b, c = http.request(url) if c ~= 200 then return nil end local result = json:decode(b) local artist = result[1].artist.name local track = result[1].title return artist, track end local function getLyrics(query) local artist, track = getInfo(query) if artist and track then local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist) ..'&song='..URL.escape(track) local b, c = http.request(url) if c ~= 200 then return nil end local xml = require("xml") local result = xml.load(b) if not result then return nil end if xml.find(result, 'LyricSong') then track = xml.find(result, 'LyricSong')[1] end if xml.find(result, 'LyricArtist') then artist = xml.find(result, 'LyricArtist')[1] end local lyric if xml.find(result, 'Lyric') then lyric = xml.find(result, 'Lyric')[1] else lyric = nil end local cover if xml.find(result, 'LyricCovertArtUrl') then cover = xml.find(result, 'LyricCovertArtUrl')[1] else cover = nil end return artist, track, lyric, cover else return nil end end local function run(msg, matches) local artist, track, lyric, cover = getLyrics(matches[1]) if track and artist and lyric then if cover then local receiver = get_receiver(msg) send_photo_from_url(receiver, cover) end return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric else return 'Oops! Lyrics not found or something like that! :/' end end return { description = 'Getting lyrics of a song', usage = '!lyrics [track or artist - track]: Search and get lyrics of the song', patterns = { '^!lyrics? (.*)$' }, run = run } end
gpl-2.0
aqasaeed/megazeus
plugins/lyrics.lua
695
2113
do local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs' local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5' local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect' local function getInfo(query) print('Getting info of ' .. query) local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY ..'&q='..URL.escape(query) local b, c = http.request(url) if c ~= 200 then return nil end local result = json:decode(b) local artist = result[1].artist.name local track = result[1].title return artist, track end local function getLyrics(query) local artist, track = getInfo(query) if artist and track then local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist) ..'&song='..URL.escape(track) local b, c = http.request(url) if c ~= 200 then return nil end local xml = require("xml") local result = xml.load(b) if not result then return nil end if xml.find(result, 'LyricSong') then track = xml.find(result, 'LyricSong')[1] end if xml.find(result, 'LyricArtist') then artist = xml.find(result, 'LyricArtist')[1] end local lyric if xml.find(result, 'Lyric') then lyric = xml.find(result, 'Lyric')[1] else lyric = nil end local cover if xml.find(result, 'LyricCovertArtUrl') then cover = xml.find(result, 'LyricCovertArtUrl')[1] else cover = nil end return artist, track, lyric, cover else return nil end end local function run(msg, matches) local artist, track, lyric, cover = getLyrics(matches[1]) if track and artist and lyric then if cover then local receiver = get_receiver(msg) send_photo_from_url(receiver, cover) end return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric else return 'Oops! Lyrics not found or something like that! :/' end end return { description = 'Getting lyrics of a song', usage = '!lyrics [track or artist - track]: Search and get lyrics of the song', patterns = { '^!lyrics? (.*)$' }, run = run } end
gpl-2.0
henry4k/LittleTanks
gamera.lua
1
5831
-- gamera.lua v1.0.1 -- Copyright (c) 2012 Enrique García Cota -- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- Based on YaciCode, from Julien Patte and LuaObject, from Sebastien Rocca-Serra local gamera = {} -- Private attributes and methods local gameraMt = {__index = gamera} local abs, min, max = math.abs, math.min, math.max local function clamp(x, minX, maxX) return x < minX and minX or (x>maxX and maxX or x) end local function checkNumber(value, name) if type(value) ~= 'number' then error(name .. " must be a number (was: " .. tostring(value) .. ")") end end local function checkPositiveNumber(value, name) if type(value) ~= 'number' or value <=0 then error(name .. " must be a positive number (was: " .. tostring(value) ..")") end end local function checkAABB(l,t,w,h) checkNumber(l, "l") checkNumber(t, "t") checkPositiveNumber(w, "w") checkPositiveNumber(h, "h") end local function getVisibleArea(self, scale) scale = scale or self.scale local sin, cos = abs(self.sin), abs(self.cos) local w,h = self.w / scale, self.h / scale w,h = cos*w + sin*h, sin*w + cos*h return min(w,self.ww), min(h, self.wh) end local function cornerTransform(self, x,y) local scale, sin, cos = self.scale, self.sin, self.cos x,y = x - self.x, y - self.y x,y = -cos*x + sin*y, -sin*x - cos*y return self.x - (x/scale + self.l), self.y - (y/scale + self.t) end local function adjustPosition(self) local wl,wt,ww,wh = self.wl, self.wt, self.ww, self.wh local w,h = getVisibleArea(self) local w2,h2 = w*0.5, h*0.5 local left, right = wl + w2, wl + ww - w2 local top, bottom = wt + h2, wt + wh - h2 self.x, self.y = clamp(self.x, left, right), clamp(self.y, top, bottom) end local function adjustScale(self) local w,h,ww,wh = self.w, self.h, self.ww, self.wh local rw,rh = getVisibleArea(self, 1) -- rotated frame: area around the window, rotated without scaling local sx,sy = rw/ww, rh/wh -- vert/horiz scale: minimun scales that the window needs to occupy the world local rscale = max(sx,sy) self.scale = max(self.scale, rscale) end -- Public interface function gamera.new(l,t,w,h) local sw,sh = love.graphics.getWidth(), love.graphics.getHeight() local cam = setmetatable({ x=0, y=0, scale=1, angle=0, sin=math.sin(0), cos=math.cos(0), l=0, t=0, w=sw, h=sh, w2=sw*0.5, h2=sh*0.5 }, gameraMt) cam:setWorld(l,t,w,h) return cam end function gamera:setWorld(l,t,w,h) checkAABB(l,t,w,h) self.wl, self.wt, self.ww, self.wh = l,t,w,h adjustPosition(self) end function gamera:setWindow(l,t,w,h) checkAABB(l,t,w,h) self.l, self.t, self.w, self.h, self.w2, self.h2 = l,t,w,h, w*0.5, h*0.5 adjustPosition(self) end function gamera:setPosition(x,y) checkNumber(x, "x") checkNumber(y, "y") self.x, self.y = x,y adjustPosition(self) end function gamera:setScale(scale) checkNumber(scale, "scale") self.scale = scale adjustScale(self) adjustPosition(self) end function gamera:setAngle(angle) checkNumber(angle, "angle") self.angle = angle self.cos, self.sin = math.cos(angle), math.sin(angle) adjustScale(self) adjustPosition(self) end function gamera:getWorld() return self.wl, self.wt, self.ww, self.wh end function gamera:getWindow() return self.l, self.t, self.w, self.h end function gamera:getPosition() return self.x, self.y end function gamera:getScale() return self.scale end function gamera:getAngle() return self.angle end function gamera:getVisible() local w,h = getVisibleArea(self) return self.x - w*0.5, self.y - h*0.5, w, h end function gamera:getVisibleCorners() local x,y,w2,h2 = self.x, self.y, self.w2, self.h2 local x1,y1 = cornerTransform(self, x-w2,y-h2) local x2,y2 = cornerTransform(self, x+w2,y-h2) local x3,y3 = cornerTransform(self, x+w2,y+h2) local x4,y4 = cornerTransform(self, x-w2,y+h2) return x1,y1,x2,y2,x3,y3,x4,y4 end function gamera:draw(f) --love.graphics.setScissor(self:getWindow()) love.graphics.push() local scale = self.scale love.graphics.scale(scale) love.graphics.translate((self.w2 + self.l) / scale, (self.h2+self.t) / scale) love.graphics.rotate(-self.angle) love.graphics.translate(-self.x, -self.y) f(self:getVisible()) love.graphics.pop() love.graphics.setScissor() end function gamera:toWorld(x,y) local scale, sin, cos = self.scale, self.sin, self.cos x,y = (x - self.w2 - self.l) / scale, (y - self.h2 - self.t) / scale x,y = cos*x - sin*y, sin*x + cos*y return x + self.x, y + self.y end function gamera:toScreen(x,y) local scale, sin, cos = self.scale, self.sin, self.cos x,y = x - self.x, y - self.y x,y = cos*x + sin*y, -sin*x + cos*y return scale * x + self.w2 + self.l, scale * y + self.h2 + self.t end return gamera
mit
KlonZK/Zero-K
LuaUI/Widgets/chili/Skins/Robocracy/skin.lua
15
5736
--//============================================================================= --// Skin local skin = { info = { name = "Robocracy", version = "0.3", author = "jK", } } --//============================================================================= --// skin.general = { focusColor = {1.0, 0.7, 0.1, 0.8}, borderColor = {1.0, 1.0, 1.0, 1.0}, font = { font = SKINDIR .. "fonts/n019003l.pfb", color = {1,1,1,1}, outlineColor = {0.05,0.05,0.05,0.9}, outline = false, shadow = true, size = 14, }, --padding = {5, 5, 5, 5}, --// padding: left, top, right, bottom } skin.icons = { imageplaceholder = ":cl:placeholder.png", } skin.button = { TileImageBK = ":cl:tech_button_bk.png", TileImageFG = ":cl:tech_button_fg.png", tiles = {22, 22, 22, 22}, --// tile widths: left,top,right,bottom padding = {10, 10, 10, 10}, backgroundColor = {1, 1, 1, 0.7}, borderColor = {1,1,1,0}, DrawControl = DrawButton, } skin.combobox = { TileImageBK = ":cl:combobox_ctrl.png", TileImageFG = ":cl:combobox_ctrl_fg.png", TileImageArrow = ":cl:combobox_ctrl_arrow.png", tiles = {22, 22, 48, 22}, padding = {10, 10, 24, 10}, backgroundColor = {1, 1, 1, 0.7}, borderColor = {1,1,1,0}, DrawControl = DrawComboBox, } skin.combobox_window = { clone = "window"; TileImage = ":cl:combobox_wnd.png"; tiles = {10, 10, 10, 10}; padding = {4, 3, 3, 4}; } skin.combobox_scrollpanel = { clone = "scrollpanel"; borderColor = {1, 1, 1, 0}; padding = {0, 0, 0, 0}; } skin.combobox_item = { clone = "button"; borderColor = {1, 1, 1, 0}; } skin.checkbox = { TileImageFG = ":cl:tech_checkbox_checked.png", TileImageBK = ":cl:tech_checkbox_unchecked.png", tiles = {3,3,3,3}, boxsize = 13, DrawControl = DrawCheckbox, } skin.editbox = { backgroundColor = {0.1, 0.1, 0.1, 0.7}, cursorColor = {1.0, 0.7, 0.1, 0.8}, TileImageBK = ":cl:panel2_bg.png", TileImageFG = ":cl:panel2_border.png", tiles = {14,14,14,14}, DrawControl = DrawEditBox, } skin.imagelistview = { imageFolder = "folder.png", imageFolderUp = "folder_up.png", --DrawControl = DrawBackground, colorBK = {1,1,1,0.3}, colorBK_selected = {1,0.7,0.1,0.8}, colorFG = {0, 0, 0, 0}, colorFG_selected = {1,1,1,1}, imageBK = ":cl:node_selected_bw.png", imageFG = ":cl:node_selected.png", tiles = {9, 9, 9, 9}, DrawItemBackground = DrawItemBkGnd, } --[[ skin.imagelistviewitem = { imageFG = ":cl:glassFG.png", imageBK = ":cl:glassBK.png", tiles = {17,15,17,20}, padding = {12, 12, 12, 12}, DrawSelectionItemBkGnd = DrawSelectionItemBkGnd, } --]] skin.panel = { TileImageBK = ":cl:tech_button.png", TileImageFG = ":cl:empty.png", tiles = {22, 22, 22, 22}, DrawControl = DrawPanel, } skin.progressbar = { TileImageFG = ":cl:tech_progressbar_full.png", TileImageBK = ":cl:tech_progressbar_empty.png", tiles = {10, 10, 10, 10}, font = { shadow = true, }, backgroundColor = {1,1,1,1}, DrawControl = DrawProgressbar, } skin.scrollpanel = { BorderTileImage = ":cl:panel2_border.png", bordertiles = {14,14,14,14}, BackgroundTileImage = ":cl:panel2_bg.png", bkgndtiles = {14,14,14,14}, TileImage = ":cl:tech_scrollbar.png", tiles = {7,7,7,7}, KnobTileImage = ":cl:tech_scrollbar_knob.png", KnobTiles = {6,8,6,8}, HTileImage = ":cl:tech_scrollbar.png", htiles = {7,7,7,7}, HKnobTileImage = ":cl:tech_scrollbar_knob.png", HKnobTiles = {6,8,6,8}, KnobColorSelected = {1,0.7,0.1,0.8}, padding = {5, 5, 5, 0}, scrollbarSize = 11, DrawControl = DrawScrollPanel, DrawControlPostChildren = DrawScrollPanelBorder, } skin.trackbar = { TileImage = ":cn:trackbar.png", tiles = {10, 14, 10, 14}, --// tile widths: left,top,right,bottom ThumbImage = ":cl:trackbar_thumb.png", StepImage = ":cl:trackbar_step.png", hitpadding = {4, 4, 5, 4}, DrawControl = DrawTrackbar, } skin.treeview = { --ImageNode = ":cl:node.png", ImageNodeSelected = ":cl:node_selected.png", tiles = {9, 9, 9, 9}, ImageExpanded = ":cl:treeview_node_expanded.png", ImageCollapsed = ":cl:treeview_node_collapsed.png", treeColor = {1,1,1,0.1}, DrawNode = DrawTreeviewNode, DrawNodeTree = DrawTreeviewNodeTree, } skin.window = { TileImage = ":c:tech_dragwindow.png", --TileImage = ":cl:tech_window.png", --TileImage = ":cl:window_tooltip.png", --tiles = {25, 25, 25, 25}, --// tile widths: left,top,right,bottom tiles = {62, 62, 62, 62}, --// tile widths: left,top,right,bottom padding = {13, 13, 13, 13}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, backgroundColor = {0.1, 0.1, 0.1, 0.7}, boxes = { resize = {-21, -21, -10, -10}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.line = { TileImage = ":cl:tech_line.png", tiles = {0, 0, 0, 0}, TileImageV = ":cl:tech_line_vert.png", tilesV = {0, 0, 0, 0}, DrawControl = DrawLine, } skin.tabbar = { padding = {3, 1, 1, 0}, } skin.tabbaritem = { TileImageBK = ":cl:tech_tabbaritem_bk.png", TileImageFG = ":cl:tech_tabbaritem_fg.png", tiles = {10, 10, 10, 0}, --// tile widths: left,top,right,bottom padding = {5, 3, 3, 2}, backgroundColor = {1, 1, 1, 1.0}, DrawControl = DrawTabBarItem, } skin.control = skin.general --//============================================================================= --// return skin
gpl-2.0
mbattersby/LiteMount
Libs/AceDB-3.0/AceDB-3.0.lua
18
24717
--- **AceDB-3.0** manages the SavedVariables of your addon. -- It offers profile management, smart defaults and namespaces for modules.\\ -- Data can be saved in different data-types, depending on its intended usage. -- The most common data-type is the `profile` type, which allows the user to choose -- the active profile, and manage the profiles of all of his characters.\\ -- The following data types are available: -- * **char** Character-specific data. Every character has its own database. -- * **realm** Realm-specific data. All of the players characters on the same realm share this database. -- * **class** Class-specific data. All of the players characters of the same class share this database. -- * **race** Race-specific data. All of the players characters of the same race share this database. -- * **faction** Faction-specific data. All of the players characters of the same faction share this database. -- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database. -- * **locale** Locale specific data, based on the locale of the players game client. -- * **global** Global Data. All characters on the same account share this database. -- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used. -- -- Creating a new Database using the `:New` function will return a new DBObject. A database will inherit all functions -- of the DBObjectLib listed here. \\ -- If you create a new namespaced child-database (`:RegisterNamespace`), you'll get a DBObject as well, but note -- that the child-databases cannot individually change their profile, and are linked to their parents profile - and because of that, -- the profile related APIs are not available. Only `:RegisterDefaults` and `:ResetProfile` are available on child-databases. -- -- For more details on how to use AceDB-3.0, see the [[AceDB-3.0 Tutorial]]. -- -- You may also be interested in [[libdualspec-1-0|LibDualSpec-1.0]] to do profile switching automatically when switching specs. -- -- @usage -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("DBExample") -- -- -- declare defaults to be used in the DB -- local defaults = { -- profile = { -- setting = true, -- } -- } -- -- function MyAddon:OnInitialize() -- -- Assuming the .toc says ## SavedVariables: MyAddonDB -- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true) -- end -- @class file -- @name AceDB-3.0.lua -- @release $Id: AceDB-3.0.lua 1142 2016-07-11 08:36:19Z nevcairiel $ local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 26 local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR) if not AceDB then return end -- No upgrade needed -- Lua APIs local type, pairs, next, error = type, pairs, next, error local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget -- WoW APIs local _G = _G -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: LibStub AceDB.db_registry = AceDB.db_registry or {} AceDB.frame = AceDB.frame or CreateFrame("Frame") local CallbackHandler local CallbackDummy = { Fire = function() end } local DBObjectLib = {} --[[------------------------------------------------------------------------- AceDB Utility Functions ---------------------------------------------------------------------------]] -- Simple shallow copy for copying defaults local function copyTable(src, dest) if type(dest) ~= "table" then dest = {} end if type(src) == "table" then for k,v in pairs(src) do if type(v) == "table" then -- try to index the key first so that the metatable creates the defaults, if set, and use that table v = copyTable(v, dest[k]) end dest[k] = v end end return dest end -- Called to add defaults to a section of the database -- -- When a ["*"] default section is indexed with a new key, a table is returned -- and set in the host table. These tables must be cleaned up by removeDefaults -- in order to ensure we don't write empty default tables. local function copyDefaults(dest, src) -- this happens if some value in the SV overwrites our default value with a non-table --if type(dest) ~= "table" then return end for k, v in pairs(src) do if k == "*" or k == "**" then if type(v) == "table" then -- This is a metatable used for table defaults local mt = { -- This handles the lookup and creation of new subtables __index = function(t,k) if k == nil then return nil end local tbl = {} copyDefaults(tbl, v) rawset(t, k, tbl) return tbl end, } setmetatable(dest, mt) -- handle already existing tables in the SV for dk, dv in pairs(dest) do if not rawget(src, dk) and type(dv) == "table" then copyDefaults(dv, v) end end else -- Values are not tables, so this is just a simple return local mt = {__index = function(t,k) return k~=nil and v or nil end} setmetatable(dest, mt) end elseif type(v) == "table" then if not rawget(dest, k) then rawset(dest, k, {}) end if type(dest[k]) == "table" then copyDefaults(dest[k], v) if src['**'] then copyDefaults(dest[k], src['**']) end end else if rawget(dest, k) == nil then rawset(dest, k, v) end end end end -- Called to remove all defaults in the default table from the database local function removeDefaults(db, defaults, blocker) -- remove all metatables from the db, so we don't accidentally create new sub-tables through them setmetatable(db, nil) -- loop through the defaults and remove their content for k,v in pairs(defaults) do if k == "*" or k == "**" then if type(v) == "table" then -- Loop through all the actual k,v pairs and remove for key, value in pairs(db) do if type(value) == "table" then -- if the key was not explicitly specified in the defaults table, just strip everything from * and ** tables if defaults[key] == nil and (not blocker or blocker[key] == nil) then removeDefaults(value, v) -- if the table is empty afterwards, remove it if next(value) == nil then db[key] = nil end -- if it was specified, only strip ** content, but block values which were set in the key table elseif k == "**" then removeDefaults(value, v, defaults[key]) end end end elseif k == "*" then -- check for non-table default for key, value in pairs(db) do if defaults[key] == nil and v == value then db[key] = nil end end end elseif type(v) == "table" and type(db[k]) == "table" then -- if a blocker was set, dive into it, to allow multi-level defaults removeDefaults(db[k], v, blocker and blocker[k]) if next(db[k]) == nil then db[k] = nil end else -- check if the current value matches the default, and that its not blocked by another defaults table if db[k] == defaults[k] and (not blocker or blocker[k] == nil) then db[k] = nil end end end end -- This is called when a table section is first accessed, to set up the defaults local function initSection(db, section, svstore, key, defaults) local sv = rawget(db, "sv") local tableCreated if not sv[svstore] then sv[svstore] = {} end if not sv[svstore][key] then sv[svstore][key] = {} tableCreated = true end local tbl = sv[svstore][key] if defaults then copyDefaults(tbl, defaults) end rawset(db, section, tbl) return tableCreated, tbl end -- Metatable to handle the dynamic creation of sections and copying of sections. local dbmt = { __index = function(t, section) local keys = rawget(t, "keys") local key = keys[section] if key then local defaultTbl = rawget(t, "defaults") local defaults = defaultTbl and defaultTbl[section] if section == "profile" then local new = initSection(t, section, "profiles", key, defaults) if new then -- Callback: OnNewProfile, database, newProfileKey t.callbacks:Fire("OnNewProfile", t, key) end elseif section == "profiles" then local sv = rawget(t, "sv") if not sv.profiles then sv.profiles = {} end rawset(t, "profiles", sv.profiles) elseif section == "global" then local sv = rawget(t, "sv") if not sv.global then sv.global = {} end if defaults then copyDefaults(sv.global, defaults) end rawset(t, section, sv.global) else initSection(t, section, section, key, defaults) end end return rawget(t, section) end } local function validateDefaults(defaults, keyTbl, offset) if not defaults then return end offset = offset or 0 for k in pairs(defaults) do if not keyTbl[k] or k == "profiles" then error(("Usage: AceDBObject:RegisterDefaults(defaults): '%s' is not a valid datatype."):format(k), 3 + offset) end end end local preserve_keys = { ["callbacks"] = true, ["RegisterCallback"] = true, ["UnregisterCallback"] = true, ["UnregisterAllCallbacks"] = true, ["children"] = true, } local realmKey = GetRealmName() local charKey = UnitName("player") .. " - " .. realmKey local _, classKey = UnitClass("player") local _, raceKey = UnitRace("player") local factionKey = UnitFactionGroup("player") local factionrealmKey = factionKey .. " - " .. realmKey local localeKey = GetLocale():lower() local regionTable = { "US", "KR", "EU", "TW", "CN" } local regionKey = regionTable[GetCurrentRegion()] local factionrealmregionKey = factionrealmKey .. " - " .. regionKey -- Actual database initialization function local function initdb(sv, defaults, defaultProfile, olddb, parent) -- Generate the database keys for each section -- map "true" to our "Default" profile if defaultProfile == true then defaultProfile = "Default" end local profileKey if not parent then -- Make a container for profile keys if not sv.profileKeys then sv.profileKeys = {} end -- Try to get the profile selected from the char db profileKey = sv.profileKeys[charKey] or defaultProfile or charKey -- save the selected profile for later sv.profileKeys[charKey] = profileKey else -- Use the profile of the parents DB profileKey = parent.keys.profile or defaultProfile or charKey -- clear the profileKeys in the DB, namespaces don't need to store them sv.profileKeys = nil end -- This table contains keys that enable the dynamic creation -- of each section of the table. The 'global' and 'profiles' -- have a key of true, since they are handled in a special case local keyTbl= { ["char"] = charKey, ["realm"] = realmKey, ["class"] = classKey, ["race"] = raceKey, ["faction"] = factionKey, ["factionrealm"] = factionrealmKey, ["factionrealmregion"] = factionrealmregionKey, ["profile"] = profileKey, ["locale"] = localeKey, ["global"] = true, ["profiles"] = true, } validateDefaults(defaults, keyTbl, 1) -- This allows us to use this function to reset an entire database -- Clear out the old database if olddb then for k,v in pairs(olddb) do if not preserve_keys[k] then olddb[k] = nil end end end -- Give this database the metatable so it initializes dynamically local db = setmetatable(olddb or {}, dbmt) if not rawget(db, "callbacks") then -- try to load CallbackHandler-1.0 if it loaded after our library if not CallbackHandler then CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0", true) end db.callbacks = CallbackHandler and CallbackHandler:New(db) or CallbackDummy end -- Copy methods locally into the database object, to avoid hitting -- the metatable when calling methods if not parent then for name, func in pairs(DBObjectLib) do db[name] = func end else -- hack this one in db.RegisterDefaults = DBObjectLib.RegisterDefaults db.ResetProfile = DBObjectLib.ResetProfile end -- Set some properties in the database object db.profiles = sv.profiles db.keys = keyTbl db.sv = sv --db.sv_name = name db.defaults = defaults db.parent = parent -- store the DB in the registry AceDB.db_registry[db] = true return db end -- handle PLAYER_LOGOUT -- strip all defaults from all databases -- and cleans up empty sections local function logoutHandler(frame, event) if event == "PLAYER_LOGOUT" then for db in pairs(AceDB.db_registry) do db.callbacks:Fire("OnDatabaseShutdown", db) db:RegisterDefaults(nil) -- cleanup sections that are empty without defaults local sv = rawget(db, "sv") for section in pairs(db.keys) do if rawget(sv, section) then -- global is special, all other sections have sub-entrys -- also don't delete empty profiles on main dbs, only on namespaces if section ~= "global" and (section ~= "profiles" or rawget(db, "parent")) then for key in pairs(sv[section]) do if not next(sv[section][key]) then sv[section][key] = nil end end end if not next(sv[section]) then sv[section] = nil end end end end end end AceDB.frame:RegisterEvent("PLAYER_LOGOUT") AceDB.frame:SetScript("OnEvent", logoutHandler) --[[------------------------------------------------------------------------- AceDB Object Method Definitions ---------------------------------------------------------------------------]] --- Sets the defaults table for the given database object by clearing any -- that are currently set, and then setting the new defaults. -- @param defaults A table of defaults for this database function DBObjectLib:RegisterDefaults(defaults) if defaults and type(defaults) ~= "table" then error("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected.", 2) end validateDefaults(defaults, self.keys) -- Remove any currently set defaults if self.defaults then for section,key in pairs(self.keys) do if self.defaults[section] and rawget(self, section) then removeDefaults(self[section], self.defaults[section]) end end end -- Set the DBObject.defaults table self.defaults = defaults -- Copy in any defaults, only touching those sections already created if defaults then for section,key in pairs(self.keys) do if defaults[section] and rawget(self, section) then copyDefaults(self[section], defaults[section]) end end end end --- Changes the profile of the database and all of it's namespaces to the -- supplied named profile -- @param name The name of the profile to set as the current profile function DBObjectLib:SetProfile(name) if type(name) ~= "string" then error("Usage: AceDBObject:SetProfile(name): 'name' - string expected.", 2) end -- changing to the same profile, dont do anything if name == self.keys.profile then return end local oldProfile = self.profile local defaults = self.defaults and self.defaults.profile -- Callback: OnProfileShutdown, database self.callbacks:Fire("OnProfileShutdown", self) if oldProfile and defaults then -- Remove the defaults from the old profile removeDefaults(oldProfile, defaults) end self.profile = nil self.keys["profile"] = name -- if the storage exists, save the new profile -- this won't exist on namespaces. if self.sv.profileKeys then self.sv.profileKeys[charKey] = name end -- populate to child namespaces if self.children then for _, db in pairs(self.children) do DBObjectLib.SetProfile(db, name) end end -- Callback: OnProfileChanged, database, newProfileKey self.callbacks:Fire("OnProfileChanged", self, name) end --- Returns a table with the names of the existing profiles in the database. -- You can optionally supply a table to re-use for this purpose. -- @param tbl A table to store the profile names in (optional) function DBObjectLib:GetProfiles(tbl) if tbl and type(tbl) ~= "table" then error("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected.", 2) end -- Clear the container table if tbl then for k,v in pairs(tbl) do tbl[k] = nil end else tbl = {} end local curProfile = self.keys.profile local i = 0 for profileKey in pairs(self.profiles) do i = i + 1 tbl[i] = profileKey if curProfile and profileKey == curProfile then curProfile = nil end end -- Add the current profile, if it hasn't been created yet if curProfile then i = i + 1 tbl[i] = curProfile end return tbl, i end --- Returns the current profile name used by the database function DBObjectLib:GetCurrentProfile() return self.keys.profile end --- Deletes a named profile. This profile must not be the active profile. -- @param name The name of the profile to be deleted -- @param silent If true, do not raise an error when the profile does not exist function DBObjectLib:DeleteProfile(name, silent) if type(name) ~= "string" then error("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected.", 2) end if self.keys.profile == name then error("Cannot delete the active profile in an AceDBObject.", 2) end if not rawget(self.profiles, name) and not silent then error("Cannot delete profile '" .. name .. "'. It does not exist.", 2) end self.profiles[name] = nil -- populate to child namespaces if self.children then for _, db in pairs(self.children) do DBObjectLib.DeleteProfile(db, name, true) end end -- switch all characters that use this profile back to the default if self.sv.profileKeys then for key, profile in pairs(self.sv.profileKeys) do if profile == name then self.sv.profileKeys[key] = nil end end end -- Callback: OnProfileDeleted, database, profileKey self.callbacks:Fire("OnProfileDeleted", self, name) end --- Copies a named profile into the current profile, overwriting any conflicting -- settings. -- @param name The name of the profile to be copied into the current profile -- @param silent If true, do not raise an error when the profile does not exist function DBObjectLib:CopyProfile(name, silent) if type(name) ~= "string" then error("Usage: AceDBObject:CopyProfile(name): 'name' - string expected.", 2) end if name == self.keys.profile then error("Cannot have the same source and destination profiles.", 2) end if not rawget(self.profiles, name) and not silent then error("Cannot copy profile '" .. name .. "'. It does not exist.", 2) end -- Reset the profile before copying DBObjectLib.ResetProfile(self, nil, true) local profile = self.profile local source = self.profiles[name] copyTable(source, profile) -- populate to child namespaces if self.children then for _, db in pairs(self.children) do DBObjectLib.CopyProfile(db, name, true) end end -- Callback: OnProfileCopied, database, sourceProfileKey self.callbacks:Fire("OnProfileCopied", self, name) end --- Resets the current profile to the default values (if specified). -- @param noChildren if set to true, the reset will not be populated to the child namespaces of this DB object -- @param noCallbacks if set to true, won't fire the OnProfileReset callback function DBObjectLib:ResetProfile(noChildren, noCallbacks) local profile = self.profile for k,v in pairs(profile) do profile[k] = nil end local defaults = self.defaults and self.defaults.profile if defaults then copyDefaults(profile, defaults) end -- populate to child namespaces if self.children and not noChildren then for _, db in pairs(self.children) do DBObjectLib.ResetProfile(db, nil, noCallbacks) end end -- Callback: OnProfileReset, database if not noCallbacks then self.callbacks:Fire("OnProfileReset", self) end end --- Resets the entire database, using the string defaultProfile as the new default -- profile. -- @param defaultProfile The profile name to use as the default function DBObjectLib:ResetDB(defaultProfile) if defaultProfile and type(defaultProfile) ~= "string" then error("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected.", 2) end local sv = self.sv for k,v in pairs(sv) do sv[k] = nil end local parent = self.parent initdb(sv, self.defaults, defaultProfile, self) -- fix the child namespaces if self.children then if not sv.namespaces then sv.namespaces = {} end for name, db in pairs(self.children) do if not sv.namespaces[name] then sv.namespaces[name] = {} end initdb(sv.namespaces[name], db.defaults, self.keys.profile, db, self) end end -- Callback: OnDatabaseReset, database self.callbacks:Fire("OnDatabaseReset", self) -- Callback: OnProfileChanged, database, profileKey self.callbacks:Fire("OnProfileChanged", self, self.keys["profile"]) return self end --- Creates a new database namespace, directly tied to the database. This -- is a full scale database in it's own rights other than the fact that -- it cannot control its profile individually -- @param name The name of the new namespace -- @param defaults A table of values to use as defaults function DBObjectLib:RegisterNamespace(name, defaults) if type(name) ~= "string" then error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected.", 2) end if defaults and type(defaults) ~= "table" then error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected.", 2) end if self.children and self.children[name] then error ("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace with that name already exists.", 2) end local sv = self.sv if not sv.namespaces then sv.namespaces = {} end if not sv.namespaces[name] then sv.namespaces[name] = {} end local newDB = initdb(sv.namespaces[name], defaults, self.keys.profile, nil, self) if not self.children then self.children = {} end self.children[name] = newDB return newDB end --- Returns an already existing namespace from the database object. -- @param name The name of the new namespace -- @param silent if true, the addon is optional, silently return nil if its not found -- @usage -- local namespace = self.db:GetNamespace('namespace') -- @return the namespace object if found function DBObjectLib:GetNamespace(name, silent) if type(name) ~= "string" then error("Usage: AceDBObject:GetNamespace(name): 'name' - string expected.", 2) end if not silent and not (self.children and self.children[name]) then error ("Usage: AceDBObject:GetNamespace(name): 'name' - namespace does not exist.", 2) end if not self.children then self.children = {} end return self.children[name] end --[[------------------------------------------------------------------------- AceDB Exposed Methods ---------------------------------------------------------------------------]] --- Creates a new database object that can be used to handle database settings and profiles. -- By default, an empty DB is created, using a character specific profile. -- -- You can override the default profile used by passing any profile name as the third argument, -- or by passing //true// as the third argument to use a globally shared profile called "Default". -- -- Note that there is no token replacement in the default profile name, passing a defaultProfile as "char" -- will use a profile named "char", and not a character-specific profile. -- @param tbl The name of variable, or table to use for the database -- @param defaults A table of database defaults -- @param defaultProfile The name of the default profile. If not set, a character specific profile will be used as the default. -- You can also pass //true// to use a shared global profile called "Default". -- @usage -- -- Create an empty DB using a character-specific default profile. -- self.db = LibStub("AceDB-3.0"):New("MyAddonDB") -- @usage -- -- Create a DB using defaults and using a shared default profile -- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true) function AceDB:New(tbl, defaults, defaultProfile) if type(tbl) == "string" then local name = tbl tbl = _G[name] if not tbl then tbl = {} _G[name] = tbl end end if type(tbl) ~= "table" then error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected.", 2) end if defaults and type(defaults) ~= "table" then error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected.", 2) end if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected.", 2) end return initdb(tbl, defaults, defaultProfile) end -- upgrade existing databases for db in pairs(AceDB.db_registry) do if not db.parent then for name,func in pairs(DBObjectLib) do db[name] = func end else db.RegisterDefaults = DBObjectLib.RegisterDefaults db.ResetProfile = DBObjectLib.ResetProfile end end
gpl-2.0
KlonZK/Zero-K
scripts/corpyro.lua
4
10294
local base = piece 'base' local low_head = piece 'low_head' local up_head = piece 'up_head' local tank = piece 'tank' local firept = piece 'firept' local l_leg = piece 'l_leg' local l_shin = piece 'l_shin' local l_foot = piece 'l_foot' local l_pist1 = piece 'l_pist1' local l_pist2 = piece 'l_pist2' local l_jetpt = piece 'l_jetpt' local r_leg = piece 'r_leg' local r_shin = piece 'r_shin' local r_foot = piece 'r_foot' local r_pist1 = piece 'r_pist1' local r_pist2 = piece 'r_pist2' local r_jetpt = piece 'r_jetpt' --by Chris Mackey --linear constant 163840 include "constants.lua" include "JumpRetreat.lua" local smokePiece = {base} local landing = false local firing = false local LINEAR_SPEED = 10 local ANGULAR_SPEED = math.rad(160) local SIG_MOVE = 2 local SIG_AIM = 4 -- JUMPING local function BeginJumpThread() Signal(SIG_MOVE) --crouch and prepare to jump Turn(l_leg, x_axis, 0, ANGULAR_SPEED*6) Turn(l_foot, x_axis, math.rad(30), ANGULAR_SPEED*4) Turn(r_leg, x_axis, 0, ANGULAR_SPEED*6) Turn(r_foot, x_axis, math.rad(30), ANGULAR_SPEED*4) Move(base, y_axis, -3, LINEAR_SPEED*4) WaitForTurn(l_leg, x_axis) --spring off with lower legs Move(base, y_axis, 3, LINEAR_SPEED*4) Move(l_shin, y_axis, -2, LINEAR_SPEED*8) Move(r_shin, y_axis, -2, LINEAR_SPEED*8) --begin rocket boost EmitSfx(l_jetpt, 1027) EmitSfx(r_jetpt, 1027) --small adjustments in flight Sleep(600) --move to neutral Move(base, y_axis, 0, LINEAR_SPEED) Move(base, z_axis, -4, LINEAR_SPEED) Move(l_shin, y_axis, 0, LINEAR_SPEED/2) Move(r_shin, y_axis, 0, LINEAR_SPEED/2) --wiggle legs in glee Turn(l_leg, x_axis, math.rad(-20), ANGULAR_SPEED) Turn(r_leg, x_axis, math.rad(-50), ANGULAR_SPEED) WaitForTurn(r_leg, x_axis) Turn(l_leg, x_axis, math.rad(-60), ANGULAR_SPEED) Turn(r_leg, x_axis, math.rad(-10), ANGULAR_SPEED) WaitForTurn(l_leg, x_axis) Turn(l_leg, x_axis, math.rad(-10), ANGULAR_SPEED) Turn(r_leg, x_axis, math.rad(-70), ANGULAR_SPEED) WaitForTurn(l_leg, x_axis) Turn(l_leg, x_axis, math.rad(-50), ANGULAR_SPEED) Turn(r_leg, x_axis, math.rad(-20), ANGULAR_SPEED) WaitForTurn(r_leg, x_axis) --move legs to landing position Turn(l_leg, x_axis, math.rad(-40), ANGULAR_SPEED/2) Turn(l_foot, x_axis, math.rad(30), ANGULAR_SPEED) Turn(r_leg, x_axis, math.rad(-40), ANGULAR_SPEED/2) Turn(r_foot, x_axis, math.rad(30), ANGULAR_SPEED) WaitForMove(r_shin, y_axis) Move(l_shin, y_axis, -1, LINEAR_SPEED/2) Move(r_shin, y_axis, -1, LINEAR_SPEED/2) end local function PrepareJumpLand() Sleep(100) Turn(low_head, x_axis, math.rad(50), ANGULAR_SPEED*2.5) Move(base, y_axis, -2, LINEAR_SPEED*2) Turn(base, x_axis, math.rad(10), ANGULAR_SPEED) Move(l_shin, y_axis, 2, LINEAR_SPEED*2) Turn(l_leg, x_axis, math.rad(-15), ANGULAR_SPEED) Turn(l_foot, x_axis, math.rad(15), ANGULAR_SPEED) Move(r_shin, y_axis, 2, LINEAR_SPEED*2) Turn(r_leg, x_axis, math.rad(-15), ANGULAR_SPEED) Turn(r_foot, x_axis, math.rad(15), ANGULAR_SPEED) WaitForTurn(low_head, x_axis) Turn(low_head, x_axis, 0, ANGULAR_SPEED) Turn(base, x_axis, 0, ANGULAR_SPEED) WaitForMove(r_shin, y_axis) Move(base, y_axis, 0, LINEAR_SPEED) Move(l_shin, y_axis, 0, LINEAR_SPEED) Move(r_shin, y_axis, 0, LINEAR_SPEED) end local function EndJumpThread() EmitSfx(l_foot, 1027) EmitSfx(r_foot, 1027) --stumble forward Move(base, z_axis, 0, LINEAR_SPEED*1.8) Turn(l_leg, x_axis, 0, ANGULAR_SPEED)--left max back Turn(l_foot, x_axis, 0, ANGULAR_SPEED) Turn(r_leg, x_axis, math.rad(-65), ANGULAR_SPEED)--right max forward Turn(r_foot, x_axis, math.rad(65), ANGULAR_SPEED) Move(r_shin, y_axis, -1.3, LINEAR_SPEED) WaitForTurn(r_leg, x_axis) Turn(l_leg, x_axis, math.rad(-20), ANGULAR_SPEED) Turn(l_foot, x_axis, math.rad(20), ANGULAR_SPEED) Move(l_shin, y_axis, 1, LINEAR_SPEED) Turn(r_leg, x_axis, math.rad(-35), ANGULAR_SPEED) Turn(r_foot, x_axis, math.rad(35), ANGULAR_SPEED) WaitForTurn(r_leg, x_axis) Turn(l_leg, x_axis, math.rad(-65), ANGULAR_SPEED)--left max forward Turn(l_foot, x_axis, math.rad(65), ANGULAR_SPEED) Move(l_shin, y_axis, -1.3, LINEAR_SPEED) Turn(l_pist1, x_axis, math.rad(-60), ANGULAR_SPEED*1.2) --Move(l_pist3, y_axis, 0.55, LINEAR_SPEED) Move(l_pist2, y_axis, 0.55, LINEAR_SPEED) Turn(r_leg, x_axis, 0, ANGULAR_SPEED)--right max back Turn(r_foot, x_axis, 0, ANGULAR_SPEED) WaitForTurn(l_leg, x_axis) Turn(r_pist1, x_axis, math.rad(-50), ANGULAR_SPEED) Move(r_pist1, y_axis, -0.45, LINEAR_SPEED) Move(r_pist2, y_axis, -0.45, LINEAR_SPEED) end function jumping(jumpPercent) if jumpPercent < 20 then EmitSfx(l_jetpt, 1026) EmitSfx(r_jetpt, 1026) end if jumpPercent > 95 and not landing then landing = true --StartThread(PrepareJumpLand) end end function preJump(turn,distance) end function beginJump() StartThread(BeginJumpThread) end function halfJump() end function endJump() landing = false StartThread(EndJumpThread) end -- MOVING local function walk() Signal(SIG_MOVE) SetSignalMask(SIG_MOVE) Turn(l_leg, x_axis, math.rad(-65), ANGULAR_SPEED) Turn(l_foot, x_axis, math.rad(65), ANGULAR_SPEED) Move(l_shin, y_axis, -2, LINEAR_SPEED) Turn(r_leg, x_axis, 0, ANGULAR_SPEED) Turn(r_foot, x_axis, 0, ANGULAR_SPEED) Move(r_shin, y_axis, 0, LINEAR_SPEED) while true do Move(base, y_axis, 1.5, LINEAR_SPEED) Turn(low_head, z_axis, math.rad(-(-7)), ANGULAR_SPEED/4) Turn(low_head, x_axis, math.rad(-5), ANGULAR_SPEED/2.4) Turn(l_leg, x_axis, math.rad(-35), ANGULAR_SPEED*1.4) Turn(l_foot, x_axis, math.rad(35), ANGULAR_SPEED) Move(l_shin, y_axis, -1.5, LINEAR_SPEED/1.5) Turn(r_leg, x_axis, math.rad(-20), ANGULAR_SPEED*1.4) Turn(r_foot, x_axis, math.rad(20), ANGULAR_SPEED) Move(r_shin, y_axis, 1, LINEAR_SPEED) Move(r_pist1, y_axis, 0.1, LINEAR_SPEED/2) Move(r_pist2, y_axis, 0.5, LINEAR_SPEED/2) WaitForTurn(low_head, x_axis) Move(base, y_axis, 0, LINEAR_SPEED/3) Turn(low_head, x_axis, math.rad(10), ANGULAR_SPEED/3) Turn(l_leg, x_axis, 0, ANGULAR_SPEED*1.6)--left max back Turn(l_foot, x_axis, 0, ANGULAR_SPEED*1.2) Turn(l_pist1, x_axis, math.rad(-50), ANGULAR_SPEED*1.2) Move(l_pist1, y_axis, -0.45, LINEAR_SPEED/2) Move(l_pist2, y_axis, -0.45, LINEAR_SPEED/2) Turn(r_leg, x_axis, math.rad(-65), ANGULAR_SPEED*1.4)--right max forward Turn(r_foot, x_axis, math.rad(65), ANGULAR_SPEED*1.2) Move(r_shin, y_axis, -1.3, LINEAR_SPEED/1.5) Turn(r_pist1, x_axis, math.rad(-60), ANGULAR_SPEED) WaitForTurn(r_leg, x_axis) Move(l_shin, y_axis, .5, LINEAR_SPEED*2) Move(base, y_axis, 1.5, LINEAR_SPEED) Turn(low_head, z_axis, math.rad(-(7)), ANGULAR_SPEED/4) Turn(low_head, x_axis, math.rad(-5), ANGULAR_SPEED/2.4) Turn(l_leg, x_axis, math.rad(-20), ANGULAR_SPEED*1.4) Turn(l_foot, x_axis, math.rad(20), ANGULAR_SPEED) Move(l_shin, y_axis, 1, LINEAR_SPEED) Move(l_pist1, y_axis, 0.1, LINEAR_SPEED/2) Move(l_pist2, y_axis, 0.5, LINEAR_SPEED/2) Turn(r_leg, x_axis, math.rad(-35), ANGULAR_SPEED*1.4) Turn(r_foot, x_axis, math.rad(35), ANGULAR_SPEED) Move(r_shin, y_axis, -1.5, LINEAR_SPEED/1.5) WaitForTurn(low_head, x_axis) Move(base, y_axis, 0, LINEAR_SPEED/3) Turn(low_head, x_axis, math.rad(10), ANGULAR_SPEED/3) Turn(l_leg, x_axis, math.rad(-65), ANGULAR_SPEED*1.4)--left max forward Turn(l_foot, x_axis, math.rad(65), ANGULAR_SPEED*1.2) Move(l_shin, y_axis, -1.3, LINEAR_SPEED/1.5) Turn(l_pist1, x_axis, math.rad(-60), ANGULAR_SPEED) Turn(r_leg, x_axis, 0, ANGULAR_SPEED*1.6)--right max back Turn(r_foot, x_axis, 0, ANGULAR_SPEED*1.4) Turn(r_pist1, x_axis, math.rad(-50), ANGULAR_SPEED*1.2) Move(r_pist1, y_axis, -0.45, LINEAR_SPEED/2) Move(r_pist2, y_axis, -0.45, LINEAR_SPEED/2) WaitForTurn(l_leg, x_axis) Move(r_shin, y_axis, .5, LINEAR_SPEED*2) end end function script.StartMoving() StartThread(walk) end function script.StopMoving() Signal(SIG_MOVE) --move all the pieces to their original spots Move(base, y_axis, 0, LINEAR_SPEED) if not firing then Turn(low_head, z_axis, math.rad(-(0)), ANGULAR_SPEED) Turn(low_head, x_axis, 0, ANGULAR_SPEED) end Turn(l_leg, x_axis, math.rad(-30), ANGULAR_SPEED) Turn(l_foot, x_axis, math.rad(30), ANGULAR_SPEED) Move(l_shin, y_axis, 0, LINEAR_SPEED) Turn(l_pist1, x_axis, math.rad(-50), ANGULAR_SPEED) Move(l_pist1, y_axis, 0, LINEAR_SPEED) Move(l_pist2, y_axis, 0, LINEAR_SPEED) Turn(r_leg, x_axis, math.rad(-30), ANGULAR_SPEED) Turn(r_foot, x_axis, math.rad(30), ANGULAR_SPEED) Move(r_shin, y_axis, 0, LINEAR_SPEED) Turn(r_pist1, x_axis, math.rad(-50), ANGULAR_SPEED) Move(r_pist1, y_axis, 0, LINEAR_SPEED) Move(r_pist2, y_axis, 0, LINEAR_SPEED) end function script.Create() StartThread(SmokeUnit, smokePiece) Spin(tank, z_axis, 70) --initialize pieces Turn(l_leg, x_axis, math.rad(-30)) Turn(l_foot, x_axis, math.rad(30)) Turn(l_pist1, x_axis, math.rad(-50)) Turn(r_leg, x_axis, math.rad(-30)) Turn(r_foot, x_axis, math.rad(30)) Turn(r_pist1, x_axis, math.rad(-50)) Turn(l_jetpt, x_axis, math.rad(50)) Turn(r_jetpt, x_axis, math.rad(50)) end function script.AimFromWeapon() return low_head end function script.QueryWeapon() return firept end local function RestoreAfterDelay() Sleep(2500) Turn(low_head, y_axis, 0, math.rad(200)) Turn(low_head, x_axis, 0, math.rad(45)) Move(up_head, y_axis, 0, LINEAR_SPEED/3) firing = false end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) firing = true --turn head, open mouth/limbs Turn(low_head, y_axis, heading, math.rad(650)) -- left-right Turn(low_head, x_axis, -pitch, math.rad(200)) --up-down Move(up_head, y_axis, 1, LINEAR_SPEED/2) WaitForTurn(low_head, y_axis) WaitForTurn(low_head, x_axis) StartThread(RestoreAfterDelay) return true end function script.FireWeapon(num) EmitSfx(firept, 1026) end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if (severity <= 0.5) then Explode(base, sfxNone) Explode(l_foot, sfxNone) Explode(l_leg, sfxNone) Explode(r_foot, sfxNone) Explode(r_leg, sfxNone) return 1 end Explode(base, sfxShatter) Explode(l_foot, sfxShatter) Explode(l_leg, sfxShatter) Explode(r_foot, sfxShatter) Explode(r_leg, sfxShatter) return 2 end
gpl-2.0
KlonZK/Zero-K
LuaUI/Widgets/unit_auto_group.lua
4
11127
local versionNum = '3.031' function widget:GetInfo() return { name = "Auto Group", desc = "v".. (versionNum) .." Alt+0-9 sets autogroup# for selected unit type(s). Newly built units get added to group# equal to their autogroup#. Alt BACKQUOTE (~) remove units. Type '/luaui autogroup help' for help or view settings at: Settings/Interface/AutoGroup'.", author = "Licho", date = "Mar 23, 2007", license = "GNU GPL, v2 or later", layer = 0, enabled = true --loaded by default? } end include("keysym.h.lua") ---- CHANGELOG ----- -- versus666, v3.03 (17dec2011) : Back to alt BACKQUOTE to remove selected units from group -- to please licho, changed help accordingly. -- versus666, v3.02 (16dec2011) : Fixed for 84, removed unused features, now alt backspace to remove -- selected units from group, changed help accordingly. -- versus666, v3.01 (07jan2011) : Added check to comply with F5. -- wagonrepairer v3.00 (07dec2010) : 'Chilified' autogroup. -- versus666, v2.25 (04nov2010) : Added switch to show or not group number, by licho's request. -- versus666, v2.24 (27oct2010) : Added switch to auto add units when built from factories. -- Add group label numbers to units in group. -- Sped up some routines & cleaned code. -- ?, v2,23 : Unknown. -- very_bad_solider,v2.22 : Ignores buildings and factories. -- Does not react when META (+ALT) is pressed. -- CarRepairer, v2.00 : Autogroups key is alt instead of alt+ctrl. -- Added commands: help, loadgroups, cleargroups, verboseMode, addall. -- Licho, v1.0 : Creation. --REMINDER : -- none -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local debug = false --of true generates debug messages local unit2group = {} -- list of unit types to group local groupableBuildingTypes = { 'tacnuke', 'empmissile', 'napalmmissile', 'seismic' } local groupableBuildings = {} for _, v in ipairs( groupableBuildingTypes ) do if UnitDefNames[v] then groupableBuildings[ UnitDefNames[v].id ] = true end end local helpText = 'Alt+0-9 sets autogroup# for selected unit type(s).\nNewly built units get added to group# equal to their autogroup#.'.. '\nAlt+BACKQUOTE (~) deletes autogrouping for selected unit type(s).' --'Ctrl+~ removes nearest selected unit from its group and selects it. ' --'Extra function: Ctrl+q picks single nearest unit from current selection.', options_order = { 'help', 'cleargroups', 'loadgroups', 'addall', 'verbose', 'immediate', 'groupnumbers', } options_path = 'Settings/Interface/AutoGroup' options = { loadgroups = { name = 'Preserve Auto Groups', desc = 'Preserve auto groupings for next game. Unchecking this clears the groups!', type = 'bool', value = true, OnChange = function(self) if not self.value then unit2group = {} Spring.Echo('game_message: Cleared Autogroups.') end end }, addall = { name = 'Add All', desc = 'Existing units will be added to group# when setting autogroup#.', type = 'bool', value = false, }, verbose = { name = 'Verbose Mode', type = 'bool', value = true, }, immediate = { name = 'Immediate Mode', desc = 'Units built/resurrected/received are added to autogroups immediately instead of waiting them to be idle.', type = 'bool', value = false, }, groupnumbers = { name = 'Display Group Numbers', type = 'bool', value = true, }, help = { name = 'Help', type = 'text', value = helpText, }, cleargroups = { name = 'Clear Auto Groups', type = 'button', OnChange = function() unit2group = {} Spring.Echo('game_message: Cleared Autogroups.') end, }, } local finiGroup = {} local myTeam local selUnitDefs = {} local loadGroups = true local createdFrame = {} local textColor = {0.7, 1.0, 0.7, 1.0} -- r g b alpha local textSize = 13.0 -- gr = groupe selected/wanted -- speedups local SetUnitGroup = Spring.SetUnitGroup local GetSelectedUnits = Spring.GetSelectedUnits local GetUnitDefID = Spring.GetUnitDefID local GetAllUnits = Spring.GetAllUnits local GetUnitHealth = Spring.GetUnitHealth local GetMouseState = Spring.GetMouseState local SelectUnitArray = Spring.SelectUnitArray local TraceScreenRay = Spring.TraceScreenRay local GetUnitPosition = Spring.GetUnitPosition local UDefTab = UnitDefs local GetGroupList = Spring.GetGroupList local GetGroupUnits = Spring.GetGroupUnits local GetGameFrame = Spring.GetGameFrame local IsGuiHidden = Spring.IsGUIHidden local Echo = Spring.Echo function printDebug( value ) if ( debug ) then Echo( value ) end end function widget:Initialize() local _, _, spec, team = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) if spec then widgetHandler:RemoveWidget() return false end myTeam = team end function widget:DrawWorld() if not IsGuiHidden() then local existingGroups = GetGroupList() if options.groupnumbers.value then for inGroup, _ in pairs(existingGroups) do units = GetGroupUnits(inGroup) for _, unit in ipairs(units) do if Spring.IsUnitInView(unit) then local ux, uy, uz = Spring.GetUnitViewPosition(unit) gl.PushMatrix() gl.Translate(ux, uy, uz) gl.Billboard() gl.Color(textColor)--unused anyway when gl.Text have option 's' (and b & w) gl.Text("" .. inGroup, 30.0, -10.0, textSize, "cns") gl.PopMatrix() end end end else end end end function widget:UnitFinished(unitID, unitDefID, unitTeam) if (unitTeam == myTeam and unitID ~= nil) then if (createdFrame[unitID] == GetGameFrame()) then local gr = unit2group[unitDefID] --printDebug("<AUTOGROUP>: Unit finished " .. unitID) -- if gr ~= nil then SetUnitGroup(unitID, gr) end else finiGroup[unitID] = 1 end end end function widget:UnitCreated(unitID, unitDefID, unitTeam, builderID) if (unitTeam == myTeam) then createdFrame[unitID] = GetGameFrame() end end function widget:UnitFromFactory(unitID, unitDefID, unitTeam) if options.immediate.value or groupableBuildings[unitDefID] then if (unitTeam == myTeam) then createdFrame[unitID] = GetGameFrame() local gr = unit2group[unitDefID] if gr ~= nil then SetUnitGroup(unitID, gr) end --printDebug("<AUTOGROUP>: Unit from factory " .. unitID) end end end function widget:UnitDestroyed(unitID, unitDefID, teamID) finiGroup[unitID] = nil createdFrame[unitID] = nil --printDebug("<AUTOGROUP> : Unit destroyed ".. unitID) end function widget:UnitGiven(unitID, unitDefID, newTeamID, teamID) if (newTeamID == myTeam) then local gr = unit2group[unitDefID] --printDebug("<AUTOGROUP> : Unit given ".. unit2group[unitDefID]) if gr ~= nil then SetUnitGroup(unitID, gr) end end createdFrame[unitID] = nil finiGroup[unitID] = nil end function widget:UnitTaken(unitID, unitDefID, oldTeamID, teamID) if (teamID == myTeam) then local gr = unit2group[unitDefID] --printDebug("<AUTOGROUP> : Unit taken ".. unit2group[unitDefID]) if gr ~= nil then SetUnitGroup(unitID, gr) end end createdFrame[unitID] = nil finiGroup[unitID] = nil end function widget:UnitIdle(unitID, unitDefID, unitTeam) if (unitTeam == myTeam and finiGroup[unitID]~=nil) then local gr = unit2group[unitDefID] if gr ~= nil then SetUnitGroup(unitID, gr) --printDebug("<AUTOGROUP> : Unit idle " .. gr) end finiGroup[unitID] = nil end end function widget:KeyPress(key, modifier, isRepeat) if ( modifier.alt and not modifier.meta ) then local gr if (key == KEYSYMS.N_0) then gr = 0 end if (key == KEYSYMS.N_1) then gr = 1 end if (key == KEYSYMS.N_2) then gr = 2 end if (key == KEYSYMS.N_3) then gr = 3 end if (key == KEYSYMS.N_4) then gr = 4 end if (key == KEYSYMS.N_5) then gr = 5 end if (key == KEYSYMS.N_6) then gr = 6 end if (key == KEYSYMS.N_7) then gr = 7 end if (key == KEYSYMS.N_8) then gr = 8 end if (key == KEYSYMS.N_9) then gr = 9 end if (key == KEYSYMS.BACKQUOTE) then gr = -1 end if (gr ~= nil) then if (gr == -1) then gr = nil end selUnitDefIDs = {} local exec = false --set to true when there is at least one unit to process for _, unitID in ipairs(GetSelectedUnits()) do local udid = GetUnitDefID(unitID) if ( not UDefTab[udid]["isFactory"] and (groupableBuildings[udid] or not UDefTab[udid]["isBuilding"] )) then selUnitDefIDs[udid] = true unit2group[udid] = gr --local x, y, z = Spring.GetUnitPosition(unitID) --Spring.MarkerAddPoint( x, y, z ) exec = true --Echo('<AUTOGROUP> : Add unit ' .. unitID .. 'to group ' .. gr) if (gr==nil) then SetUnitGroup(unitID, -1) else SetUnitGroup(unitID, gr) end end end if ( exec == false ) then return false --nothing to do end for udid,_ in pairs(selUnitDefIDs) do if options.verbose.value then if gr then Echo('game_message: Added '.. UnitDefs[udid].humanName ..' to autogroup #'.. gr ..'.') else Echo('game_message: Removed '.. UnitDefs[udid].humanName ..' from autogroups.') end end end if options.addall.value then local myUnits = Spring.GetTeamUnits(myTeam) for _, unitID in pairs(myUnits) do local curUnitDefID = GetUnitDefID(unitID) if selUnitDefIDs[curUnitDefID] then if gr then local _, _, _, _, buildProgress = GetUnitHealth(unitID) if buildProgress == 1 then SetUnitGroup(unitID, gr) SelectUnitArray({unitID}, true) end else SetUnitGroup(unitID, -1) end end end end return true --key was processed by widget end elseif (modifier.ctrl and not modifier.meta) then if (key == KEYSYMS.BACKQUOTE) then local mx,my = GetMouseState() local _,pos = TraceScreenRay(mx,my,true) local mindist = math.huge local muid = nil if (pos == nil) then return end for _, uid in ipairs(GetSelectedUnits()) do local x,_,z = GetUnitPosition(uid) dist = (pos[1]-x)*(pos[1]-x) + (pos[3]-z)*(pos[3]-z) if (dist < mindist) then mindist = dist muid = uid end end if (muid ~= nil) then SetUnitGroup(muid,-1) SelectUnitArray({muid}) end end --[[ if (key == KEYSYMS.Q) then for _, uid in ipairs(GetSelectedUnits()) do SetUnitGroup(uid,-1) end end --]] end return false end function widget:GetConfigData() local groups = {} for id, gr in pairs(unit2group) do table.insert(groups, {UnitDefs[id].name, gr}) end local ret = { version = versionNum, groups = groups, } return ret end function widget:SetConfigData(data) if (data and type(data) == 'table' and data.version and (data.version+0) > 2.1) then local groupData = data.groups if groupData and type(groupData) == 'table' then for _, nam in ipairs(groupData) do if type(nam) == 'table' then local gr = UnitDefNames[nam[1]] if (gr ~= nil) then unit2group[gr.id] = nam[2] end end end end end end --------------------------------------------------------------------------------
gpl-2.0
Kamshak/LibK
lua/libk/3rdparty/glib/net/layer2/outboundsplitpacket.lua
2
1304
local self = {} GLib.Net.Layer2.OutboundSplitPacket = GLib.MakeConstructor (self) function self:ctor (id, data) self.Id = id self.Data = data self.EncodedData = data self.EncodedLength = #self.EncodedData self.ChunkSize = 0 self.ChunkCount = 0 self.NextChunk = 1 end function self:GetId () return self.Id end function self:IsFinished () return self.NextChunk > 1 and self.NextChunk > self.ChunkCount end function self:IsStarted () return self.NextChunk > 1 end function self:SerializeFirstChunk (outBuffer) outBuffer:UInt32 (self.EncodedLength) outBuffer:UInt32 (self.ChunkSize) self:SerializeNextChunk (outBuffer) end function self:SerializeNextChunk (outBuffer) -- Include the next chunk local chunkStart = (self.NextChunk - 1) * self.ChunkSize + 1 local chunkEnd = self.NextChunk * self.ChunkSize local chunk = string.sub (self.EncodedData, chunkStart, chunkEnd) outBuffer:LongString (chunk) self.NextChunk = self.NextChunk + 1 end function self:SetChunkSize (chunkSize) if self:IsStarted () then GLib.Error ("OutboundSplitPacket:SetChunkSize : Cannot set chunk size after transmission has started.") end self.ChunkSize = chunkSize self.ChunkCount = math.ceil (self.EncodedLength / self.ChunkSize) end function self:SetId (id) self.Id = id end
mit
finnoleary/love-edit
main.lua
1
1589
require 'editor' function love.load() love.keyboard.setKeyRepeat(true) screen_width = love.window.getWidth() screen_height = love.window.getHeight() variables() require 'vi' require 'norm' editor:switch_mode(norm) love.graphics.setBackgroundColor(33, 11, 22) editor:load_init_file() end function variables() command_mode = false command_input = "" buffer_uno = {""} current_dir = editor:get_homedir() current_file = current_dir .. "filename.txt" lines = buffer_uno cursor_uno = { line = 1, column = 1 } end function love.update(dt) end function love.keypressed(key, isrep) if command_mode == true then if key == m.keys.delete then command_input = command_input:sub(1, command_input:len()-1) elseif key == m.keys.command_enter then local ci = command_input if m:command_enter(command_input) then if loadstring(command_input) == nil then command_input = "Error with input." command_mode = false else loadstring(command_input)() if command_input == ci then command_input = "" end command_mode = false end else if command_input == ci then -- print(ci) -- print(command_input) command_input = "" end command_mode = false end end m:command_mode(key, isrep) else m:keypress(key, isrep) end end function love.textinput(key) if command_mode == true then command_input = command_input:sub(0, command_input:len()) .. key else m:textin(key) end end function love.draw() m:draw() love.graphics.print("Mode : " .. m.modename, 660, screen_height-50) end
lgpl-2.1
XxMTxX/XxMTxX
plugins/Reply.lua
2
1671
-- made by { @Mouamle } do ws = {} rs = {} -- some examples of how to use this :3 ws[1] = "مرحبا" -- msg rs[1] = "مراحب" -- reply ws[2] = "شلونك" -- msg rs[2] = "تمام وانت" -- reply ws[3] = "دووم" -- msg rs[3] = "تسلم" -- reply ws[4] = "شكو ماكو" -- msg rs[4] = "ماكو غير الضوجة" -- reply -- the main function function run( msg, matches ) -- just a local variables that i used in my algorithm local i = 0; local w = false -- the main part that get the message that the user send and check if it equals to one of the words in the ws table :) -- this section loops through all the words table and assign { k } to the word index and { v } to the word itself for k,v in pairs(ws) do -- change the message text to uppercase and the { v } value that toke form the { ws } table and than compare it in a specific pattern if ( string.find(string.upper(msg.text), "^" .. string.upper(v) .. "$") ) then -- assign the { i } to the index of the reply and the { w } to true ( we will use it later ) i = k; w = true; end end -- check if { w } is not false and { i } not equals to 0 if ( (w ~= false) and (i ~= 0) ) then -- get the receiver :3 R = get_receiver(msg) -- send him the proper message from the index that { i } assigned to send_large_msg ( R , rs[i] ); end -- don't edit this section if ( msg.text == "about" ) then if ( msg.from.username == "Mouamle" ) then R = get_receiver(msg) send_large_msg ( R , "Made by @Mouamle" ); end end end return { patterns = { "(.*)" }, run = run } end
gpl-2.0
CSS98/csgroup
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
KlonZK/Zero-K
LuaRules/Configs/MetalSpots/Brazillian_Battlefield_Remake_V2.lua
17
1550
return { spots = { {x = 3265, z = 363, metal = 1.8}, {x = 3140, z = 105, metal = 1.8}, {x = 3744, z = 484, metal = 1.8}, {x = 3607, z = 647, metal = 1.8}, {x = 3153, z = 4019, metal = 1.8}, {x = 3185, z = 3811, metal = 1.8}, {x = 3980, z = 3224, metal = 1.8}, {x = 3733, z = 3033, metal = 1.8}, {x = 770, z = 3940, metal = 1.8}, {x = 1077, z = 3939, metal = 1.8}, {x = 101, z = 3477, metal = 1.8}, {x = 470, z = 3606, metal = 1.8}, {x = 784, z = 578, metal = 1.8}, {x = 483, z = 692, metal = 1.8}, {x = 265, z = 996, metal = 1.8}, {x = 129, z = 1213, metal = 1.8}, {x = 2856, z = 1251, metal = 1.8}, {x = 3030, z = 746, metal = 1.8}, {x = 2918, z = 2981, metal = 1.8}, {x = 3108, z = 3248, metal = 1.8}, {x = 1040, z = 2794, metal = 1.8}, {x = 771, z = 3023, metal = 1.8}, {x = 965, z = 1096, metal = 1.8}, {x = 989, z = 1424, metal = 1.8}, {x = 1776, z = 1823, metal = 1.8}, {x = 1859, z = 2424, metal = 1.8}, {x = 2261, z = 2470, metal = 1.8}, {x = 2524, z = 2012, metal = 1.8}, {x = 1741, z = 1267, metal = 1.8}, {x = 163, z = 1831, metal = 1.8}, {x = 860, z = 1883, metal = 1.8}, {x = 2346, z = 391, metal = 1.8}, {x = 2443, z = 1466, metal = 1.8}, {x = 2932, z = 1786, metal = 1.8}, {x = 3969, z = 1848, metal = 1.8}, {x = 3722, z = 2479, metal = 1.8}, {x = 3181, z = 2294, metal = 1.8}, {x = 2453, z = 2872, metal = 1.8}, {x = 2344, z = 3626, metal = 1.8}, {x = 1590, z = 790, metal = 1.8}, {x = 939, z = 2336, metal = 1.8}, {x = 1741, z = 3995, metal = 1.8}, {x = 1661, z = 2947, metal = 1.8}, {x = 251, z = 2293, metal = 1.8}, } }
gpl-2.0
morynicz/pyroshark
test/lua/common_sets.lua
35
13691
-- See Copyright Notice in the file LICENSE -- This file should contain only test sets that behave identically -- when being run with pcre or posix regex libraries. local luatest = require "luatest" local N = luatest.NT local function norm(a) return a==nil and N or a end local function get_gsub (lib) return lib.gsub or function (subj, pattern, repl, n) return lib.new (pattern) : gsub (subj, repl, n) end end local function set_f_gmatch (lib, flg) -- gmatch (s, p, [cf], [ef]) local function test_gmatch (subj, patt) local out, guard = {}, 10 for a, b in lib.gmatch (subj, patt) do table.insert (out, { norm(a), norm(b) }) guard = guard - 1 if guard == 0 then break end end return unpack (out) end return { Name = "Function gmatch", Func = test_gmatch, --{ subj patt results } { {"ab", lib.new"."}, {{"a",N}, {"b",N} } }, { {("abcd"):rep(3), "(.)b.(d)"}, {{"a","d"},{"a","d"},{"a","d"}} }, { {"abcd", ".*" }, {{"abcd",N},{"",N} } },--zero-length match { {"abc", "^." }, {{"a",N}} },--anchored pattern } end local function set_f_split (lib, flg) -- split (s, p, [cf], [ef]) local function test_split (subj, patt) local out, guard = {}, 10 for a, b, c in lib.split (subj, patt) do table.insert (out, { norm(a), norm(b), norm(c) }) guard = guard - 1 if guard == 0 then break end end return unpack (out) end return { Name = "Function split", Func = test_split, --{ subj patt results } { {"ab", lib.new","}, {{"ab",N,N}, } }, { {"ab", ","}, {{"ab",N,N}, } }, { {",", ","}, {{"",",",N}, {"", N, N}, } }, { {",,", ","}, {{"",",",N}, {"",",",N}, {"",N,N} } }, { {"a,b", ","}, {{"a",",",N}, {"b",N,N}, } }, { {",a,b", ","}, {{"",",",N}, {"a",",",N}, {"b",N,N}} }, { {"a,b,", ","}, {{"a",",",N}, {"b",",",N}, {"",N,N} } }, { {"a,,b", ","}, {{"a",",",N}, {"",",",N}, {"b",N,N}} }, { {"ab<78>c", "<(.)(.)>"}, {{"ab","7","8"}, {"c",N,N}, } }, { {"abc", "^."}, {{"", "a",N}, {"bc",N,N}, } },--anchored pattern { {"abc", "^"}, {{"", "", N}, {"abc",N,N}, } }, -- { {"abc", "$"}, {{"abc","",N}, {"",N,N}, } }, -- { {"abc", "^|$"}, {{"", "", N}, {"abc","",N},{"",N,N},} }, } end local function set_f_find (lib, flg) return { Name = "Function find", Func = lib.find, -- {subj, patt, st}, { results } { {"abcd", lib.new".+"}, { 1,4 } }, -- [none] { {"abcd", ".+"}, { 1,4 } }, -- [none] { {"abcd", ".+", 2}, { 2,4 } }, -- positive st { {"abcd", ".+", -2}, { 3,4 } }, -- negative st { {"abcd", ".*"}, { 1,4 } }, -- [none] { {"abc", "bc"}, { 2,3 } }, -- [none] { {"abcd", "(.)b.(d)"}, { 1,4,"a","d" }}, -- [captures] } end local function set_f_match (lib, flg) return { Name = "Function match", Func = lib.match, -- {subj, patt, st}, { results } { {"abcd", lib.new".+"}, {"abcd"} }, -- [none] { {"abcd", ".+"}, {"abcd"} }, -- [none] { {"abcd", ".+", 2}, {"bcd"} }, -- positive st { {"abcd", ".+", -2}, {"cd"} }, -- negative st { {"abcd", ".*"}, {"abcd"} }, -- [none] { {"abc", "bc"}, {"bc"} }, -- [none] { {"abcd", "(.)b.(d)"}, {"a","d"} }, -- [captures] } end local function set_m_exec (lib, flg) return { Name = "Method exec", Method = "exec", --{patt}, {subj, st} { results } { {".+"}, {"abcd"}, {1,4,{}} }, -- [none] { {".+"}, {"abcd",2}, {2,4,{}} }, -- positive st { {".+"}, {"abcd",-2}, {3,4,{}} }, -- negative st { {".*"}, {"abcd"}, {1,4,{}} }, -- [none] { {"bc"}, {"abc"}, {2,3,{}} }, -- [none] { { "(.)b.(d)"}, {"abcd"}, {1,4,{1,1,4,4}}},--[captures] { {"(a+)6+(b+)"}, {"Taa66bbT",2}, {2,7,{2,3,6,7}}},--[st+captures] } end local function set_m_tfind (lib, flg) return { Name = "Method tfind", Method = "tfind", --{patt}, {subj, st} { results } { {".+"}, {"abcd"}, {1,4,{}} }, -- [none] { {".+"}, {"abcd",2}, {2,4,{}} }, -- positive st { {".+"}, {"abcd",-2}, {3,4,{}} }, -- negative st { {".*"}, {"abcd"}, {1,4,{}} }, -- [none] { {"bc"}, {"abc"}, {2,3,{}} }, -- [none] { {"(.)b.(d)"}, {"abcd"}, {1,4,{"a","d"}}},--[captures] } end local function set_m_find (lib, flg) return { Name = "Method find", Method = "find", --{patt}, {subj, st} { results } { {".+"}, {"abcd"}, {1,4} }, -- [none] { {".+"}, {"abcd",2}, {2,4} }, -- positive st { {".+"}, {"abcd",-2}, {3,4} }, -- negative st { {".*"}, {"abcd"}, {1,4} }, -- [none] { {"bc"}, {"abc"}, {2,3} }, -- [none] { {"(.)b.(d)"}, {"abcd"}, {1,4,"a","d"}},--[captures] } end local function set_m_match (lib, flg) return { Name = "Method match", Method = "match", --{patt}, {subj, st} { results } { {".+"}, {"abcd"}, {"abcd"} }, -- [none] { {".+"}, {"abcd",2}, {"bcd" } }, -- positive st { {".+"}, {"abcd",-2}, {"cd" } }, -- negative st { {".*"}, {"abcd"}, {"abcd"} }, -- [none] { {"bc"}, {"abc"}, {"bc" } }, -- [none] {{ "(.)b.(d)"}, {"abcd"}, {"a","d"} }, --[captures] } end local function set_f_gsub1 (lib, flg) local subj, pat = "abcdef", "[abef]+" local cpat = lib.new(pat) return { Name = "Function gsub, set1", Func = get_gsub (lib), --{ s, p, f, n, res1, res2, res3 }, { {subj, cpat, "", 0}, {subj, 0, 0} }, -- test "n" + empty_replace { {subj, pat, "", 0}, {subj, 0, 0} }, -- test "n" + empty_replace { {subj, pat, "", -1}, {subj, 0, 0} }, -- test "n" + empty_replace { {subj, pat, "", 1}, {"cdef", 1, 1} }, { {subj, pat, "", 2}, {"cd", 2, 2} }, { {subj, pat, "", 3}, {"cd", 2, 2} }, { {subj, pat, "" }, {"cd", 2, 2} }, { {subj, pat, "#", 0}, {subj, 0, 0} }, -- test "n" + non-empty_replace { {subj, pat, "#", 1}, {"#cdef", 1, 1} }, { {subj, pat, "#", 2}, {"#cd#", 2, 2} }, { {subj, pat, "#", 3}, {"#cd#", 2, 2} }, { {subj, pat, "#" }, {"#cd#", 2, 2} }, { {"abc", "^.", "#" }, {"#bc", 1, 1} }, -- anchored pattern } end local function set_f_gsub2 (lib, flg) local subj, pat = "abc", "([ac])" return { Name = "Function gsub, set2", Func = get_gsub (lib), --{ s, p, f, n, res1, res2, res3 }, { {subj, pat, "<%1>" }, {"<a>b<c>", 2, 2} }, -- test non-escaped chars in f { {subj, pat, "%<%1%>" }, {"<a>b<c>", 2, 2} }, -- test escaped chars in f { {subj, pat, "" }, {"b", 2, 2} }, -- test empty replace { {subj, pat, "1" }, {"1b1", 2, 2} }, -- test odd and even %'s in f { {subj, pat, "%1" }, {"abc", 2, 2} }, { {subj, pat, "%%1" }, {"%1b%1", 2, 2} }, { {subj, pat, "%%%1" }, {"%ab%c", 2, 2} }, { {subj, pat, "%%%%1" }, {"%%1b%%1", 2, 2} }, { {subj, pat, "%%%%%1" }, {"%%ab%%c", 2, 2} }, } end local function set_f_gsub3 (lib, flg) return { Name = "Function gsub, set3", Func = get_gsub (lib), --{ s, p, f, n, res1,res2,res3 }, { {"abc", "a", "%0" }, {"abc", 1, 1} }, -- test (in)valid capture index { {"abc", "a", "%1" }, {"abc", 1, 1} }, { {"abc", "[ac]", "%1" }, {"abc", 2, 2} }, { {"abc", "(a)", "%1" }, {"abc", 1, 1} }, { {"abc", "(a)", "%2" }, "invalid capture index" }, } end local function set_f_gsub4 (lib, flg) return { Name = "Function gsub, set4", Func = get_gsub (lib), --{ s, p, f, n, res1, res2, res3 }, { {"a2c3", ".", "#" }, {"####", 4, 4} }, -- test . { {"a2c3", ".+", "#" }, {"#", 1, 1} }, -- test .+ { {"a2c3", ".*", "#" }, {"##", 2, 2} }, -- test .* { {"/* */ */", "\\/\\*(.*)\\*\\/", "#" }, {"#", 1, 1} }, { {"a2c3", "[0-9]", "#" }, {"a#c#", 2, 2} }, -- test %d { {"a2c3", "[^0-9]", "#" }, {"#2#3", 2, 2} }, -- test %D { {"a \t\nb", "[ \t\n]", "#" }, {"a###b", 3, 3} }, -- test %s { {"a \t\nb", "[^ \t\n]", "#" }, {"# \t\n#", 2, 2} }, -- test %S } end local function set_f_gsub5 (lib, flg) local function frep1 () end -- returns nothing local function frep2 () return "#" end -- ignores arguments local function frep3 (...) return table.concat({...}, ",") end -- "normal" local function frep4 () return {} end -- invalid return type local function frep5 () return "7", "a" end -- 2-nd return is "a" local function frep6 () return "7", "break" end -- 2-nd return is "break" local subj = "a2c3" return { Name = "Function gsub, set5", Func = get_gsub (lib), --{ s, p, f, n, res1, res2, res3 }, { {subj, "a(.)c(.)", frep1 }, {subj, 1, 0} }, { {subj, "a(.)c(.)", frep2 }, {"#", 1, 1} }, { {subj, "a(.)c(.)", frep3 }, {"2,3", 1, 1} }, { {subj, "a.c.", frep3 }, {subj, 1, 1} }, { {subj, "z*", frep1 }, {subj, 5, 0} }, { {subj, "z*", frep2 }, {"#a#2#c#3#", 5, 5} }, { {subj, "z*", frep3 }, {subj, 5, 5} }, { {subj, subj, frep4 }, "invalid return type" }, { {"abc",".", frep5 }, {"777", 3, 3} }, { {"abc",".", frep6 }, {"777", 3, 3} }, } end local function set_f_gsub6 (lib, flg) local tab1, tab2, tab3 = {}, { ["2"] = 56 }, { ["2"] = {} } local subj = "a2c3" return { Name = "Function gsub, set6", Func = get_gsub (lib), --{ s, p, f, n, res1,res2,res3 }, { {subj, "a(.)c(.)", tab1 }, {subj, 1, 0} }, { {subj, "a(.)c(.)", tab2 }, {"56", 1, 1} }, { {subj, "a(.)c(.)", tab3 }, "invalid replacement type" }, { {subj, "a.c.", tab1 }, {subj, 1, 0} }, { {subj, "a.c.", tab2 }, {subj, 1, 0} }, { {subj, "a.c.", tab3 }, {subj, 1, 0} }, } end local function set_f_gsub8 (lib, flg) local subj, patt, repl = "abcdef", "..", "*" return { Name = "Function gsub, set8", Func = get_gsub (lib), --{ s, p, f, n, res1, res2, res3 }, { {subj, patt, repl, function() end }, {"abcdef", 3, 0} }, { {subj, patt, repl, function() return nil end }, {"abcdef", 3, 0} }, { {subj, patt, repl, function() return false end }, {"abcdef", 3, 0} }, { {subj, patt, repl, function() return true end }, {"***", 3, 3} }, { {subj, patt, repl, function() return {} end }, {"***", 3, 3} }, { {subj, patt, repl, function() return "#" end }, {"###", 3, 3} }, { {subj, patt, repl, function() return 57 end }, {"575757", 3, 3} }, { {subj, patt, repl, function (from) return from end }, {"135", 3, 3} }, { {subj, patt, repl, function (from, to) return to end }, {"246", 3, 3} }, { {subj, patt, repl, function (from,to,rep) return rep end }, {"***", 3, 3} }, { {subj, patt, repl, function (from, to, rep) return rep..to..from end }, {"*21*43*65", 3, 3} }, { {subj, patt, repl, function() return nil end }, {"abcdef", 3, 0} }, { {subj, patt, repl, function() return nil, nil end }, {"abcdef", 3, 0} }, { {subj, patt, repl, function() return nil, false end }, {"abcdef", 3, 0} }, { {subj, patt, repl, function() return nil, true end }, {"ab**", 3, 2} }, { {subj, patt, repl, function() return true, true end }, {"***", 3, 3} }, { {subj, patt, repl, function() return nil, 0 end }, {"abcdef", 1, 0} }, { {subj, patt, repl, function() return true, 0 end }, {"*cdef", 1, 1} }, { {subj, patt, repl, function() return nil, 1 end }, {"ab*ef", 2, 1} }, { {subj, patt, repl, function() return true, 1 end }, {"**ef", 2, 2} }, } end return function (libname, isglobal) local lib = isglobal and _G[libname] or require (libname) return { set_f_gmatch (lib), set_f_split (lib), set_f_find (lib), set_f_match (lib), set_m_exec (lib), set_m_tfind (lib), set_m_find (lib), set_m_match (lib), set_f_gsub1 (lib), set_f_gsub2 (lib), set_f_gsub3 (lib), set_f_gsub4 (lib), set_f_gsub5 (lib), set_f_gsub6 (lib), set_f_gsub8 (lib), } end
gpl-2.0
EvolSknaht/cqui
Assets/UI/Screens/techtree.lua
1
72405
-- =========================================================================== -- TechTree -- Tabs set to 4 spaces retaining tab. -- -- The tech "Index" is the internal ID the gamecore used to track the tech. -- This value is essentially the database (db) row id minus 1 since it's 0 based. -- (e.g., TECH_MINING has a db rowid of 3, so it's gamecore index is 2.) -- -- Items exist in one of 8 "rows" that span horizontally and within a -- "column" based on the era and cost. -- -- Rows Start Eras-> -- -3 _____ _____ -- -2 /-|_____|----/-|_____| -- -1 | _____ | Nodes -- 0 O----%-|_____|----' -- 1 -- 2 -- 3 -- 4 -- -- =========================================================================== include( "ToolTipHelper" ); include( "SupportFunctions" ); include( "Civ6Common" ); -- Tutorial check support include( "TechAndCivicSupport"); -- (Already includes Civ6Common and InstanceManager) PopulateUnlockablesForTech include( "TechFilterFunctions" ); include( "ModalScreen_PlayerYieldsHelper" ); -- =========================================================================== -- DEBUG -- Toggle these for temporary debugging help. -- =========================================================================== local m_debugFilterEraMaxIndex :number = -1; -- (-1 default) Only load up to a specific ERA (Value less than 1 to disable) local m_debugOutputTechInfo :boolean= false; -- (false default) Send to console detailed information on tech? local m_debugShowIDWithName :boolean= false; -- (false default) Show the ID before the name in each node. local m_debugShowAllMarkers :boolean= false; -- (false default) Show all player markers in the timline; even if they haven't been met. -- =========================================================================== -- CONSTANTS -- =========================================================================== -- Graphic constants local PIC_BOLT_OFF :string = "Controls_BoltOff"; local PIC_BOLT_ON :string = "Controls_BoltOn"; local PIC_BOOST_OFF :string = "BoostTech"; local PIC_BOOST_ON :string = "BoostTechOn"; local PIC_DEFAULT_ERA_BACKGROUND:string = "TechTree_BGAncient"; local PIC_MARKER_PLAYER :string = "Tree_TimePipPlayer"; local PIC_MARKER_OTHER :string = "Controls_TimePip"; local PIC_METER_BACK :string = "Tree_Meter_GearBack"; local PIC_METER_BACK_DONE :string = "TechTree_Meter_Done"; local SIZE_ART_ERA_OFFSET_X :number = 40; -- How far to push each era marker local SIZE_ART_ERA_START_X :number = 40; -- How far to set the first era marker local SIZE_MARKER_PLAYER_X :number = 122; -- Marker of player local SIZE_MARKER_PLAYER_Y :number = 42; -- " local SIZE_MARKER_OTHER_X :number = 34; -- Marker of other players local SIZE_MARKER_OTHER_Y :number = 37; -- " local SIZE_NODE_X :number = 370; -- Item node dimensions local SIZE_NODE_Y :number = 84; local SIZE_OPTIONS_X :number = 200; local SIZE_OPTIONS_Y :number = 150; local SIZE_PATH :number = 40; local SIZE_PATH_HALF :number = SIZE_PATH / 2; local SIZE_TIMELINE_AREA_Y :number = 41; local SIZE_TOP_AREA_Y :number = 60; local SIZE_WIDESCREEN_HEIGHT :number = 768; local PATH_MARKER_OFFSET_X :number = 20; local PATH_MARKER_OFFSET_Y :number = 50; local PATH_MARKER_NUMBER_0_9_OFFSET :number = 20; local PATH_MARKER_NUMBER_10_OFFSET :number = 15; -- Other constants local COLUMN_WIDTH :number = 250; -- Space of node and line(s) after it to the next node local COLUMNS_NODES_SPAN :number = 2; -- How many colunms do the nodes span local DATA_FIELD_LIVEDATA :string = "_LIVEDATA"; -- The current status of an item. local DATA_FIELD_PLAYERINFO :string = "_PLAYERINFO";-- Holds a table with summary information on that player. local DATA_FIELD_UIOPTIONS :string = "_UIOPTIONS"; -- What options the player has selected for this screen. local DATA_ICON_PREFIX :string = "ICON_"; local ERA_ART :table = {}; local ITEM_STATUS :table = { BLOCKED = 1, READY = 2, CURRENT = 3, RESEARCHED = 4, }; local LINE_LENGTH_BEFORE_CURVE :number = 20; -- How long to make a line before a node before it curves local PADDING_TIMELINE_LEFT :number = 250; local PADDING_NODE_STACK_Y :number = 0; local PADDING_PAST_ERA_LEFT :number = 90; local PARALLAX_SPEED :number = 1.1; -- Speed for how much slower background moves (1.0=regular speed, 0.5=half speed) local PARALLAX_ART_SPEED :number = 1.2; -- Speed for how much slower background moves (1.0=regular speed, 0.5=half speed) local PREREQ_ID_TREE_START :string = "_TREESTART"; -- Made up, unique value, to mark a non-node tree start local ROW_MAX :number = 4; -- Highest level row above 0 local ROW_MIN :number = -3; -- Lowest level row below 0 local STATUS_ART :table = {}; local TIMELINE_LEFT_PADDING :number = 320; local TREE_START_ROW :number = 0; -- Which virtual "row" does tree start on? local TREE_START_COLUMN :number = 0; -- Which virtual "column" does tree start on? (Can be negative!) local TREE_START_NONE_ID :number = -999; -- Special, unique value, to mark no special tree start node. local TXT_BOOSTED :string = Locale.Lookup("LOC_BOOST_BOOSTED"); local TXT_TO_BOOST :string = Locale.Lookup("LOC_BOOST_TO_BOOST"); local VERTICAL_CENTER :number = (SIZE_NODE_Y) / 2; local MAX_BEFORE_TRUNC_TO_BOOST :number = 310; local MAX_BEFORE_TRUNC_KEY_LABEL:number = 100; -- CQUI CONSTANTS local CQUI_STATUS_MESSAGE_TECHS :number = 4; -- Number to distinguish tech messages STATUS_ART[ITEM_STATUS.BLOCKED] = { Name="BLOCKED", TextColor0=0xff202726, TextColor1=0x00000000, FillTexture="TechTree_GearButtonTile_Disabled.dds",BGU=0,BGV=(SIZE_NODE_Y*3), IsButton=false, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.READY] = { Name="READY", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=0, IsButton=true, BoltOn=false, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.CURRENT] = { Name="CURRENT", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture=nil, BGU=0,BGV=(SIZE_NODE_Y*4), IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK }; STATUS_ART[ITEM_STATUS.RESEARCHED] = { Name="RESEARCHED", TextColor0=0xaaffffff, TextColor1=0x88000000, FillTexture="TechTree_GearButtonTile_Done.dds", BGU=0,BGV=(SIZE_NODE_Y*5), IsButton=false, BoltOn=true, IconBacking=PIC_METER_BACK_DONE }; -- =========================================================================== -- MEMBERS / VARIABLES -- =========================================================================== local m_kNodeIM :table = InstanceManager:new( "NodeInstance", "Top", Controls.NodeScroller ); local m_kLineIM :table = InstanceManager:new( "LineImageInstance", "LineImage",Controls.NodeScroller ); local m_kEraArtIM :table = InstanceManager:new( "EraArtInstance", "Top", Controls.FarBackArtScroller ); local m_kEraLabelIM :table = InstanceManager:new( "EraLabelInstance", "Top", Controls.ArtScroller ); local m_kEraDotIM :table = InstanceManager:new( "EraDotInstance", "Dot", Controls.ScrollbarBackgroundArt ); local m_kMarkerIM :table = InstanceManager:new( "PlayerMarkerInstance", "Top", Controls.TimelineScrollbar ); local m_kSearchResultIM :table = InstanceManager:new( "SearchResultInstance", "Root", Controls.SearchResultsStack); local m_kPathMarkerIM :table = InstanceManager:new( "TechPathMarker", "Top", Controls.NodeScroller); local m_researchHash :number; local m_width :number= SIZE_MIN_SPEC_X; -- Screen Width (default / min spec) local m_height :number= SIZE_MIN_SPEC_Y; -- Screen Height (default / min spec) local m_previousHeight :number= SIZE_MIN_SPEC_Y; -- Screen Height (default / min spec) local m_scrollWidth :number= SIZE_MIN_SPEC_X; -- Width of the scroll bar local m_kEras :table = {}; -- type to costs local m_kEraCounter :table = {}; -- counter to determine which eras have techs local m_maxColumns :number= 0; -- # of columns (highest column #) local m_ePlayer :number= -1; local m_kAllPlayersTechData :table = {}; -- All data for local players. local m_kCurrentData :table = {}; -- Current set of data. local m_kItemDefaults :table = {}; -- Static data about items local m_kNodeGrid :table = {}; -- Static data about node location once it's laid out local m_uiNodes :table = {}; local m_uiConnectorSets :table = {}; local m_kFilters :table = {}; local m_shiftDown :boolean = false; local m_ToggleTechTreeId; -- CQUI variables local CQUI_halfwayNotified :table = {}; -- =========================================================================== -- Return string respresenation of a prereq table -- =========================================================================== function GetPrereqsString( prereqs:table ) local out:string = ""; for _,prereq in pairs(prereqs) do if prereq == PREREQ_ID_TREE_START then out = "n/a "; else out = out .. m_kItemDefaults[prereq].Type .. " "; -- Add space between techs end end return "[" .. string.sub(out,1,string.len(out)-1) .. "]"; -- Remove trailing space end -- =========================================================================== function SetCurrentNode( hash:number ) if hash ~= nil then local localPlayerTechs = Players[Game.GetLocalPlayer()]:GetTechs(); -- Get the complete path to the tech local pathToTech = localPlayerTechs:GetResearchPath( hash ); local tParameters = {}; tParameters[PlayerOperations.PARAM_TECH_TYPE] = pathToTech; if m_shiftDown then tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_APPEND; else tParameters[PlayerOperations.PARAM_INSERT_MODE] = PlayerOperations.VALUE_EXCLUSIVE; end UI.RequestPlayerOperation(Game.GetLocalPlayer(), PlayerOperations.RESEARCH, tParameters); UI.PlaySound("Confirm_Tech_TechTree"); else UI.DataError("Attempt to change current tree item with NIL hash!"); end end -- =========================================================================== -- If the next item isn't immediate, show a path of #s traversing the tree -- to the desired node. -- =========================================================================== function RealizePathMarkers() local pTechs :table = Players[Game.GetLocalPlayer()]:GetTechs(); local kNodeIds :table = pTechs:GetResearchQueue(); -- table: index, IDs m_kPathMarkerIM:ResetInstances(); for i,nodeNumber in pairs(kNodeIds) do local pathPin = m_kPathMarkerIM:GetInstance(); if(i < 10) then pathPin.NodeNumber:SetOffsetX(PATH_MARKER_NUMBER_0_9_OFFSET); else pathPin.NodeNumber:SetOffsetX(PATH_MARKER_NUMBER_10_OFFSET); end pathPin.NodeNumber:SetText(tostring(i)); for j,node in pairs(m_kItemDefaults) do if node.Index == nodeNumber then local x:number = m_uiNodes[node.Type].x; local y:number = m_uiNodes[node.Type].y; pathPin.Top:SetOffsetX(x-PATH_MARKER_OFFSET_X); pathPin.Top:SetOffsetY(y-PATH_MARKER_OFFSET_Y); end end end end -- =========================================================================== -- Convert a virtual column # and row # to actual pixels within the -- scrollable tree area. -- =========================================================================== function ColumnRowToPixelXY( column:number, row:number) local horizontal :number = ((column-1) * COLUMNS_NODES_SPAN * COLUMN_WIDTH) + PADDING_TIMELINE_LEFT + PADDING_PAST_ERA_LEFT; local vertical :number = PADDING_NODE_STACK_Y + (SIZE_WIDESCREEN_HEIGHT / 2) + (row * SIZE_NODE_Y); return horizontal, vertical; end -- =========================================================================== -- Get the width of the scroll panel -- =========================================================================== function GetMaxScrollWidth() return m_maxColumns + (m_maxColumns * COLUMN_WIDTH) + TIMELINE_LEFT_PADDING; end -- =========================================================================== -- Take the default item data and build the nodes that work with it. -- One time creation, any dynamic pieces should be -- -- No state specific data (e.g., selected node) should be set here in order -- to reuse the nodes across viewing other players' trees for single seat -- multiplayer or if a (spy) game rule allows looking at another's tree. -- =========================================================================== function AllocateUI() m_uiNodes = {}; m_kNodeIM:ResetInstances(); m_uiConnectorSets = {}; m_kLineIM:ResetInstances(); --[[ Layout logic for purely pre-reqs... In the existing Tech Tree there are many lines running across nodes using this algorithm as a smarter method than just "pushing a node forward" when a crossed node occurs needs to be implemented. If this gets completely re-written, it's likely a method that tracks the entire traceback of the line and then "untangles" by pushing node(s) forward should be explored. -TRON ]] -- Layout the nodes in columns based on increasing cost within an era. -- Loop items, put into era columns. for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; if era.Columns[item.Cost] == nil then era.Columns[item.Cost] = {}; end table.insert( era.Columns[item.Cost], item.Type ); era.NumColumns = table.count( era.Columns ); -- This isn't great; set every iteration! end -- Loop items again, assigning column based off of total columns used for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; local i :number = 0; local isFound :boolean = false; for cost,columns in orderedPairs( era.Columns ) do if cost ~= "__orderedIndex" then -- skip temp table used for order i = i + 1; for _,itemType in ipairs(columns) do if itemType == item.Type then item.Column = i; isFound = true; break; end end if isFound then break; end end end era.Columns.__orderedIndex = nil; end -- Determine total # of columns prior to a given era, and max columns overall. local index = 1; local priorColumns:number = 0; m_maxColumns = 0; for row:table in GameInfo.Eras() do for era,eraData in pairs(m_kEras) do if eraData.Index == index then eraData.PriorColumns = priorColumns; priorColumns = priorColumns + eraData.NumColumns + 1; -- Add one for era art between break; end end index = index + 1; end m_maxColumns = priorColumns; -- Set nodes in the rows specified and columns computed above. m_kNodeGrid = {}; for i = ROW_MIN,ROW_MAX,1 do m_kNodeGrid[i] = {}; end for _,item in pairs(m_kItemDefaults) do local era :table = m_kEras[item.EraType]; local columnNum :number = era.PriorColumns + item.Column; m_kNodeGrid[item.UITreeRow][columnNum] = item.Type; end -- Era divider information m_kEraArtIM:ResetInstances(); m_kEraLabelIM:ResetInstances(); m_kEraDotIM:ResetInstances(); for era,eraData in pairs(m_kEras) do local instArt :table = m_kEraArtIM:GetInstance(); if eraData.BGTexture ~= nil then instArt.BG:SetTexture( eraData.BGTexture ); else UI.DataError("Tech tree is unable to find an EraTechBackgroundTexture entry for era '"..eraData.Description.."'; using a default."); instArt.BG:SetTexture(PIC_DEFAULT_ERA_BACKGROUND); end local startx, _ = ColumnRowToPixelXY( eraData.PriorColumns + 1, 0); instArt.Top:SetOffsetX( (startx ) * (1/PARALLAX_ART_SPEED) ); instArt.Top:SetOffsetY( (SIZE_WIDESCREEN_HEIGHT * 0.5) - (instArt.BG:GetSizeY()*0.5) ); instArt.Top:SetSizeVal(eraData.NumColumns*SIZE_NODE_X, 600); local inst:table = m_kEraLabelIM:GetInstance(); local eraMarkerx, _ = ColumnRowToPixelXY( eraData.PriorColumns + 1, 0) - PADDING_PAST_ERA_LEFT; -- Need to undo the padding in place that nodes use to get past the era marker column inst.Top:SetOffsetX( (eraMarkerx - (SIZE_NODE_X*0.5)) * (1/PARALLAX_SPEED) ); inst.EraTitle:SetText( Locale.Lookup("LOC_GAME_ERA_DESC",eraData.Description) ); -- Dots on scrollbar local markerx:number = (eraData.PriorColumns / m_maxColumns) * Controls.ScrollbarBackgroundArt:GetSizeX(); if markerx > 0 then local inst:table = m_kEraDotIM:GetInstance(); inst.Dot:SetOffsetX(markerx); end end local playerId = Game.GetLocalPlayer(); if (playerId == -1) then return; end -- Actually build UI nodes for _,item in pairs(m_kItemDefaults) do local tech = GameInfo.Technologies[item.Index]; local techType = tech and tech.TechnologyType; local unlockableTypes = GetUnlockablesForTech_Cached(techType, playerId); local node :table; local numUnlocks :number = 0; if unlockableTypes ~= nil then for _, unlockItem in ipairs(unlockableTypes) do local typeInfo = GameInfo.Types[unlockItem[1]]; numUnlocks = numUnlocks + 1; end end node = m_kNodeIM:GetInstance(); node.Top:SetTag( item.Hash ); -- Set the hash of the technology to the tag of the node (for tutorial to be able to callout) local era:table = m_kEras[item.EraType]; -- Horizontal # = All prior nodes across all previous eras + node position in current era (based on cost vs. other nodes in that era) local horizontal, vertical = ColumnRowToPixelXY(era.PriorColumns + item.Column, item.UITreeRow ); -- Add data fields to UI component node.Type = techType; -- Dynamically add "Type" field to UI node for quick look ups in item data table. node.x = horizontal; -- Granted x,y can be looked up via GetOffset() but caching the values here for node.y = vertical - VERTICAL_CENTER; -- other LUA functions to use removes the necessity of a slow C++ roundtrip. if node["unlockIM"] ~= nil then node["unlockIM"]:DestroyInstances() end node["unlockIM"] = InstanceManager:new( "UnlockInstance", "UnlockIcon", node.UnlockStack ); if node["unlockGOV"] ~= nil then node["unlockGOV"]:DestroyInstances() end node["unlockGOV"] = InstanceManager:new( "GovernmentIcon", "GovernmentInstanceGrid", node.UnlockStack ); PopulateUnlockablesForTech(playerId, item.Index, node["unlockIM"], function() SetCurrentNode(item.Hash); end); -- What happens when clicked function OpenPedia() LuaEvents.OpenCivilopedia(techType); end node.NodeButton:RegisterCallback( Mouse.eLClick, function() SetCurrentNode(item.Hash); end); node.OtherStates:RegisterCallback( Mouse.eLClick, function() SetCurrentNode(item.Hash); end); -- Only wire up Civilopedia handlers if not in a on-rails tutorial; as clicking it can take a player off the rails... if IsTutorialRunning()==false then node.NodeButton:RegisterCallback( Mouse.eRClick, OpenPedia); node.OtherStates:RegisterCallback( Mouse.eRClick, OpenPedia); end -- Set position and save. node.Top:SetOffsetVal( horizontal, vertical); m_uiNodes[item.Type] = node; end if Controls.TreeStart ~= nil then local h,v = ColumnRowToPixelXY( TREE_START_COLUMN, TREE_START_ROW ); Controls.TreeStart:SetOffsetVal( h+SIZE_NODE_X-42,v-71 ); -- TODO: Science-out the magic (numbers). end -- Determine the lines between nodes. -- NOTE: Potentially move this to view, since lines are constantly change in look, but -- it makes sense to have at least the routes computed here since they are -- consistent regardless of the look. for type,item in pairs(m_kItemDefaults) do local node:table = m_uiNodes[item.Type]; for _,prereqId in pairs(item.Prereqs) do local previousRow :number = 0; local previousColumn:number = 0; if prereqId == PREREQ_ID_TREE_START then previousRow = TREE_START_ROW; previousColumn = TREE_START_COLUMN; else local prereq :table = m_kItemDefaults[prereqId]; previousRow = prereq.UITreeRow; previousColumn = m_kEras[prereq.EraType].PriorColumns + prereq.Column; end local startColumn :number = m_kEras[item.EraType].PriorColumns + item.Column; local column :number = startColumn; local isEarlyBend :boolean= false; local isAtPrior :boolean= false; while( not isAtPrior ) do column = column - 1; -- Move backwards one -- If a node is found, make sure it's the previous node this is looking for. if (m_kNodeGrid[previousRow][column] ~= nil) then if m_kNodeGrid[previousRow][column] == prereqId then isAtPrior = true; end elseif column <= TREE_START_COLUMN then isAtPrior = true; end if (not isAtPrior) and m_kNodeGrid[item.UITreeRow][column] ~= nil then -- Was trying to hold off bend until start, but it looks to cross -- another node, so move the bend to the end. isEarlyBend = true; end if column < 0 then UI.DataError("Tech tree could not find prior for '"..prereqId.."'"); break; end end if previousRow == TREE_START_NONE_ID then -- Nothing goes before this, not even a fake start area. elseif previousRow < item.UITreeRow or previousRow > item.UITreeRow then -- Obtain grid pieces to ____________________ -- use in order to draw ___ ________| | -- lines. |L2 |L1 | NODE | -- |___|________| | -- _____________________ |L3 | x1 |____________________| -- | |___________|___| -- | PREVIOUS NODE | L5 |L4 | -- | |___________|___| -- |_____________________| x2 -- local inst :table = m_kLineIM:GetInstance(); local line1 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line2 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line3 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line4 :table = inst.LineImage; inst = m_kLineIM:GetInstance(); local line5 :table = inst.LineImage; -- Find all the empty space before the node before to make a bend. local LineEndX1:number = 0; local LineEndX2:number = 0; if isEarlyBend then LineEndX1 = (node.x - LINE_LENGTH_BEFORE_CURVE ) ; LineEndX2, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX2 = LineEndX2 + SIZE_NODE_X; else LineEndX1, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX2, _ = ColumnRowToPixelXY( column, item.UITreeRow ); LineEndX1 = LineEndX1 + SIZE_NODE_X + LINE_LENGTH_BEFORE_CURVE; LineEndX2 = LineEndX2 + SIZE_NODE_X; end local prevY :number = 0; -- y position of the previous node being connected to if previousRow < item.UITreeRow then prevY = node.y-((item.UITreeRow-previousRow)*SIZE_NODE_Y);-- above line2:SetTexture("Controls_TreePathDashSE"); line4:SetTexture("Controls_TreePathDashES"); else prevY = node.y+((previousRow-item.UITreeRow)*SIZE_NODE_Y);-- below line2:SetTexture("Controls_TreePathDashNE"); line4:SetTexture("Controls_TreePathDashEN"); end line1:SetOffsetVal(LineEndX1 + SIZE_PATH_HALF, node.y - SIZE_PATH_HALF); line1:SetSizeVal( node.x - LineEndX1 - SIZE_PATH_HALF, SIZE_PATH); line1:SetTexture("Controls_TreePathDashEW"); line2:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, node.y - SIZE_PATH_HALF); line2:SetSizeVal( SIZE_PATH, SIZE_PATH); line3:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, math.min(node.y + SIZE_PATH_HALF, prevY + SIZE_PATH_HALF) ); line3:SetSizeVal( SIZE_PATH, math.abs(node.y - prevY) - SIZE_PATH ); line3:SetTexture("Controls_TreePathDashNS"); line4:SetOffsetVal(LineEndX1 - SIZE_PATH_HALF, prevY - SIZE_PATH_HALF); line4:SetSizeVal( SIZE_PATH, SIZE_PATH); line5:SetSizeVal( LineEndX1 - LineEndX2 - SIZE_PATH_HALF, SIZE_PATH ); line5:SetOffsetVal(LineEndX2, prevY - SIZE_PATH_HALF); line1:SetTexture("Controls_TreePathDashEW"); -- Directly store the line (not instance) with a key name made up of this type and the prereq's type. m_uiConnectorSets[item.Type..","..prereqId] = {line1,line2,line3,line4,line5}; else -- Prereq is on the same row local inst:table = m_kLineIM:GetInstance(); local line:table = inst.LineImage; line:SetTexture("Controls_TreePathDashEW"); local end1, _ = ColumnRowToPixelXY( column, item.UITreeRow ); end1 = end1 + SIZE_NODE_X; line:SetOffsetVal(end1, node.y - SIZE_PATH_HALF); line:SetSizeVal( node.x - end1, SIZE_PATH); -- Directly store the line (not instance) with a key name made up of this type and the prereq's type. m_uiConnectorSets[item.Type..","..prereqId] = {line}; end end end Controls.NodeScroller:CalculateSize(); Controls.NodeScroller:ReprocessAnchoring(); Controls.ArtScroller:CalculateSize(); Controls.FarBackArtScroller:CalculateSize(); Controls.NodeScroller:RegisterScrollCallback( OnScroll ); -- We use a separate BG within the PeopleScroller control since it needs to scroll with the contents Controls.ModalBG:SetHide(true); Controls.ModalScreenClose:RegisterCallback(Mouse.eLClick, OnClose); Controls.ModalScreenTitle:SetText(Locale.ToUpper(Locale.Lookup("LOC_TECH_TREE_HEADER"))); end -- =========================================================================== -- UI Event -- Callback when the main scroll panel is scrolled. -- =========================================================================== function OnScroll( control:table, percent:number ) -- Parallax Controls.ArtScroller:SetScrollValue( percent ); Controls.FarBackArtScroller:SetScrollValue( percent ); -- Audio if percent==0 or percent==1.0 then UI.PlaySound("UI_TechTree_ScrollTick_End"); else UI.PlaySound("UI_TechTree_ScrollTick"); end end -- =========================================================================== -- Display the state of the tree (filter, node display, etc...) based on the -- active player's item data. -- =========================================================================== function View( playerTechData:table ) -- Output the node states for the tree for _,node in pairs(m_uiNodes) do local item :table = m_kItemDefaults[node.Type]; -- static item data local live :table = playerTechData[DATA_FIELD_LIVEDATA][node.Type]; -- live (changing) data local artInfo :table = STATUS_ART[live.Status]; -- art/styles for this state if(live.Status == ITEM_STATUS.RESEARCHED) then for _,prereqId in pairs(item.Prereqs) do if(prereqId ~= PREREQ_ID_TREE_START) then local prereq :table = m_kItemDefaults[prereqId]; local previousRow :number = prereq.UITreeRow; local previousColumn:number = m_kEras[prereq.EraType].PriorColumns; for lineNum,line in pairs(m_uiConnectorSets[item.Type..","..prereqId]) do if(lineNum == 1 or lineNum == 5) then line:SetTexture("Controls_TreePathEW"); end if( lineNum == 3) then line:SetTexture("Controls_TreePathNS"); end if(lineNum==2)then if previousRow < item.UITreeRow then line:SetTexture("Controls_TreePathSE"); else line:SetTexture("Controls_TreePathNE"); end end if(lineNum==4)then if previousRow < item.UITreeRow then line:SetTexture("Controls_TreePathES"); else line:SetTexture("Controls_TreePathEN"); end end end end end end node.NodeName:SetColor( artInfo.TextColor0, 0 ); node.NodeName:SetColor( artInfo.TextColor1, 1 ); if m_debugShowIDWithName then node.NodeName:SetText( tostring(item.Index).." "..Locale.Lookup(item.Name) ); -- Debug output else node.NodeName:SetText( Locale.ToUpper( Locale.Lookup(item.Name) )); -- Normal output end if live.Turns > 0 then node.Turns:SetHide( false ); node.Turns:SetColor( artInfo.TextColor0, 0 ); node.Turns:SetColor( artInfo.TextColor1, 1 ); node.Turns:SetText( Locale.Lookup("LOC_TECH_TREE_TURNS",live.Turns) ); else node.Turns:SetHide( true ); end if item.IsBoostable and live.Status ~= ITEM_STATUS.RESEARCHED then node.BoostIcon:SetHide( false ); node.BoostText:SetHide( false ); node.BoostText:SetColor( artInfo.TextColor0, 0 ); node.BoostText:SetColor( artInfo.TextColor1, 1 ); local boostText:string; if live.IsBoosted then boostText = TXT_BOOSTED.." "..item.BoostText; node.BoostIcon:SetTexture( PIC_BOOST_ON ); node.BoostMeter:SetHide( true ); else boostText = TXT_TO_BOOST.." "..item.BoostText; node.BoostedBack:SetHide( true ); node.BoostIcon:SetTexture( PIC_BOOST_OFF ); node.BoostMeter:SetHide( false ); local boostAmount = (item.BoostAmount*.01) + (live.Progress/ live.Cost); node.BoostMeter:SetPercent( boostAmount ); end TruncateStringWithTooltip(node.BoostText, MAX_BEFORE_TRUNC_TO_BOOST, boostText); else node.BoostIcon:SetHide( true ); node.BoostText:SetHide( true ); node.BoostedBack:SetHide( true ); node.BoostMeter:SetHide( true ); end if live.Status == ITEM_STATUS.CURRENT then node.GearAnim:SetHide( false ); else node.GearAnim:SetHide( true ); end if live.Progress > 0 then node.ProgressMeter:SetHide( false ); node.ProgressMeter:SetPercent(live.Progress / live.Cost); else node.ProgressMeter:SetHide( true ); end -- Show/Hide Recommended Icon if live.IsRecommended and live.AdvisorType ~= nil then node.RecommendedIcon:SetIcon(live.AdvisorType); node.RecommendedIcon:SetHide(false); else node.RecommendedIcon:SetHide(true); end -- Set art for icon area if(node.Type ~= nil) then local iconName :string = DATA_ICON_PREFIX .. node.Type; if (artInfo.Name == "BLOCKED") then node.IconBacking:SetHide(true); iconName = iconName .. "_FOW"; node.BoostMeter:SetColor(0x66ffffff); node.BoostIcon:SetColor(0x66000000); else node.IconBacking:SetHide(false); iconName = iconName; node.BoostMeter:SetColor(0xffffffff); node.BoostIcon:SetColor(0xffffffff); end local textureOffsetX, textureOffsetY, textureSheet = IconManager:FindIconAtlas(iconName, 42); if (textureOffsetX ~= nil) then node.Icon:SetTexture( textureOffsetX, textureOffsetY, textureSheet ); end end if artInfo.IsButton then node.OtherStates:SetHide( true ); node.NodeButton:SetTextureOffsetVal( artInfo.BGU, artInfo.BGV ); else node.OtherStates:SetHide( false ); node.OtherStates:SetTextureOffsetVal( artInfo.BGU, artInfo.BGV ); end if artInfo.FillTexture ~= nil then node.FillTexture:SetHide( false ); node.FillTexture:SetTexture( artInfo.FillTexture ); else node.FillTexture:SetHide( true ); end if artInfo.BoltOn then node.Bolt:SetTexture(PIC_BOLT_ON); else node.Bolt:SetTexture(PIC_BOLT_OFF); end node.NodeButton:SetToolTipString(ToolTipHelper.GetToolTip(item.Type, Game.GetLocalPlayer())); node.IconBacking:SetTexture(artInfo.IconBacking); -- Darken items not making it past filter. local currentFilter:table = playerTechData[DATA_FIELD_UIOPTIONS].filter; if currentFilter == nil or currentFilter.Func == nil or currentFilter.Func( item.Type ) then node.FilteredOut:SetHide( true ); else node.FilteredOut:SetHide( false ); end end -- Fill in where the markers (representing players) are at: m_kMarkerIM:ResetInstances(); local PADDING :number = 24; local thisPlayerID :number = Game.GetLocalPlayer(); local markers :table = m_kCurrentData[DATA_FIELD_PLAYERINFO].Markers; for _,markerStat in ipairs( markers ) do -- Only build a marker if a player has started researching... if markerStat.HighestColumn ~= -1 then local instance :table = m_kMarkerIM:GetInstance(); if markerStat.IsPlayerHere then -- Representing the player viewing the tree instance.Portrait:SetHide( true ); instance.TurnGrid:SetHide( false ); instance.TurnLabel:SetText( Locale.Lookup("LOC_TECH_TREE_TURN_NUM" )); --instance.TurnNumber:SetText( tostring(Game.GetCurrentGameTurn()) ); local turn = Game.GetCurrentGameTurn(); instance.TurnNumber:SetText(tostring(turn)); local turnLabelWidth = PADDING + instance.TurnLabel:GetSizeX() + instance.TurnNumber:GetSizeX(); instance.TurnGrid:SetSizeX( turnLabelWidth ); instance.Marker:SetTexture( PIC_MARKER_PLAYER ); instance.Marker:SetSizeVal( SIZE_MARKER_PLAYER_X, SIZE_MARKER_PLAYER_Y ); else -- An other player instance.TurnGrid:SetHide( true ); instance.Marker:SetTexture( PIC_MARKER_OTHER ); instance.Marker:SetSizeVal( SIZE_MARKER_OTHER_X, SIZE_MARKER_OTHER_Y ); end -- Different content in marker based on if there is just 1 player in the column, or more than 1 local tooltipString :string = Locale.Lookup("LOC_TREE_ERA", Locale.Lookup(GameInfo.Eras[markerStat.HighestEra].Name) ).."[NEWLINE]"; local numOfPlayersAtThisColumn :number = table.count(markerStat.PlayerNums); if numOfPlayersAtThisColumn < 2 then instance.Num:SetHide( true ); local playerNum :number = markerStat.PlayerNums[1]; local pPlayerConfig :table = PlayerConfigurations[playerNum]; tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetPlayerName()); -- ??TRON: Temporary using player name until leaderame is fixed if not markerStat.IsPlayerHere then local iconName:string = "ICON_"..pPlayerConfig:GetLeaderTypeName(); local textureOffsetX:number, textureOffsetY:number, textureSheet:string = IconManager:FindIconAtlas(iconName); instance.Portrait:SetHide( false ); instance.Portrait:SetTexture( textureOffsetX, textureOffsetY, textureSheet ); end else instance.Portrait:SetHide( true ); instance.Num:SetHide( false ); instance.Num:SetText(tostring(numOfPlayersAtThisColumn)); for i,playerNum in ipairs(markerStat.PlayerNums) do local pPlayerConfig :table = PlayerConfigurations[playerNum]; --[[ ??TRON debug: The human player, player 0, has whack values! No leader name coming from engine! local name = pPlayerConfig:GetPlayerName(); local nick = pPlayerConfig:GetNickName(); local leader = pPlayerConfig:GetLeaderName(); local civ = pPlayerConfig:GetCivilizationTypeName(); local isHuman = pPlayerConfig:IsHuman(); print("debug info:",name,nick,leader,civ,isHuman); ]] --tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetLeaderName()); tooltipString = tooltipString.. Locale.Lookup(pPlayerConfig:GetPlayerName()); -- ??TRON: Temporary using player name until leaderame is fixed if i < numOfPlayersAtThisColumn then tooltipString = tooltipString.."[NEWLINE]"; end end end instance.Marker:SetToolTipString( tooltipString ); local MARKER_OFFSET_START:number = 20; local markerPercent :number = math.clamp( markerStat.HighestColumn / m_maxColumns, 0, 1 ); local markerX :number = MARKER_OFFSET_START + (markerPercent * m_scrollWidth ); instance.Top:SetOffsetVal(markerX ,0); end end RealizePathMarkers(); RealizeFilterPulldown(); RealizeKeyPanel(); RealizeTutorialNodes(); end -- =========================================================================== -- Load all the 'live' data for a player. -- =========================================================================== function GetLivePlayerData( ePlayer:number, eCompletedTech:number ) -- If first time, initialize player data tables. local data :table = m_kAllPlayersTechData[ePlayer]; if data == nil then -- Initialize player's top level tables: data = {}; data[DATA_FIELD_LIVEDATA] = {}; data[DATA_FIELD_PLAYERINFO] = {}; data[DATA_FIELD_UIOPTIONS] = {}; -- Initialize data, and sub tables within the top tables. data[DATA_FIELD_PLAYERINFO].Player = ePlayer; -- Number of this player data[DATA_FIELD_PLAYERINFO].Markers = {}; -- Hold a condenced, UI-ready version of stats data[DATA_FIELD_PLAYERINFO].Stats = {}; -- Hold stats on where each player is (based on what this player can see) end local kPlayer :table = Players[ePlayer]; local playerTechs :table = kPlayer:GetTechs(); local currentTechID :number = playerTechs:GetResearchingTech(); -- DEBUG: Output header to console. if m_debugOutputTechInfo then print(" Item Id Status Progress $ Era Prereqs"); print("------------------------------ --- ---------- --------- --- ---------------- --------------------------"); end -- Loop through all items and place in appropriate buckets as well -- read in the associated information for it. for type,item in pairs(m_kItemDefaults) do local status :number = ITEM_STATUS.BLOCKED; local turnsLeft :number = playerTechs:GetTurnsToResearch(item.Index); if playerTechs:HasTech(item.Index) or item.Index == eCompletedTech then status = ITEM_STATUS.RESEARCHED; turnsLeft = 0; elseif item.Index == currentTechID then status = ITEM_STATUS.CURRENT; turnsLeft = playerTechs:GetTurnsLeft(); elseif playerTechs:CanResearch(item.Index) then status = ITEM_STATUS.READY; end data[DATA_FIELD_LIVEDATA][type] = { Cost = playerTechs:GetResearchCost(item.Index), IsBoosted = playerTechs:HasBoostBeenTriggered(item.Index), Progress = playerTechs:GetResearchProgress(item.Index), Status = status, Turns = turnsLeft } -- DEBUG: Output to console detailed information about the tech. if m_debugOutputTechInfo then local this:table = data[DATA_FIELD_LIVEDATA][type]; print( string.format("%30s %-3d %-10s %4d/%-4d %3d %-16s %s", type,item.Index, STATUS_ART[status].Name, this.Progress, this.Cost, this.Turns, item.EraType, GetPrereqsString(item.Prereqs) )); end end local players = Game.GetPlayers{Major = true}; -- Determine where all players are. local playerVisibility = PlayersVisibility[ePlayer]; if playerVisibility ~= nil then for i, otherPlayer in ipairs(players) do local playerID :number = otherPlayer:GetID(); local playerTech :table = players[i]:GetTechs(); local currentTech :number = playerTech:GetResearchingTech(); data[DATA_FIELD_PLAYERINFO].Stats[playerID] = { CurrentID = currentTech, -- tech currently being researched HasMet = kPlayer:GetDiplomacy():HasMet(playerID) or playerID==ePlayer or m_debugShowAllMarkers; HighestColumn = -1, -- where they are in the timeline HighestEra = "" }; -- The latest tech a player may be researching may not be the one -- furthest along in time; so go through ALL the techs and track -- the highest column of all researched tech. local highestColumn :number = -1; local highestEra :string = ""; for _,item in pairs(m_kItemDefaults) do if playerTech:HasTech(item.Index) then local column:number = item.Column + m_kEras[item.EraType].PriorColumns; if column > highestColumn then highestColumn = column; highestEra = item.EraType; end end end data[DATA_FIELD_PLAYERINFO].Stats[playerID].HighestColumn = highestColumn; data[DATA_FIELD_PLAYERINFO].Stats[playerID].HighestEra = highestEra; end end -- All player data is added.. build markers data based on player data. local checkedID:table = {}; data[DATA_FIELD_PLAYERINFO].Markers = {}; for playerID:number, targetPlayer:table in pairs(data[DATA_FIELD_PLAYERINFO].Stats) do -- Only look for IDs that haven't already been merged into a marker. if checkedID[playerID] == nil and targetPlayer.HasMet then checkedID[playerID] = true; local markerData:table = {}; if data[DATA_FIELD_PLAYERINFO].Markers[playerID] ~= nil then markerData = data[DATA_FIELD_PLAYERINFO].Markers[playerID]; markerData.HighestColumn = targetPlayer.HighestColumn; markerData.HighestEra = targetPlayer.HighestEra; markerData.IsPlayerHere = (playerID == ePlayer); else markerData = { HighestColumn = targetPlayer.HighestColumn, -- Which column this marker should be placed HighestEra = targetPlayer.HighestEra, IsPlayerHere = (playerID == ePlayer), PlayerNums = {playerID}} -- All players who share this marker spot table.insert( data[DATA_FIELD_PLAYERINFO].Markers, markerData ); end -- SPECIAL CASE: Current player starts at column 0 so it's immediately visible on timeline: if playerID == ePlayer and markerData.HighestColumn == -1 then markerData.HighestColumn = 0; local firstEra:table = nil; for _,era in pairs(m_kEras) do if firstEra == nil or era.Index < firstEra.Index then firstEra = era; end end markerData.HighestEra = firstEra.Index; end -- Traverse all the IDs and merge them with this one. for anotherID:number, anotherPlayer:table in pairs(data[DATA_FIELD_PLAYERINFO].Stats) do -- Don't add if: it's ourself, if hasn't researched at least 1 tech, if we haven't met if playerID ~= anotherID and anotherPlayer.HighestColumn > -1 and anotherPlayer.HasMet then if markerData.HighestColumn == data[DATA_FIELD_PLAYERINFO].Stats[anotherID].HighestColumn then checkedID[anotherID] = true; -- Need to do this check if player's ID didn't show up first in the list in creating the marker. if anotherID == ePlayer then markerData.IsPlayerHere = true; end local foundAnotherID:boolean = false; for _, playernumsID in pairs(markerData.PlayerNums) do if not foundAnotherID and playernumsID == anotherID then foundAnotherID = true; end end if not foundAnotherID then table.insert( markerData.PlayerNums, anotherID ); end end end end end end return data; end -- =========================================================================== function OnLocalPlayerTurnBegin() local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then --local kPlayer :table = Players[ePlayer]; if m_ePlayer ~= ePlayer then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( ePlayer ); end -------------------------------------------------------------------------- -- CQUI Check for Tech Progress -- Get the current tech local kPlayer :table = Players[ePlayer]; local playerTechs :table = kPlayer:GetTechs(); local currentTechID :number = playerTechs:GetResearchingTech(); local isCurrentBoosted :boolean = playerTechs:HasBoostBeenTriggered(currentTechID); -- Make sure there is a technology selected before continuing with checks if currentTechID ~= -1 then local techName = GameInfo.Technologies[currentTechID].Name; local techType = GameInfo.Technologies[currentTechID].Type; local currentCost = playerTechs:GetResearchCost(currentTechID); local currentProgress = playerTechs:GetResearchProgress(currentTechID); local currentYield = playerTechs:GetScienceYield(); local percentageToBeDone = (currentProgress + currentYield) / currentCost; local percentageNextTurn = (currentProgress + currentYield*2) / currentCost; local CQUI_halfway:number = 0.5; -- Finds boost amount, always 50 in base game, China's +10% modifier is not applied here for row in GameInfo.Boosts() do if(row.ResearchType == techType) then CQUI_halfway = (100 - row.Boost) / 100; break; end end --If playing as china, apply boost modifier. Not sure where I can query this value... if(PlayerConfigurations[Game.GetLocalPlayer()]:GetCivilizationTypeName() == "CIVILIZATION_CHINA") then CQUI_halfway = CQUI_halfway - .1; end -- Is it greater than 50% and has yet to be displayed? if isCurrentBoosted then CQUI_halfwayNotified[techName] = true; elseif percentageNextTurn >= CQUI_halfway and isCurrentBoosted == false and CQUI_halfwayNotified[techName] ~= true then LuaEvents.CQUI_AddStatusMessage(Locale.Lookup("LOC_CQUI_TECH_MESSAGE_S") .. " " .. Locale.Lookup( techName ) .. " " .. Locale.Lookup("LOC_CQUI_HALF_MESSAGE_E"), 10, CQUI_STATUS_MESSAGE_TECHS); CQUI_halfwayNotified[techName] = true; end end -- end of techID check -------------------------------------------------------------------------- end -- end of playerID check end -- =========================================================================== -- EVENT -- Player turn is ending -- =========================================================================== function OnLocalPlayerTurnEnd() -- If current data set is for the player, save back any changes into -- the table of player tables. local ePlayer :number = Game.GetLocalPlayer(); if ePlayer ~= -1 then if m_kCurrentData[DATA_FIELD_PLAYERINFO].Player == ePlayer then m_kAllPlayersTechData[ePlayer] = m_kCurrentData; end end if(GameConfiguration.IsHotseat()) then Close(); end end -- =========================================================================== function OnResearchChanged( ePlayer:number, eTech:number ) if ePlayer == Game.GetLocalPlayer() then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( m_ePlayer, -1 ); if not ContextPtr:IsHidden() then View( m_kCurrentData ); end end end -- =========================================================================== function OnResearchComplete( ePlayer:number, eTech:number) if ePlayer == Game.GetLocalPlayer() then m_ePlayer = ePlayer; m_kCurrentData = GetLivePlayerData( m_ePlayer, eTech ); if not ContextPtr:IsHidden() then View( m_kCurrentData ); end -------------------------------------------------------------------------- -- CQUI Completion Notification -- Get the current tech local kPlayer :table = Players[ePlayer]; local currentTechID :number = eTech; -- Make sure there is a technology selected before continuing with checks if currentTechID ~= -1 then local techName = GameInfo.Technologies[currentTechID].Name; LuaEvents.CQUI_AddStatusMessage(Locale.Lookup("LOC_TECH_BOOST_COMPLETE", techName), 10, CQUI_STATUS_MESSAGE_TECHS); end -- end of techID check -------------------------------------------------------------------------- end end -- =========================================================================== -- Initially size static UI elements -- (or re-size if screen resolution changed) -- =========================================================================== function Resize() m_width, m_height = UIManager:GetScreenSizeVal(); -- Cache screen dimensions m_scrollWidth = m_width - 80; -- Scrollbar area (where markers are placed) slightly smaller than screen width -- Determine how far art will span. -- First obtain the size of the tree by taking the visible size and multiplying it by the ratio of the full content local scrollPanelX:number = (Controls.NodeScroller:GetSizeX() / Controls.NodeScroller:GetRatio()); local artAndEraScrollWidth:number = scrollPanelX * (1/PARALLAX_SPEED); Controls.ArtParchmentDecoTop:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentDecoBottom:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentRippleTop:SetSizeX( artAndEraScrollWidth ); Controls.ArtParchmentRippleBottom:SetSizeX( artAndEraScrollWidth ); Controls.ForceSizeX:SetSizeX( artAndEraScrollWidth ); Controls.ArtScroller:CalculateSize(); Controls.ArtCornerGrungeTR:ReprocessAnchoring(); Controls.ArtCornerGrungeBR:ReprocessAnchoring(); local PADDING_DUE_TO_LAST_BACKGROUND_ART_IMAGE:number = 100; local backArtScrollWidth:number = scrollPanelX * (1/PARALLAX_ART_SPEED); Controls.Background:SetSizeX( backArtScrollWidth + PADDING_DUE_TO_LAST_BACKGROUND_ART_IMAGE ); Controls.Background:SetSizeY( SIZE_WIDESCREEN_HEIGHT - (SIZE_TIMELINE_AREA_Y-8) ); Controls.FarBackArtScroller:CalculateSize(); end -- =========================================================================== function OnUpdateUI( type:number, tag:string, iData1:number, iData2:number, strData1:string) if type == SystemUpdateUI.ScreenResize then Resize(); end end -- =========================================================================== -- Obtain the data from the DB that doesn't change -- Base costs and relationships (prerequisites) -- RETURN: A table of node data (techs/civics/etc...) with a prereq for each entry. -- =========================================================================== function PopulateItemData( tableName:string, tableColumn:string, prereqTableName:string, itemColumn:string, prereqColumn:string) -- Build main item table. m_kItemDefaults = {}; local index :number = 0; function GetHash(t) local r = GameInfo.Types[t]; if(r) then return r.Hash; else return 0; end end for row:table in GameInfo[tableName]() do local entry:table = {}; entry.Type = row[tableColumn]; entry.Name = row.Name; entry.BoostText = ""; entry.Column = -1; entry.Cost = row.Cost; entry.Description = row.Description and Locale.Lookup( row.Description ); entry.EraType = row.EraType; entry.Hash = GetHash(entry.Type); --entry.Icon = row.Icon; entry.Index = index; entry.IsBoostable = false; entry.Prereqs = {}; entry.UITreeRow = row.UITreeRow; entry.Unlocks = {}; -- Each unlock has: unlockType, iconUnavail, iconAvail, tooltip -- Boost? for boostRow in GameInfo.Boosts() do if boostRow.TechnologyType == entry.Type then entry.BoostText = Locale.Lookup( boostRow.TriggerDescription ); entry.IsBoostable = true; entry.BoostAmount = boostRow.Boost; break; end end for prereqRow in GameInfo[prereqTableName]() do if prereqRow[itemColumn] == entry.Type then table.insert( entry.Prereqs, prereqRow[prereqColumn] ); end end -- If no prereqs were found, set item to special tree start value if table.count(entry.Prereqs) == 0 then table.insert(entry.Prereqs, PREREQ_ID_TREE_START); end -- Warn if DB has an out of bounds entry. if entry.UITreeRow < ROW_MIN or entry.UITreeRow > ROW_MAX then UI.DataError("UITreeRow for '"..entry.Type.."' has an out of bound UITreeRow="..tostring(entry.UITreeRow).." MIN="..tostring(ROW_MIN).." MAX="..tostring(ROW_MAX)); end -- Only build up a limited number of eras if debug information is forcing a subset. if m_debugFilterEraMaxIndex < 1 or m_debugFilterEraMaxIndex ~= -1 then m_kItemDefaults[entry.Type] = entry; index = index + 1; end if m_kEraCounter[entry.EraType] == nil then m_kEraCounter[entry.EraType] = 0; end m_kEraCounter[entry.EraType] = m_kEraCounter[entry.EraType] + 1; end end -- =========================================================================== -- Create a hash table of EraType to its chronological index. -- =========================================================================== function PopulateEraData() m_kEras = {}; for row:table in GameInfo.Eras() do if m_kEraCounter[row.EraType] and m_kEraCounter[row.EraType] > 0 and m_debugFilterEraMaxIndex < 1 or row.ChronologyIndex <= m_debugFilterEraMaxIndex then m_kEras[row.EraType] = { BGTexture = row.EraTechBackgroundTexture, NumColumns = 0, Description = Locale.Lookup(row.Name), Index = row.ChronologyIndex, PriorColumns= -1, Columns = {} -- column data } end end end -- =========================================================================== -- -- =========================================================================== function PopulateFilterData() -- Hard coded/special filters: -- Load entried into filter table from TechFilters XML data --[[ TODO: Only add filters based on what is in the game database. ??TRON for row in GameInfo.TechFilters() do table.insert( m_kFilters, { row.IconString, row.Description, g_TechFilters[row.Type] }); end ]] m_kFilters = {}; table.insert( m_kFilters, { Func=nil, Description="LOC_TECH_FILTER_NONE", Icon=nil } ); --table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_RECOMMENDED"], Description="LOC_TECH_FILTER_RECOMMENDED", Icon="[ICON_Recommended]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_FOOD"], Description="LOC_TECH_FILTER_FOOD", Icon="[ICON_Food]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_SCIENCE"], Description="LOC_TECH_FILTER_SCIENCE", Icon="[ICON_Science]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_PRODUCTION"], Description="LOC_TECH_FILTER_PRODUCTION", Icon="[ICON_Production]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_CULTURE"], Description="LOC_TECH_FILTER_CULTURE", Icon="[ICON_Culture]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_GOLD"], Description="LOC_TECH_FILTER_GOLD", Icon="[ICON_Gold]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_FAITH"], Description="LOC_TECH_FILTER_FAITH", Icon="[ICON_Faith]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_HOUSING"], Description="LOC_TECH_FILTER_HOUSING", Icon="[ICON_Housing]" }); --table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_AMENITIES"], Description="LOC_TECH_FILTER_AMENITIES", Icon="[ICON_Amenities]" }); --table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_HEALTH"], Description="LOC_TECH_FILTER_HEALTH", Icon="[ICON_Health]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_UNITS"], Description="LOC_TECH_FILTER_UNITS", Icon="[ICON_Units]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_IMPROVEMENTS"], Description="LOC_TECH_FILTER_IMPROVEMENTS", Icon="[ICON_Improvements]" }); table.insert( m_kFilters, { Func=g_TechFilters["TECHFILTER_WONDERS"], Description="LOC_TECH_FILTER_WONDERS", Icon="[ICON_Wonders]" }); for i,filter in ipairs(m_kFilters) do local filterLabel = Locale.Lookup( filter.Description ); local filterIconText = filter.Icon; local controlTable = {}; Controls.FilterPulldown:BuildEntry( "FilterItemInstance", controlTable ); -- If a text icon exists, use it and bump the label in the button over. --[[ TODO: Uncomment if icons are added. if filterIconText ~= nil and filterIconText ~= "" then controlTable.IconText:SetText( Locale.Lookup(filterIconText) ); controlTable.DescriptionText:SetOffsetX(24); else controlTable.IconText:SetText( "" ); controlTable.DescriptionText:SetOffsetX(4); end ]] controlTable.DescriptionText:SetOffsetX(8); controlTable.DescriptionText:SetText( filterLabel ); -- Callback controlTable.Button:RegisterCallback( Mouse.eLClick, function() OnFilterClicked(filter); end ); end Controls.FilterPulldown:CalculateInternals(); end -- =========================================================================== -- Populate Full Text Search -- =========================================================================== function PopulateSearchData() -- Populate Full Text Search local searchContext = "Technologies"; if(Search.CreateContext(searchContext, "[COLOR_LIGHTBLUE]", "[ENDCOLOR]", "...")) then for row in GameInfo.Technologies() do local description = row.Description and Locale.Lookup(row.Description) or ""; Search.AddData(searchContext, row.TechnologyType, Locale.Lookup(row.Name), description); end for row in GameInfo.Improvements() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup(GameInfo.Technologies[row.PrereqTech].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Units() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup(GameInfo.Technologies[row.PrereqTech].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Buildings() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup(GameInfo.Technologies[row.PrereqTech].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Districts() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup(GameInfo.Technologies[row.PrereqTech].Name), Locale.Lookup(row.Name)); end end for row in GameInfo.Resources() do if(row.PrereqTech) then Search.AddData(searchContext, row.PrereqTech, Locale.Lookup(GameInfo.Technologies[row.PrereqTech].Name), Locale.Lookup(row.Name)); end end Search.Optimize(searchContext); end end -- =========================================================================== -- Update the Filter text with the current label. -- =========================================================================== function RealizeFilterPulldown() local pullDownButton = Controls.FilterPulldown:GetButton(); if m_kCurrentData[DATA_FIELD_UIOPTIONS].filter == nil or m_kCurrentData[DATA_FIELD_UIOPTIONS].filter.Func== nil then pullDownButton:SetText( " "..Locale.Lookup("LOC_TREE_FILTER_W_DOTS")); else local description:string = m_kCurrentData[DATA_FIELD_UIOPTIONS].filter.Description; pullDownButton:SetText( " "..Locale.Lookup( description )); end end -- =========================================================================== -- filterLabel, Readable lable of the current filter. -- filterFunc, The funciton filter to apply to each node as it's built, -- nil will reset the filters to none. -- =========================================================================== function OnFilterClicked( filter ) m_kCurrentData[DATA_FIELD_UIOPTIONS].filter = filter; View( m_kCurrentData ) end -- =========================================================================== function OnOpen() if (Game.GetLocalPlayer() == -1) then return end UI.PlaySound("UI_Screen_Open"); View( m_kCurrentData ); ContextPtr:SetHide(false); -- From ModalScreen_PlayerYieldsHelper RefreshYields(); -- From Civ6_styles: FullScreenVignetteConsumer Controls.ScreenAnimIn:SetToBeginning(); Controls.ScreenAnimIn:Play(); LuaEvents.TechTree_OpenTechTree(); Controls.SearchEditBox:TakeFocus(); end -- =========================================================================== -- Show the Key panel based on the state -- =========================================================================== function RealizeKeyPanel() if UserConfiguration.GetShowTechTreeKey() then Controls.KeyPanel:SetHide( false ); UI.PlaySound("UI_TechTree_Filter_Open"); else if(not ContextPtr:IsHidden()) then UI.PlaySound("UI_TechTree_Filter_Closed"); Controls.KeyPanel:SetHide( true ); end end if Controls.KeyPanel:IsHidden() then Controls.ToggleKeyButton:SetText(Locale.Lookup("LOC_TREE_SHOW_KEY")); Controls.ToggleKeyButton:SetSelected(false); else Controls.ToggleKeyButton:SetText(Locale.Lookup("LOC_TREE_HIDE_KEY")); Controls.ToggleKeyButton:SetSelected(true); end end -- =========================================================================== -- Reparents all tutorial controls, guarantee they will be on top of the -- nodes and lines dynamically added. -- =========================================================================== function RealizeTutorialNodes() Controls.CompletedTechNodePointer:Reparent(); Controls.IncompleteTechNodePointer:Reparent(); Controls.UnavailableTechNodePointer:Reparent(); Controls.ChooseWritingPointer:Reparent(); Controls.ActiveTechNodePointer:Reparent(); Controls.TechUnlocksPointer:Reparent(); end -- =========================================================================== -- Show/Hide key panel -- =========================================================================== function OnClickToggleKey() if Controls.KeyPanel:IsHidden() then UserConfiguration.SetShowTechTreeKey(true); else UserConfiguration.SetShowTechTreeKey(false); end RealizeKeyPanel(); end -- =========================================================================== function OnClickFiltersPulldown() if Controls.FilterPulldown:IsOpen() then UI.PlaySound("UI_TechTree_Filter_Open"); else UI.PlaySound("UI_TechTree_Filter_Closed"); end end -- =========================================================================== -- Main close function all exit points should call. -- =========================================================================== function Close() UI.PlaySound("UI_Screen_Close"); ContextPtr:SetHide(true); LuaEvents.TechTree_CloseTechTree(); Controls.SearchResultsPanelContainer:SetHide(true); end -- =========================================================================== -- Close via click -- =========================================================================== function OnClose() Close(); end -- =========================================================================== -- Input -- UI Event Handler -- =========================================================================== function KeyDownHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = true; -- let it fall through end return false; end function KeyUpHandler( key:number ) if key == Keys.VK_SHIFT then m_shiftDown = false; -- let it fall through end if key == Keys.VK_ESCAPE then Close(); return true; end if key == Keys.VK_RETURN then -- Don't let enter propigate or it will hit action panel which will raise a screen (potentially this one again) tied to the action. return true; end return false; end function OnInputHandler( pInputStruct:table ) local uiMsg = pInputStruct:GetMessageType(); if uiMsg == KeyEvents.KeyDown then return KeyDownHandler( pInputStruct:GetKey() ); end if uiMsg == KeyEvents.KeyUp then return KeyUpHandler( pInputStruct:GetKey() ); end return false; end -- =========================================================================== -- UI Event Handler -- =========================================================================== function OnShutdown() -- Clean up events LuaEvents.LaunchBar_CloseTechTree.Remove( OnClose ); LuaEvents.LaunchBar_RaiseTechTree.Remove( OnOpen ); LuaEvents.ResearchChooser_RaiseTechTree.Remove( OnOpen ); LuaEvents.Tutorial_TechTreeScrollToNode.Remove( OnTutorialScrollToNode ); Events.LocalPlayerTurnBegin.Remove( OnLocalPlayerTurnBegin ); Events.LocalPlayerTurnEnd.Remove( OnLocalPlayerTurnEnd ); Events.ResearchChanged.Remove( OnResearchChanged ); Events.ResearchQueueChanged.Remove( OnResearchChanged ); Events.ResearchCompleted.Remove( OnResearchComplete ); Events.SystemUpdateUI.Remove( OnUpdateUI ); Search.DestroyContext("Technologies"); end function OnSearchBarGainFocus() Controls.SearchEditBox:ClearString(); Controls.SearchResultsPanelContainer:SetHide(true); end function OnSearchBarLoseFocus() Controls.SearchEditBox:SetText(Locale.Lookup("LOC_TREE_SEARCH_W_DOTS")); end -- =========================================================================== -- Centers scroll panel (if possible) on a specfic type. -- =========================================================================== function ScrollToNode( typeName:string ) local percent:number = 0; local x = m_uiNodes[typeName].x - ( m_width * 0.5); local size = (m_width / Controls.NodeScroller:GetRatio()) - m_width; percent = math.clamp( x / size, 0, 1); Controls.NodeScroller:SetScrollValue(percent); m_kSearchResultIM:DestroyInstances(); Controls.SearchResultsPanelContainer:SetHide(true); end -- =========================================================================== -- LuaEvent -- =========================================================================== function OnTutorialScrollToNode( typeName:string ) ScrollToNode( typeName ); end -- =========================================================================== -- Input Hotkey Event -- =========================================================================== function OnInputActionTriggered( actionId ) if actionId == m_ToggleTechTreeId then UI.PlaySound("Play_UI_Click"); if(ContextPtr:IsHidden()) then LuaEvents.LaunchBar_RaiseTechTree(); else OnClose(); end end end function OnSearchCharCallback() local str = Controls.SearchEditBox:GetText(); local has_found = {}; if str ~= nil and str ~= Locale.Lookup("LOC_TREE_SEARCH_W_DOTS") then local results = Search.Search("Technologies", str); m_kSearchResultIM:DestroyInstances(); if (results and #results > 0) then for i, v in ipairs(results) do if has_found[v[1]] == nil then -- v[1]chnologyType -- v[2] == Name of Technology w/ search term highlighted. -- v[3] == Snippet of Technology description w/ search term highlighted. local instance = m_kSearchResultIM:GetInstance(); local techType:number; for row in GameInfo.Technologies() do if row.TechnologyType == v[1] then techType = row.Index; end end -- Going to take this out right now... we may decide we want this back. --if instance["unlockIM"] ~= nil then -- instance["unlockIM"]:DestroyInstances() --end --instance["unlockIM"] = InstanceManager:new( "UnlockInstance", "UnlockIcon", instance.SearchUnlockStack ); --PopulateUnlockablesForTech(Players[Game.GetLocalPlayer()]:GetID(), techType, instance["unlockIM"], function() ScrollToNode(v[1]); end); -- Search results already localized. local techName:string = v[2]; instance.Name:SetText(Locale.ToUpper(techName)); local iconName :string = DATA_ICON_PREFIX .. v[1]; instance.SearchIcon:SetIcon(iconName); instance.Button:RegisterCallback(Mouse.eLClick, function() ScrollToNode(v[1]); end ); instance.Button:SetToolTipString(ToolTipHelper.GetToolTip(v[1], Game.GetLocalPlayer())); has_found[v[1]] = true; end end Controls.SearchResultsStack:CalculateSize(); Controls.SearchResultsStack:ReprocessAnchoring(); Controls.SearchResultsPanel:CalculateSize(); Controls.SearchResultsPanelContainer:SetHide(false); else Controls.SearchResultsPanelContainer:SetHide(true); end end end -- =========================================================================== -- Load all static information as well as display information for the -- current local player. -- =========================================================================== function Initialize() --profile.runtime("start"); PopulateItemData("Technologies","TechnologyType","TechnologyPrereqs","Technology","PrereqTech"); PopulateEraData(); PopulateFilterData(); PopulateSearchData(); AllocateUI(); -- May be observation mode. m_ePlayer = Game.GetLocalPlayer(); if (m_ePlayer == -1) then return; end Resize(); m_kCurrentData = GetLivePlayerData( m_ePlayer ); View( m_kCurrentData ); -- UI Events ContextPtr:SetInputHandler( OnInputHandler, true ); ContextPtr:SetShutdown( OnShutdown ); Controls.FilterPulldown:GetButton():RegisterCallback( Mouse.eLClick, OnClickFiltersPulldown ); Controls.FilterPulldown:RegisterSelectionCallback( OnClickFiltersPulldown ); Controls.SearchEditBox:RegisterStringChangedCallback(OnSearchCharCallback); Controls.SearchEditBox:RegisterHasFocusCallback( OnSearchBarGainFocus); Controls.SearchEditBox:RegisterCommitCallback( OnSearchBarLoseFocus); Controls.ToggleKeyButton:RegisterCallback(Mouse.eLClick, OnClickToggleKey); -- LUA Events LuaEvents.LaunchBar_CloseTechTree.Add( OnClose ); LuaEvents.LaunchBar_RaiseTechTree.Add( OnOpen ); LuaEvents.ResearchChooser_RaiseTechTree.Add( OnOpen ); LuaEvents.Tutorial_TechTreeScrollToNode.Add( OnTutorialScrollToNode ); -- Game engine Event Events.LocalPlayerTurnBegin.Add( OnLocalPlayerTurnBegin ); Events.LocalPlayerTurnEnd.Add( OnLocalPlayerTurnEnd ); Events.LocalPlayerChanged.Add(AllocateUI); Events.ResearchChanged.Add( OnResearchChanged ); Events.ResearchQueueChanged.Add( OnResearchChanged ); Events.ResearchCompleted.Add( OnResearchComplete ); Events.SystemUpdateUI.Add( OnUpdateUI ); -- Hot Key Handling m_ToggleTechTreeId = Input.GetActionId("ToggleTechTree"); if m_ToggleTechTreeId ~= nil then Events.InputActionTriggered.Add( OnInputActionTriggered ); end -- Key Label Truncation to Tooltip TruncateStringWithTooltip(Controls.AvailableLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.AvailableLabelKey:GetText()); TruncateStringWithTooltip(Controls.UnavailableLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.UnavailableLabelKey:GetText()); TruncateStringWithTooltip(Controls.ResearchingLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.ResearchingLabelKey:GetText()); TruncateStringWithTooltip(Controls.CompletedLabelKey, MAX_BEFORE_TRUNC_KEY_LABEL, Controls.CompletedLabelKey:GetText()); -- CQUI add exceptions to the 50% notifications by putting techs into the CQUI_halfwayNotified table CQUI_halfwayNotified["LOC_TECH_POTTERY_NAME"] = true; CQUI_halfwayNotified["LOC_TECH_MINING_NAME"] = true; CQUI_halfwayNotified["LOC_TECH_ANIMAL_HUSBANDRY_NAME"] = true; end Initialize();
mit
aedansilver/wowlikearcemuold
src/scripts/lua/Lua/Stable Scripts/Outland/Sethekk Halls/BOSS_SethekkHalls_Syth.lua
30
2322
function Syth_HealthCheckA(Unit) if Unit:GetHealthPct() < 75 and Didthat == 0 then Unit:SpawnCreature(19204, -143.9, 162.9, 0, 0, 18, 36000000); Unit:SpawnCreature(19204, -136.8, 174.3, 0, 0, 18, 36000000); Unit:SpawnCreature(19204, -142.6, 183.7, 0, 0, 18, 36000000); Didthat = 1 else end end function Syth_HealthCheckB(Unit) if Unit:GetHealthPct() < 50 and Didthat == 1 then Unit:SpawnCreature(19204, -143.9, 162.9, 0, 0, 18, 36000000); Unit:SpawnCreature(19204, -136.8, 174.3, 0, 0, 18, 36000000); Unit:SpawnCreature(19204, -142.6, 183.7, 0, 0, 18, 36000000); Didthat = 2 else end end function Syth_HealthCheckC(Unit) if Unit:GetHealthPct() < 25 and Didthat == 2 then Unit:SpawnCreature(19204, -143.9, 162.9, 0, 0, 18, 36000000); Unit:SpawnCreature(19204, -136.8, 174.3, 0, 0, 18, 36000000); Unit:SpawnCreature(19204, -142.6, 183.7, 0, 0, 18, 36000000); Didthat = 3 else end end function Syth_Frost(Unit, event, miscunit, misc) print "Syth Frost" Unit:FullCastSpellOnTarget(37865,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Do you some ice cream...") end function Syth_Flame(Unit, event, miscunit, misc) print "Syth_Flame" Unit:FullCastSpellOnTarget(34354,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "Let's do a campfire with your bones...") end function Syth_Shadow(Unit, event, miscunit, misc) print "Syth Shadow" Unit:FullCastSpellOnTarget(30138,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "The shadow surround you...") end function Syth_Arcane(Unit, event, miscunit, misc) print "Syth Arcane" Unit:FullCastSpellOnTarget(37132,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "I like arcane...") end function Syth_Chain(Unit, event, miscunit, misc) print "Syth Chain" Unit:FullCastSpellOnTarget(39945,Unit:GetClosestPlayer()) Unit:SendChatMessage(11, 0, "You are weak...") end function Syth(unit, event, miscunit, misc) print "Syth" unit:RegisterEvent("Syth_HealthCheckA",1000,1) unit:RegisterEvent("Syth_HealthCheckB",1000,1) unit:RegisterEvent("Syth_HealthCheckC",1000,1) unit:RegisterEvent("Syth_Frost",10000,0) unit:RegisterEvent("Syth_Flame",15000,0) unit:RegisterEvent("Syth_Shadow",21000,0) unit:RegisterEvent("Syth_Arcane",26000,0) unit:RegisterEvent("Syth_Chain",29000,0) end RegisterUnitEvent(18472,1,"Syth")
agpl-3.0
DipColor/joon12
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
LoPhatKao/EggstraClucks
monsters/ground/feedstate.lua
2
5188
------------------------------------------------- feedState = {} ------------------------------------------------- function feedState.enter() if hasTarget() then return nil end if creature ~= nil and creature.isTamed() and self.feedCooldown ~= nil then local delta = os.time() - self.feedCooldown local cooldown = entity.configParameter("tamedParameters.feedCooldown", 10) if delta > cooldown and creature.getHunger() < creature.maxHunger then return feedState.enterWith({feed = true}) end end return nil,entity.configParameter("tamedParameters.cooldown", 10) end function feedState.enterWith(params) if params.feed then local position = entity.position() local feed = feedState.findSeed(position) if feed ~= nil then return { targetId = feed.targetId, targetPosition = feed.targetPosition, timer = entity.randomizeParameterRange("tamedParameters.feedTime"), feedType = feed.feedType, feedRange = feed.feedRange } end end return nil,entity.configParameter("tamedParameters.cooldown", 10) end ------------------------------------------------- function feedState.update(dt, stateData) if hasTarget() then return true end stateData.timer = stateData.timer - dt local position = entity.position() local toTarget = world.distance(stateData.targetPosition, position) local distance = world.magnitude(toTarget) if distance < stateData.feedRange then entity.setAnimationState("movement", "idle") if stateData.timer < 0 then local r = nil if stateData.feedType == 1 then local feed = feedState.matchFeed(stateData.targetId) if feed and world.containerConsume(stateData.targetId, feed) then r = {} end elseif stateData.feedType == 2 then if world.entityExists(stateData.targetId) then world.callScriptedEntity(stateData.targetId, "entity.smash") r = {} end else r = world.takeItemDrop(stateData.targetId, entity.id()) end if r then if r.count ~= nil and r.count > 1 then world.spawnItem(r.name, stateData.targetPosition, r.count - 1) end --TODO variable hunger creature.updateHunger(18) self.feedCooldown = os.time() return true,entity.configParameter("tamedParameters.cooldown", 10) end end else entity.setAnimationState("movement", "run") move({util.toDirection(toTarget[1]), toTarget[2]}) end return stateData.timer < 0 end ------------------------------------------------- function feedState.findSeed(position) local feedType = entity.configParameter("tamedFeedType", {"animalfeed"}) if type(feedType) ~= "table" then feedType = {feedType} end local feedRange = entity.configParameter("tamedParameters.feedRange", 2) local range = entity.configParameter("tamedParameters.searchRange", 5.0) local p1 = {position[1] - range, position[2] - 1} local p2 = {position[1] + range, position[2] + 1} --look for dropped feed local objectIds = world.itemDropQuery(position, range) --p1, p2) for _,oId in pairs(objectIds) do local n = world.entityName(oId) for i,v in ipairs(feedType) do local match = string.find(n, v) if match ~= nil then local oPos = world.entityPosition(oId) oPos[2] = oPos[2] + 1 if entity.entityInSight(oId) then return { targetId = oId, targetPosition = oPos, feedType = 0, feedRange = feedRange } end end end end --look for feed in containers objectIds = world.objectQuery(position, range, { callScript = "entity.configParameter", callScriptArgs = {"category"}, callScriptResult = "storage" }) for _,oId in ipairs(objectIds) do if entity.entityInSight(oId) then local feed = feedState.matchFeed(oId) if feed ~= nil then if entity.type() ~= "smallshroom" and entity.type() ~= "chicken" and math.random() < 0.5 then --world.placeObject("poop", {position[1], position[2] - 2}) end local oPos = world.entityPosition(oId) oPos[2] = oPos[2] + 1 return { targetId = oId, targetPosition = oPos, feedType = 1, feedRange = feedRange } end end end --look for feed as placed objects for i,v in ipairs(feedType) do objectIds = world.objectQuery(position, range, { name = v }) for _,oId in ipairs(objectIds) do if entity.entityInSight(oId) then local oPos = world.entityPosition(oId) oPos[2] = oPos[2] + 1 return { targetId = oId, targetPosition = oPos, feedType = 2, feedRange = feedRange } end end end return nil end ------------------------------------------------- function feedState.matchFeed(containerId) local feedType = entity.configParameter("tamedFeedType", {"animalfeed"}) local size = world.containerSize(containerId) if size == nil then return end for i = 0,size,1 do for _,n in ipairs(feedType) do local item = world.containerItemAt(containerId, i) if item ~= nil then local r = string.find(item.name, n) if r ~= nil then return {name = item.name, 1} end end end end end
apache-2.0
lawnight/skynet
test/testmysql.lua
28
3810
local skynet = require "skynet" local mysql = require "mysql" local function dump(obj) local getIndent, quoteStr, wrapKey, wrapVal, dumpObj getIndent = function(level) return string.rep("\t", level) end quoteStr = function(str) return '"' .. string.gsub(str, '"', '\\"') .. '"' end wrapKey = function(val) if type(val) == "number" then return "[" .. val .. "]" elseif type(val) == "string" then return "[" .. quoteStr(val) .. "]" else return "[" .. tostring(val) .. "]" end end wrapVal = function(val, level) if type(val) == "table" then return dumpObj(val, level) elseif type(val) == "number" then return val elseif type(val) == "string" then return quoteStr(val) else return tostring(val) end end dumpObj = function(obj, level) if type(obj) ~= "table" then return wrapVal(obj) end level = level + 1 local tokens = {} tokens[#tokens + 1] = "{" for k, v in pairs(obj) do tokens[#tokens + 1] = getIndent(level) .. wrapKey(k) .. " = " .. wrapVal(v, level) .. "," end tokens[#tokens + 1] = getIndent(level - 1) .. "}" return table.concat(tokens, "\n") end return dumpObj(obj, 0) end local function test2( db) local i=1 while true do local res = db:query("select * from cats order by id asc") print ( "test2 loop times=" ,i,"\n","query result=",dump( res ) ) res = db:query("select * from cats order by id asc") print ( "test2 loop times=" ,i,"\n","query result=",dump( res ) ) skynet.sleep(1000) i=i+1 end end local function test3( db) local i=1 while true do local res = db:query("select * from cats order by id asc") print ( "test3 loop times=" ,i,"\n","query result=",dump( res ) ) res = db:query("select * from cats order by id asc") print ( "test3 loop times=" ,i,"\n","query result=",dump( res ) ) skynet.sleep(1000) i=i+1 end end skynet.start(function() local function on_connect(db) db:query("set charset utf8"); end local db=mysql.connect({ host="127.0.0.1", port=3306, database="skynet", user="root", password="1", max_packet_size = 1024 * 1024, on_connect = on_connect }) if not db then print("failed to connect") end print("testmysql success to connect to mysql server") local res = db:query("drop table if exists cats") res = db:query("create table cats " .."(id serial primary key, ".. "name varchar(5))") print( dump( res ) ) res = db:query("insert into cats (name) " .. "values (\'Bob\'),(\'\'),(null)") print ( dump( res ) ) res = db:query("select * from cats order by id asc") print ( dump( res ) ) -- test in another coroutine skynet.fork( test2, db) skynet.fork( test3, db) -- multiresultset test res = db:query("select * from cats order by id asc ; select * from cats") print ("multiresultset test result=", dump( res ) ) print ("escape string test result=", mysql.quote_sql_str([[\mysql escape %string test'test"]]) ) -- bad sql statement local res = db:query("select * from notexisttable" ) print( "bad query test result=" ,dump(res) ) local i=1 while true do local res = db:query("select * from cats order by id asc") print ( "test1 loop times=" ,i,"\n","query result=",dump( res ) ) res = db:query("select * from cats order by id asc") print ( "test1 loop times=" ,i,"\n","query result=",dump( res ) ) skynet.sleep(1000) i=i+1 end --db:disconnect() --skynet.exit() end)
mit
ld-test/split
test/test-special-cases.lua
3
1518
#!/usr/bin/env lua local t = require 'tapered' package.path = '../src/?.lua;' .. package.path local split = require 'split'.split local s, got -- First special case: split on an empty string returns each character, one -- at a time. s = 'foo' got = split(s, '') t.is(#got, 3, "split('foo', '') should have three items.") t.is(got[1], 'f', "First item should be 'f'.") t.is(got[2], 'o', "Second item should be 'o'.") t.is(got[3], 'o', "Third item should be 'o'.") -- Second special case: split on nil acts like you want to split on -- continuous runs of spaces or tabs. s = 'foo bar bizz bang' got = split(s, nil) t.is(#got, 4, "split('foo bar bizz bang') should have four items.") t.is(got[1], 'foo', "First item should be 'foo'.") t.is(got[2], 'bar', "Second item should be 'bar'.") t.is(got[3], 'bizz', "Third item should be 'bizz'.") t.is(got[4], 'bang', "Fourth item should be 'bang'.") -- An edge case: final item is only one character. s = 'foo, ba, b' got = split(s, ', ') t.is(#got, 3, "split('foo, ba, b', ', ') should have three items.") t.is(got[1], 'foo', "First item should be 'foo'.") t.is(got[2], 'ba', "Second item should be 'ba'.") t.is(got[3], 'b', "Third item should be 'b'.") -- An edge case: first item is only one character. s = 'a,be,cee' got = split(s, ',') t.is(#got, 3, "split('a,be,cee', ',') should have three items.") t.is(got[1], 'a', "First item should be 'a'.") t.is(got[2], 'be', "Second item should be 'be'.") t.is(got[3], 'cee', "Third item should be 'cee'.") t.done()
bsd-3-clause
KlonZK/Zero-K
LuaRules/Gadgets/unit_stealth.lua
7
6694
-- $Id: unit_stealth.lua 3171 2008-11-06 09:06:29Z det $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- THIS ISN'T THE ORIGINAL! (it contains a bugfix by jK) -- -- file: unit_stealth.lua -- brief: adds active unit stealth capability -- author: Dave Rodgers (bugfixed by jK) -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "UnitStealth", desc = "Adds active unit stealth capability", author = "trepan (bugfixed by jK)", date = "May 02, 2007", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- FIXME: (TODO) -- - don't allow state changes during pauses (tied to the above) -- -------------------------------------------------------------------------------- include("LuaRules/Configs/customcmds.h.lua") include("LuaRules/Configs/constants.lua") local SetUnitStealth = Spring.SetUnitStealth local UseUnitResource = Spring.UseUnitResource local SetUnitRulesParam = Spring.SetUnitRulesParam -------------------------------------------------------------------------------- local stealthDefs = {} local stealthUnits = {} -- make it global in Initialize() local wantingUnits = {} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function ValidateStealthDefs(mds) local newDefs = {} for udName,stealthData in pairs(mds) do local ud = UnitDefNames[udName] if (not ud) then Spring.Log(gadget:GetInfo().name, LOG.WARNING, 'Bad stealth unit type: ' .. udName) else local newData = {} newData.draw = stealthData.draw newData.init = stealthData.init newData.energy = stealthData.energy or 0 newData.delay = stealthData.delay or 30 newData.tieToCloak = stealthData.tieToCloak newDefs[ud.id] = newData --[[ print('Stealth ' .. udName) print(' init = ' .. tostring(newData.init)) print(' delay = ' .. tostring(newData.delay)) print(' energy = ' .. tostring(newData.energy)) --]] end end return newDefs end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function AddStealthUnit(unitID, stealthDef) local stealthData = { id = unitID, def = stealthDef, draw = stealthDef.draw, active = stealthDef.init, energy = stealthDef.energy / TEAM_SLOWUPDATE_RATE, tieToCloak = stealthDef.tieToCloak } stealthUnits[unitID] = stealthData if (stealthDef.init) then wantingUnits[unitID] = stealthData SetUnitRulesParam(unitID, "stealth", 2) else SetUnitRulesParam(unitID, "stealth", 0) end end -------------------------------------------------------------------------------- function gadget:Initialize() -- get the stealthDefs stealthDefs = include("LuaRules/Configs/stealth_defs.lua") if (not stealthDefs) then gadgetHandler:RemoveGadget() return end stealthDefs = ValidateStealthDefs(stealthDefs) -- add the Stealth command to existing units for _,unitID in ipairs(Spring.GetAllUnits()) do local unitDefID = Spring.GetUnitDefID(unitID) local stealthDef = stealthDefs[unitDefID] if (stealthDef) then AddStealthUnit(unitID, stealthDef) end end end -------------------------------------------------------------------------------- function gadget:UnitCreated(unitID, unitDefID, unitTeam) local stealthDef = stealthDefs[unitDefID] if (not stealthDef) then return end AddStealthUnit(unitID, stealthDef) end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) stealthUnits[unitID] = nil wantingUnits[unitID] = nil end function gadget:UnitTaken(unitID, unitDefID, unitTeam) local stealthUnit = stealthUnits[unitID] if (stealthUnit) then local stealthDef = stealthUnit.def if (stealthDef.init) then wantingUnits[unitID] = stealthData SetUnitRulesParam(unitID, "stealth", 2) else wantingUnits[unitID] = nil SetUnitRulesParam(unitID, "stealth", 0) end end end -------------------------------------------------------------------------------- function gadget:GameFrame() for unitID, stealthData in pairs(wantingUnits) do if (stealthData.delay) then stealthData.delay = stealthData.delay - 1 if (stealthData.delay <= 0) then stealthData.delay = nil end else local newState if (Spring.GetUnitIsStunned(unitID) or (Spring.GetUnitRulesParam(unitID, "disarmed") == 1)) then newState = false else newState = UseUnitResource(unitID, 'e', stealthData.energy) end if (stealthData.active ~= newState) then stealthData.active = newState SetUnitStealth(unitID, stealthData.active) if (newState) then SetUnitRulesParam(unitID, "stealth", 2) else SetUnitRulesParam(unitID, "stealth", 1) stealthData.delay = stealthData.def.delay end end end end end -------------------------------------------------------------------------------- function SetStealth(unitID, state) local stealthData = stealthUnits[unitID] if (not stealthData) then return false end if (state) then wantingUnits[unitID] = stealthData SetUnitRulesParam(unitID, "stealth", 2) else wantingUnits[unitID] = nil SetUnitRulesParam(unitID, "stealth", 0) end stealthData.active = state SetUnitStealth(unitID, state) end function gadget:UnitCloaked(unitID, unitDefID, teamID) local stealthData = stealthUnits[unitID] if (not stealthData) then return false end SetStealth(unitID, true) end function gadget:UnitDecloaked(unitID, unitDefID, teamID) local stealthData = stealthUnits[unitID] if (not stealthData) then return false end SetStealth(unitID, false) end
gpl-2.0
hacker44-h44/original
plugins/steam.lua
645
2117
-- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI do local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 200 local function unescape(str) str = string.gsub( str, '&lt;', '<' ) str = string.gsub( str, '&gt;', '>' ) str = string.gsub( str, '&quot;', '"' ) str = string.gsub( str, '&apos;', "'" ) str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end ) str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end ) str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others return str end local function get_steam_data (appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&cc=us' local res,code = http.request(url) if code ~= 200 then return nil end local data = json:decode(res)[appid].data return data end local function price_info (data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' (US)' end return price end local function send_steam_data(data, receiver) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = price_info(data.price_overview) local text = title..' '..price..'\n'..description local image_url = data.header_image local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end local function run(msg, matches) local appid = matches[1] local data = get_steam_data(appid) local receiver = get_receiver(msg) send_steam_data(data, receiver) end return { description = "Grabs Steam info for Steam links.", usage = "", patterns = { "http://store.steampowered.com/app/([0-9]+)", }, run = run } end
gpl-2.0
zzzaidddddd/zzaiddd
plugins/kickal.lua
1
1225
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ (@zzaiddd) : المطور ▀▄ ▄▀ ▀▄ ▄▀ (@zzzaiddd) : قناة ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function kick_all(cb_extra, success, result) local receiver = cb_extra.receiver local msg = cb_extra.msg local deleted = 0 if success == 0 then send_large_msg(receiver, "للمطورين فقط :/") end for k,v in pairs(result) do kick_user(v.peer_id,msg.to.id) end send_large_msg(receiver, "تم الطرد") end local function run(msg, matches) if is_owner(msg) then local receiver = get_receiver(msg) channel_get_users(receiver, kick_all,{receiver = receiver, msg = msg}) end end return { patterns = { "^(طرد الكل)$" }, run = run, }
gpl-2.0
DipColor/joon12
bot/seedbot.lua
1
10019
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '1.0' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) -- mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "spam" }, sudo_users = {150575718,161731036},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @Rondoozle [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] @iranseed [persian] ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !br [group_id] [text] !br 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
caa-dev-apps/libcef_v2
LuaJIT-2.0.0-beta8/dist/share/luajit-2.0.0-beta8/jit/v.lua
2
5403
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2011 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20000, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local link = traceinfo(tr).link if link == 0 then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif link == tr then out:write(format("[TRACE %3s %s%s]\n", tr, startex, startloc)) else out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. module(...) on = dumpon off = dumpoff start = dumpon -- For -j command line option.
mit
aedansilver/wowlikearcemuold
src/scripts/lua/LuaBridge/0Misc/0LCF_Includes/LCF_Taxi_Packet_etc.lua
13
1698
--[[ * ArcEmu MMORPG Server * Copyright (C) 2005-2007 Ascent Team <http://www.ascentemu.com/> * Copyright (C) 2008-2010 <http://www.ArcEmu.org/> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. *]] assert( include("LCF.lua") ) local function alias(LHAname, LBname) LCF.PacketMethods[LHAname] = function(self, ...) return self[LBname](self, ...); end end -----TAXI----- function LCF.TaxiMethods:QuickAddPathNode(map, x, y, z, idx) idx = idx or self:GetNodeCount(); local n = TaxiPathNode(map, x, y, z) self:AddPathNode(idx, n) end function LCF.TaxiMethods:GetId() return self:GetID(); end function LCF.TaxiMethods:GetObjectType() return "TaxiPath"; end -----PACKET----- alias("GetOpcode", "opcode") alias("GetSize", "size") function LCF.PacketMethods:WriteUnitWoWGuid(unit) self:writeWoWGuid(unit:GetNewGuid()); end function LCF.PacketMethods:WriteUnitGuid(unit) self:WriteGUID(unit:GetGUID()); end function LCF.PacketMethods:GetObjectType() return "Packet"; end -----QRESULT------ function LCF.QResultMethods:GetColumnCount() return self:GetFieldCount(); end
agpl-3.0
jkeywo/KFactorioMods
k-core_0.1.0/prototypes/targeters.lua
1
1780
local function create_targeter(data) local _name = data.name return { type = "item", name = _name, icon = data.sprite..".png", flags = {"goes-to-quickbar"}, order = "a[".._name.."]", place_result = (data.type and data.type == "target" and _name) or nil, stack_size = 2 } end local function create_selection_targeter(data) local _name = data.name return { type = "selection-tool", name = _name, icon = data.sprite..".png", flags = {"goes-to-quickbar"}, order = "a[".._name.."]", stack_size = 2, selection_color = { r = 1, g = 1, b = 0 }, selection_mode = data.mode or {"any-entity"}, selection_cursor_box_type = data.box_type or "copy", alt_selection_color = { r = 1, g = 1, b = 0 }, alt_selection_mode = data.alt_mode or {"any-entity"}, alt_selection_cursor_box_type = data.alt_box_type or "copy" } end local function create_dummy_entity(data) local _name = data.name return { type = "decorative", name = _name, flags = {"placeable-neutral", "placeable-off-grid", "not-on-map"}, icon = data.sprite..".png", order = "a-b-a", collision_box = {{-0.4, -0.4}, {0.4, 0.4}}, selection_box = {{-0.4, -0.4}, {0.4, 0.4}}, selectable_in_game = false, pictures = { { filename = data.sprite..".png", width = 32, height = 32, }, } } end function register_ability( _data ) if not _data.type or _data.type == "activate" then data:extend({ create_targeter( _data ) }) elseif _data.type == "target" then data:extend({ create_targeter( _data ), create_dummy_entity( _data ) }) elseif _data.type == "area" then data:extend({ create_selection_targeter( _data ) }) end end
mit
jkeywo/KFactorioMods
spaceex_plus_bobs_0.1.0/prototypes/recipe/recipe-updates.lua
1
4692
local function try_replace( recipe, from, ... ) for i, to in ipairs({...}) do if data.raw.item[to.name or to] or data.raw.fluid[to.name or to] or data.raw.module[to.name or to] then bobmods.lib.replace_recipe_item(recipe, from, to) return true end end return false end local function try_add( recipe, ... ) for i, to in ipairs({...}) do if data.raw.item[to.name or to] or data.raw.fluid[to.name or to] or data.raw.module[to.name or to] then bobmods.lib.recipe.add_ingredient(recipe, to) return true end end return false end -- rocket-silo try_replace( "rocket-silo", "pipe", "tungsten-pipe" ) try_replace( "rocket-silo", "processing-unit", "advanced-processing-unit" ) -- satellite try_replace( "satellite", "radar", "radar-5" ) try_replace( "satellite", "solar-panel", "solar-panel-large-3" ) try_replace( "satellite", "accumulator", "fast-accumulator-3" ) try_replace( "satellite", "processing-unit", "advanced-processing-unit" ) -- low-density-structure try_replace( "low-density-structure", "steel-plate", "nitinol-alloy" ) try_replace( "low-density-structure", "copper-plate", "aluminium-plate" ) -- rocket-fuel data.raw.recipe["rocket-fuel"].category = "chemistry" if not try_add( "rocket-fuel", {type="fluid", name="nitroglycerin", amount=3} ) then try_add( "rocket-fuel", {type="fluid", name="sulfuric-acid", amount=10} ) try_add( "rocket-fuel", {type="fluid", name="nitric-acid", amount=10} ) end -- rocket-control-unit try_replace( "rocket-control-unit", "processing-unit", "advanced-processing-unit" ) try_replace( "rocket-control-unit", "speed-module", "god-module-5", "raw-speed-module-8", "speed-module-8" ) -- rocket-engine try_replace( "rocket-engine", "steel-plate", "cobalt-steel-alloy") try_replace( "rocket-engine", "iron-plate", "invar-alloy") try_replace( "rocket-engine", "copper-plate", "tungsten-plate") -- rocket-part try_add( "rocket-part", {type="item", name="rocket-engine", amount=10} ) -- assembly-robot try_replace( "assembly-robot", "construction-robot", "bob-construction-robot-4" ) try_replace( "assembly-robot", "speed-module-3", "god-module-5", "raw-speed-module-8", "speed-module-8" ) try_replace( "assembly-robot", "effectivity-module-3", "god-module-5", "green-module-8", "effectivity-module-8" ) -- drydock-assembly try_replace( "drydock-assembly", "processing-unit", "advanced-processing-unit" ) try_replace( "drydock-assembly", "solar-panel", "solar-panel-large-3" ) -- drydock-structural -- fusion-reactor try_replace( "fusion-reactor", "fusion-reactor-equipment", "fusion-reactor-equipment-4" ) -- hull-component try_replace( "hull-component", "steel-plate", "cobalt-steel-alloy" ) -- protection-field try_replace( "protection-field", "energy-shield-mk2-equipment", "energy-shield-mk6-equipment" ) -- space-thruster try_replace( "space-thruster", "speed-module-3", "god-module-5", "raw-speed-module-8", "speed-module-8" ) try_replace( "space-thruster", "pipe", "tungsten-pipe" ) try_replace( "space-thruster", "processing-unit", "advanced-processing-unit" ) -- fuel-cell try_replace( "fuel-cell", "steel-plate", "invar-alloy" ) try_replace( "fuel-cell", "processing-unit", "advanced-processing-unit" ) -- habitation try_replace( "habitation", "steel-plate", "tungsten-plate" ) try_replace( "habitation", "processing-unit", "advanced-processing-unit" ) -- life-support try_replace( "life-support", "productivity-module-3", "god-module-5", "raw-productivity-module-8", "productivity-module-8" ) try_replace( "life-support", "pipe", "tungsten-pipe" ) try_replace( "life-support", "processing-unit", "advanced-processing-unit" ) -- command try_replace( "command", "speed-module-3", "god-module-5", "raw-speed-module-8", "speed-module-8" ) try_replace( "command", "effectivity-module-3", "god-module-5", "green-module-8", "effectivity-module-8" ) try_replace( "command", "productivity-module-3", "god-module-5", "raw-productivity-module-8", "productivity-module-8" ) try_replace( "command", "processing-unit", "advanced-processing-unit" ) -- astrometrics try_replace( "astrometrics", "speed-module-3", "god-module-5", "raw-speed-module-8", "speed-module-8" ) try_replace( "astrometrics", "processing-unit", "advanced-processing-unit" ) -- ftl-drive try_replace( "ftl-drive", "speed-module-3", "god-module-5", "raw-speed-module-8", "speed-module-8" ) try_replace( "ftl-drive", "effectivity-module-3", "god-module-5", "green-module-8", "effectivity-module-8" ) try_replace( "ftl-drive", "productivity-module-3", "god-module-5", "raw-productivity-module-8", "productivity-module-8" ) try_replace( "ftl-drive", "processing-unit", "advanced-processing-unit" )
mit
ms2008/lor
spec/cases/path_pattern_2_spec.lua
2
1567
before_each(function() lor = _G.lor app = lor({ debug = false }) Request = _G.request Response = _G.response req = Request:new() res = Response:new() count = 0 match = 1 app:get("/all", function(req, res, next) count = 1 end) local testRouter = lor:Router() testRouter:get("/all", function(req, res, next) count = 6 match = 2 next() end) testRouter:get("/find/:type", function(req, res, next) count = 7 next() end) app:use("/test", testRouter()) end) after_each(function() lor = nil app = nil Request = nil Response = nil req = nil res = nil match = nil end) describe("path match test", function() it("test case 1", function() req.path = "/test/all" req.method = "get" app:handle(req, res) assert.is.equals(2, match) assert.is.equals(6, count) end) it("test case 2", function() req.path = "/test/find/all" req.method = "get" app:handle(req, res) assert.is.equals(1, match) -- should not match "/test/all" assert.is.equals(7, count) end) it("test case 3", function() req.path = "/test/find/all/1" req.method = "get" app:erroruse(function(err, req, res, next) -- 404 error assert.is.truthy(err) assert.is.equals(false, req:is_found()) end) app:handle(req, res) assert.is.equals(1, match) assert.is.equals(0, count) end) end)
mit
mohammadclashclash/telefree
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
annulen/premake
tests/actions/vstudio/sln2005/test_header.lua
5
1349
-- -- tests/actions/vstudio/sln2005/test_header.lua -- Validate generation of Visual Studio 2005+ solution header. -- Copyright (c) 2009-2014 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_sln2005_header") local sln2005 = premake.vstudio.sln2005 -- -- Setup -- local sln, prj function suite.setup() sln = test.createsolution() end local function prepare() sln2005.header() end -- -- Each supported action should output the corresponding version numbers. -- function suite.on2005() _ACTION = "vs2005" prepare() test.capture [[ Microsoft Visual Studio Solution File, Format Version 9.00 # Visual Studio 2005 ]] end function suite.on2008() _ACTION = "vs2008" prepare() test.capture [[ Microsoft Visual Studio Solution File, Format Version 10.00 # Visual Studio 2008 ]] end function suite.on2010() _ACTION = "vs2010" prepare() test.capture [[ Microsoft Visual Studio Solution File, Format Version 11.00 # Visual Studio 2010 ]] end function suite.on2012() _ACTION = "vs2012" prepare() test.capture [[ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 ]] end function suite.on2013() _ACTION = "vs2013" prepare() test.capture [[ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 ]] end
bsd-3-clause
KlonZK/Zero-K
effects/theora.lua
18
3147
-- theora_pillar -- transtheora_pillar -- transtheora -- theora return { ["theora_pillar"] = { rocks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, colormap = [[0 0 0 0.01 0.8 0.8 0.8 1 0.8 0.8 0.8 1 0.8 0.8 0.8 1 0.8 0.8 0.8 1 0.8 0.8 0.8 1 0.8 0.8 0.8 1 0 0 0 0.01]], directional = false, emitrot = 120, emitrotspread = 10, emitvector = [[0, 1, 0]], gravity = [[0.001 r-0.002, 0.01 r-0.02, 0.001 r-0.002]], numparticles = 1, particlelife = 150, particlelifespread = 150, particlesize = 170, particlesizespread = 170, particlespeed = 5, particlespeedspread = 5, pos = [[0, 0, 0]], sizegrowth = 0.05, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["transtheora_pillar"] = { rocks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, underwater = true, properties = { airdrag = 0.97, colormap = [[0 0 0 0.01 1 0.6 0 1 1 0.7 0.3 1 1 0.7 0.5 1 1 0.8 0.6 1 0.8 0.8 0.8 1 0 0 0 0.01]], directional = false, emitrot = 90, emitrotspread = 10, emitvector = [[0, 1, 0]], gravity = [[0.001 r-0.002, 0.01 r-0.02, 0.001 r-0.002]], numparticles = 1, particlelife = 150, particlelifespread = 150, particlesize = 90, particlesizespread = 90, particlespeed = 5, particlespeedspread = 5, pos = [[0, 0, 0]], sizegrowth = 0.05, sizemod = 1.0, texture = [[smokesmall]], }, }, }, ["transtheora"] = { nw = { air = true, class = [[CExpGenSpawner]], count = 150, ground = true, water = true, underwater = true, properties = { delay = [[0 i4]], explosiongenerator = [[custom:TRANSTHEORA_PILLAR]], pos = [[20 r40, i20, -20 r40]], }, }, }, ["theora"] = { nw = { air = true, class = [[CExpGenSpawner]], count = 150, ground = true, water = true, underwater = true, properties = { delay = [[0 i4]], explosiongenerator = [[custom:THEORA_PILLAR]], pos = [[20 r40, i20, -20 r40]], }, }, }, }
gpl-2.0
aqasaeed/megazeus
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
MOSAVI17/XYZ
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
rastin45/catybot
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
DarkAngel39/Events
WorldPvP/Zone_NA_pvp.lua
1
5849
local SPLL_TOKEN_ALLIANCE = 33005 local SPLL_TOKEN_HORDE = 33004 local SPLL_CAPTURE_BUFF = 33795 local NA_CREDIT_MARKER = 24867 local NA_GUARDS_MAX = 15 local NA_BUFF_ZONE = 3518 local NA_HALAA_GRAVEYARD_ZONE = 3518 local NA_RESPAWN_TIME = 3600000 local WORLDSTATE_UI_HORDE_GUARDS_SHOW = 2503 local WORLDSTATE_UI_ALLIANCE_GUARDS_SHOW = 2502 local WORLDSTATE_UI_GUARDS_MAX = 2493 local WORLDSTATE_UI_GUARDS_LEFT = 2491 local WORLDSTATE_UI_TOWER_SLIDER_DISPLAY = 2495 local WORLDSTATE_UI_TOWER_SLIDER_POS = 2494 local WORLDSTATE_UI_TOWER_SLIDER_N = 2497 --[[ NA_MAP_HALAA_NEUTRAL = 2671, NA_MAP_HALAA_NEU_A = 2676, NA_MAP_HALAA_NEU_H = 2677, NA_MAP_HALAA_HORDE = 2672, NA_MAP_HALAA_ALLIANCE = 2673]]-- local zone_controll = -1 local capture = true local C_BAR_NEUTRAL = 80 -- the neutral vallue of the capture bar. MUST BE UNDER 100. local C_BAR_CAPTURE = (100 - C_BAR_NEUTRAL)/2 local self = getfenv(1) -- go p n nH nA H A local point_data = {182210,50,2671,2677,2676,2672,2673}; local go_data = { -- hordec,alliancec,x,y,z,o NH, NA H A fly {182267,182301,-1815.8,8036.51,-26.2354,-2.89725,0.0,0.0,0.992546,-0.121869,2760,2670,2668,2669,32059}, -- ALLY_ROOST_SOUTH {182280,182302,-1507.95,8132.1,-19.5585,-1.3439,0.0,0.0,0.622515,-0.782608,2761,2667,2665,2666,32068}, -- ALLY_ROOST_WEST {182281,182303,-1384.52,7779.33,-11.1663,-0.575959,0.0,0.0,0.284015,-0.95882,2762,2662,2663,2664,32075}, -- ALLY_ROOST_NORTH {182282,182304,-1650.11,7732.56,-15.4505,-2.80998,0.0,0.0,0.986286,-0.165048,2763,2659,2660,2661,32081}, -- ALLY_ROOST_EAST {182222,182305,-1825.4022,8039.2602,-26.08,-2.89725,0.0,0.0,0.992546,-0.121869,0,0,0,0,0}, -- HORDE_BOMB_WAGON_SOUTH {182272,182306,-1515.37,8136.91,-20.42,-1.3439,0.0,0.0,0.622515,-0.782608,0,0,0,0,0}, -- HORDE_BOMB_WAGON_WEST {182273,182307,-1377.95,7773.44,-10.31,-0.575959,0.0,0.0,0.284015,-0.95882,0,0,0,0,0}, -- HORDE_BOMB_WAGON_NORTH {182274,182308,-1659.87,7733.15,-15.75,-2.80998,0.0,0.0,0.986286,-0.165048,0,0,0,0,0}, -- HORDE_BOMB_WAGON_EAST {182266,182297,-1815.8,8036.51,-26.2354,-2.89725,0.0,0.0,0.992546,-0.121869,0,0,0,0,0}, -- DESTROYED_ALLY_ROOST_SOUTH {182275,182298,-1507.95,8132.1,-19.5585,-1.3439,0.0,0.0,0.622515,-0.782608,0,0,0,0,0}, -- DESTROYED_ALLY_ROOST_WEST {182276,182299,-1384.52,7779.33,-11.1663,-0.575959,0.0,0.0,0.284015,-0.95882,0,0,0,0,0}, -- DESTROYED_ALLY_ROOST_NORTH {182277,182300,-1650.11,7732.56,-15.4505,-2.80998,0.0,0.0,0.986286,-0.165048,0,0,0,0,0} -- DESTROYED_ALLY_ROOST_EAST } local npc_data = { {1,1,18816,-1523.92,7951.76,-17.6942,3.51172}, {1,2,18821,-1527.75,7952.46,-17.6948,3.99317}, {1,3,21474,-1520.14,7927.11,-20.2527,3.39389}, {1,4,21484,-1524.84,7930.34,-20.182,3.6405}, {1,5,21483,-1570.01,7993.8,-22.4505,5.02655}, {1,6,18192,-1654.06,8000.46,-26.59,3.37}, {1,7,18192,-1487.18,7899.1,-19.53,0.954}, {1,8,18192,-1480.88,7908.79,-19.19,4.485}, {1,9,18192,-1540.56,7995.44,-20.45,0.947}, {1,10,18192,-1546.95,8000.85,-20.72,6.035}, {1,11,18192,-1595.31,7860.53,-21.51,3.747}, {1,12,18192,-1642.31,7995.59,-25.8,3.317}, {1,13,18192,-1545.46,7995.35,-20.63,1.094}, {1,14,18192,-1487.58,7907.99,-19.27,5.567}, {1,15,18192,-1651.54,7988.56,-26.5289,2.98451}, {1,16,18192,-1602.46,7866.43,-22.1177,4.74729}, {1,17,18192,-1591.22,7875.29,-22.3536,4.34587}, {1,18,18192,-1550.6,7944.45,-21.63,3.559}, {1,19,18192,-1545.57,7935.83,-21.13,3.448}, {1,20,18192,-1550.86,7937.56,-21.7,3.801}, {0,1,18817,-1591.18,8020.39,-22.2042,4.59022}, {0,2,18822,-1588.0,8019.0,-22.2042,4.06662}, {0,3,21485,-1521.93,7927.37,-20.2299,3.24631}, {0,4,21487,-1540.33,7971.95,-20.7186,3.07178}, {0,5,21488,-1570.01,7993.8,-22.4505,5.02655}, {0,6,18256,-1654.06,8000.46,-26.59,3.37}, {0,7,18256,-1487.18,7899.1,-19.53,0.954}, {0,8,18256,-1480.88,7908.79,-19.19,4.485}, {0,9,18256,-1540.56,7995.44,-20.45,0.947}, {0,10,18256,-1546.95,8000.85,-20.72,6.035}, {0,11,18256,-1595.31,7860.53,-21.51,3.747}, {0,12,18256,-1642.31,7995.59,-25.8,3.317}, {0,13,18256,-1545.46,7995.35,-20.63,1.094}, {0,14,18256,-1487.58,7907.99,-19.27,5.567}, {0,15,18256,-1651.54,7988.56,-26.5289,2.98451}, {0,16,18256,-1602.46,7866.43,-22.1177,4.74729}, {0,17,18256,-1591.22,7875.29,-22.3536,4.34587}, {0,18,18256,-1603.75,8000.36,-24.18,4.516}, {0,19,18256,-1585.73,7994.68,-23.29,4.439}, {0,20,18256,-1595.5,7991.27,-23.53,4.738}; } function OnLoad(pGO) self[tostring(pGO)] = { plrvall = 0 }; if(point_data[1][1] == pGO:GetEntry())then if(point_data[1][2] < 100 - C_BAR_CAPTURE and point_data[1][2] > C_BAR_CAPTURE)then pGO:SetByte(GAMEOBJECT_BYTES_1,2,21) elseif(point_data[1][2] < 100 - C_BAR_CAPTURE)then pGO:SetByte(GAMEOBJECT_BYTES_1,2,1) elseif(point_data[1][2] >= 100 - C_BAR_CAPTURE)then pGO:SetByte(GAMEOBJECT_BYTES_1,2,2) end end pGO:RegisterAIUpdateEvent(1000) end function AIUpdate(pGO) if(pGO == nil)then pGO:RemoveAIUpdateEvent() end local vars = self[tostring(pGO)] if(pGO:GetClosestPlayer())then for k,m in pairs (pGO:GetInRangePlayers())do if(m:IsPvPFlagged() and m:IsStealthed() == false and m:IsAlive() and battle == 1)then if(pGO:GetDistanceYards(m) <= 90)then if(m:GetTeam() == 0)then vars.plrvall = vars.plrvall + 1 elseif(m:GetTeam() == 1)then vars.plrvall = vars.plrvall - 1 end m:SetWorldStateForPlayer(WORLDSTATE_UI_TOWER_SLIDER_DISPLAY,1) if(pGO:GetEntry() == point_data[1][1])then m:SetWorldStateForPlayer(WORLDSTATE_UI_TOWER_SLIDER_POS,point_data[1][2]) end m:SetWorldStateForPlayer(WORLDSTATE_UI_TOWER_SLIDER_N,C_BAR_NEUTRAL) else m:SetWorldStateForPlayer(WORLDSTATE_UI_TOWER_SLIDER_DISPLAY,0) m:SetWorldStateForPlayer(WORLDSTATE_UI_TOWER_SLIDER_POS,0) m:SetWorldStateForPlayer(WORLDSTATE_UI_TOWER_SLIDER_N,0) end end end end end RegisterGameObjectEvent(point_data[i][1],5,AIUpdate) RegisterGameObjectEvent(point_data[i][1],2,OnLoad)
agpl-3.0
alimashmamali/fff
plugins/rae.lua
15
1313
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
KlonZK/Zero-K
LuaRules/Gadgets/lavarise.lua
5
5752
if not (gadgetHandler:IsSyncedCode()) then return end function gadget:GetInfo() return { name = "lavarise", desc = "gayly hot", author = "Adapted from knorke's gadget by jseah", date = "Feb 2011, 2011; May 2012", license = "weeeeeee iam on horse", layer = -3, enabled = true } end local modOptions = Spring.GetModOptions() if (modOptions.zkmode ~= "lavarise") then return end --- SYNCED: local sin = math.sin local random = math.random local spGetGroundHeight = Spring.GetGroundHeight local spGetAllUnits = Spring.GetAllUnits local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitBasePosition = Spring.GetUnitBasePosition local spDestroyUnit = Spring.DestroyUnit local spEcho = Spring.Echo local GAME_SPEED = Game.gameSpeed local terraunitDefID = UnitDefNames["terraunit"].id local tideRhym = {} local tideIndex = 1 local currentTide local tideContinueFrame = 0 local lavaRiseCycles = (modOptions.lavarisecycles or 7) local lavaRisePeriod = (modOptions.lavariseperiod or 120) local lavaGrowSpeed = 0.25 local minheight, maxheight = Spring.GetGroundExtremes() local lavaRise = (maxheight - minheight) / lavaRiseCycles local lavaGrow = lavaGrowSpeed local lavaLevel = minheight - lavaRise - 20 local nextMessageFrame = -1 local function addTideRhym (targetLevel, speed, remainTime) local newTide = { targetLevel = targetLevel, speed = speed, remainTime = remainTime } tideRhym[#tideRhym + 1] = newTide end function gadget:Initialize() addTideRhym (lavaLevel + lavaRise, lavaGrowSpeed, lavaRisePeriod) --addTideRhym (-21, 0.25, 5) --addTideRhym (150, 0.25, 3) --addTideRhym (-20, 0.25, 5) --addTideRhym (150, 0.25, 5) --addTideRhym (-20, 1, 5) --addTideRhym (180, 0.5, 60) --addTideRhym (240, 0.2, 10) currentTide = tideRhym[tideIndex] end local function updateLava (gameframe) if (lavaGrow < 0 and lavaLevel < currentTide.targetLevel) or (lavaGrow > 0 and lavaLevel > currentTide.targetLevel) then tideContinueFrame = gameframe + currentTide.remainTime * GAME_SPEED lavaGrow = 0 if (nextMessageFrame <= gameframe) then spEcho ("Next LAVA LEVEL change in " .. (tideContinueFrame-gameframe) / GAME_SPEED .. " seconds", "Lava Height now " .. currentTide.targetLevel, "Next Lava Height " .. currentTide.targetLevel + lavaRise) nextMessageFrame = gameframe + 30 * GAME_SPEED end end if (gameframe == tideContinueFrame) then addTideRhym (lavaLevel + lavaRise, lavaGrowSpeed, lavaRisePeriod) tideIndex = tideIndex + 1 currentTide = tideRhym[tideIndex] --spEcho ("tideIndex=" .. tideIndex .. " target=" .. currentTide.targetLevel ) if (lavaLevel < currentTide.targetLevel) then lavaGrow = currentTide.speed else lavaGrow = -currentTide.speed end end end local function lavaDeathCheck () local allUnits = spGetAllUnits() for i = 1, #allUnits do local unitID = allUnits[i] local unitDefID = spGetUnitDefID(unitID) if (unitDefID ~= terraunitDefID) then _,y,_ = spGetUnitBasePosition (unitID) if (y and y < lavaLevel) then --Spring.AddUnitDamage (unitID,1000) spDestroyUnit (unitID) --Spring.SpawnCEG("tpsmokecloud", x, y, z) end end end end function gadget:GameFrame (f) --if (f%2==0) then updateLava (f) lavaLevel = lavaLevel+lavaGrow --if (lavaLevel == 160) then lavaGrow=-0.5 end --if (lavaLevel == -10) then lavaGrow=0.25 end --end if (f%10==0) then lavaDeathCheck() end _G.lavaLevel = lavaLevel + sin(f/30)*2 --make it visible from unsynced _G.frame = f --[[ if (f%10==0) then local x = random(1,Game.mapSizeX) local z = random(1,Game.mapSizeY) local y = spGetGroundHeight(x,z) if y < lavaLevel then Spring.SpawnCEG("tpsmokecloud", x, lavaLevel, z) end end --]] end -- Unsynced part should be moved to widget --[[ local sin = math.sin local glTexCoord = gl.TexCoord local glVertex = gl.Vertex local glPushAttrib = gl.PushAttrib local glDepthTest = gl.DepthTest local glDepthMask = gl.DepthMask local glTexture = gl.Texture local glColor = gl.Color local glBeginEnd = gl.BeginEnd local glPopAttrib = gl.PopAttrib local GL_QUADS = GL.QUADS local GL_ALL_ATTRIB_BITS = GL.ALL_ATTRIB_BITS local lavaTexture = ":a:" .. "bitmaps/lava2.jpg" local mapSizeX = Game.mapSizeX local mapSizeY = Game.mapSizeZ local function DrawGroundHuggingSquareVertices(x1,z1, x2,z2, HoverHeight) local y = HoverHeight --+Spring.GetGroundHeight(x,z) local s = 2+sin(SYNCED.frame/50)/10 glTexCoord(-s,-s) glVertex(x1 ,y, z1) glTexCoord(-s,s) glVertex(x1,y,z2) glTexCoord(s,s) glVertex(x2,y,z2) glTexCoord(s,-s) glVertex(x2,y,z1) end local function DrawGroundHuggingSquare(red,green,blue,alpha, x1,z1,x2,z2, HoverHeight) glPushAttrib(GL_ALL_ATTRIB_BITS) glDepthTest(true) glDepthMask(true) glTexture(lavaTexture) -- Texture file glColor(red,green,blue,alpha) glBeginEnd(GL_QUADS, DrawGroundHuggingSquareVertices, x1,z1, x2,z2, HoverHeight) glTexture(false) glDepthMask(false) glDepthTest(false) glPopAttrib() end function gadget:DrawWorld () if (SYNCED.lavaLevel) then -- Make this a GameRulesParam --glColor(1-cm1,1-cm1-cm2,0.5,1) --DrawGroundHuggingSquare(1-cm1,1-cm1-cm2,0.5,1, 0, 0, mapSizeX, mapSizeY, SYNCED.lavaLevel) --***map.width bla DrawGroundHuggingSquare(1,1,1,1, -1000, -1000, mapSizeX + 1000, mapSizeY + 1000, SYNCED.lavaLevel) --***map.width bla --DrawGroundHuggingSquare(0,0.5,0.8,0.8, 0, 0, mapSizeX, mapSizeY, SYNCED.lavaLevel) --***map.width bla end end --]]
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Wajaom_Woodlands/mobs/Hydra.lua
6
1292
----------------------------------- -- Area: Wajaom Woodlands -- MOB: Hydra -- @pos -282 -24 -1 51 ----------------------------------- require("scripts/globals/titles"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; function onMobFight(mob, target) local battletime = mob:getBattleTime(); local headgrow = mob:getLocalVar("headgrow"); local broken = mob:AnimationSub(); if (headgrow < battletime and broken > 0) then mob:AnimationSub(broken - 1); mob:setLocalVar("headgrow", battletime + 300); end end; function onCriticalHit(mob) local rand = math.random(); local battletime = mob:getBattleTime(); local headgrow = mob:getLocalVar("headgrow"); local headbreak = mob:getLocalVar("headbreak"); local broken = mob:AnimationSub(); if (rand <= 0.15 and battletime >= headbreak and broken < 2) then mob:AnimationSub(broken + 1); mob:setLocalVar("headgrow", battletime + math.random(120, 240)) mob:setLocalVar("headbreak", battletime + 300); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) ally:addTitle(HYDRA_HEADHUNTER); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Abyssea-Konschtat/Zone.lua
33
1801
----------------------------------- -- -- Zone: Abyssea - Konschtat -- ----------------------------------- -- Research -- EventID 0x0400-0x0405 aura of boundless rage -- EventID 0x0800-0x0883 The treasure chest will disappear is 180 seconds menu. -- EventID 0x0884 Teleport? -- EventID 0x0885 DEBUG Menu ----------------------------------- package.loaded["scripts/zones/Abyssea-Konschtat/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Konschtat/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- Note: in retail even tractor lands you back at searing ward, will handle later. if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(153,-72,-840,140); end if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED and player:getVar("1stTimeAyssea") == 0) then player:setVar("1stTimeAyssea",1); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
mynameiscraziu/karizma
plugins/webshot.lua
919
1473
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Send an screenshot of a website.", usage = { "!webshot [url]: Take an screenshot of the web and send it back to you." }, patterns = { "^!webshot (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
hadirahimi1380/-AhRiMaN-
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Sacrarium/Zone.lua
19
3611
----------------------------------- -- -- Zone: Sacrarium (28) -- ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/zones/Sacrarium/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Set random variable for determining Old Prof. Mariselle's spawn location local rand = math.random((2),(7)); SetServerVariable("Old_Prof_Spawn_Location", rand); UpdateTreasureSpawnPoint(16892179); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-219.996,-18.587,82.795,64); end -- ZONE LEVEL RESTRICTION if (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,50,0,0); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onGameDay ----------------------------------- function onGameDay() -- Labyrinth local day = VanadielDayElement() ; local tbl; local SacrariumWallOffset = 16892109; if (day == 3 or day == 7) then tbl = {9,9,8,8,9,9,8,9,8,8,9,8,8,8,9,8,9,8}; elseif (day == 1 or day == 5) then tbl = {9,9,8,9,8,8,8,8,9,9,9,8,9,8,8,8,8,9}; elseif (day == 0 or day == 4) then tbl = {8,9,8,9,8,9,9,8,9,9,8,8,9,8,8,8,8,9}; else tbl = {9,8,9,9,8,9,8,8,9,8,8,9,8,9,8,9,8,8}; end GetNPCByID(SacrariumWallOffset):setAnimation(tbl[1]); GetNPCByID(SacrariumWallOffset+6):setAnimation(tbl[2]); GetNPCByID(SacrariumWallOffset+12):setAnimation(tbl[3]); GetNPCByID(SacrariumWallOffset+13):setAnimation(tbl[4]); GetNPCByID(SacrariumWallOffset+1):setAnimation(tbl[5]); GetNPCByID(SacrariumWallOffset+7):setAnimation(tbl[6]); GetNPCByID(SacrariumWallOffset+14):setAnimation(tbl[7]); GetNPCByID(SacrariumWallOffset+2):setAnimation(tbl[8]); GetNPCByID(SacrariumWallOffset+8):setAnimation(tbl[9]); GetNPCByID(SacrariumWallOffset+9):setAnimation(tbl[10]); GetNPCByID(SacrariumWallOffset+3):setAnimation(tbl[11]); GetNPCByID(SacrariumWallOffset+15):setAnimation(tbl[12]); GetNPCByID(SacrariumWallOffset+16):setAnimation(tbl[13]); GetNPCByID(SacrariumWallOffset+10):setAnimation(tbl[14]); GetNPCByID(SacrariumWallOffset+4):setAnimation(tbl[15]); GetNPCByID(SacrariumWallOffset+17):setAnimation(tbl[16]); GetNPCByID(SacrariumWallOffset+11):setAnimation(tbl[17]); GetNPCByID(SacrariumWallOffset+5):setAnimation(tbl[18]); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
pczarn/kollos
components/main/kollos/location.lua
2
3912
--[[ location object prototype for the Kollos project according to https://github.com/rns/kollos-luif-doc/blob/master/etc/internals.md --]] --[[ The blob name. Required. Archetypally a file name, but not all locations will be in files. Blob name must be suitable for appearing in messages. start() and end() -- start and end positions. Length of the text will be end - start. range() -- start and end positions as a two-element array. text() -- the text from start to end. LUIF source follows Lua restrictions, which means no Unicode. line_column(pos) -- given a position, of the sort returned by start() and end(), returns the position in a more convenient representation. What is "more convenient" depends on the class of the blob, but typically this will be line and column. sublocation() -- the current location within the blob in form suitable for an error message. location() -- the current location, including the blob name. --]] -- namespace local location_class = {} -- methods to go to prototype local function location_method (location_object) return location_object._blob .. ': ' .. location_object._line end -- Only for errors -- it does a lot of checking which -- usually should be unnecessary. -- We query subtype often and do -- not even want call a function every time we do it local function trace_subtype(location_object) local metatable = getmetatable(location_object) if not metatable then error("Bad location object: no metatable") end local prototype = metatable.__index if not prototype then error("Bad location object: metatable has no __index prototype") end if not prototype._type or prototype._type ~= 'location' then error("Bad location object: prototype is not for location object") end return location_object._subtype end local function cursor_set(self, new_cursor) if self._subtype ~= 'reader' then error("cursor_set() called, but object is ", trace_subtype(self)) end self.cursor = new_cursor end local function cursor(self) if self._subtype ~= 'reader' then error("cursor() called, but object is ", trace_subtype(self)) end return self.cursor end --[[ This is for optimized reading of long strings, so that we don't have to call a function for each character --]] local function fixed_string(self) if self._subtype ~= 'reader' then error("fixed_string() called, but object is " .. trace_subtype(self)) end return self._string, self.cursor end -- Some day we may do dynamic strings, and this method may -- be less efficient than fixed_string(), but will -- work with them. local function string_method(self) -- luacheck: ignore self error('location.string() is not yet implemented') end local default_prototype = { _type = 'location', _fixed = true, -- for now, all strings fixed for the -- life of the prototype _blob = '[No file]', _line = '[No line data]', location = location_method, cursor_set = cursor_set, cursor = cursor, fixed_string = fixed_string, string = string_method } -- metatable location_class.mt = {} -- the __index metamethod points to prototype -- Basic constructor, creates a location from a string. -- It creates a dedicated metatable and prototype. -- Other locator objects referring to this same string will -- be created from this one, and share the same metatable -- and prototype function location_class.new_from_string (string) local location_object = { _subtype = 'reader', cursor = 1 } local prototype = {} for field,default_value in pairs(default_prototype) do prototype[field] = default_value end prototype._string = string local metatable = {} metatable.__index = prototype metatable.__tostring = prototype.location setmetatable(location_object, metatable) return location_object end return location_class
mit
Wiladams/cream
ovs/lib/util.lua
1
16416
local ffi = require("ffi") local bit = require("bit") local band, bor, rshift = bit.band, bit.bor, bit.rshift; local bitutils = require("bitutils") --[[ #include <arpa/inet.h> #include "compiler.h" #include "openvswitch/types.h" #include "openvswitch/util.h" --]] local Lib_util = ffi.load("openvswitch") ffi.cdef[[ typedef uint64_t uintmax_t; ]] --[[ #ifndef va_copy #ifdef __va_copy #define va_copy __va_copy #else #define va_copy(dst, src) ((dst) = (src)) #endif #endif --]] --[[ #ifdef __CHECKER__ #define BUILD_ASSERT(EXPR) ((void) 0) #define BUILD_ASSERT_DECL(EXPR) extern int (*build_assert(void))[1] #elif !defined(__cplusplus) /* Build-time assertion building block. */ #define BUILD_ASSERT__(EXPR) \ sizeof(struct { unsigned int build_assert_failed : (EXPR) ? 1 : -1; }) /* Build-time assertion for use in a statement context. */ #define BUILD_ASSERT(EXPR) (void) BUILD_ASSERT__(EXPR) /* Build-time assertion for use in a declaration context. */ #define BUILD_ASSERT_DECL(EXPR) \ extern int (*build_assert(void))[BUILD_ASSERT__(EXPR)] #else /* __cplusplus */ #include <boost/static_assert.hpp> #define BUILD_ASSERT BOOST_STATIC_ASSERT #define BUILD_ASSERT_DECL BOOST_STATIC_ASSERT #endif /* __cplusplus */ --]] --[[ #ifdef __GNUC__ #define BUILD_ASSERT_GCCONLY(EXPR) BUILD_ASSERT(EXPR) #define BUILD_ASSERT_DECL_GCCONLY(EXPR) BUILD_ASSERT_DECL(EXPR) #else #define BUILD_ASSERT_GCCONLY(EXPR) ((void) 0) #define BUILD_ASSERT_DECL_GCCONLY(EXPR) ((void) 0) #endif /* Like the standard assert macro, except writes the failure message to the * log. */ #ifndef NDEBUG #define ovs_assert(CONDITION) \ if (!OVS_LIKELY(CONDITION)) { \ ovs_assert_failure(OVS_SOURCE_LOCATOR, __func__, #CONDITION); \ } #else #define ovs_assert(CONDITION) ((void) (CONDITION)) #endif --]] ffi.cdef[[ void ovs_assert_failure(const char *, const char *, const char *); ]] --[[ /* Casts 'pointer' to 'type' and issues a compiler warning if the cast changes * anything other than an outermost "const" or "volatile" qualifier. * * The cast to int is present only to suppress an "expression using sizeof * bool" warning from "sparse" (see * http://permalink.gmane.org/gmane.comp.parsers.sparse/2967). */ #define CONST_CAST(TYPE, POINTER) \ ((void) sizeof ((int) ((POINTER) == (TYPE) (POINTER))), \ (TYPE) (POINTER)) --]] --extern char *program_name; local function __ARRAY_SIZE_NOCHECK(ARRAY) return ffi.sizeof(ARRAY) / ffi.sizeof(ARRAY[0]) end --[[ #ifdef __GNUC__ /* return 0 for array types, 1 otherwise */ #define __ARRAY_CHECK(ARRAY) \ !__builtin_types_compatible_p(typeof(ARRAY), typeof(&ARRAY[0])) /* compile-time fail if not array */ #define __ARRAY_FAIL(ARRAY) (sizeof(char[-2*!__ARRAY_CHECK(ARRAY)])) #define __ARRAY_SIZE(ARRAY) \ __builtin_choose_expr(__ARRAY_CHECK(ARRAY), \ __ARRAY_SIZE_NOCHECK(ARRAY), __ARRAY_FAIL(ARRAY)) #else --]] local function __ARRAY_SIZE(ARRAY) return __ARRAY_SIZE_NOCHECK(ARRAY); end -- Returns the number of elements in ARRAY. */ local function ARRAY_SIZE(ARRAY) return __ARRAY_SIZE(ARRAY); end -- Returns X / Y, rounding up. X must be nonnegative to round correctly. */ local function DIV_ROUND_UP(X, Y) return (X + (Y - 1)) / Y end -- Returns X rounded up to the nearest multiple of Y. */ local function ROUND_UP(X, Y) return DIV_ROUND_UP(X, Y) * Y end -- Returns the least number that, when added to X, yields a multiple of Y. */ local function PAD_SIZE(X, Y) return ROUND_UP(X, Y) - X end -- Returns X rounded down to the nearest multiple of Y. */ local function ROUND_DOWN(X, Y) return X / Y * Y end --/* Returns true if X is a power of 2, otherwise false. */ local function IS_POW2(X) return (X ~= 0) and band(X, (X - 1)) == 0 end local function is_pow2(x) return IS_POW2(x); end --[[ /* Returns X rounded up to a power of 2. X must be a constant expression. */ #define ROUND_UP_POW2(X) RUP2__(X) #define RUP2__(X) (RUP2_1(X) + 1) #define RUP2_1(X) (RUP2_2(X) | (RUP2_2(X) >> 16)) #define RUP2_2(X) (RUP2_3(X) | (RUP2_3(X) >> 8)) #define RUP2_3(X) (RUP2_4(X) | (RUP2_4(X) >> 4)) #define RUP2_4(X) (RUP2_5(X) | (RUP2_5(X) >> 2)) #define RUP2_5(X) (RUP2_6(X) | (RUP2_6(X) >> 1)) #define RUP2_6(X) ((X) - 1) /* Returns X rounded down to a power of 2. X must be a constant expression. */ #define ROUND_DOWN_POW2(X) RDP2__(X) #define RDP2__(X) (RDP2_1(X) - (RDP2_1(X) >> 1)) #define RDP2_1(X) (RDP2_2(X) | (RDP2_2(X) >> 16)) #define RDP2_2(X) (RDP2_3(X) | (RDP2_3(X) >> 8)) #define RDP2_3(X) (RDP2_4(X) | (RDP2_4(X) >> 4)) #define RDP2_4(X) (RDP2_5(X) | (RDP2_5(X) >> 2)) #define RDP2_5(X) ( (X) | ( (X) >> 1)) --]] --[[ --/* This system's cache line size, in bytes. -- * Being wrong hurts performance but not correctness. */ #define CACHE_LINE_SIZE 64 BUILD_ASSERT_DECL(IS_POW2(CACHE_LINE_SIZE)); static inline void ovs_prefetch_range(const void *start, size_t size) { const char *addr = (const char *)start; size_t ofs; for (ofs = 0; ofs < size; ofs += CACHE_LINE_SIZE) { OVS_PREFETCH(addr + ofs); } } --]] local function OVS_NOT_REACHED() error() end --[[ /* Given a pointer-typed lvalue OBJECT, expands to a pointer type that may be * assigned to OBJECT. */ #ifdef __GNUC__ #define OVS_TYPEOF(OBJECT) typeof(OBJECT) #else #define OVS_TYPEOF(OBJECT) void * #endif /* Given OBJECT of type pointer-to-structure, expands to the offset of MEMBER * within an instance of the structure. * * The GCC-specific version avoids the technicality of undefined behavior if * OBJECT is null, invalid, or not yet initialized. This makes some static * checkers (like Coverity) happier. But the non-GCC version does not actually * dereference any pointer, so it would be surprising for it to cause any * problems in practice. */ #ifdef __GNUC__ #define OBJECT_OFFSETOF(OBJECT, MEMBER) offsetof(typeof(*(OBJECT)), MEMBER) #else #define OBJECT_OFFSETOF(OBJECT, MEMBER) \ ((char *) &(OBJECT)->MEMBER - (char *) (OBJECT)) #endif /* Given POINTER, the address of the given MEMBER in a STRUCT object, returns the STRUCT object. */ #define CONTAINER_OF(POINTER, STRUCT, MEMBER) \ ((STRUCT *) (void *) ((char *) (POINTER) - offsetof (STRUCT, MEMBER))) /* Given POINTER, the address of the given MEMBER within an object of the type * that that OBJECT points to, returns OBJECT as an assignment-compatible * pointer type (either the correct pointer type or "void *"). OBJECT must be * an lvalue. * * This is the same as CONTAINER_OF except that it infers the structure type * from the type of '*OBJECT'. */ #define OBJECT_CONTAINING(POINTER, OBJECT, MEMBER) \ ((OVS_TYPEOF(OBJECT)) (void *) \ ((char *) (POINTER) - OBJECT_OFFSETOF(OBJECT, MEMBER))) /* Given POINTER, the address of the given MEMBER within an object of the type * that that OBJECT points to, assigns the address of the outer object to * OBJECT, which must be an lvalue. * * Evaluates to (void) 0 as the result is not to be used. */ #define ASSIGN_CONTAINER(OBJECT, POINTER, MEMBER) \ ((OBJECT) = OBJECT_CONTAINING(POINTER, OBJECT, MEMBER), (void) 0) /* As explained in the comment above OBJECT_OFFSETOF(), non-GNUC compilers * like MSVC will complain about un-initialized variables if OBJECT * hasn't already been initialized. To prevent such warnings, INIT_CONTAINER() * can be used as a wrapper around ASSIGN_CONTAINER. */ #define INIT_CONTAINER(OBJECT, POINTER, MEMBER) \ ((OBJECT) = NULL, ASSIGN_CONTAINER(OBJECT, POINTER, MEMBER)) /* Given ATTR, and TYPE, cast the ATTR to TYPE by first casting ATTR to * (void *). This is to suppress the alignment warning issued by clang. */ #define ALIGNED_CAST(TYPE, ATTR) ((TYPE) (void *) (ATTR)) --]] --[[ /* Use "%"PRIuSIZE to format size_t with printf(). */ #ifdef _WIN32 #define PRIdSIZE "Id" #define PRIiSIZE "Ii" #define PRIoSIZE "Io" #define PRIuSIZE "Iu" #define PRIxSIZE "Ix" #define PRIXSIZE "IX" #else #define PRIdSIZE "zd" #define PRIiSIZE "zi" #define PRIoSIZE "zo" #define PRIuSIZE "zu" #define PRIxSIZE "zx" #define PRIXSIZE "zX" #endif #ifndef _WIN32 typedef uint32_t HANDLE; #endif --]] --[[ local function set_program_name(name) return ovs_set_program_name(name, OVS_PACKAGE_VERSION); end --]] ffi.cdef[[ const char *get_subprogram_name(void); void set_subprogram_name(const char *format, ...); void ovs_print_version(uint8_t min_ofp, uint8_t max_ofp); ]] ffi.cdef[[ void out_of_memory(void); void *xmalloc(size_t); void *xcalloc(size_t, size_t); void *xzalloc(size_t) ; void *xrealloc(void *, size_t); void *xmemdup(const void *, size_t); char *xmemdup0(const char *, size_t); char *xstrdup(const char *); char *xasprintf(const char *format, ...) ; char *xvasprintf(const char *format, va_list) ; void *x2nrealloc(void *p, size_t *n, size_t s); void *xmalloc_cacheline(size_t); void *xzalloc_cacheline(size_t); void free_cacheline(void *); ]] ffi.cdef[[ void ovs_strlcpy(char *dst, const char *src, size_t size); void ovs_strzcpy(char *dst, const char *src, size_t size); void ovs_abort(int err_no, const char *format, ...); void ovs_abort_valist(int err_no, const char *format, va_list); void ovs_fatal(int err_no, const char *format, ...); void ovs_fatal_valist(int err_no, const char *format, va_list); void ovs_error(int err_no, const char *format, ...); void ovs_error_valist(int err_no, const char *format, va_list); const char *ovs_retval_to_string(int); const char *ovs_strerror(int); //void ovs_hex_dump(FILE *, const void *, size_t, uintptr_t offset, bool ascii); ]] ffi.cdef[[ bool str_to_int(const char *, int base, int *); bool str_to_long(const char *, int base, long *); bool str_to_llong(const char *, int base, long long *); bool str_to_uint(const char *, int base, unsigned int *); bool ovs_scan(const char *s, const char *format, ...) ; bool ovs_scan_len(const char *s, int *n, const char *format, ...); bool str_to_double(const char *, double *); int hexit_value(int c); uintmax_t hexits_value(const char *s, size_t n, bool *ok); const char *english_list_delimiter(size_t index, size_t total); char *get_cwd(void); char *abs_file_name(const char *dir, const char *file_name); char *follow_symlinks(const char *filename); void ignore(bool x); ]] if ffi.os == "Windows" then ffi.cdef[[ char *dir_name(const char *file_name); char *base_name(const char *file_name); ]] end --[[ /* Bitwise tests. */ /* Returns the number of trailing 0-bits in 'n'. Undefined if 'n' == 0. */ #if __GNUC__ >= 4 static inline int raw_ctz(uint64_t n) { /* With GCC 4.7 on 32-bit x86, if a 32-bit integer is passed as 'n', using * a plain __builtin_ctzll() here always generates an out-of-line function * call. The test below helps it to emit a single 'bsf' instruction. */ return (__builtin_constant_p(n <= UINT32_MAX) && n <= UINT32_MAX ? __builtin_ctz(n) : __builtin_ctzll(n)); } local function raw_clz64(n) return bitutils.minbytes(n); -- __builtin_clzll(n); end --]] ffi.cdef[[ /* Defined in util.c. */ int raw_ctz(uint64_t n); int raw_clz64(uint64_t n); ]] -- Returns the number of trailing 0-bits in 'n', or 32 if 'n' is 0. */ local function ctz32(n) if n == 0 then return 32 end; return Lib_util.raw_ctz(n); end -- Returns the number of trailing 0-bits in 'n', or 64 if 'n' is 0. */ local function ctz64(n) if n == 0 then return 64; end return Lib_util.raw_ctz(n); end -- Returns the number of leading 0-bits in 'n', or 32 if 'n' is 0. */ local function clz32(n) if n == 0 then return 32; end return Lib_util.raw_clz64(n) - 32; end -- Returns the number of leading 0-bits in 'n', or 64 if 'n' is 0. */ local function clz64(n) if n == 0 then return 64; end return Lib_util.raw_clz64(n); end --/* Given a word 'n', calculates floor(log_2('n')). This is equivalent -- * to finding the bit position of the most significant one bit in 'n'. It is -- * an error to call this function with 'n' == 0. */ local function log_2_floor(n) return 63 - Lib_util.raw_clz64(n); end --/* Given a word 'n', calculates ceil(log_2('n')). It is an error to -- * call this function with 'n' == 0. */ --[[ local function log_2_ceil(uint64_t n) return log_2_floor(n) + !is_pow2(n); end --]] --/* unsigned int count_1bits(uint64_t x): -- * -- * Returns the number of 1-bits in 'x', between 0 and 64 inclusive. */ if ffi.abi("64bit") then local UINT64_C = ffi.typeof("uint64_t"); local h55 = UINT64_C(0x5555555555555555); local h33 = UINT64_C(0x3333333333333333); local h0F = UINT64_C(0x0F0F0F0F0F0F0F0F); local h01 = UINT64_C(0x0101010101010101); local function count_1bits(x) -- This portable implementation is the fastest one we know of for 64 -- bits, and about 3x faster than GCC 4.7 __builtin_popcountll(). */ x = x - band(rshift(x, 1), h55); -- Count of each 2 bits in-place. x = band(x, h33) + band(rshift(x, 2), h33); -- Count of each 4 bits in-place. x = band((x + rshift(x, 4)), h0F); -- Count of each 8 bits in-place. return rshift((x * h01), 56); -- Sum of all bytes. end else -- Not 64-bit. --[[ extern const uint8_t count_1bits_8[256]; static inline unsigned int local function count_1bits_32__(x) /* This portable implementation is the fastest one we know of for 32 bits, * and faster than GCC __builtin_popcount(). */ return (count_1bits_8[x & 0xff] + count_1bits_8[(x >> 8) & 0xff] + count_1bits_8[(x >> 16) & 0xff] + count_1bits_8[x >> 24]); end local function count_1bits(x) return count_1bits_32__(x) + count_1bits_32__rshift(x, 32); end --]] end -- Returns the rightmost 1-bit in 'x' (e.g. 01011000 => 00001000), or 0 if 'x' -- is 0. local function rightmost_1bit(x) return band(x, -x); end -- Returns 'x' with its rightmost 1-bit changed to a zero (e.g. 01011000 => -- 01010000), or 0 if 'x' is 0. */ local function zero_rightmost_1bit(x) return band(x, (x - 1)); end --[[ /* Returns the index of the rightmost 1-bit in 'x' (e.g. 01011000 => 3), or 32 * if 'x' is 0. * * Unlike the other functions for rightmost 1-bits, this function only works * with 32-bit integers. */ static inline int rightmost_1bit_idx(uint32_t x) { return ctz32(x); } /* Returns the index of the leftmost 1-bit in 'x' (e.g. 01011000 => 6), or 32 * if 'x' is 0. * * This function only works with 32-bit integers. */ static inline uint32_t leftmost_1bit_idx(uint32_t x) { return x ? log_2_floor(x) : 32; } /* Return a ovs_be32 prefix in network byte order with 'plen' highest bits set. * Shift with 32 is undefined behavior, but we rather use 64-bit shift than * compare. */ static inline ovs_be32 be32_prefix_mask(int plen) { return htonl((uint64_t)UINT32_MAX << (32 - plen)); } --]] ffi.cdef[[ bool is_all_zeros(const void *, size_t); bool is_all_ones(const void *, size_t); void bitwise_copy(const void *src, unsigned int src_len, unsigned int src_ofs, void *dst, unsigned int dst_len, unsigned int dst_ofs, unsigned int n_bits); void bitwise_zero(void *dst_, unsigned int dst_len, unsigned dst_ofs, unsigned int n_bits); void bitwise_one(void *dst_, unsigned int dst_len, unsigned dst_ofs, unsigned int n_bits); bool bitwise_is_all_zeros(const void *, unsigned int len, unsigned int ofs, unsigned int n_bits); unsigned int bitwise_scan(const void *, unsigned int len, bool target, unsigned int start, unsigned int end); void bitwise_put(uint64_t value, void *dst, unsigned int dst_len, unsigned int dst_ofs, unsigned int n_bits); uint64_t bitwise_get(const void *src, unsigned int src_len, unsigned int src_ofs, unsigned int n_bits); void xsleep(unsigned int seconds); ]] if ffi.os == "Windows" then ffi.cdef[[ char *ovs_format_message(int error); char *ovs_lasterror_to_string(void); int ftruncate(int fd, off_t length); ]] end local exports = { ovs_abort = Lib_util.ovs_abort; ovs_fatal = Lib_util.ovs_fatal; } return exports;
mit
AdamGagorik/darkstar
scripts/zones/Valkurm_Dunes/npcs/Tsunashige_IM.lua
13
3317
----------------------------------- -- Area: Valkurm Dunes -- NPC: Tsunashige, I.M. -- Outpost Conquest Guards -- @pos 139.394 -7.885 100.384 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ff9; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
ModMountain/hash.js
plugins/lua/user_modules/fn/list.lua
4
3123
f = f or {} f.mt = f.mt or {} f.mt.list = f.mt.list or {} f.list = function (t) t = t or {} local list = { array = {} } setmetatable (list, f.mt.list) for i = 1, #t do list [i] = t [i] end return list end f.map = function (mapF, r, ...) mapF = f.toFunction (mapF) if mapF == print then print (f.concat (f.map (tostring, r), ", ")) return end local rr = f.list () for i = 1, #r do rr [i] = mapF (r [i], ...) end return rr end f.filter = function (filterF, r, ...) filterF = f.toFunction (filterF) local rr = f.list () for i = 1, #r do if filterF (r [i], ...) then rr [#rr + 1] = r [i] end end return rr end f.foldr = function (x0, binaryF, r, ...) binaryF = f.toFunction (binaryF) for i = #r, 1, -1 do x0 = binaryF (r [i], x0, ...) end return x0 end f.foldl = function (x0, binaryF, r, ...) binaryF = f.toFunction (binaryF) for i = 1, #r do x0 = binaryF (x0, r [i], ...) end return x0 end f.range = function (x0, x1, dx) dx = dx or 1 local r = f.list () for i = x0, x1, dx do r [#r + 1] = i end return r end f.rep = function (v, n) local r = f.list () for i = 1, n do r [i] = v end return r end f.sum = function (r) return foldr (0, f.add, r) end f.prod = function (r) return foldr (1, f.mul, r) end f.keys = function (t) local r = f.list () for k, _ in pairs (t) do r [#r + 1] = k end return r end f.values = function (t) local r = f.list () for _, v in pairs (t) do r [#r + 1] = v end return r end f.mt.list.__index = {} f.mt.list.__len = function (self) return #self.array end f.mt.list.__pairs = function (self) return pairs (self.array) end f.mt.list.methods = {} f.mt.list.methods.clone = function (self) local t = {} for k, v in pairs (self.array) do t [k] = v end return f.list (t) end f.mt.list.methods.map = function (r, mapF, ...) return f.map (mapF, r, ...) end f.mt.list.methods.filter = function (r, filterF, ...) return f.filter (filterF, r, ...) end f.mt.list.methods.foldr = function (r, binaryF, x0, ...) return f.foldr (x0, binaryF, r, ...) end f.mt.list.methods.foldl = function (r, binaryF, x0, ...) return f.foldl (x0, binaryF, r, ...) end f.mt.list.methods.sum = f.sum f.mt.list.methods.prod = f.prod f.mt.list.methods.concat = f.concat f.mt.list.methods.sort = function (self, comparator) local t = self:clone () table.sort (t.array) return t end f.mt.list.methods.tostring = function (self) if #self == 0 then return "{}" end return "{ " .. self:map (f.toString):concat (", ") .. " }" end f.mt.list.__tostring = f.mt.list.methods.tostring f.mt.list.__index = function (self, k) if f.mt.list.methods [k] then return f.mt.list.methods [k] elseif type (k) == "number" then return self.array [k] elseif type (k) == "table" then return f.list (k):map (self) end end f.mt.list.__newindex = function (self, k, v) if type (k) == "number" then self.array [k] = v elseif type (k) == "table" then if type (v) == "table" then for i = 1, #k do self [k [i]] = v [i] end else for i = 1, #k do self [k [i]] = v end end end end
cc0-1.0
AdamGagorik/darkstar
scripts/zones/Wajaom_Woodlands/npcs/Watisa.lua
32
1643
----------------------------------- -- Area: Wajaom Woodlands -- NPC: Watisa -- Type: Chocobo Renter -- @pos -201 -11 93 51 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 20) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); player:startEvent(0x0009,price,gil); else player:startEvent(0x000a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x0009 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); end end end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Nashmau/npcs/Jajaroon.lua
13
1671
----------------------------------- -- Area: Nashmau -- NPC: Jajaroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,JAJAROON_SHOP_DIALOG); stock = {0x0880,48, -- Fire Card 0x0881,48, -- Ice Card 0x0882,48, -- Wind Card 0x0883,48, -- Earth Card 0x0884,48, -- Thunder Card 0x0885,48, -- Water Card 0x0886,48, -- Light Card 0x0887,48, -- Dark Card 0x16ee,10000, -- Trump Card Case 0x1570,35200, -- Samurai Die 0x1571,600, -- Ninja Die 0x1572,82500, -- Dragoon Die 0x1573,40000, -- Summoner Die 0x1574,3525, -- Blue Mage Die 0x1575,316, -- Corsar Die 0x1576,9216} -- Puppetmaster Die showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
sjznxd/lc-20130204
modules/rpc/luasrc/controller/rpc.lua
70
4443
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then -- if authentication token was given local sdat = luci.sauth.read(auth) if sdat then -- if given token is valid if sdat.user and luci.util.contains(accs, sdat.user) then return sdat.user, auth end end end luci.http.status(403, "Forbidden") end local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local sauth = require "luci.sauth" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local loginstat local server = {} server.challenge = function(user, pass) local sid, token, secret if sys.user.checkpasswd(user, pass) then sid = sys.uniqueid(16) token = sys.uniqueid(16) secret = sys.uniqueid(16) http.header("Set-Cookie", "sysauth=" .. sid.."; path=/") sauth.reap() sauth.write(sid, { user=user, token=token, secret=secret }) end return sid and {sid=sid, token=token, secret=secret} end server.login = function(...) local challenge = server.challenge(...) return challenge and challenge.sid end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end
apache-2.0
Mr-Pi/nodemcu-extended-httpserver
httpserver/server.lua
1
1342
-- vim: ts=4 sw=4 -- -- httpserver main module require "console" require "config" Handler = require "httpserver/handler" local cb={} local server function cb.start() console.log("starting httpserver") server=net.createServer(net.TCP, 30) server:listen(config.get("http.port"), function(socket) local handler=Handler(socket) end) local ipap = tostring( wifi.ap.getip() or "") local ipsta= tostring(wifi.sta.getip() or "") console.log("httpserver is listing at: ".. ipap..(ipap~="" and ipsta~="" and " and " or "")..ipsta) ipap=nil ipsta=nil collectgarbage() end function cb.stop() console.log("stopping httpserver") server:close() server=nil collectgarbage() end function cb.startSafemode() console.log("switching to safemode") if not config.loaded then config.loaded={} end config.loaded.http = {port=80, prefix="http-init"} tmr.register(0, config.get("safemode.timeout"), tmr.ALARM_SINGLE, function() console.log("switching back to normal serve mode") config.load() if not config.get("http.enabled") then cb.stop() end end) tmr.start(0) end httpreq.updateResponders() if config.get("safemode.enabled") or config.get("http.enabled") then cb.start() end if config.get("safemode.enabled") then cb.startSafemode() end local function loaded(args) console.moduleLoaded(args) return cb end return loaded(...)
mit
kanaka/raft.js
research_class/pgfplots/tex/generic/pgfplots/lua/pgfplots/binary.lua
4
1660
-- Attention: functions in this file are part of the backend driver. -- They are supposed to work back with Lua 5.1 . -- Note that most of the 'lua backend' requires Lua 5.2 (currently) pgfplotsGetLuaBinaryStringFromCharIndicesChunkSize = 7000; if unpack == nil then -- LUA 0.76 renamed unpack to table.unpack pgfplotsUnpack = table.unpack; else pgfplotsUnpack = unpack; end -- Takes a table containing an arbitrary number of integers in the range 0..255 and converts it -- into a binary stream of the corresponding binary chars. -- -- @param charIndices a table containing 0...N arguments; each in the range 0..255 -- -- @return a string containing binary content, one byte for each input integer. function pgfplotsGetLuaBinaryStringFromCharIndices(charIndices) -- unpack extracts only the indices (we can't provide a table to string.char). -- note that pdf.immediateobj has been designed to avoid sanity checking for invalid UTF strings - -- in other words: it accepts binary strings. -- -- unfortunately, this here fails for huge input tables: -- pgfplotsretval=string.char(unpack(charIndices)); -- we have to create it incrementally using chunks: local len = #charIndices; local chunkSize = pgfplotsGetLuaBinaryStringFromCharIndicesChunkSize; local buf = {}; -- ok, append all full chunks of chunkSize first: local numFullChunks = math.floor(len/chunkSize); for i = 0, numFullChunks-1, 1 do table.insert(buf, string.char(pgfplotsUnpack(charIndices, 1+i*chunkSize, (i+1)*chunkSize))); end -- append the rest: table.insert(buf, string.char(pgfplotsUnpack(charIndices, 1+numFullChunks*chunkSize))); return table.concat(buf); end
mpl-2.0
AdamGagorik/darkstar
scripts/zones/Lower_Jeuno/npcs/_l07.lua
13
1554
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -45.148 0 -47.279 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 4) then player:setVar("cService",5); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 17) then player:setVar("cService",18); end end end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Nashmau/npcs/Awaheen.lua
13
1903
----------------------------------- -- Area: Nashmau -- NPC: Awaheen -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade: Receive: -- 1 x Imperial Gold Piece (2187) 5 x Imperial Mythril Piece(2186) -- 1 x Imperial Mythril Piece(2186) 2 x Imperial Silver Piece(2185) -- 1 x Imperial Silver Piece (2185) 5 x Imperial Bronze Piece(2184) local nbr = 0; local reward = 0; if (trade:getItemCount() == 1) then if (trade:hasItemQty(2187,1)) then nbr = 5 ; reward = 2186; elseif (trade:hasItemQty(2186,1)) then nbr = 2 ; reward = 2185; elseif (trade:hasItemQty(2185,1)) then nbr = 5 ; reward = 2184; end end if (reward > 0) then local boucle; if (player:getFreeSlotsCount() >= 1) then player:tradeComplete(); player:addItem(reward,nbr); for boucle=1,nbr,1 do player:messageSpecial(ITEM_OBTAINED,reward); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00F0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Hostle/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/system.lua
78
2244
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.util") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) s = m:section(TypedSection, "system", "") s.anonymous = true s.addremove = false local sysinfo = luci.util.ubus("system", "info") or { } local boardinfo = luci.util.ubus("system", "board") or { } local uptime = sysinfo.uptime or 0 local loads = sysinfo.load or { 0, 0, 0 } local memory = sysinfo.memory or { total = 0, free = 0, buffered = 0, shared = 0 } s:option(DummyValue, "_system", translate("Model")).value = boardinfo.model or "?" s:option(DummyValue, "_cpu", translate("System")).value = boardinfo.system or "?" s:option(DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0) s:option(DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s)", tonumber(memory.total) / 1024 / 1024, 100 * memory.buffered / memory.total, tostring(translate("buffered")), 100 * memory.free / memory.total, tostring(translate("free")) ) s:option(DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("Hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
apache-2.0
TrurlMcByte/docker-prosody
etc/prosody-modules/mod_muc_access_control/mod_muc_access_control.lua
1
1783
local st = require "util.stanza"; local jid = require "util.jid"; local nodeprep = require "util.encodings".stringprep.nodeprep; local unprepped_access_lists = module:get_option("muc_access_lists", {}); local access_lists = {}; -- Make sure all input is prepped for unprepped_room_name, unprepped_list in pairs(unprepped_access_lists) do local prepped_room_name = nodeprep(unprepped_room_name); if not prepped_room_name then module:log("error", "Invalid room name: %s", unprepped_room_name); else local prepped_list = {}; for _, unprepped_jid in ipairs(unprepped_list) do local prepped_jid = jid.prep(jid); if not prepped_jid then module:log("error", "Invalid JID: %s", unprepped_jid); else table.insert(prepped_list, jid.pep(jid)); end end end end local function is_restricted(room, who) local allowed = access_lists[room]; if allowed == nil or allowed[who] or allowed[select(2, jid.split(who))] then return nil; end return "forbidden"; end module:hook("presence/full", function(event) local stanza = event.stanza; if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Leaving events get discarded return; end -- Get the room local room = jid.split(stanza.attr.to); if not room then return; end -- Get who has tried to join it local who = jid.bare(stanza.attr.from) -- Checking whether room is restricted local check_restricted = is_restricted(room, who) if check_restricted ~= nil then event.allowed = false; event.stanza.attr.type = 'error'; return event.origin.send(st.error_reply(event.stanza, "cancel", "forbidden", "You're not allowed to enter this room: " .. check_restricted)); end end, 10);
mit
DigitalPulseSoftware/NazaraEngine
xmake.lua
1
8843
local modules = { Audio = { Deps = {"NazaraCore"}, Packages = {"dr_wav", "libflac", "libvorbis", "minimp3"}, Custom = function () add_packages("openal-soft", {links = {}}) -- Don't link OpenAL (it will be loaded dynamically) end }, Core = { Custom = function () add_headerfiles("include/(Nazara/*.hpp)") -- NazaraMath is header-only, make it part of the core project add_headerfiles("include/(Nazara/Math/**.hpp)", "include/(Nazara/Math/**.inl)") if is_plat("windows", "mingw") then add_syslinks("ole32") elseif is_plat("linux") then add_syslinks("dl", "pthread", "uuid") end end, PublicPackages = { "nazarautils" } }, Graphics = { Deps = {"NazaraRenderer"}, Packages = {"entt"} }, Network = { Deps = {"NazaraCore"}, Custom = function() if is_plat("windows", "mingw") then add_syslinks("ws2_32") end if is_plat("linux") then remove_files("src/Nazara/Network/Posix/SocketPollerImpl.hpp") remove_files("src/Nazara/Network/Posix/SocketPollerImpl.cpp") end end }, OpenGLRenderer = { Deps = {"NazaraRenderer"}, Custom = function() if is_plat("windows", "mingw") then add_syslinks("gdi32", "user32") else remove_files("src/Nazara/OpenGLRenderer/Wrapper/Win32/**.cpp") remove_files("src/Nazara/OpenGLRenderer/Wrapper/WGL/**.cpp") end if is_plat("linux") then add_defines("EGL_NO_X11") else remove_files("src/Nazara/OpenGLRenderer/Wrapper/Linux/**.cpp") end end }, Physics2D = { Deps = {"NazaraUtility"}, Packages = {"entt", "chipmunk2d"} }, Physics3D = { Deps = {"NazaraUtility"}, Packages = {"entt", "newtondynamics"} }, Platform = { Deps = {"NazaraUtility"}, Packages = {"libsdl"}, Custom = function() if is_plat("windows", "mingw") then add_defines("SDL_VIDEO_DRIVER_WINDOWS=1") elseif is_plat("linux") then add_defines("SDL_VIDEO_DRIVER_X11=1") add_defines("SDL_VIDEO_DRIVER_WAYLAND=1") elseif is_plat("macosx") then add_defines("SDL_VIDEO_DRIVER_COCOA=1") add_packages("libx11", { links = {} }) -- we only need X11 headers end end }, Renderer = { Deps = {"NazaraPlatform"}, PublicPackages = { "nazarautils", "nzsl" } }, Utility = { Deps = {"NazaraCore"}, Packages = {"entt", "freetype", "frozen", "ordered_map", "stb"} }, VulkanRenderer = { Deps = {"NazaraRenderer"}, Custom = function() add_defines("VK_NO_PROTOTYPES") if is_plat("windows", "mingw") then add_defines("VK_USE_PLATFORM_WIN32_KHR") add_syslinks("user32") elseif is_plat("linux") then add_defines("VK_USE_PLATFORM_XLIB_KHR") add_defines("VK_USE_PLATFORM_WAYLAND_KHR") elseif is_plat("macosx") then add_defines("VK_USE_PLATFORM_METAL_EXT") add_files("src/Nazara/VulkanRenderer/**.mm") add_frameworks("quartzcore", "AppKit") end end }, Widgets = { Deps = {"NazaraGraphics"}, Packages = {"entt", "kiwisolver"} } } NazaraModules = modules includes("xmake/**.lua") option("compile-shaders") set_default(true) set_showmenu(true) set_description("Compile nzsl shaders into an includable binary version") option_end() option("embed-resources") set_default(true) set_showmenu(true) set_description("Turn builtin resources into includable headers") option_end() option("usepch") set_default(false) set_showmenu(true) set_description("Use precompiled headers to speedup compilation") option_end() option("unitybuild") set_default(false) set_showmenu(true) set_description("Build the engine using unity build") option_end() set_project("NazaraEngine") set_xmakever("2.6.3") add_requires("chipmunk2d", "dr_wav", "efsw", "entt >=3.9", "fmt", "frozen", "kiwisolver", "libflac", "libsdl", "minimp3", "ordered_map", "stb") add_requires("freetype", { configs = { bzip2 = true, png = true, woff2 = true, zlib = true, debug = is_mode("debug") } }) add_requires("libvorbis", { configs = { with_vorbisenc = false } }) add_requires("openal-soft", { configs = { shared = true }}) add_requires("newtondynamics", { debug = is_plat("windows") and is_mode("debug") }) -- Newton doesn't like compiling in Debug on Linux add_repositories("nazara-engine-repo https://github.com/NazaraEngine/xmake-repo") add_requires("nazarautils", "nzsl", { debug = is_mode("debug") }) if is_plat("macosx") then add_requires("libx11") end add_rules("mode.asan", "mode.coverage", "mode.debug", "mode.releasedbg") add_rules("plugin.vsxmake.autoupdate") add_rules("build.rendererplugins") add_rules("download.assets.examples") if has_config("tests") then add_rules("download.assets.tests") end set_allowedplats("windows", "mingw", "linux", "macosx") set_allowedarchs("windows|x64", "mingw|x86_64", "linux|x86_64", "macosx|x86_64") set_allowedmodes("debug", "releasedbg", "asan", "coverage") set_defaultmode("debug") if is_mode("debug") then add_rules("debug.suffix") elseif is_mode("asan") then set_optimize("none") -- by default xmake will optimize asan builds elseif is_mode("coverage") then if not is_plat("windows") then add_links("gcov") end elseif is_mode("releasedbg") then set_fpmodels("fast") add_vectorexts("sse", "sse2", "sse3", "ssse3") end add_includedirs("include") add_sysincludedirs("thirdparty/include") set_languages("c89", "cxx17") set_rundir("./bin/$(plat)_$(arch)_$(mode)") set_symbols("debug", "hidden") set_targetdir("./bin/$(plat)_$(arch)_$(mode)") set_warnings("allextra") if is_mode("debug") then add_defines("NAZARA_DEBUG") end if is_plat("windows") then set_runtimes(is_mode("debug") and "MDd" or "MD") add_defines("_CRT_SECURE_NO_WARNINGS") add_cxxflags("/bigobj", "/permissive-", "/Zc:__cplusplus", "/Zc:externConstexpr", "/Zc:inline", "/Zc:lambda", "/Zc:preprocessor", "/Zc:referenceBinding", "/Zc:strictStrings", "/Zc:throwingNew") add_cxflags("/w44062") -- Enable warning: switch case not handled add_cxflags("/wd4251") -- Disable warning: class needs to have dll-interface to be used by clients of class blah blah blah add_cxflags("/wd4275") -- Disable warning: DLL-interface class 'class_1' used as base for DLL-interface blah elseif is_plat("mingw") then add_cxflags("-Og", "-Wa,-mbig-obj") add_ldflags("-Wa,-mbig-obj") end for name, module in pairs(modules) do target("Nazara" .. name) set_kind("shared") set_group("Modules") add_rpathdirs("$ORIGIN") if module.Deps then add_deps(table.unpack(module.Deps)) end if module.Packages then add_packages(table.unpack(module.Packages)) end if module.PublicPackages then for _, pkg in ipairs(module.PublicPackages) do add_packages(pkg, { public = true }) end end if module.Custom then module.Custom() end if has_config("usepch") then set_pcxxheader("include/Nazara/" .. name .. ".hpp") end if has_config("unitybuild") then add_defines("NAZARA_UNITY_BUILD") add_rules("c++.unity_build", {uniqueid = "NAZARA_UNITY_ID", batchsize = 12}) end add_defines("NAZARA_BUILD") add_defines("NAZARA_" .. name:upper() .. "_BUILD") add_defines("NAZARA_UTILS_WINDOWS_NT6=1") if is_mode("debug") then add_defines("NAZARA_" .. name:upper() .. "_DEBUG") end -- Add header and source files local headerExts = {".h", ".hpp", ".inl", ".natvis"} for _, ext in ipairs(headerExts) do add_headerfiles("include/(Nazara/" .. name .. "/**" .. ext .. ")") add_headerfiles("src/Nazara/" .. name .. "/**" .. ext) end add_files("src/Nazara/" .. name .. "/**.cpp") add_includedirs("src") if has_config("embed-resources") then local embedResourceRule = false for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**|**.h|**.nzsl|**.nzslb")) do if not embedResourceRule then add_rules("embed.resources") embedResourceRule = true end add_files(filepath, {rule = "embed.resources"}) end end if has_config("compile-shaders") then local compileShaderRule = false for _, filepath in pairs(os.files("src/Nazara/" .. name .. "/Resources/**.nzsl")) do if not compileShaderRule then add_rules("nzsl.compile.shaders") compileShaderRule = true end add_files(filepath, {rule = "nzsl.compile.shaders"}) end end -- Remove platform-specific files if is_plat("windows", "mingw") then for _, ext in ipairs(headerExts) do remove_headerfiles("src/Nazara/" .. name .. "/Posix/**" .. ext) end remove_files("src/Nazara/" .. name .. "/Posix/**.cpp") else for _, ext in ipairs(headerExts) do remove_headerfiles("src/Nazara/" .. name .. "/Posix/**" .. ext) end remove_files("src/Nazara/" .. name .. "/Win32/**.cpp") end if not is_plat("linux") then for _, ext in ipairs(headerExts) do remove_headerfiles("src/Nazara/" .. name .. "/Linux/**" .. ext) end remove_files("src/Nazara/" .. name .. "/Linux/**.cpp") end end includes("tools/*.lua") includes("tests/*.lua") includes("plugins/*/xmake.lua") includes("examples/*/xmake.lua")
mit
Snazz2001/fbcunn
test/test_OneBitDataParallel.lua
9
3011
require('fb.luaunit') require('fbtorch') require('fbcunn') require('fbnn') local TU = require('test.test_Util') local fboptim = require('fboptim') local function dp() return nn.OneBitDataParallel( 1, {momentum_rate=1.0, adagrad_learning_rate=1.0, min_elements=20} ) end function testDataParallelRunsForwardPass() local sim = TU.Sim { num_hidden = 2, output_width = 1, hidden_width = 512, input_width = 32, num_columns = 4, } local model, columns = sim:build_data_parallel(dp()) local inputs, _ = sim:gen_wide_example() local outputs = model:forward(inputs) for column_id = 1, sim.opts.num_columns do local column_input = sim:get_narrowed_input(inputs, column_id):double() print(column_input:size()) local gpu_output = outputs[{ {column_id} }] local cpu_output = columns[column_id]:forward(column_input) local norm_delta = TU.tensor_norm_difference(gpu_output, cpu_output) print(column_input:size(), gpu_output:size(), cpu_output:size()) print(gpu_output:norm(), cpu_output:norm()) assertTrue(norm_delta < 1E-5) end end function testDataParallelOnForwardPassIsEquivalentToSeparateColumns() local sim = TU.Sim { num_hidden = 2, output_width = 1, hidden_width = 512, input_width = 32, num_columns = 4, } local model, columns = sim:build_data_parallel(dp()) local inputs, _ = sim:gen_wide_example() local outputs = model:forward(inputs) for column_id = 1, sim.opts.num_columns do local column_input = sim:get_narrowed_input(inputs, column_id):double() print(column_input:size()) local gpu_output = outputs[{ {column_id} }] local cpu_output = columns[column_id]:forward(column_input) local norm_delta = TU.tensor_norm_difference(gpu_output, cpu_output) print(column_input:size(), gpu_output:size(), cpu_output:size()) print(gpu_output:norm(), cpu_output:norm()) assertTrue(norm_delta < 1E-5) end end function testDataParallelOnOptimLearns() local sim = TU.Sim { num_hidden = 1, output_width = 1, hidden_width = 500, input_width = 5, num_columns = 4, num_opt_rounds = 2, } local optim_state = { learningRate = 1e-1, weightDecay = 1e-4, momentum = 0.9, learningRateDecay = 1e-7 } local model, _columns = sim:build_data_parallel(dp()) local opt = nn.Optim(model, optim_state) local criterion = nn.MSECriterion():cuda() for round = 1,sim.opts.num_opt_rounds do local inputs, targets = sim:gen_wide_example() local _outputs = model:forward(inputs) opt:optimize(fboptim.sgd, inputs, targets, criterion) local out = model:forward(inputs) print(out) local err = criterion:forward(out, targets) print(round, err) end end LuaUnit:main()
bsd-3-clause
neechbear/colloquy
src/lists.lua
1
42679
-- lists -- table layout: -- -- lists[listname] = { -- listname = "capitalised list name", -- description = "description of the list", -- owner = "who owns this list, and is always a list master", -- created = "when this list was created", -- flags = "flags - O = open, L = locked, P = permanent, A = anonymous", -- members = { -- "bob", -- "god", -- "foo" -- }, -- masters = { -- "bob", -- "god" -- } -- used = time since the epoch that the list was last used. -- } lists = { masters = { listname = "Masters", description = "Talker administration", flags = "OLP", owner = "god", created = date("%a %b %d %H:%M:%S %Z %Y"), members = { "god" }, masters = {} } } function numberOfListsOwned(username) local username = strlower(username) local t = 0; for i, v in lists do if ( v.owner == username and not strfind(v.flags, "P") ) then t = t + 1; end; end; return t; end; function searchForUser(realName) -- searches for a user with realName local l, i, v = strlower(realName); for i, v in colloquy.connections do if (v.realUser and l == strlower(v.realUser)) then return v; end; end; return nil; end; function isListMaster(listname, username) listname = strlower(listname); username = strlower(username); local l = lists[listname]; if l.owner == username or strfind((connection(username).privs or ""), "M", 1, 1) then return 1; end for i, v in (l.masters or {}) do if v == username then return 1; end; end; return nil; end function getListMembers(listname, talking) local r, i, v = {}; for i, v in lists[listname].members do if (i ~= "n") then local bing = searchForUser(v); if (type(bing) == "table") then if (talking) then if (not listHasPaused(bing, listname)) then tinsert(r, bing); end; else tinsert(r, bing); end; end; end; end; return r; end; function listIsMember(user, list, real) local m, l, i, v = strlower(user), strlower(list); if (not lists[list]) then return nil end; if (not real and strfind(lists[list].flags, "O", 1, 1)) then return 0 end; for i, v in lists[l].members do if (type(v) == "string" and v == m) then return i end; end; return nil; end; function listByName(conn, list, talk) local found, i, v = {}; local luser = strlower(conn.realUser); local llist = strlower(list); if (lists[llist] ~= nil ) then return llist; end; for i, v in lists do if (type(v) == "table") then if (strfind(i, llist, 1, 1) == 1) then if (listIsMember(luser, i) or not talk) then tinsert(found, i); end; end; end; end; for i, v in found do if (v == llist) then return v; end; end; if (getn(found) == 0) then if (lists[llist] ~= nil ) then return llist; end; return nil, "That list does not exist!"; end; if (getn(found) > 1) then local r = list .. " is ambiguous - matches "; for i, v in found do if (type(v) == "string") then r = r .. lists[v].listname .. ", "; end; end; r = strsub(r, 1, -3) .. "."; return nil, r; end; return found[1]; end; function commandListTell(connection, line, params) local p = split(params); local conn = colloquy.connections[connection]; if (p[1] == nil or p[2] == nil) then send("Whispering nothing to a list is silly.", colloquy.connections[connection], S_ERROR); return nil; end; local l = strlower(p[1]); local l, err = listByName(conn, l, 1); if (l == nil) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("No such list.", conn, S_ERROR); return nil; end; if (not listIsMember(conn.realUser, l) and not strfind(conn.privs or "", "M", 1, 1)) then send("You are not a member of that list, and it is not open!", conn, S_ERROR); return nil; end; if (strfind(lists[l].flags, "R", 1, 1)) then -- the list is read-only. Check if they're the owner, or a master. if not isListMaster(l, conn.realUser) then send("That list is read-only.", conn, S_ERROR); return nil; end; end; if (listHasPaused(conn, lists[l].listname)) then listUnpause(conn, l); end; local m = getListMembers(l, 1); local t = strsub(line, strfind(line, p[1], 1, 1) + strlen(p[1]) + 1, strlen(line)); local a = conn.username .. strrep(" ", 11); a = strsub(a, 1, 12) .. "%" .. t .. " {" .. lists[l].listname .. "}"; sendTo(a, m, S_LISTTALK); if (not listIsMember(conn.realUser, l, 1)) then send(format("Whispered to list %s: '%s'", lists[l].listname, t), conn, S_DONETELL); end; lists[l].used = secs; end; function commandListEmote(connection, line, params) local p = split(params); local conn = colloquy.connections[connection]; if (p[1] == nil or p[2] == nil) then send("Whispering nothing to a list is silly.", colloquy.connections[connection], S_ERROR); return nil; end; local l = strlower(p[1]); local l, err = listByName(conn, l, 1); if (l == nil) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("No such list.", colloquy.connections[connection], S_ERROR); return nil; end; if (not listIsMember(conn.realUser, l) and not strfind(conn.privs, "M", 1, 1)) then send("You are not a member of that list, and it is not open!", conn, S_ERROR); return nil; end; if (strfind(lists[l].flags, "R", 1, 1)) then -- the list is read-only. Check if they're the owner, or a master. if not isListMaster(l, conn.realUser) then send("That list is read-only.", conn, S_ERROR); return nil; end; end; if (listHasPaused(conn, lists[l].listname)) then listUnpause(conn, l); end; local m = getListMembers(l, 1); local t = strsub(line, strfind(line, p[1], 1, 1) + strlen(p[1]) + 1, strlen(line)); local blah = " "; if (strfind(punctuation, strsub(t, 1, 1), 1, 1)) then blah = ""; end; sendTo(format("%% %s%s%s {%s}", colloquy.connections[connection].username, blah, t, lists[l].listname) , m, S_LISTEMOTE); if (not listIsMember(conn.realUser, l, 1)) then send(format("REmote'd to list %s: '%s%s%s'", lists[l].listname, conn.username, blah, t), conn, S_DONETELL); end; lists[l].used = secs; end; function commandList(connection, line, params) local conn = colloquy.connections[connection]; local p = split(params); if (p[1] == nil) then send("Usage: .list <command> <parameters...>", conn, S_ERROR); return nil; end; if (p[1] == "info") then if (p[2] == nil) then return commandLists(connection, ".lists", ""); else listInfo(conn, p[2]); return nil; end; end; if (p[1] == "create") then if (p[2] == nil) then send("Usage: .list create <listname>", conn, S_ERROR); return nil; else listCreate(conn, p[2]); return nil; end; end; if (p[1] == "delete") then if (p[2] == nil) then send("Usage: .list delete <listname>", conn, S_ERROR); return nil; else listDelete(conn, p[2]); return nil; end; end; if (p[1] == "join") then if (p[2] == nil) then send("Usage: .list join <listname>", conn, S_ERROR); return nil; else listJoin(conn, p[2]); return nil; end; end; if (p[1] == "leave") then if (p[2] == nil) then send("Usage: .list leave <listname>", conn, S_ERROR); return nil; else listLeave(conn, p[2]); return nil; end; end; if (p[1] == "invite") then if (p[2] == nil or p[3] == nil) then send("Usage: .list invite <listname> <username>", conn, S_ERROR); return nil; else listInvite(conn, p[2], p[3]); return nil; end; end; if (p[1] == "owner") then if (p[2] == nil or p[3] == nil) then send("Usage: .list owner <listname> <username>", conn, S_ERROR); return nil; else listOwner(conn, p[2], p[3]); return nil; end; end; if (p[1] == "description") then if (p[2] == nil or p[3] == nil) then send("Usage: .list description <listname> <description>", conn, S_ERROR); return nil; else listDescription(conn, p[2], strsub(params, strfind(params, p[2], 1, 1) + strlen(p[2]) + 1, -1)); return nil; end; end; if (p[1] == "lock") then if (p[2] == nil) then send("Usage: .list lock <listname>", conn, S_ERROR); return nil; else listLock(conn, p[2]); return nil; end; end; if (p[1] == "unlock") then if (p[2] == nil) then send("Usage: .list unlock <listname>", conn, S_ERROR); return nil; else listUnlock(conn, p[2]); return nil; end; end; if (p[1] == "evict") then if (not p[2] or not p[3]) then send("Usage: .list evict <listname> <username>", conn, S_ERROR); return nil; else listEvict(conn, p[2], p[3]); return nil; end; end; if (p[1] == "open") then if (not p[2]) then send("Usage: .list open <listname>", conn, S_ERROR); return nil; else listOpen(conn, p[2]); return nil; end; end; if (p[1] == "close") then if (not p[2]) then send("Usage: .list close <listname>", conn, S_ERROR); return nil; else listClose(conn, p[2]); return nil; end; end; if (p[1] == "pause") then listPause(conn, p[2]); return nil; end; if (p[1] == "unpause") then listUnpause(conn, p[2]); return nil; end; if (p[1] == "permanent") then if not p[2] then send("Usage: .list permanent <listname>", conn, S_ERROR); return nil; end; listPermanent(conn, p[2]); return nil; end; if (p[1] == "unpermanent") then if not p[2] then send("Usage: .list unpermanent <listname>", conn, S_ERROR); return nil; end; listUnpermanent(conn, p[2]); return nil; end; if (p[1] == "anonymous") then if not p[2] then send("Usage: .list anonymous <listname>", conn, S_ERROR); return nil; end; listAnonymous(conn, p[2]); return nil; end; if (p[1] == "unanonymous") then if not p[2] then send("Usage: .list unanonymous <listname>", conn, S_ERROR); return nil; end; listUnanonymous(conn, p[2]); return nil; end; if (p[1] == "readonly") then if not p[2] then send("Usage: .list readonly <listname>", conn, S_ERROR); return nil; end; listReadOnly(conn, p[2]); return nil; end; if (p[1] == "readwrite") then if not p[2] then send("Usage: .list readwrite <listname>", conn, S_ERROR); return nil; end listReadWrite(conn, p[2]); return nil; end; if (p[1] == "master") then if (not p[2] or not p[3]) then send("Usage: .list master <listname> <username>", conn, S_ERROR); return nil; else listMaster(conn, p[2], p[3]); return nil; end; end; if (p[1] == "unmaster") then if (not p[2] or not p[3]) then send("Usage: .list unmaster <listname> <username>", conn, S_ERROR); return nil; else listUnmaster(conn, p[2], p[3]); return nil; end; end; if (p[1] == "rename") then listRename(conn, p[2], p[3]); return nil; end; send("Unknown .list command.", conn, S_ERROR); end; function listMember(list, user) -- returns a * if user is a member of list, or " " otherwise. if (lists[strlower(list)] == nil) then return " " end; local m, i, v = lists[strlower(list)].members; for i, v in m do if (type(v) == "string" and v == user) then return "*"; end; end; return " "; end; function commandLists(connection, line, params) local p = split(params); local conn = colloquy.connections[connection]; if (p[1]) then listInfo(conn, p[1]); return nil; end; local sortedLists = {}; local i, v; local u = strlower(conn.realUser); local t = 0; for i, v in lists do if (type(v) == "table" and strfind(v.flags, "L", 1, 1)) then tinsert(sortedLists, v.listname); end; end; t = getn(sortedLists); if (getn(sortedLists) > 0) then send("Available locked lists are: ('*' marks ones currently subscribed to)", conn, S_LISTSHDR); sort(sortedLists); for i, v in sortedLists do if (type(v) == "string") then sortedLists[i] = listMember(v, u) .. v; end; end; local rl = columns(sortedLists, (conn.width-6)/17, 17); for i=1,getn(rl) do send(" " .. rl[i], conn, S_LISTS); end; end; sortedLists = {}; for i, v in lists do if (type(v) == "table" and not strfind(v.flags, "L", 1, 1)) then tinsert(sortedLists, v.listname); end; end; t = t + getn(sortedLists); if (getn(sortedLists) > 0) then send("Available unlocked lists are: ('*' marks ones currently subscribed to)", conn, S_LISTSHDR); sort(sortedLists); for i, v in sortedLists do if (type(v) == "string") then sortedLists[i] = listMember(v, u) .. v; end; end; local rl = columns(sortedLists, (conn.width-6)/17, 17); for i=1,getn(rl) do send(" " .. rl[i], conn, S_LISTS); end; end; if (t == 0) then send("There are no lists.", conn, S_ERROR); else send(tostring(t) .. " total.", conn, S_DONE); end; end; function listInfo(conn, params) local l = strlower(params); local l, err = listByName(conn, l); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("This list does not exist!", conn, S_ERROR); return nil; end; send(format("%-15.15s %s", "Name:", lists[l].listname), conn, S_LISTINFO); if (lists[l].description ~= "") then send(format("%-15.15s %s", "Description:", lists[l].description), conn, S_LISTINFO); end; if (lists[l].flags ~= "" and lists[l].flags ~= nil) then local f = lists[l].flags; f = gsub(f, "A", "Anonymous "); f = gsub(f, "L", "Locked "); f = gsub(f, "O", "Open "); f = gsub(f, "P", "Permanent "); f = gsub(f, "R", "Read-Only "); send(format("%-15.15s %s", "Flags:", f), conn, S_LISTINFO); end; send(format("%-15.15s %s", "Created:", lists[l].created), conn, S_LISTINFO); send(format("%-15.15s %s", "Owner:", lists[l].owner), conn, S_LISTINFO); local on, off = "", ""; local i, v; if not strfind(lists[l].flags, "A", 1, 1) then for i, v in lists[l].members do if (type(v) == "string") then local vconn = connection(v); local lmaster; if (vconn) then lmaster = isListMaster(l, vconn.realUser); local pconn = listHasPaused(vconn, lists[l].listname); if lmaster then on = on .. "*"; end if (pconn) then on = on .. "(" .. v .. ") "; elseif (vconn.veryIdle) then on = on .. "[" .. v .. "] "; else on = on .. v .. " "; end; else if lmaster then off = off .. "*"; end; off = off .. v .. " "; end; end; end; end; if (lists[l].used) then send(format("%-15.15s %s", "Last used:", strsub(timeToString(secs - lists[l].used), 1, -2) .. " ago."), conn, S_LISTINFO); end; if (on ~= "") then send(format("%-15.15s %s", "Users online:", on), conn, S_LISTINFO); end; if (off ~= "") then send(format("%-15.15s %s", "Users offline:", off), conn, S_LISTINFO); end; end; function listCreate(conn, params) local l = strlower(params); if (lists[l] ~= nil) then send("That list already exists!", conn, S_ERROR); return nil; end; if ( numberOfListsOwned(conn.realUser) >= colloquy.listQuota ) then send("You have exhausted your list quota. Either delete some old lists, or ask a master to make some of them permanent.", conn, S_ERROR); return nil; end; if (strlen(gsub(l, "[%w%-]", "")) > 0 or (strlen(params) > 15)) then send("That isn't a valid list name.", conn, S_ERROR); return nil; end; lists[l] = { listname = params, description = "", flags = "", owner = strlower(conn.realUser), created = date("%a %b %e %H:%M:%S %Y"), members = { strlower(conn.realUser) } }; saveOneList(l); send("List created.", conn, S_DONE); end; function listDelete(conn, params) local l = strlower(params); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if ((strlower(conn.realUser) ~= lists[l].owner) and (conn.privs == nil or strfind(conn.privs, "M", 1, 1) == nil)) then send("You cannot delete a list you do not own.", conn, S_ERROR); return nil; end; updateInvitations("%" .. l, ""); sendTo(format("%s has deleted the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTDELETE); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has deleted the list. {%s}", conn.username, lists[l].listname), conn, S_LISTDELETE); end; lists[l] = nil; remove(colloquy.lists .. "/" .. l) end; function listJoin(conn, params) local l = strlower(params); local l, err = listByName(conn, l); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; local u, i, v = strlower(conn.realUser); for i, v in lists[l].members do if (type(v) == "string" and v == u) then send("You are already a member of that list.", conn, S_ERROR); return nil; end; end; if (lists[l].flags and strfind(lists[l].flags, "L", 1, 1) and (not checkInvitation(conn, "%" .. l))) then if ( not (conn.privs and strfind(conn.privs, "M", 1, 1))) then send("That list is locked.", conn, S_ERROR); return nil; end; end; tinsert(lists[l].members, u); removeInvitation(conn, "%" .. l); if strfind(lists[l].flags, "A", 1, 1) then -- this list is anonymous. Don't tell the list that this person has joined. send(format("You have joined the list anonymously. {%s}", lists[l].listname), conn, S_LISTJOIN); else sendTo(format("%s has joined the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTJOIN); end; saveOneList(l); end; function listLeave(conn, params) local l = strlower(params); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if (lists[l].owner == strlower(conn.realUser)) then send("You cannot leave a list you own.", conn, S_ERROR); return nil; end; local u, i, v = strlower(conn.realUser); for i, v in lists[l].members do if (type(v) == "string" and v == u) then if strfind(lists[l].flags, "A", 1, 1) then -- this list is anonymous. Don't tell the list that this person has left. send(format("You have left the list anonymously. {%s}", lists[l].listname), conn, S_LISTLEAVE); else sendTo(format("%s has left the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTLEAVE); end; tremove(lists[l].members, i); saveOneList(l); return nil; end; end; send("You are not a member of that list.", conn, S_ERROR); end; function listInvite(conn, list, user) local l = strlower(list); local u = userByName(user); local master; -- is this a master override? local l, err = listByName(conn, l); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if (u == nil) then send("No such user.", conn, S_ERROR); return nil; end; if (type(u) == "string") then send(u, conn, S_ERROR); return nil; end; if (lists[l].flags and strfind(lists[l].flags, "L", 1, 1) and (not strfind(conn.privs or "", "M", 1, 1))) then local m, i, v, f; m = strlower(conn.realUser); for i, v in lists[l].members do if (type(v) == "string" and v == m) then f = 1; break; end; end; if (f ~= 1) then send("Only list members can invite users to locked lists.", conn, S_ERROR); return nil; end; end; local n = strlower(u.realUser); local f = nil; local un = strlower(conn.realUser); local m, i, v = lists[l].members; for i, v in m do if (type(v) == "string" and v == n) then send("User is already a member.", conn, S_ERROR); return nil; end; if (v == un) then f = 1; end; end; addInvitation(u, "%" .. l); if strfind(lists[l].flags, "A", 1, 1) then -- this list is anonymous. Don't tell the whole list about it. send(format("You invite %s to the list anonymously. {%s}", u.username, lists[l].listname), conn, S_LISTINVITE); else sendTo(format("%s invites %s to the list. {%s}", conn.username, u.username, lists[l].listname), getListMembers(l), S_LISTINVITE); end; if (not listIsMember(conn.realUser, l, 1)) then if strfind(lists[l].flags, "A", 1, 1) then send(format("You invite %s to the list anonymously. {%s}", u.username, lists[l].listname), conn, S_LISTINVITE); else send(format("%s invites %s to the list. {%s}", conn.username, u.username, lists[l].listname), conn, S_LISTINVITE); end; end; local an = ""; if strfind(lists[l].flags, "A", 1, 1) then an = " anonymously" end; send(format("%s invites you to %%%s%s. To respond, type .list join %s", conn.username, lists[l].listname, an, lists[l].listname), u, S_LISTINVITE); end; function listOwner(conn, list, user) local l = strlower(list); local u = userByName(user); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if (u == nil) then send("No such user.", conn, S_ERROR); return nil; end; if (type(u) == "string") then send(u, conn, S_ERROR); return nil; end; if (lists[l].owner ~= strlower(conn.realUser)) then if (not (conn.privs and strfind(conn.privs, "M", 1, 1))) then send("You cannot change the owner of lists you do not own.", conn, S_ERROR); return nil; end; end; local n = strlower(u.realUser); if ( numberOfListsOwned(n) >= colloquy.listQuota ) then send(format("%s has exhausted their list quota, and cannot take ownership.", u.username), conn, S_ERROR); return nil; end; local m, i, v = lists[l].members; for i, v in m do if (type(v) == "string" and (v == n)) then sendTo(format("%s makes %s the list owner. {%s}", conn.username, u.username, lists[l].listname), getListMembers(l), S_LISTOWNER); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s makes %s the list owner. {%s}", conn.username, u.username, lists[l].listname), conn, S_LISTOWNER); end; lists[l].owner = n; saveOneList(l); return nil; end; end; send("Only a list's members can be made the owner.", conn, S_ERROR); end; function listDescription(conn, list, desc) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot change the descriptions of lists you are not a master of.", conn, S_ERROR); return nil; end; lists[l].description = desc; sendTo(format("%s has changed the list's description to '%s'. {%s}", conn.username, desc, lists[l].listname), getListMembers(l), S_LISTDESC); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has changed the list's description to '%s'. {%s}", conn.username, desc, lists[l].listname), conn, S_LISTDESC); end; saveOneList(l); end; function listLock(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot lock lists that you are not a master of.", conn, S_ERROR); end; if (lists[l].flags and (strfind(lists[l].flags, "L", 1, 1))) then send("That list is already locked.", conn, S_ERROR); return nil; end; if (not lists[l].flags) then lists[l].flags = "" end; lists[l].flags = lists[l].flags .. "L"; sendTo(format("%s has locked the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTLOCK); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has locked the list. {%s}", conn.username, lists[l].listname), conn, S_LISTLOCK); end; saveOneList(l); end; function listUnlock(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot unlock lists that you are not a master of.", conn, S_ERROR); return nil; end; if (lists[l].flags and (not strfind(lists[l].flags, "L", 1, 1))) then send("That list is already unlocked.", conn, S_ERROR); return nil; end; if (not lists[l].flags) then lists[l].flags = "" end; lists[l].flags = gsub(lists[l].flags, "L", ""); updateInvitations("%" .. l, ""); sendTo(format("%s has unlocked the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTUNLOCK); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has unlocked the list. {%s}", conn.username, lists[l].listname), conn, S_LISTUNLOCK); end; saveOneList(l); end; function listEvict(conn, list, user) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (lists[l] == nil) then send("That list does not exist!", conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot evict users from lists you are not a master of.", conn, S_ERROR); return nil; end; local m, i, v; m = userByName(user); if (m == nil) then send("No such user.", conn, S_ERROR); return nil; end; if (type(m) == "string") then send(m, conn, S_ERROR); return nil; end; local mm = strlower(m.username); if (mm == lists[l].owner) then send("You cannot evict the list owner.", conn, S_ERROR); return nil; end; for i, v in lists[l].members do if (type(v) == "string" and v == mm) then sendTo(format("%s has evicted %s from the list. {%s}", conn.username, m.username, lists[l].listname), getListMembers(l), S_LISTEVICT); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has evicted %s from the list. {%s}", conn.username, m.username, lists[l].listname), conn, S_LISTEVICT); end; tremove(lists[l].members, i); saveOneList(l); return nil; end; end; send("User isn't on that list.", conn, S_ERROR); end; function listOpen(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot open a list that you are not a master of.", conn, S_ERROR); return nil; end; if (strfind(lists[l].flags, "O", 1, 1)) then send("That list is already open!", conn, S_ERROR); return nil; end; lists[l].flags = lists[l].flags .. "O"; sendTo(format("%s has opened the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTOPEN); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has opened the list. {%s}", conn.username, lists[l].listname), conn, S_LISTOPEN); end; saveOneList(l); end; function listPermanent(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (not (conn.privs and strfind(conn.privs, "M", 1, 1))) then send("Only masters can do that.", conn, S_ERROR); return nil; end; if (strfind(lists[l].flags, "P", 1, 1)) then send("That list is already permanent!", conn, S_ERROR); return nil; end; lists[l].flags = lists[l].flags .. "P"; sendTo(format("%s has made the list permanent. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTPERM); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has made the list permanent. {%s}", conn.username, lists[l].listname), conn, S_LISTPERM); end; saveOneList(1); end; function listUnpermanent(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (not (conn.privs and strfind(conn.privs, "M", 1, 1))) then send("Only masters can do that.", conn, S_ERROR); return nil; end; if (not strfind(lists[l].flags, "P", 1, 1)) then send("That list isn't permanent!", conn, S_ERROR); return nil; end; lists[l].flags = gsub(lists[l].flags, "P", ""); sendTo(format("%s has made the list non-permanent. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTUNPERM); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has made the list non-permanent. {%s}", conn.username, lists[l].listname), conn, S_LISTUNPERM); end; saveOneList(l); end; function listAnonymous(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (not (conn.privs and strfind(conn.privs, "M", 1, 1))) then send("Only masters can do that.", conn, S_ERROR); return nil; end; if (strfind(lists[l].flags, "A", 1, 1)) then send("That list is already anonymous!", conn, S_ERROR); return nil; end; lists[l].flags = lists[l].flags .. "A"; sendTo(format("%s has made the list anonymous. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTANON); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has made the list anonymous. {%s}", conn.username, lists[l].listname), conn, S_LISTANON); end; saveOneList(l); end; function listUnanonymous(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if (not (conn.privs and strfind(conn.privs, "M", 1, 1))) then send("Only masters can do that.", conn, S_ERROR); return nil; end; if (not strfind(lists[l].flags, "A", 1, 1)) then send("That list isn't anonymous!", conn, S_ERROR); return nil; end; lists[l].flags = gsub(lists[l].flags, "A", ""); sendTo(format("%s has made the list non-anonymous. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTUNANON); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has made the list non-anonymous. {%s}", conn.username, lists[l].listname), conn, S_LISTUNANON); end; saveOneList(l); end; function listReadOnly(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot make a list read-only that you are not a master of.", conn, S_ERROR); return nil; end; if (strfind(lists[l].flags, "R", 1, 1)) then send("That list is already read-only!", conn, S_ERROR); return nil; end; lists[l].flags = lists[l].flags .. "R"; sendTo(format("%s has made the list read-only. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTREAD); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has made the list read-only. {%s}", conn.username, lists[l].listname), conn, S_LISTREAD); end; saveOneList(l); end; function listReadWrite(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot make a list read-write that you are not a master of.", conn, S_ERROR); return nil; end; if (not strfind(lists[l].flags, "R", 1, 1)) then send("That list isn't read-only!", conn, S_ERROR); return nil; end; lists[l].flags = gsub(lists[l].flags, "R", ""); sendTo(format("%s has made the list read-write. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTUNREAD); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has made the list read-write. {%s}", conn.username, lists[l].listname), conn, S_LISTUNREAD); end; saveOneList(l); end; function listClose(conn, list) local l = strlower(list); local l, err = listByName(conn, l, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot close a list that you are not a master of.", conn, S_ERROR); return nil; end; if (not strfind(lists[l].flags, "O", 1, 1)) then send("That list is already closed!", conn, S_ERROR); return nil; end; lists[l].flags = gsub(lists[l].flags, "O", ""); sendTo(format("%s has closed the list. {%s}", conn.username, lists[l].listname), getListMembers(l), S_LISTCLOSE); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has closed the list. {%s}", conn.username, lists[l].listname), conn, S_LISTCLOSE); end; saveOneList(l); end; function listPause(conn, list) if (not list) then if (not conn.pausedLists) then send("You have no paused lists.", conn, S_DONE); return nil; else send("Paused lists: " .. conn.pausedLists, conn, S_DONE); end; return nil; end; local llist = strlower(list); local rlist, err = listByName(conn, list); if (not rlist) then send(err, conn, S_ERROR); return nil; end; if (not listIsMember(conn.realUser, rlist)) then send("You cannot pause lists you are not a member of.", conn, S_ERROR); return nil; end; rlist = lists[rlist].listname; if (conn.pausedLists and strfind(conn.pausedLists, rlist .. " ", 1, 1)) then send("You already have that list paused!", conn, S_ERROR); return nil; end; if (not conn.pausedLists) then conn.pausedLists = ""; end; conn.pausedLists = conn.pausedLists .. rlist .. " "; send("Paused list " .. rlist .. ".", conn, S_DONE); end; function listUnpause(conn, list) if (not list) then if (not conn.pausedLists) then send("You have no paused lists.", conn, S_DONE); return nil; else send("Paused lists: " .. conn.pausedLists, conn, S_DONE); end; return nil; end; local llist = strlower(list); local rlist, err = listByName(conn, list); if (not rlist) then send(err, conn, S_ERROR); return nil; end; if (not listIsMember(conn.realUser, rlist)) then send("You cannot unpause lists you are not a member of.", conn, S_ERROR); return nil; end; rlist = lists[rlist].listname; if (not conn.pausedLists or not strfind(conn.pausedLists, rlist .. " ", 1, 1)) then send("You do not have that list paused!", conn, S_ERROR); return nil; end; conn.pausedLists = gsub(conn.pausedLists, rlist .. " ", ""); if (conn.pausedLists == "") then conn.pausedLists = nil; end; send("Unpaused list " .. rlist .. ".", conn, S_DONE); end; function listRename(conn, oldName, newName) if (oldName == nil or newName == nil) then send("Usage: .List Rename <list> <newname>", conn, S_ERROR); return nil; end; local oldName = strlower(oldName); local l, err = listByName(conn, oldName, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; oldName = strlower(l) if not isListMaster(l, conn.realUser) then send("You cannot rename a list that you are not a master of.", conn, S_ERROR); return nil; end; if (lists[strlower(newName)]) then send("There is already a list with that name.", conn, S_ERROR); return nil; end; sendTo(format("%s has renamed %%%s to %%%s. {%s}", conn.username, lists[oldName].listname, newName, newName), getListMembers(oldName), S_LISTRENAME); if (not listIsMember(conn.realUser, l, 1)) then send(format("%s has renamed %%%s to %%%s. {%s}", conn.username, lists[oldName].listname, newName, newName), conn, S_LISTRENAME); end; lists[strlower(newName)] = lists[oldName]; lists[oldName] = nil; lists[strlower(newName)].listname = newName; remove(colloquy.lists .. "/" .. strlower(oldName)); saveOneList(strlower(newName)); end; function listMaster(conn, list, user) local l, err = listByName(conn, list, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot make somebody a master on a list you are not a master of.", conn, S_ERROR); return nil; end; local m, i, v; m = userByName(user); if (m == nil) then send("No such user.", conn, S_ERROR); return nil; end; if (type(m) == "string") then send(m, conn, S_ERROR); return nil; end; local mm = strlower(m.username); if isListMaster(l, m.realUser) then send(format("%s is already a master of that list.", m.username), conn, S_ERROR); return nil; end; if not listIsMember(m.realUser, l) then send(format("%s is not on that list.", m.username), conn, S_ERROR); return nil; end if not lists[l].masters then lists[l].masters = {}; end; tinsert(lists[l].masters, strlower(m.realUser)); sendTo(format("%s has made %s a list master. {%s}", conn.username, m.username, lists[l].listname), getListMembers(l), S_LISTMASTER); if not listIsMember(conn.realUser, l, 1) then send(format("%s has made %s a list master. {%s}", conn.username, m.username, lists[l].listname), conn, S_LISTMASTER); end; saveOneList(l); end; function listUnmaster(conn, list, user) local l, err = listByName(conn, list, 1); if (not l) then send(err, conn, S_ERROR); return nil; end; if not isListMaster(l, conn.realUser) then send("You cannot unmaster somebody on a list you are not a master of.", conn, S_ERROR); return nil; end; local m, i, v; m = userByName(user); if (m == nil) then send("No such user.", conn, S_ERROR); return nil; end; if (type(m) == "string") then send(m, conn, S_ERROR); return nil; end; local mm = strlower(m.username); if not isListMaster(l, m.realUser) then send(format("%s is not a master of that list.", m.username), conn, S_ERROR); return nil; end; if not listIsMember(m.realUser, l) then send(format("%s is not on that list.", m.username), conn, S_ERROR); return nil; end for i, v in lists[l].masters or {} do if v == strlower(m.realUser) then tremove(lists[l].masters, i); break; end; end; sendTo(format("%s has unmastered %s. {%s}", conn.username, m.username, lists[l].listname), getListMembers(l), S_LISTMASTER); if not listIsMember(conn.realUser, l, 1) then send(format("%s has unmastered %s. {%s}", conn.username, m.username, lists[l].listname), conn, S_LISTMASTER); end; saveOneList(l); end; function listHasPaused(conn, list) if (conn.pausedLists) then return strfind(conn.pausedLists, lists[strlower(list)].listname .. " ", 1, 1); else return nil; end; end; function loadLists(dirname) dirname = dirname or colloquy.lists local dir = pfiles(dirname .. "/") if dir then local e = dir(); while (e) do if (not strfind(e, "^%.") and strlower(e) == e) then lists[e] = dofile(dirname .. "/" .. e) end e = dir() end else -- let's check to see if there's an old-style single-file -- lists file that we can convert to the new style. if pstat(colloquy.base .. "/data/lists.lua") then write(" (importing old list data)"); flush(); dofile(colloquy.base .. "/data/lists.lua") rename(colloquy.base .. "/data/lists.lua", colloquy.base .. "/data/lists-old.lua") end pmkdir(dirname) saveLists(dirname) end end function saveLists(dirname) dirname = dirname or colloquy.lists for i, v in lists do if (type(v) == "table" and strlower(i) == i) then local f = openfile(dirname .. "/" .. strlower(i), "w") write(f, "return ") dumpList(v, f, 0) closefile(f) end end end function saveOneList(list) local f = openfile(colloquy.lists .. "/" .. strlower(list), "w") write(f, "return ") dumpList(lists[list], f, 0) closefile(f) end function dumpList(table, f, indent) write(f, "{\n") indent = indent + 2 for j, k in table do if (j ~= "n") then write(f, strrep(" ", indent) .. j .. " = ") t = type(k) if (t == "string") then k = format("%q", k) write(f, k, ",\n") elseif (t == "number") then write(f, k, ",\n") elseif (t == "table") then -- tables inside list tables only ever contain strings, so -- this is slightly easier. write(f, "{ ") for q, w in k do if type(w) == "string" then write(f, format("%q, ", w)) end end write(f, "},\n") end end end indent = indent - 2; write(f, strrep(" ", indent), "}\n") end
mit
AdamGagorik/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Nivorajean.lua
13
1063
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Nivorajean -- Type: Standard NPC -- @zone: 26 -- @pos 15.890 -22.999 13.322 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00dd); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/PsoXja/npcs/_09c.lua
13
2831
----------------------------------- -- Area: Pso'Xja -- NPC: _09c (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos 290.000 -1.925 -18.400 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == 6) then local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z <= -19) then if (GetMobAction(16814093) == 0) then local Rand = math.random(1,2); -- estimated 50% success as per the wiki if (Rand == 1) then -- Spawn Gargoyle player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814093,120):updateClaim(player); -- Gargoyle else player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end player:tradeComplete(); else player:messageSpecial(DOOR_LOCKED); end end end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z <= -19) then if (GetMobAction(16814093) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814093,120):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif (Z >= -18) then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
aquileia/wesnoth
data/lua/on_event.lua
4
1309
local utils = wesnoth.require "lua/wml-utils.lua" -- registers an event handler. note that, like all lua variables this is not persitent in savefiles, -- so you have to call this function from a toplevel lua tag or from a preload event. -- It is also not possible to use this for first_time_only=yes events. local event_handlers = {} local old_on_event = wesnoth.game_events.on_event or function(eventname) end wesnoth.game_events.on_event = function(eventname) old_on_event(eventname) local context = nil for k,v in pairs(event_handlers[eventname] or {}) do if context == nil then context = wesnoth.current.event_context end v.h(context) end end local function on_event(eventname, arg1, arg2) if string.match(eventname, ",") then for elem in utils.split(eventname or "") do on_event(elem, arg1, arg2) end end local priority = 0 local handler = nil if type(arg1) == "function" then handler = arg1 else priority = arg1 handler = arg2 end eventname = string.gsub(eventname, " ", "_") event_handlers[eventname] = event_handlers[eventname] or {} local eh = event_handlers[eventname] table.insert(eh, { h = handler, p = priority}) -- sort it. for i = #eh - 1, 1, -1 do if eh[i].p < eh[i + 1].p then eh[i], eh[i + 1] = eh[i + 1], eh[i] end end end return on_event
gpl-2.0
AdamGagorik/darkstar
scripts/zones/Sealions_Den/mobs/Tenzen.lua
6
1169
----------------------------------- -- Area: Sealion den -- NPC: Tenzen ----------------------------------- ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) switch (mob:getID()) : caseof { [16908310] = function (x) GetMobByID(16908311):updateEnmity(target); GetMobByID(16908312):updateEnmity(target); GetMobByID(16908313):updateEnmity(target); end, [16908314] = function (x) GetMobByID(16908315):updateEnmity(target); GetMobByID(16908316):updateEnmity(target); GetMobByID(16908317):updateEnmity(target); end, [16908318] = function (x) GetMobByID(16908319):updateEnmity(target); GetMobByID(16908320):updateEnmity(target); GetMobByID(16908321):updateEnmity(target); end, } end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/items/plate_of_sole_sushi.lua
16
1699
----------------------------------------- -- ID: 5149 -- Item: plate_of_sole_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 20 -- Strength 5 -- Dexterity 6 -- Accuracy % 15 -- Ranged ACC % 15 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5149); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_STR, 5); target:addMod(MOD_DEX, 6); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 72); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 72); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_STR, 5); target:delMod(MOD_DEX, 6); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 72); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 72); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
AdamGagorik/darkstar
scripts/zones/Valkurm_Dunes/npcs/Stone_Monument.lua
13
1273
----------------------------------- -- Area: Valkurm Dunes -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -311.299 -4.420 -138.878 103 ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x00008); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AdamGagorik/darkstar
scripts/globals/mobskills/Dragon_Breath.lua
34
1375
--------------------------------------------- -- Dragon Breath -- -- Description: Deals Fire damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Fafnir, Nidhogg, Cynoprosopi, and Wyrm. Because of the high damage output from Fafnir/Nidhogg/Wyrm, it is usually avoided by -- standing on (or near) the wyrm's two front feet. Cynoprosopi's breath attack is much less painful. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() ~= 0) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_FIRE, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); dmgmod = utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
ObsidianGuardian/xenia
tools/build/scripts/platform_files.lua
4
1511
include("build_paths.lua") include("util.lua") local function match_platform_files(base_path, base_match) files({ base_path.."/"..base_match..".h", base_path.."/"..base_match..".c", base_path.."/"..base_match..".cc", base_path.."/"..base_match..".cpp", base_path.."/"..base_match..".inc", }) removefiles({base_path.."/".."**_main.cc"}) removefiles({base_path.."/".."**_test.cc"}) removefiles({base_path.."/".."**_posix.h", base_path.."/".."**_posix.cc"}) removefiles({base_path.."/".."**_linux.h", base_path.."/".."**_linux.cc"}) removefiles({base_path.."/".."**_mac.h", base_path.."/".."**_mac.cc"}) removefiles({base_path.."/".."**_win.h", base_path.."/".."**_win.cc"}) filter("platforms:Windows") files({ base_path.."/"..base_match.."_win.h", base_path.."/"..base_match.."_win.cc", }) filter("platforms:Linux") files({ base_path.."/"..base_match.."_posix.h", base_path.."/"..base_match.."_posix.cc", base_path.."/"..base_match.."_linux.h", base_path.."/"..base_match.."_linux.cc", }) filter({}) end -- Adds all .h and .cc files in the current path that match the current platform -- suffix (_win, etc). function local_platform_files(base_path) match_platform_files(base_path or ".", "*") end -- Adds all .h and .cc files in the current path and all subpaths that match -- the current platform suffix (_win, etc). function recursive_platform_files(base_path) match_platform_files(base_path or ".", "**") end
bsd-3-clause
AdamGagorik/darkstar
scripts/globals/items/istiridye.lua
18
1404
----------------------------------------- -- ID: 5456 -- Item: Istiridye -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 4 -- Defense +17.07% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5456); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 4); target:addMod(MOD_DEFP, 17.07); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 4); target:delMod(MOD_DEFP, 17.07); end;
gpl-3.0