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
istr/busted
spec/cl_failing_support.lua
10
4738
describe('bad support functions should fail, sync test', function() describe('bad setup should properly fail a test', function() setup(function() error('failing a setup method') end) before_each(function() end) after_each(function() end) teardown(function() end) it('Tests nothing, should always fail due to failing support functions', function() assert(false) end) it('Tests nothing, should always fail due to failing support functions', function() assert(false) end) end) describe('bad before_each should properly fail a test', function() setup(function() end) before_each(function() error('failing a before_each method') end) after_each(function() end) teardown(function() end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad after_each should properly fail a test', function() setup(function() end) before_each(function() end) after_each(function() error('failing an after_each method') end) teardown(function() end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad teardown should properly fail a test', function() setup(function() end) before_each(function() end) after_each(function() end) teardown(function() error('failing a teardown method') end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad setup/teardown should properly fail a test', function() setup(function() error('failing a setup method') end) before_each(function() end) after_each(function() end) teardown(function() error('failing a teardown method') end) it('Tests nothing, should always fail due to failing support functions', function() assert(false) end) end) end) describe('bad support functions should fail, async test', function() describe('bad setup should properly fail a test, async', function() setup(function() async() error('failing a setup method') end) before_each(function() end) after_each(function() end) teardown(function() end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad before_each should properly fail a test, async', function() setup(function() end) before_each(function() async() error('failing a before_each method') end) after_each(function() end) teardown(function() end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad after_each should properly fail a test, async', function() setup(function() end) before_each(function() end) after_each(function() async() error('failing an after_each method') end) teardown(function() end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad teardown should properly fail a test, async', function() setup(function() end) before_each(function() end) after_each(function() end) teardown(function() async() error('failing a teardown method') end) it('Tests nothing, should always fail due to failing support functions', function() end) it('Tests nothing, should always fail due to failing support functions', function() end) end) describe('bad setup/teardown should properly fail a test, async', function() setup(function() async() error('failing a setup method') end) before_each(function() end) after_each(function() end) teardown(function() async() error('failing a teardown method') end) it('Tests nothing, should always fail due to failing support functions', function() assert(false) end) it('Tests nothing, should always fail due to failing support functions', function() assert(false) end) end) end)
mit
greasydeal/darkstar
scripts/zones/The_Sanctuary_of_ZiTah/npcs/qm4.lua
18
1723
----------------------------------- -- Area: The Sanctuary of Zitah -- NPC: ??? -- Finishes Quest: Lovers in the Dusk -- @zone 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/weather"); require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local LoversInTheDusk = player:getQuestStatus(BASTOK,LOVERS_IN_THE_DUSK); local TOTD = VanadielTOTD(); if (TOTD == TIME_DUSK and LoversInTheDusk == QUEST_ACCEPTED) then player:startEvent(0x00cc); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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); if(csid == 0x00cc) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17346); else player:addItem(17346); player:messageSpecial(ITEM_OBTAINED,17346); -- Siren Flute player:addFame(BASTOK,BAS_FAME*120); player:completeQuest(BASTOK,A_TEST_OF_TRUE_LOVE); end end end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Beaucedine_Glacier/mobs/Tundra_Tiger.lua
23
1425
----------------------------------- -- Area: Beaucedine Glacier -- MOB: Tundra Tiger -- Note: PH for Nue, Kirata ----------------------------------- require("scripts/globals/fieldsofvalor"); require("scripts/zones/Beaucedine_Glacier/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) checkRegime(killer,mob,46,1); checkRegime(killer,mob,47,1); -- Kirata mob = mob:getID(); if (Kirata_PH[mob] ~= nil) then ToD = GetServerVariable("[POP]Kirata"); if (ToD <= os.time(t) and GetMobAction(Kirata) == 0) then if (math.random((1),(15)) == 5) then UpdateNMSpawnPoint(Kirata); GetMobByID(Kirata):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Kirata", mob); DeterMob(mob, true); end end end -- Nue if (Nue_PH[mob] ~= nil) then ToD = GetServerVariable("[POP]Nue"); if (ToD <= os.time(t) and GetMobAction(Nue) == 0) then if (math.random((1),(15)) == 5) then UpdateNMSpawnPoint(Nue); GetMobByID(Nue):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Nue", mob); DeterMob(mob, true); end end end end;
gpl-3.0
LegionXI/darkstar
scripts/globals/spells/bluemagic/radiant_breath.lua
25
2259
----------------------------------------- -- Spell: Radiant Breath -- Deals light damage to enemies within a fan-shaped area of effect originating from the caster. Additional effect: Slow and Silence. -- Spell cost: 116 MP -- Monster Type: Wyverns -- Spell Type: Magical (Light) -- Blue Magic Points: 4 -- Stat Bonus: CHR+1, HP+5 -- Level: 54 -- Casting Time: 5.25 seconds -- Recast Time: 33.75 seconds -- Magic Bursts on: Transfixion, Fusion, Light -- Combos: None ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage local multi = 2.90; if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then multi = multi + 0.50; end params.multiplier = multi; params.tMultiplier = 1.5; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_SLOW; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,35,0,getBlueEffectDuration(caster,resist,typeEffect)); end if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_SILENCE; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,25,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
ibm2431/darkstar
scripts/globals/spells/poisonga.lua
12
1432
----------------------------------------- -- Spell: Poisonga ----------------------------------------- require("scripts/globals/magic") require("scripts/globals/msg") require("scripts/globals/status") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT) local skill = caster:getSkillLevel(dsp.skill.ENFEEBLING_MAGIC) local power = math.max(skill / 25, 1) if skill > 400 then power = math.min((skill - 225) / 5, 55) -- Cap is 55 hp/tick end power = calculatePotency(power, spell:getSkillType(), caster, target) local duration = calculateDuration(60, spell:getSkillType(), spell:getSpellGroup(), caster, target) local params = {} params.diff = dINT params.skillType = dsp.skill.ENFEEBLING_MAGIC params.bonus = 0 params.effect = dsp.effect.POISON local resist = applyResistanceEffect(caster, target, spell, params) if resist >= 0.5 then -- effect taken if target:addStatusEffect(params.effect, power, 3, duration * resist) then spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end else -- resist entirely. spell:setMsg(dsp.msg.basic.MAGIC_RESIST) end return params.effect end
gpl-3.0
evrooije/beerarchy
mods/00_bt_nodes/farming/corn.lua
1
3358
--[[ Original textures from GeMinecraft http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/wip-mods/1440575-1-2-5-generation-minecraft-beta-1-2-farming-and ]] local S = farming.intllib -- corn minetest.register_craftitem("farming:corn", { description = S("Corn"), inventory_image = "farming_corn.png", on_place = function(itemstack, placer, pointed_thing) return farming.place_seed(itemstack, placer, pointed_thing, "farming:corn_1") end, on_use = minetest.item_eat(3), }) -- corn on the cob (texture by TenPlus1) minetest.register_craftitem("farming:corn_cob", { description = S("Corn on the Cob"), inventory_image = "farming_corn_cob.png", on_use = minetest.item_eat(5), }) minetest.register_craft({ type = "cooking", cooktime = 10, output = "farming:corn_cob", recipe = "farming:corn" }) -- ethanol (thanks to JKMurray for this idea) minetest.register_node("farming:bottle_ethanol", { description = S("Bottle of Ethanol"), drawtype = "plantlike", tiles = {"farming_bottle_ethanol.png"}, inventory_image = "farming_bottle_ethanol.png", wield_image = "farming_bottle_ethanol.png", paramtype = "light", is_ground_content = false, walkable = false, selection_box = { type = "fixed", fixed = {-0.25, -0.5, -0.25, 0.25, 0.3, 0.25} }, groups = {vessel = 1, dig_immediate = 3, attached_node = 1}, sounds = default.node_sound_glass_defaults(), }) minetest.register_craft( { output = "farming:bottle_ethanol", recipe = { { "vessels:glass_bottle", "farming:corn", "farming:corn"}, { "farming:corn", "farming:corn", "farming:corn"}, } }) minetest.register_craft({ type = "fuel", recipe = "farming:bottle_ethanol", burntime = 240, replacements = {{ "farming:bottle_ethanol", "vessels:glass_bottle"}} }) -- corn definition local crop_def = { drawtype = "plantlike", tiles = {"farming_corn_1.png"}, paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, drop = "", selection_box = farming.select, groups = { snappy = 3, flammable = 2, plant = 1, attached_node = 1, not_in_creative_inventory = 1, growing = 1 }, sounds = default.node_sound_leaves_defaults() } -- stage 1 minetest.register_node("farming:corn_1", table.copy(crop_def)) -- stage 2 crop_def.tiles = {"farming_corn_2.png"} minetest.register_node("farming:corn_2", table.copy(crop_def)) -- stage 3 crop_def.tiles = {"farming_corn_3.png"} minetest.register_node("farming:corn_3", table.copy(crop_def)) -- stage 4 crop_def.tiles = {"farming_corn_4.png"} minetest.register_node("farming:corn_4", table.copy(crop_def)) -- stage 5 crop_def.tiles = {"farming_corn_5.png"} minetest.register_node("farming:corn_5", table.copy(crop_def)) -- stage 6 crop_def.tiles = {"farming_corn_6.png"} crop_def.visual_scale = 1.9 -- 1.45 minetest.register_node("farming:corn_6", table.copy(crop_def)) -- stage 7 crop_def.tiles = {"farming_corn_7.png"} crop_def.drop = { items = { {items = {'farming:corn'}, rarity = 2}, {items = {'farming:corn'}, rarity = 4}, } } minetest.register_node("farming:corn_7", table.copy(crop_def)) -- stage 8 (final) crop_def.tiles = {"farming_corn_8.png"} crop_def.groups.growing = 0 crop_def.drop = { items = { {items = {'farming:corn'}, rarity = 1}, {items = {'farming:corn 2'}, rarity = 4}, } } minetest.register_node("farming:corn_8", table.copy(crop_def))
lgpl-2.1
pokemoncentral/wiki-lua-modules
PokémonInfo-Regionaldex.lua
1
5593
-- Modulo da usare nel template PokémonInfo per determinare -- i dex regionali local rdex = {} -- stylua: ignore start local txt = require('Wikilib-strings') local tab = require('Wikilib-tables') local links = require('Links') local dex = require("Dex-data") local c = require("Colore-data") local sup = require("Sup-data") -- stylua: ignore end -- Ritorna il dex regionale di un Pokémon nel vecchio -- dex regionale specificato: nel caso in cui non sia -- presente, ritorna nil local getOldDex = function(newDex, oldDexTable, changedDexTable) if changedDexTable and changedDexTable[newDex] then return txt.tf(changedDexTable[newDex]) end for subtract, ndex in ipairs(oldDexTable) do if ndex == newDex then return nil elseif ndex > newDex then return txt.tf(newDex - subtract + 1) end end return txt.tf(newDex - tab.getn(oldDexTable)) end -- Aggiunge un title al primo argomento costituito -- dal secondo e dal terzo separati da uno spazio local addtt = function(newDex, oldDex, title) return txt.interp(links.tt(newDex, oldDex .. title)) end -- Inserisce le informazioni relative al vecchio dex -- regionale: per Sinnoh un sup di platino, per le -- altre un title local insOld = {} insOld.johto = function(newDex, oldDex) return addtt(newDex, oldDex, " in seconda generazione") end insOld.hoenn = function(newDex, oldDex) return addtt(newDex, oldDex, " in terza generazione") end insOld.sinnoh = function(newDex, oldDex) return newDex .. sup.Pt end insOld.unima = function(newDex, oldDex) return addtt(newDex, oldDex, " in Nero e Bianco") end insOld.alola = function(newDex, oldDex) return addtt(newDex, oldDex, " in Sole e Luna") end -- Ordina la tabella store: la table è esterna alla -- funzione così da non essere ricreata ogni volta local regiongens = { Kanto = { ord = 1 }, Johto = { ord = 2 }, Hoenn = { ord = 3 }, Sinnoh = { ord = 4 }, Unima = { ord = 5 }, Kalos = { ord = 6 }, Alola = { ord = 7 }, Galar = { ord = 8 }, Armatura = { ord = 9, pref = "" }, Corona = { ord = 10, pref = "" }, Hisui = { ord = 11 }, Paldea = { ord = 12 }, } local region_sort = function(c, d) local a, b = c:match(">(%a+)</span>"), d:match(">(%a+)</span>") return regiongens[a].ord < regiongens[b].ord end --[[ La funzione che genera le celle per i dex regionali: nello scorrere la tabella fornita dalla search, controlla che il dex non sia tra quelli aggiornati in seguito ed effettua l'inserimento; se ciò non accade, concatena all'ultimo elemento l'asterisco giusto chiamando la funzione olddex. --]] local dexlist = function(dexes) if tab.getn(dexes) == 0 then return nil end local store = {} local str = [=[<span><div class="small-font">'''[[Elenco Pokémon secondo il Pokédex ${pref}${reg}|<span class="black-text">${reg}</span>]]'''</div>#${rdex}</span>]=] local kalos = [=[<span><div class="small-font">'''[[Elenco Pokémon secondo i Pokédex di Kalos#Pokédex di Kalos ${reg}|<span style="color:#${c}">Kalos</span>]]'''</div>#${ttdex}</span>]=] for region, rdex in pairs(dexes) do if region:find("kalos") then local zone = region:match("kalos(%a+)$") table.insert( store, txt.interp(kalos, { c = c["kalos" .. zone].normale, ttdex = links.tt(rdex, zone), reg = zone, }) ) else local oldDexTable = dex[region .. "Added"] if oldDexTable then local oldDex = getOldDex( tonumber(rdex), oldDexTable, dex[region .. "Changed"] ) if oldDex ~= rdex then rdex = insOld[region](rdex, oldDex or "Non disponibile") end end local regionName = txt.fu(region) table.insert( store, txt.interp(str, { reg = regionName, pref = regiongens[regionName].pref or "di ", rdex = rdex, }) ) end end table.sort(store, region_sort) for k, v in ipairs(store) do store[k] = v end if #store > 5 then table.insert( store, 1 + math.floor(#store / 2), '<div class="width-xl-100"></div>' ) end return table.concat(store) end -- Semplicemente cerca tra tutti i dex se si trova il numero di dex -- nazionale fornito: in caso positivo, lo inserisce come elemento -- di una table con indice il nome della regione. Se una certa regione -- ha più dex regionali (es: alola) inserisce come valore una table -- contenente il numero di dex nazionale local search = function(ndex) local dexes = {} for region, regionalDex in pairs(dex) do local rdex = tab.search(regionalDex, ndex) if rdex then dexes[region] = txt.three_figures(rdex) end end return dexes end --Interfaccia. Riceve un ndex su tre cifre e un tipo, e interpola il colore standard -- del tipo e la lista dei dex regionali, creata con la funzione dexlist, al box in wikicode rdex.regionaldex = function(frame) local ndex = txt.trim(frame.args[1]) or "000" return dexlist(search(ndex)) or "In nessun Pokédex regionale" end rdex.Regionaldex, rdex.RegionalDex = rdex.regionaldex, rdex.regionaldex return rdex
cc0-1.0
LegionXI/darkstar
scripts/globals/items/zucchini.lua
12
1268
----------------------------------------- -- ID: 5726 -- Item: Zucchini -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -3 -- Defense -1 ----------------------------------------- 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,300,5726); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -3); target:addMod(MOD_DEF, -1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -3); target:delMod(MOD_DEF, -1); end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Upper_Jeuno/npcs/Paya-Sabya.lua
19
1333
----------------------------------- -- Area: Upper Jeuno -- NPC: Paya-Sabya -- Involved in Mission: Magicite -- @zone 244 -- @pos 9 1 70 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(SILVER_BELL) and player:hasKeyItem(YAGUDO_TORCH) == false and player:getVar("YagudoTorchCS") == 0) then player:startEvent(0x0050); else player:startEvent(0x004f); 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); if(csid == 0x0050) then player:setVar("YagudoTorchCS",1); end end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Apollyon/mobs/Thunder_Elemental.lua
119
2423
----------------------------------- -- Area: Apollyon SW -- NPC: elemental ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger") - 1; local correctelement=false; switch (elementalday): caseof { [0] = function (x) if(mobID==16932913 or mobID==16932921 or mobID==16932929)then correctelement=true; end end , [1] = function (x) if(mobID==16932912 or mobID==16932920 or mobID==16932928 )then correctelement=true; end end , [2] = function (x) if(mobID==16932916 or mobID==16932924 or mobID==16932932 )then correctelement=true; end end , [3] = function (x) if(mobID==16932910 or mobID==16932918 or mobID==16932926 )then correctelement=true; end end , [4] = function (x) if(mobID==16932914 or mobID==16932922 or mobID==16932930 )then correctelement=true; end end , [5] = function (x) if(mobID==16932917 or mobID==16932925 or mobID==16932933 )then correctelement=true; end end , [6] = function (x) if(mobID==16932931 or mobID==16932915 or mobID==16932923 )then correctelement=true; end end , [7] = function (x) if(mobID==16932911 or mobID==16932919 or mobID==16932927 )then correctelement=true; end end , }; if(correctelement==true and IselementalDayAreDead()==true)then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(STATUS_NORMAL); end end;
gpl-3.0
greasydeal/darkstar
scripts/globals/items/serving_of_salmon_meuniere.lua
35
1404
----------------------------------------- -- ID: 4583 -- Item: serving_of_salmon_meuniere -- Food Effect: 180Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -2 -- Ranged ACC % 7 -- Ranged ACC Cap 10 ----------------------------------------- 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,10800,4583); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -2); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -2); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 10); end;
gpl-3.0
LegionXI/darkstar
scripts/globals/items/dish_of_homemade_carbonara.lua
12
1870
----------------------------------------- -- ID: 5706 -- Item: dish_of_homemade_carbonara -- Food Effect: 30Min, All Races ----------------------------------------- -- CHR +1 -- Accuracy +12% (cap 80) -- Attack +10% (cap 40) -- Ranged Accuracy +12% (cap 80) -- Ranged Attack +10% (cap 40) ----------------------------------------- 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,5706); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_CHR, 1); target:addMod(MOD_FOOD_ACCP, 12); target:addMod(MOD_FOOD_ACC_CAP, 80); target:addMod(MOD_FOOD_ATTP, 10); target:addMod(MOD_FOOD_ATT_CAP, 40); target:addMod(MOD_FOOD_RACCP, 12); target:addMod(MOD_FOOD_RACC_CAP, 80); target:addMod(MOD_FOOD_RATTP, 10); target:addMod(MOD_FOOD_RATT_CAP, 40); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_CHR, 1); target:delMod(MOD_FOOD_ACCP, 12); target:delMod(MOD_FOOD_ACC_CAP, 80); target:delMod(MOD_FOOD_ATTP, 10); target:delMod(MOD_FOOD_ATT_CAP, 40); target:delMod(MOD_FOOD_RACCP, 12); target:delMod(MOD_FOOD_RACC_CAP, 80); target:delMod(MOD_FOOD_RATTP, 10); target:delMod(MOD_FOOD_RATT_CAP, 40); end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Bostaunieux_Oubliette/npcs/Grounds_Tome.lua
34
1160
----------------------------------- -- Area: Bostaunieux Oubliette -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_BOSTAUNIEUX_OUBLIETTE,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,610,611,612,613,614,615,616,617,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,610,611,612,613,614,615,616,617,0,0,GOV_MSG_BOSTAUNIEUX_OUBLIETTE); end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Beadeaux/npcs/The_Mute.lua
14
1296
----------------------------------- -- Area: Beadeaux -- NPC: ??? -- @pos -166.230 -1 -73.685 147 ----------------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beadeaux/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local duration = math.random(600,900); if (player:getQuestStatus(BASTOK,THE_CURSE_COLLECTOR) == QUEST_ACCEPTED and player:getVar("cCollectSilence") == 0) then player:setVar("cCollectSilence",1); end player:addStatusEffect(EFFECT_SILENCE,0,0,duration); 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
greasydeal/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Sahnn_Dhansett.lua
38
1054
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Sahnn Dhansett -- Type: Standard NPC -- @zone: 94 -- @pos 112.820 -3.122 47.857 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01a1); 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
greasydeal/darkstar
scripts/globals/abilities/pets/burning_strike.lua
25
1274
--------------------------------------------------- -- Burning Strike M = 6? --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/summon"); require("scripts/globals/magic"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local numhits = 1; local accmod = 1; local dmgmod = 6; local totaldamage = 0; local damage = AvatarPhysicalMove(pet,target,skill,numhits,accmod,dmgmod,0,TP_NO_EFFECT,1,2,3); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_FIRE); --get the resisted damage damage.dmg = damage.dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) damage.dmg = mobAddBonuses(pet,spell,target,damage.dmg,1); totaldamage = AvatarFinalAdjustments(damage.dmg,pet,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,numhits); target:delHP(totaldamage); target:updateEnmityFromDamage(pet,totaldamage); return totaldamage; end
gpl-3.0
HeavenIsLost/ChronusServer
data/actions/scripts/other/food.lua
2
4485
local FOODS = { [2362] = {5, "Crunch."}, -- carrot [2666] = {15, "Munch."}, -- meat [2667] = {12, "Munch."}, -- fish [2668] = {10, "Mmmm."}, -- salmon [2669] = {17, "Munch."}, -- northern pike [2670] = {4, "Gulp."}, -- shrimp [2671] = {30, "Chomp."}, -- ham [2672] = {60, "Chomp."}, -- dragon ham [2673] = {5, "Yum."}, -- pear [2674] = {6, "Yum."}, -- red apple [2675] = {13, "Yum."}, -- orange [2676] = {8, "Yum."}, -- banana [2677] = {1, "Yum."}, -- blueberry [2678] = {18, "Slurp."}, -- coconut [2679] = {1, "Yum."}, -- cherry [2680] = {2, "Yum."}, -- strawberry [2681] = {9, "Yum."}, -- grapes [2682] = {20, "Yum."}, -- melon [2683] = {17, "Munch."}, -- pumpkin [2684] = {5, "Crunch."}, -- carrot [2685] = {6, "Munch."}, -- tomato [2686] = {9, "Crunch."}, -- corncob [2687] = {2, "Crunch."}, -- cookie [2688] = {2, "Munch."}, -- candy cane [2689] = {10, "Crunch."}, -- bread [2690] = {3, "Crunch."}, -- roll [2691] = {8, "Crunch."}, -- brown bread [2695] = {6, "Gulp."}, -- egg [2696] = {9, "Smack."}, -- cheese [2787] = {9, "Munch."}, -- white mushroom [2788] = {4, "Munch."}, -- red mushroom [2789] = {22, "Munch."}, -- brown mushroom [2790] = {30, "Munch."}, -- orange mushroom [2791] = {9, "Munch."}, -- wood mushroom [2792] = {6, "Munch."}, -- dark mushroom [2793] = {12, "Munch."}, -- some mushrooms [2794] = {3, "Munch."}, -- some mushrooms [2795] = {36, "Munch."}, -- fire mushroom [2796] = {5, "Munch."}, -- green mushroom [5097] = {4, "Yum."}, -- mango [6125] = {8, "Gulp."}, -- tortoise egg [6278] = {10, "Mmmm."}, -- cake [6279] = {15, "Mmmm."}, -- decorated cake [6393] = {12, "Mmmm."}, -- valentine's cake [6394] = {15, "Mmmm."}, -- cream cake [6501] = {20, "Mmmm."}, -- gingerbread man [6541] = {6, "Gulp."}, -- coloured egg (yellow) [6542] = {6, "Gulp."}, -- coloured egg (red) [6543] = {6, "Gulp."}, -- coloured egg (blue) [6544] = {6, "Gulp."}, -- coloured egg (green) [6545] = {6, "Gulp."}, -- coloured egg (purple) [6569] = {1, "Mmmm."}, -- candy [6574] = {5, "Mmmm."}, -- bar of chocolate [7158] = {15, "Munch."}, -- rainbow trout [7159] = {13, "Munch."}, -- green perch [7372] = {2, "Yum."}, -- ice cream cone (crispy chocolate chips) [7373] = {2, "Yum."}, -- ice cream cone (velvet vanilla) [7374] = {2, "Yum."}, -- ice cream cone (sweet strawberry) [7375] = {2, "Yum."}, -- ice cream cone (chilly cherry) [7376] = {2, "Yum."}, -- ice cream cone (mellow melon) [7377] = {2, "Yum."}, -- ice cream cone (blue-barian) [7909] = {4, "Crunch."}, -- walnut [7910] = {4, "Crunch."}, -- peanut [7963] = {60, "Munch."}, -- marlin [8112] = {9, "Urgh."}, -- scarab cheese [8838] = {10, "Gulp."}, -- potato [8839] = {5, "Yum."}, -- plum [8840] = {1, "Yum."}, -- raspberry [8841] = {1, "Urgh."}, -- lemon [8842] = {7, "Munch."}, -- cucumber [8843] = {5, "Crunch."}, -- onion [8844] = {1, "Gulp."}, -- jalapeño pepper [8845] = {5, "Munch."}, -- beetroot [8847] = {11, "Yum."}, -- chocolate cake [9005] = {7, "Slurp."}, -- yummy gummy worm [9114] = {5, "Crunch."}, -- bulb of garlic [9996] = {0, "Slurp."}, -- banana chocolate shake [10454] = {0, "Your head begins to feel better."}, -- headache pill [11246] = {15, "Yum."}, -- rice ball [11370] = {3, "Urgh."}, -- terramite eggs [11429] = {10, "Mmmm."}, -- crocodile steak [12415] = {20, "Yum."}, -- pineapple [12416] = {10, "Munch."}, -- aubergine [12417] = {8, "Crunch."}, -- broccoli [12418] = {9, "Crunch."}, -- cauliflower [12637] = {55, "Gulp."}, -- ectoplasmic sushi [12638] = {18, "Yum."}, -- dragonfruit [12639] = {2, "Munch."}, -- peas [13297] = {20, "Crunch."}, -- haunch of boar [15405] = {55, "Munch."}, -- sandfish [15487] = {14, "Urgh."}, -- larvae [15488] = {15, "Munch."}, -- deepling filet [16014] = {60, "Mmmm."}, -- anniversary cake [18397] = {33, "Munch."}, -- mushroom pie [19737] = {10, "Urgh."}, -- insectoid eggs [20100] = {15, "Smack."}, -- soft cheese [20101] = {12, "Smack."} -- rat cheese } function onUse(player, item, fromPosition, itemEx, toPosition, isHotkey) local food = FOODS[item.itemid] if food == nil then return false end local condition = player:getCondition(CONDITION_REGENERATION, CONDITIONID_DEFAULT) if condition and math.floor(condition:getTicks() / 1000 + food[1]) >= 1200 then player:sendTextMessage(MESSAGE_STATUS_SMALL, "You are full.") else player:feed(food[1] * 12) player:say(food[2], TALKTYPE_MONSTER_SAY) Item(item.uid):remove(1) end return true end
gpl-2.0
rigeirani/btg
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
icyxp/kong
spec/03-plugins/17-jwt/03-access_spec.lua
1
23088
local cjson = require "cjson" local helpers = require "spec.helpers" local fixtures = require "spec.03-plugins.17-jwt.fixtures" local jwt_encoder = require "kong.plugins.jwt.jwt_parser" local utils = require "kong.tools.utils" local PAYLOAD = { iss = nil, nbf = os.time(), iat = os.time(), exp = os.time() + 3600 } describe("Plugin: jwt (access)", function() local jwt_secret, base64_jwt_secret, rsa_jwt_secret_1, rsa_jwt_secret_2, rsa_jwt_secret_3 local proxy_client, admin_client setup(function() helpers.run_migrations() local apis = {} for i = 1, 8 do apis[i] = assert(helpers.dao.apis:insert({ name = "tests-jwt" .. i, hosts = { "jwt" .. i .. ".com" }, upstream_url = helpers.mock_upstream_url, })) end local cdao = helpers.dao.consumers local consumer1 = assert(cdao:insert({ username = "jwt_tests_consumer" })) local consumer2 = assert(cdao:insert({ username = "jwt_tests_base64_consumer" })) local consumer3 = assert(cdao:insert({ username = "jwt_tests_rsa_consumer_1" })) local consumer4 = assert(cdao:insert({ username = "jwt_tests_rsa_consumer_2" })) local consumer5 = assert(cdao:insert({ username = "jwt_tests_rsa_consumer_5" })) local anonymous_user = assert(cdao:insert({ username = "no-body" })) local pdao = helpers.dao.plugins assert(pdao:insert({ name = "jwt", api_id = apis[1].id, config = {}, })) assert(pdao:insert({ name = "jwt", api_id = apis[2].id, config = { uri_param_names = { "token", "jwt" } }, })) assert(pdao:insert({ name = "jwt", api_id = apis[3].id, config = { claims_to_verify = {"nbf", "exp"} }, })) assert(pdao:insert({ name = "jwt", api_id = apis[4].id, config = { key_claim_name = "aud" }, })) assert(pdao:insert({ name = "jwt", api_id = apis[5].id, config = { secret_is_base64 = true }, })) assert(pdao:insert({ name = "jwt", api_id = apis[6].id, config = { anonymous = anonymous_user.id }, })) assert(pdao:insert({ name = "jwt", api_id = apis[7].id, config = { anonymous = utils.uuid() }, })) assert(pdao:insert({ name = "jwt", api_id = apis[8].id, config = { run_on_preflight = false }, })) jwt_secret = assert(helpers.dao.jwt_secrets:insert {consumer_id = consumer1.id}) base64_jwt_secret = assert(helpers.dao.jwt_secrets:insert {consumer_id = consumer2.id}) rsa_jwt_secret_1 = assert(helpers.dao.jwt_secrets:insert { consumer_id = consumer3.id, algorithm = "RS256", rsa_public_key = fixtures.rs256_public_key }) rsa_jwt_secret_2 = assert(helpers.dao.jwt_secrets:insert { consumer_id = consumer4.id, algorithm = "RS256", rsa_public_key = fixtures.rs256_public_key }) rsa_jwt_secret_3 = assert(helpers.dao.jwt_secrets:insert { consumer_id = consumer5.id, algorithm = "RS512", rsa_public_key = fixtures.rs512_public_key }) assert(helpers.start_kong { real_ip_header = "X-Forwarded-For", real_ip_recursive = "on", trusted_ips = "0.0.0.0/0, ::/0", nginx_conf = "spec/fixtures/custom_nginx.template", }) proxy_client = helpers.proxy_client() admin_client = helpers.admin_client() end) teardown(function() if proxy_client then proxy_client:close() end if admin_client then admin_client:close() end helpers.stop_kong() end) describe("refusals", function() it("returns 401 Unauthorized if no JWT is found in the request", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "jwt1.com", } }) assert.res_status(401, res) end) it("returns 401 if the claims do not contain the key to identify a secret", function() local jwt = jwt_encoder.encode(PAYLOAD, "foo") local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = assert.res_status(401, res) local json = cjson.decode(body) assert.same({ message = "No mandatory 'iss' in claims" }, json) end) it("returns 403 Forbidden if the iss does not match a credential", function() PAYLOAD.iss = "123456789" local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "No credentials found for given 'iss'" }, json) end) it("returns 403 Forbidden if the signature is invalid", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, "foo") local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid signature" }, json) end) it("returns 403 Forbidden if the alg does not match the credential", function() local header = {typ = "JWT", alg = 'RS256'} local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret, 'HS256', header) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = assert.res_status(403, res) local json = cjson.decode(body) assert.same({ message = "Invalid algorithm" }, json) end) it("returns 200 on OPTIONS requests if run_on_preflight is false", function() local res = assert(proxy_client:send { method = "OPTIONS", path = "/request", headers = { ["Host"] = "jwt8.com" } }) assert.res_status(200, res) end) it("returns Unauthorized on OPTIONS requests if run_on_preflight is true", function() local res = assert(proxy_client:send { method = "OPTIONS", path = "/request", headers = { ["Host"] = "jwt1.com" } }) local body = assert.res_status(401, res) assert.equal([[{"message":"Unauthorized"}]], body) end) end) describe("HS256", function() it("proxies the request with token and consumer headers if it was verified", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_consumer", body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("proxies the request if secret key is stored in a field other than iss", function() PAYLOAD.aud = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt4.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_consumer", body.headers["x-consumer-username"]) end) it("proxies the request if secret is base64", function() PAYLOAD.iss = base64_jwt_secret.key local original_secret = base64_jwt_secret.secret local base64_secret = ngx.encode_base64(base64_jwt_secret.secret) local res = assert(admin_client:send { method = "PATCH", path = "/consumers/jwt_tests_base64_consumer/jwt/" .. base64_jwt_secret.id, body = { key = base64_jwt_secret.key, secret = base64_secret}, headers = { ["Content-Type"] = "application/json" } }) assert.res_status(200, res) local jwt = jwt_encoder.encode(PAYLOAD, original_secret) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt5.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_base64_consumer", body.headers["x-consumer-username"]) end) it("finds the JWT if given in URL parameters", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt=" .. jwt, headers = { ["Host"] = "jwt1.com", } }) assert.res_status(200, res) end) it("illegal formatted JWT token", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer+" .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = assert.res_status(401, res) assert.equal('{"message":"Unauthorized"}', body) end) it("finds the JWT if given in cookie", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "jwt1.com", ["Set-Cookie"] = "Authorization=" .. authorization .. "; path=/;domain=.jwt1.com" } }) assert.res_status(200, res) end) it("finds the JWT if given in a custom URL parameter", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?token=" .. jwt, headers = { ["Host"] = "jwt2.com", } }) assert.res_status(200, res) end) end) describe("RS256", function() it("verifies JWT", function() PAYLOAD.iss = rsa_jwt_secret_1.key local jwt = jwt_encoder.encode(PAYLOAD, fixtures.rs256_private_key, 'RS256') local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_rsa_consumer_1", body.headers["x-consumer-username"]) end) it("identifies Consumer", function() PAYLOAD.iss = rsa_jwt_secret_2.key local jwt = jwt_encoder.encode(PAYLOAD, fixtures.rs256_private_key, 'RS256') local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_rsa_consumer_2", body.headers["x-consumer-username"]) end) end) describe("RS512", function() it("verifies JWT", function() PAYLOAD.iss = rsa_jwt_secret_3.key local jwt = jwt_encoder.encode(PAYLOAD, fixtures.rs512_private_key, "RS512") local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_rsa_consumer_5", body.headers["x-consumer-username"]) end) it("identifies Consumer", function() PAYLOAD.iss = rsa_jwt_secret_3.key local jwt = jwt_encoder.encode(PAYLOAD, fixtures.rs512_private_key, "RS512") local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt1.com", } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal(authorization, body.headers.authorization) assert.equal("jwt_tests_rsa_consumer_5", body.headers["x-consumer-username"]) end) end) describe("JWT private claims checks", function() it("requires the checked fields to be in the claims", function() local payload = { iss = jwt_secret.key } local jwt = jwt_encoder.encode(payload, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt=" .. jwt, headers = { ["Host"] = "jwt3.com" } }) local body = assert.res_status(401, res) assert.equal('{"nbf":"must be a number","exp":"must be a number"}', body) end) it("checks if the fields are valid: `exp` claim", function() local payload = { iss = jwt_secret.key, exp = os.time() - 10, nbf = os.time() - 10 } local jwt = jwt_encoder.encode(payload, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt=" .. jwt, headers = { ["Host"] = "jwt3.com" } }) local body = assert.res_status(401, res) assert.equal('{"exp":"token expired"}', body) end) it("checks if the fields are valid: `nbf` claim", function() local payload = { iss = jwt_secret.key, exp = os.time() + 10, nbf = os.time() + 5 } local jwt = jwt_encoder.encode(payload, jwt_secret.secret) local res = assert(proxy_client:send { method = "GET", path = "/request/?jwt=" .. jwt, headers = { ["Host"] = "jwt3.com" } }) local body = assert.res_status(401, res) assert.equal('{"nbf":"token not valid yet"}', body) end) end) describe("config.anonymous", function() it("works with right credentials and anonymous", function() PAYLOAD.iss = jwt_secret.key local jwt = jwt_encoder.encode(PAYLOAD, jwt_secret.secret) local authorization = "Bearer " .. jwt local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Authorization"] = authorization, ["Host"] = "jwt6.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal('jwt_tests_consumer', body.headers["x-consumer-username"]) assert.is_nil(body.headers["x-anonymous-consumer"]) end) it("works with wrong credentials and anonymous", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "jwt6.com" } }) local body = cjson.decode(assert.res_status(200, res)) assert.equal('true', body.headers["x-anonymous-consumer"]) assert.equal('no-body', body.headers["x-consumer-username"]) end) it("errors when anonymous user doesn't exist", function() local res = assert(proxy_client:send { method = "GET", path = "/request", headers = { ["Host"] = "jwt7.com" } }) assert.response(res).has.status(500) end) end) end) describe("Plugin: jwt (access)", function() local client, user1, user2, anonymous, jwt_token setup(function() local api1 = assert(helpers.dao.apis:insert { name = "api-1", hosts = { "logical-and.com" }, upstream_url = helpers.mock_upstream_url .. "/request", }) assert(helpers.dao.plugins:insert { name = "jwt", api_id = api1.id, }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api1.id, }) anonymous = assert(helpers.dao.consumers:insert { username = "Anonymous", }) user1 = assert(helpers.dao.consumers:insert { username = "Mickey", }) user2 = assert(helpers.dao.consumers:insert { username = "Aladdin", }) local api2 = assert(helpers.dao.apis:insert { name = "api-2", hosts = { "logical-or.com" }, upstream_url = helpers.mock_upstream_url .. "/request", }) assert(helpers.dao.plugins:insert { name = "jwt", api_id = api2.id, config = { anonymous = anonymous.id, }, }) assert(helpers.dao.plugins:insert { name = "key-auth", api_id = api2.id, config = { anonymous = anonymous.id, }, }) assert(helpers.dao.keyauth_credentials:insert { key = "Mouse", consumer_id = user1.id, }) local jwt_secret = assert(helpers.dao.jwt_secrets:insert { consumer_id = user2.id, }) PAYLOAD.iss = jwt_secret.key jwt_token = "Bearer " .. jwt_encoder.encode(PAYLOAD, jwt_secret.secret) assert(helpers.start_kong({ nginx_conf = "spec/fixtures/custom_nginx.template", })) client = helpers.proxy_client() end) teardown(function() if client then client:close() end helpers.stop_kong() end) describe("multiple auth without anonymous, logical AND", function() it("passes with all credentials provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["apikey"] = "Mouse", ["Authorization"] = jwt_token, } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert(id == user1.id or id == user2.id) end) it("fails 401, with only the first credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["apikey"] = "Mouse", } }) assert.response(res).has.status(401) end) it("fails 401, with only the second credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", ["Authorization"] = jwt_token, } }) assert.response(res).has.status(401) end) it("fails 401, with no credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-and.com", } }) assert.response(res).has.status(401) end) end) describe("multiple auth with anonymous, logical OR", function() it("passes with all credentials provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["apikey"] = "Mouse", ["Authorization"] = jwt_token, } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert(id == user1.id or id == user2.id) end) it("passes with only the first credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["apikey"] = "Mouse", } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert.equal(user1.id, id) end) it("passes with only the second credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", ["Authorization"] = jwt_token, } }) assert.response(res).has.status(200) assert.request(res).has.no.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.not_equal(id, anonymous.id) assert.equal(user2.id, id) end) it("passes with no credential provided", function() local res = assert(client:send { method = "GET", path = "/request", headers = { ["Host"] = "logical-or.com", } }) assert.response(res).has.status(200) assert.request(res).has.header("x-anonymous-consumer") local id = assert.request(res).has.header("x-consumer-id") assert.equal(id, anonymous.id) end) end) end)
apache-2.0
greasydeal/darkstar
scripts/zones/Al_Zahbi/npcs/Rughadjeen.lua
38
1030
----------------------------------- -- Area: Al Zahbi -- NPC: Rughadjeen -- Type: Skyserpent General -- @zone: 48 -- @pos -74.150 -7 70.656 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0109); 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
LegionXI/darkstar
scripts/zones/Southern_San_dOria/npcs/Endracion.lua
9
6381
----------------------------------- -- Area: Southern San d'Oria -- NPC: Endracion -- @pos -110 1 -34 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) CurrentMission = player:getCurrentMission(SANDORIA); OrcishScoutCompleted = player:hasCompletedMission(SANDORIA,SMASH_THE_ORCISH_SCOUTS); BatHuntCompleted = player:hasCompletedMission(SANDORIA,BAT_HUNT); TheCSpringCompleted = player:hasCompletedMission(SANDORIA,THE_CRYSTAL_SPRING); MissionStatus = player:getVar("MissionStatus"); Count = trade:getItemCount(); if (CurrentMission ~= 255) then if (CurrentMission == SMASH_THE_ORCISH_SCOUTS and trade:hasItemQty(16656,1) and Count == 1 and OrcishScoutCompleted == false) then -- Trade Orcish Axe player:startEvent(0x03fc); -- Finish Mission "Smash the Orcish scouts" (First Time) elseif (CurrentMission == SMASH_THE_ORCISH_SCOUTS and trade:hasItemQty(16656,1) and Count == 1) then -- Trade Orcish Axe player:startEvent(0x03ea); -- Finish Mission "Smash the Orcish scouts" (Repeat) elseif (CurrentMission == BAT_HUNT and trade:hasItemQty(1112,1) and Count == 1 and BatHuntCompleted == false and MissionStatus == 2) then -- Trade Orcish Mail Scales player:startEvent(0x03ff); -- Finish Mission "Bat Hunt" elseif (CurrentMission == BAT_HUNT and trade:hasItemQty(891,1) and Count == 1 and BatHuntCompleted == true) then -- Trade Bat Fang player:startEvent(0x03eb); -- Finish Mission "Bat Hunt" (repeat) elseif (CurrentMission == THE_CRYSTAL_SPRING and trade:hasItemQty(4528,1) and Count == 1 and TheCSpringCompleted == false) then -- Trade Crystal Bass player:startEvent(0x0406); -- Dialog During Mission "The Crystal Spring" elseif (CurrentMission == THE_CRYSTAL_SPRING and trade:hasItemQty(4528,1) and Count == 1 and TheCSpringCompleted) then -- Trade Crystal Bass player:startEvent(0x03f5); -- Finish Mission "The Crystal Spring" (repeat) else player:startEvent(0x03f0); -- Wrong Item end else player:startEvent(0x03f2); -- Mission not activated end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local PresOfPapsqueCompleted = player:hasCompletedMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE); if (player:getNation() ~= NATION_SANDORIA) then player:startEvent(0x03F3); -- for Non-San d'Orians else CurrentMission = player:getCurrentMission(SANDORIA); MissionStatus = player:getVar("MissionStatus"); pRank = player:getRank(); cs, p, offset = getMissionOffset(player,1,CurrentMission,MissionStatus); if (CurrentMission <= 15 and (cs ~= 0 or offset ~= 0 or (CurrentMission == 0 and offset == 0))) then if (cs == 0) then player:showText(npc,ORIGINAL_MISSION_OFFSET + offset); -- dialog after accepting mission else player:startEvent(cs,p[1],p[2],p[3],p[4],p[5],p[6],p[7],p[8]); end elseif (pRank == 1 and player:hasCompletedMission(SANDORIA,SMASH_THE_ORCISH_SCOUTS) == false) then player:startEvent(0x03e8); -- Start First Mission "Smash the Orcish scouts" elseif (player:hasKeyItem(ANCIENT_SANDORIAN_BOOK)) then player:startEvent(0x040b); elseif (CurrentMission == RANPERRE_S_FINAL_REST and player:getVar("MissionStatus",4) and tonumber(os.date("%j")) == player:getVar("Wait1DayForRanperre_date")) then player:startEvent(0x040d); elseif (CurrentMission == RANPERRE_S_FINAL_REST and player:getVar("MissionStatus") == 4 and tonumber(os.date("%j")) ~= player:getVar("Wait1DayForRanperre_date")) then -- Ready now. player:startEvent(0x040f); elseif (CurrentMission == RANPERRE_S_FINAL_REST and player:getVar("MissionStatus") == 6) then player:startEvent(0x040f); elseif (CurrentMission == RANPERRE_S_FINAL_REST and player:getVar("MissionStatus") == 9) then player:startEvent(0x0409); elseif (CurrentMission ~= THE_SECRET_WEAPON and pRank == 7 and PresOfPapsqueCompleted == true and getMissionRankPoints(player,19) == 1 and player:getVar("SecretWeaponStatus") == 0) then player:startEvent(0x003d); elseif (CurrentMission == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") == 3) then player:startEvent(0x0413); elseif ((CurrentMission ~= 255) and not (player:getVar("MissionStatus") == 8)) then player:startEvent(0x03e9); -- Have mission already activated else mission_mask, repeat_mask = getMissionMask(player); player:startEvent(0x03f1,mission_mask, 0, 0 ,0 ,0 ,repeat_mask); -- Mission List end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); finishMissionTimeline(player,1,csid,option); if (csid == 0x040b) then player:setVar("MissionStatus",4); player:delKeyItem(ANCIENT_SANDORIAN_BOOK); player:setVar("Wait1DayForRanperre_date", os.date("%j")); elseif (csid == 0x040d) then player:setVar("MissionStatus",6); elseif (csid == 0x040f) then player:setVar("MissionStatus",7); player:setVar("Wait1DayForRanperre_date",0); elseif (csid == 0x0409) then finishMissionTimeline(player,2,csid,option); elseif (csid == 0x003d) then player:setVar("SecretWeaponStatus",1); elseif (csid == 0x0413) then finishMissionTimeline(player,2,csid,option); end end;
gpl-3.0
greasydeal/darkstar
scripts/globals/weaponskills/skullbreaker.lua
30
1486
----------------------------------- -- Skullbreaker -- Club weapon skill -- Skill level: 150 -- Lowers enemy's INT. Chance of lowering INT varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Snow Gorget & Aqua Gorget. -- Aligned with the Snow Belt & Aqua Belt. -- Element: None -- Modifiers: STR:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end if damage > 0 and (target:hasStatusEffect(EFFECT_INT_DOWN) == false) then target:addStatusEffect(EFFECT_INT_DOWN, 10, 0, 140); end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
greasydeal/darkstar
scripts/globals/items/plate_of_mushroom_paella.lua
36
1409
----------------------------------------- -- ID: 5970 -- Item: Plate of Mushroom Paella -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- HP 40 -- Strength -1 -- Mind 5 -- Magic Accuracy 5 -- Undead Killer 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,10800,5970); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 40); target:addMod(MOD_STR, -1); target:addMod(MOD_MND, 5); target:addMod(MOD_MACC, 5); target:addMod(MOD_UNDEAD_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 40); target:delMod(MOD_STR, -1); target:delMod(MOD_MND, 5); target:delMod(MOD_MACC, 5); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
bbn1234/uzzbot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
pleonex/telegram-bot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
everhopingandwaiting/telegram-bot
plugins/danbooru.lua
616
1750
do local URL = "http://danbooru.donmai.us" local URL_NEW = "/posts.json" local URL_POP = "/explore/posts/popular.json" local scale_day = "?scale=day" local scale_week = "?scale=week" local scale_month = "?scale=month" local function get_post(url) local b, c, h = http.request(url) if c ~= 200 then return nil end local posts = json:decode(b) return posts[math.random(#posts)] end local function run(msg, matches) local url = URL if matches[1] == "!danbooru" then url = url .. URL_NEW else url = url .. URL_POP if matches[1] == "d" then url = url .. scale_day elseif matches[1] == "w" then url = url .. scale_week elseif matches[1] == "m" then url = url .. scale_month end end local post = get_post(url) if post then vardump(post) local img = URL .. post.large_file_url send_photo_from_url(get_receiver(msg), img) local txt = '' if post.tag_string_artist ~= '' then txt = 'Artist: ' .. post.tag_string_artist .. '\n' end if post.tag_string_character ~= '' then txt = txt .. 'Character: ' .. post.tag_string_character .. '\n' end if post.file_size ~= '' then txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url end return txt end end return { description = "Gets a random fresh or popular image from Danbooru", usage = { "!danbooru - gets a random fresh image from Danbooru 🔞", "!danboorud - random daily popular image 🔞", "!danbooruw - random weekly popular image 🔞", "!danboorum - random monthly popular image 🔞" }, patterns = { "^!danbooru$", "^!danbooru ?(d)$", "^!danbooru ?(w)$", "^!danbooru ?(m)$" }, run = run } end
gpl-2.0
naclander/tome
game/modules/tome/data/maps/vaults/hostel.lua
3
2066
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org setStatusAll{no_teleport=true} rotates = {"default", "90", "180", "270", "flipx", "flipy"} defineTile(' ', "FLOOR") defineTile('+', "DOOR") defineTile('!', "DOOR_VAULT") defineTile('X', "HARDWALL") defineTile('$', "FLOOR", {random_filter={add_levels=10, tome_mod="vault"}}) defineTile('~', "FLOOR", {random_filter={add_levels=5}}, nil, {random_filter={add_levels=5}}) defineTile('^', "FLOOR", nil, nil, {random_filter={add_levels=5}}) defineTile('o', "FLOOR", {random_filter={add_levels=10, tome_mod="vault"}}, {random_filter={add_levels=10}}) defineTile('O', "FLOOR", {random_filter={add_levels=15, tome_mod="vault"}}, {random_filter={add_levels=15}}) defineTile('P', "FLOOR", {random_filter={add_levels=20, tome_mod="gvault"}}, {random_filter={add_levels=20}}) startx = 28 starty = 8 return { [[XXXXXXXXXXXXXXXXXXXXXXXXXXXXX]], [[X~~^+ ^+$$X]], [[X~~^X XXXXXX+XXX+XXXXXX+XXXXX]], [[XXXXX X ooXo X XPPX $o X]], [[X$$$X + ooX o X o XOOXo$oo X]], [[X X X ooX XXX~~$X$$XXXX X]], [[XO ^X X ooXo OX$$~X$o oX]], [[XO ^+ XXXXXXXXXXXXXXXXXXXXXXX]], [[XO ^X ^!]], [[XXXXX+XXX+XXXXX+XXX+XXXXX+XXX]], [[X~XX XO +$X Xo +$X XX]], [[X$XX X O XXXO oX oXXX o XX]], [[X$~+ P Xo XP+ X O X$+ oXX]], [[XXXXXXXXXXXXXXXXXXXXXXXXXXXXX]], }
gpl-3.0
LegionXI/darkstar
scripts/zones/West_Sarutabaruta_[S]/npcs/Sealed_Entrance_2.lua
29
2250
----------------------------------- -- Area: West Sarutabaruta [S] -- NPC: Sealed Entrance (Sealed_Entrance_2) -- @pos 263.600 -6.512 40.000 95 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/West_Sarutabaruta_[S]/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local QuestStatus = player:getQuestStatus(CRYSTAL_WAR, SNAKE_ON_THE_PLAINS); local HasPutty = player:hasKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY); local MaskBit1 = player:getMaskBit(player:getVar("SEALED_DOORS"),0) local MaskBit2 = player:getMaskBit(player:getVar("SEALED_DOORS"),1) local MaskBit3 = player:getMaskBit(player:getVar("SEALED_DOORS"),2) if (QuestStatus == QUEST_ACCEPTED and HasPutty) then if (MaskBit2 == false) then if (MaskBit1 == false or MaskBit3 == false) then player:setMaskBit(player:getVar("SEALED_DOORS"),"SEALED_DOORS",1,true); player:messageSpecial(DOOR_OFFSET+1,ZONPAZIPPAS_ALLPURPOSE_PUTTY); else player:setMaskBit(player:getVar("SEALED_DOORS"),"SEALED_DOORS",1,true); player:messageSpecial(DOOR_OFFSET+4,ZONPAZIPPAS_ALLPURPOSE_PUTTY); player:delKeyItem(ZONPAZIPPAS_ALLPURPOSE_PUTTY); end else player:messageSpecial(DOOR_OFFSET+2,ZONPAZIPPAS_ALLPURPOSE_PUTTY); end elseif (player:getQuestStatus(CRYSTAL_WAR,SNAKE_ON_THE_PLAINS) == QUEST_COMPLETED) then player:messageSpecial(DOOR_OFFSET+2, ZONPAZIPPAS_ALLPURPOSE_PUTTY); else player:messageSpecial(DOOR_OFFSET+3); 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
lache/RacingKingLee
crazyclient/frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/TMXObjectGroup.lua
18
3248
-------------------------------- -- @module TMXObjectGroup -- @extend Ref -- @parent_module cc -------------------------------- -- Sets the offset position of child objects. <br> -- param offset The offset position of child objects. -- @function [parent=#TMXObjectGroup] setPositionOffset -- @param self -- @param #vec2_table offset -- @return TMXObjectGroup#TMXObjectGroup self (return value: cc.TMXObjectGroup) -------------------------------- -- Return the value for the specific property name. <br> -- param propertyName The specific property name.<br> -- return Return the value for the specific property name.<br> -- js NA -- @function [parent=#TMXObjectGroup] getProperty -- @param self -- @param #string propertyName -- @return Value#Value ret (return value: cc.Value) -------------------------------- -- Gets the offset position of child objects. <br> -- return The offset position of child objects. -- @function [parent=#TMXObjectGroup] getPositionOffset -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- Return the dictionary for the specific object name.<br> -- It will return the 1st object found on the array for the given name.<br> -- return Return the dictionary for the specific object name. -- @function [parent=#TMXObjectGroup] getObject -- @param self -- @param #string objectName -- @return map_table#map_table ret (return value: map_table) -------------------------------- -- @overload self -- @overload self -- @function [parent=#TMXObjectGroup] getObjects -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- Set the group name. <br> -- param groupName A string,it is used to set the group name. -- @function [parent=#TMXObjectGroup] setGroupName -- @param self -- @param #string groupName -- @return TMXObjectGroup#TMXObjectGroup self (return value: cc.TMXObjectGroup) -------------------------------- -- @overload self -- @overload self -- @function [parent=#TMXObjectGroup] getProperties -- @param self -- @return map_table#map_table ret (return value: map_table) -------------------------------- -- Get the group name. <br> -- return The group name. -- @function [parent=#TMXObjectGroup] getGroupName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Sets the list of properties.<br> -- param properties The list of properties. -- @function [parent=#TMXObjectGroup] setProperties -- @param self -- @param #map_table properties -- @return TMXObjectGroup#TMXObjectGroup self (return value: cc.TMXObjectGroup) -------------------------------- -- Sets the array of the objects.<br> -- param objects The array of the objects. -- @function [parent=#TMXObjectGroup] setObjects -- @param self -- @param #array_table objects -- @return TMXObjectGroup#TMXObjectGroup self (return value: cc.TMXObjectGroup) -------------------------------- -- js ctor -- @function [parent=#TMXObjectGroup] TMXObjectGroup -- @param self -- @return TMXObjectGroup#TMXObjectGroup self (return value: cc.TMXObjectGroup) return nil
mit
Igalia/snabbswitch
src/apps/lwaftr/ndp.lua
2
18478
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- NDP address resolution (RFC 4861) -- This app uses the neighbor discovery protocol to determine the -- Ethernet address of an IPv6 next-hop. It's a limited -- implementation; if you need to route traffic to multiple IPv6 -- next-hops on the local network, probably you want to build a more -- capable NDP app. -- -- All non-NDP traffic coming in on the "south" interface (i.e., from -- the network card) is directly forwarded out the "north" interface -- to be handled by the network function. Incoming traffic on the -- "north" inferface is dropped until the MAC address of the next-hop -- is known. Once we do have a MAC address for the next-hop, this app -- sends all outgoing traffic there, overwriting the source and -- destination Ethernet addresses on outgoing southbound traffic. module(..., package.seeall) local bit = require("bit") local ffi = require("ffi") local packet = require("core.packet") local link = require("core.link") local lib = require("core.lib") local shm = require("core.shm") local checksum = require("lib.checksum") local datagram = require("lib.protocol.datagram") local ethernet = require("lib.protocol.ethernet") local ipv6 = require("lib.protocol.ipv6") local alarms = require("lib.yang.alarms") local counter = require("core.counter") local S = require("syscall") alarms.add_to_inventory( {alarm_type_id='ndp-resolution'}, {resource=tostring(S.getpid()), has_clear=true, description='Raise up if NDP app cannot resolve IPv6 address'}) local resolve_alarm = alarms.declare_alarm( {resource=tostring(S.getpid()), alarm_type_id='ndp-resolution'}, {perceived_severity = 'critical', alarm_text = 'Make sure you can NDP resolve IP addresses on NIC'}) local htons, ntohs = lib.htons, lib.ntohs local htonl, ntohl = lib.htonl, lib.ntohl local receive, transmit = link.receive, link.transmit local mac_t = ffi.typeof('uint8_t[6]') local ether_header_t = ffi.typeof [[ /* All values in network byte order. */ struct { uint8_t dhost[6]; uint8_t shost[6]; uint16_t type; } __attribute__((packed)) ]] local ipv6_header_t = ffi.typeof [[ /* All values in network byte order. */ struct { uint32_t v_tc_fl; // version, tc, flow_label uint16_t payload_length; uint8_t next_header; uint8_t hop_limit; uint8_t src_ip[16]; uint8_t dst_ip[16]; } __attribute__((packed)) ]] local icmpv6_header_t = ffi.typeof [[ /* All values in network byte order. */ struct { uint8_t type; uint8_t code; uint16_t checksum; } __attribute__((packed)) ]] local na_header_t = ffi.typeof [[ /* All values in network byte order. */ struct { uint32_t flags; /* Bit 31: Router; Bit 30: Solicited; Bit 29: Override; Bits 28-0: Reserved. */ uint8_t target_ip[16]; uint8_t options[0]; } __attribute__((packed)) ]] local ns_header_t = ffi.typeof [[ /* All values in network byte order. */ struct { uint32_t flags; /* Bits 31-0: Reserved. */ uint8_t target_ip[16]; uint8_t options[0]; } __attribute__((packed)) ]] local option_header_t = ffi.typeof [[ /* All values in network byte order. */ struct { uint8_t type; uint8_t length; } __attribute__((packed)) ]] local ether_option_header_t = ffi.typeof ([[ /* All values in network byte order. */ struct { $ header; uint8_t addr[6]; } __attribute__((packed)) ]], option_header_t) local ipv6_pseudoheader_t = ffi.typeof [[ struct { char src_ip[16]; char dst_ip[16]; uint32_t ulp_length; uint32_t next_header; } __attribute__((packed)) ]] local ndp_header_t = ffi.typeof([[ struct { $ ether; $ ipv6; $ icmpv6; uint8_t body[0]; } __attribute__((packed))]], ether_header_t, ipv6_header_t, icmpv6_header_t) local function ptr_to(t) return ffi.typeof('$*', t) end local ether_header_ptr_t = ptr_to(ether_header_t) local ndp_header_ptr_t = ptr_to(ndp_header_t) local na_header_ptr_t = ptr_to(na_header_t) local ns_header_ptr_t = ptr_to(ns_header_t) local option_header_ptr_t = ptr_to(option_header_t) local ether_option_header_ptr_t = ptr_to(ether_option_header_t) local ndp_header_len = ffi.sizeof(ndp_header_t) local ether_type_ipv6 = 0x86DD local proto_icmpv6 = 58 local icmpv6_ns = 135 local icmpv6_na = 136 local na_router_bit = 31 local na_solicited_bit = 30 local na_override_bit = 29 local option_source_link_layer_address = 1 local option_target_link_layer_address = 2 -- Special addresses local ipv6_all_nodes_local_segment_addr = ipv6:pton("ff02::1") local ipv6_unspecified_addr = ipv6:pton("0::0") -- aka ::/128 -- Really just the first 13 bytes of the following... local ipv6_solicited_multicast = ipv6:pton("ff02:0000:0000:0000:0000:0001:ff00:00") local scratch_ph = ipv6_pseudoheader_t() local function checksum_pseudoheader_from_header(ipv6_fixed_header) scratch_ph.src_ip = ipv6_fixed_header.src_ip scratch_ph.dst_ip = ipv6_fixed_header.dst_ip scratch_ph.ulp_length = htonl(ntohs(ipv6_fixed_header.payload_length)) scratch_ph.next_header = htonl(ipv6_fixed_header.next_header) return checksum.ipsum(ffi.cast('char*', scratch_ph), ffi.sizeof(ipv6_pseudoheader_t), 0) end local function is_ndp(pkt) if pkt.length < ndp_header_len then return false end local h = ffi.cast(ndp_header_ptr_t, pkt.data) if ntohs(h.ether.type) ~= ether_type_ipv6 then return false end if h.ipv6.next_header ~= proto_icmpv6 then return false end return h.icmpv6.type >= 133 and h.icmpv6.type <= 137 end local function make_ndp_packet(src_mac, dst_mac, src_ip, dst_ip, message_type, message, option) local pkt = packet.allocate() pkt.length = ndp_header_len local h = ffi.cast(ndp_header_ptr_t, pkt.data) h.ether.dhost = dst_mac h.ether.shost = src_mac h.ether.type = htons(ether_type_ipv6) h.ipv6.v_tc_fl = 0 lib.bitfield(32, h.ipv6, 'v_tc_fl', 0, 4, 6) -- IPv6 Version lib.bitfield(32, h.ipv6, 'v_tc_fl', 4, 8, 0) -- Traffic class lib.bitfield(32, h.ipv6, 'v_tc_fl', 12, 20, 0) -- Flow label h.ipv6.payload_length = 0 h.ipv6.next_header = proto_icmpv6 h.ipv6.hop_limit = 255 h.ipv6.src_ip = src_ip h.ipv6.dst_ip = dst_ip h.icmpv6.type = message_type h.icmpv6.code = 0 h.icmpv6.checksum = 0 packet.append(pkt, message, ffi.sizeof(message)) packet.append(pkt, option, ffi.sizeof(option)) -- Now fix up lengths and checksums. h.ipv6.payload_length = htons(pkt.length - ffi.sizeof(ether_header_t) - ffi.sizeof(ipv6_header_t)) ptr = ffi.cast('char*', h.icmpv6) local base_checksum = checksum_pseudoheader_from_header(h.ipv6) h.icmpv6.checksum = htons(checksum.ipsum(ptr, pkt.length - (ptr - pkt.data), bit.bnot(base_checksum))) return pkt end -- Respond to a neighbor solicitation for our own address. local function make_na_packet(src_mac, dst_mac, src_ip, dst_ip, is_router) local message = na_header_t() local flags = bit.lshift(1, na_solicited_bit) if is_router then flags = bit.bor(bit.lshift(1, na_router_bit), flags) end message.flags = htonl(flags) message.target_ip = src_ip local option = ether_option_header_t() option.header.type = option_target_link_layer_address option.header.length = 1 -- One 8-byte unit. option.addr = src_mac return make_ndp_packet(src_mac, dst_mac, src_ip, dst_ip, icmpv6_na, message, option) end -- Solicit a neighbor's address. local function make_ns_packet(src_mac, src_ip, dst_ip) local message = ns_header_t() message.flags = 0 message.target_ip = dst_ip local option = ether_option_header_t() option.header.type = option_source_link_layer_address option.header.length = 1 -- One 8-byte unit. option.addr = src_mac local broadcast_mac = ethernet:pton("ff:ff:ff:ff:ff:ff") return make_ndp_packet(src_mac, broadcast_mac, src_ip, dst_ip, icmpv6_ns, message, option) end local function verify_icmp_checksum(pkt) local h = ffi.cast(ndp_header_ptr_t, pkt.data) local ph_csum = checksum_pseudoheader_from_header(h.ipv6) local icmp_length = ntohs(h.ipv6.payload_length) local a = checksum.ipsum(ffi.cast('char*', h.icmpv6), icmp_length, bit.bnot(ph_csum)) return a == 0 end local function ipv6_eq(a, b) return ffi.C.memcmp(a, b, 16) == 0 end -- IPv6 multicast addresses start with FF. local function is_address_multicast(ipv6_addr) return ipv6_addr[0] == 0xff end -- Solicited multicast addresses have their first 13 bytes set to -- ff02::1:ff00:0/104, aka ff02:0000:0000:0000:0000:0001:ff[UV:WXYZ]. local function is_solicited_node_multicast_address(addr) return ffi.C.memcmp(addr, ipv6_solicited_multicast, 13) == 0 end local function random_locally_administered_unicast_mac_address() local mac = lib.random_bytes(6) -- Bit 0 is 0, indicating unicast. Bit 1 is 1, indicating locally -- administered. mac[0] = bit.lshift(mac[0], 2) + 2 return mac end NDP = {} NDP.shm = { ["next-hop-macaddr-v6"] = {counter}, } local ndp_config_params = { -- Source MAC address will default to a random address. self_mac = { default=false }, -- Source IP is required though. self_ip = { required=true }, -- The next-hop MAC address can be statically configured. next_mac = { default=false }, -- But if the next-hop MAC isn't configured, NDP will figure it out. next_ip = { default=false }, is_router = { default=true }, -- Emit alarms if set. alarm_notification = { default=false }, -- This NDP resolver might be part of a set of peer processes sharing -- work via RSS. In that case, a response will probably arrive only -- at one process, not all of them! In that case we can arrange for -- the NDP app that receives the reply to write the resolved next-hop -- to a shared file. RSS peers can poll that file. shared_next_mac_key = {}, } function NDP:new(conf) local o = lib.parse(conf, ndp_config_params) if not o.self_mac then o.self_mac = random_locally_administered_unicast_mac_address() end if not o.next_mac then assert(o.next_ip, 'NDP needs next-hop IPv6 address to learn next-hop MAC') self.ns_interval = 3 -- Send a new NS every three seconds. end return setmetatable(o, {__index=NDP}) end function NDP:ndp_resolving (ip) print(("NDP: Resolving '%s'"):format(ipv6:ntop(ip))) if self.alarm_notification then resolve_alarm:raise() end end function NDP:maybe_send_ns_request (output) if self.next_mac then return end self.next_ns_time = self.next_ns_time or engine.now() if self.next_ns_time <= engine.now() then self:ndp_resolving(self.next_ip) transmit(self.output.south, make_ns_packet(self.self_mac, self.self_ip, self.next_ip)) self.next_ns_time = engine.now() + self.ns_interval end end function NDP:ndp_resolved (ip, mac, provenance) print(("NDP: '%s' resolved (%s)"):format(ipv6:ntop(ip), ethernet:ntop(mac))) if self.alarm_notification then resolve_alarm:clear() end self.next_mac = mac if self.next_mac then local buf = ffi.new('union { uint64_t u64; uint8_t bytes[6]; }') buf.bytes = self.next_mac counter.set(self.shm["next-hop-macaddr-v6"], buf.u64) end if self.shared_next_mac_key then if provenance == 'remote' then -- If we are getting this information from a packet and not -- from the shared key, then update the shared key. local ok, shared = pcall(shm.create, self.shared_next_mac_key, mac_t) if not ok then ok, shared = pcall(shm.open, self.shared_next_mac_key, mac_t) end if not ok then print('warning: ndp: failed to update shared next MAC key!') else ffi.copy(shared, mac, 6) shm.unmap(shared) end else assert(provenance == 'peer') -- Pass. end end end function NDP:resolve_next_hop(next_mac) -- It's possible for a NA packet to indicate the MAC address in -- more than one way (e.g. unicast ethernet source address and the -- link layer address in the NDP options). Just take the first -- one. if self.next_mac then return end self:ndp_resolved(self.next_ip, next_mac, 'remote') end local function copy_mac(src) local dst = ffi.new('uint8_t[6]') ffi.copy(dst, src, 6) return dst end function NDP:handle_ndp (pkt) local h = ffi.cast(ndp_header_ptr_t, pkt.data) -- Generic checks. if h.ipv6.hop_limit ~= 255 then return end if h.icmpv6.code ~= 0 then return end if not verify_icmp_checksum(pkt) then return end if h.icmpv6.type == icmpv6_na then -- Only process advertisements when we are looking for a -- next-hop MAC. if self.next_mac then return end -- Drop packets that are too short. if pkt.length < ndp_header_len + ffi.sizeof(na_header_t) then return end local na = ffi.cast(na_header_ptr_t, h.body) local solicited = bit.lshift(1, na_solicited_bit) -- Reject unsolicited advertisements. if bit.band(solicited, ntohl(na.flags)) ~= solicited then return end -- We only are looking for the MAC of our next-hop; no others. if not ipv6_eq(na.target_ip, self.next_ip) then return end -- First try to get the MAC from the options. local offset = na.options - pkt.data while offset < pkt.length do local option = ffi.cast(option_header_ptr_t, pkt.data + offset) -- Any option whose length is 0 or too large causes us to -- drop the packet. if option.length == 0 then return end if offset + option.length*8 > pkt.length then return end offset = offset + option.length*8 if option.type == option_target_link_layer_address then if option.length ~= 1 then return end local ether = ffi.cast(ether_option_header_ptr_t, option) self:resolve_next_hop(copy_mac(ether.addr)) end end -- Otherwise, when responding to unicast solicitations, the -- option can be omitted since the sender of the solicitation -- has the correct link-layer address. See 4.4. Neighbor -- Advertisement Message Format. self:resolve_next_hop(copy_mac(h.ether.shost)) elseif h.icmpv6.type == icmpv6_ns then if pkt.length < ndp_header_len + ffi.sizeof(ns_header_t) then return end local ns = ffi.cast(ns_header_ptr_t, h.body) if is_address_multicast(ns.target_ip) then return end if not ipv6_eq(ns.target_ip, self.self_ip) then return end local dst_ip if ipv6_eq(h.ipv6.src_ip, ipv6_unspecified_addr) then if is_solicited_node_multicast_address(h.ipv6.dst_ip) then return end dst_ip = ipv6_all_nodes_local_segment_addr else dst_ip = h.ipv6.src_ip end -- We don't need the options, but we do need to check them for -- validity. local offset = ns.options - pkt.data while offset < pkt.length do local option = ffi.cast(option_header_ptr_t, pkt.data + offset) -- Any option whose length is 0 or too large causes us to -- drop the packet. if option.length == 0 then return end if offset + option.length * 8 > pkt.length then return end offset = offset + option.length*8 if option.type == option_source_link_layer_address then if ipv6_eq(h.ipv6.src_ip, ipv6_unspecified_addr) then return end end end link.transmit(self.output.south, make_na_packet(self.self_mac, h.ether.shost, self.self_ip, dst_ip, self.is_router)) else -- Unhandled NDP packet; silently drop. return end end function NDP:push() local isouth, osouth = self.input.south, self.output.south local inorth, onorth = self.input.north, self.output.north -- TODO: do unsolicited neighbor advertisement on start and on -- configuration reloads? -- This would be an optimization, not a correctness issue self:maybe_send_ns_request(osouth) for _ = 1, link.nreadable(isouth) do local p = receive(isouth) if is_ndp(p) then self:handle_ndp(p) packet.free(p) else transmit(onorth, p) end end -- Don't read southbound packets until the next hop's ethernet -- address is known. if self.next_mac then for _ = 1, link.nreadable(inorth) do local p = receive(inorth) local h = ffi.cast(ether_header_ptr_t, p.data) h.shost = self.self_mac h.dhost = self.next_mac transmit(osouth, p) end elseif self.shared_next_mac_key then local ok, mac = pcall(shm.open, self.shared_next_mac_key, mac_t) -- Use the shared pointer directly, without copying; if it is ever -- updated, we will get its new value. if ok then self:ndp_resolved(self.next_ip, mac, 'peer') end end end function selftest() print("selftest: ndp") local config = require("core.config") local sink = require("apps.basic.basic_apps").Sink local c = config.new() config.app(c, "nd1", NDP, { self_ip = ipv6:pton("2001:DB8::1"), next_ip = ipv6:pton("2001:DB8::2"), shared_next_mac_key = "foo" }) config.app(c, "nd2", NDP, { self_ip = ipv6:pton("2001:DB8::2"), next_ip = ipv6:pton("2001:DB8::1"), shared_next_mac_key = "bar" }) config.app(c, "sink1", sink) config.app(c, "sink2", sink) config.link(c, "nd1.south -> nd2.south") config.link(c, "nd2.south -> nd1.south") config.link(c, "sink1.tx -> nd1.north") config.link(c, "nd1.north -> sink1.rx") config.link(c, "sink2.tx -> nd2.north") config.link(c, "nd2.north -> sink2.rx") engine.configure(c) engine.main({ duration = 0.1 }) local function mac_eq(a, b) return ffi.C.memcmp(a, b, 6) == 0 end local nd1, nd2 = engine.app_table.nd1, engine.app_table.nd2 assert(nd1.next_mac) assert(nd2.next_mac) assert(mac_eq(nd1.next_mac, nd2.self_mac)) assert(mac_eq(nd2.next_mac, nd1.self_mac)) print("selftest: ok") end
apache-2.0
bittorf/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/wifi.lua
7
11454
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- Data init -- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() if not uci:get("network", "wan") then uci:section("network", "interface", "wan", {proto="none", ifname=" "}) uci:save("network") uci:commit("network") end local wlcursor = luci.model.uci.cursor_state() local wireless = wlcursor:get_all("wireless") local wifidevs = {} local ifaces = {} for k, v in pairs(wireless) do if v[".type"] == "wifi-iface" then table.insert(ifaces, v) end end wlcursor:foreach("wireless", "wifi-device", function(section) table.insert(wifidevs, section[".name"]) end) -- Main Map -- m = Map("wireless", translate("Wireless"), translate("Here you can configure installed wifi devices.")) m:chain("network") -- Status Table -- s = m:section(Table, ifaces, translate("Networks")) link = s:option(DummyValue, "_link", translate("Link")) function link.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d/%d" %{ iwinfo.quality, iwinfo.quality_max } or "-" end essid = s:option(DummyValue, "ssid", "ESSID") bssid = s:option(DummyValue, "_bsiid", "BSSID") function bssid.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and iwinfo.bssid or "-" end channel = s:option(DummyValue, "channel", translate("Channel")) function channel.cfgvalue(self, section) return wireless[self.map:get(section, "device")].channel end protocol = s:option(DummyValue, "_mode", translate("Protocol")) function protocol.cfgvalue(self, section) local mode = wireless[self.map:get(section, "device")].mode return mode and "802." .. mode end mode = s:option(DummyValue, "mode", translate("Mode")) encryption = s:option(DummyValue, "encryption", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) power = s:option(DummyValue, "_power", translate("Power")) function power.cfgvalue(self, section) local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) return iwinfo and "%d dBm" % iwinfo.txpower or "-" end scan = s:option(Button, "_scan", translate("Scan")) scan.inputstyle = "find" function scan.cfgvalue(self, section) return self.map:get(section, "ifname") or false end -- WLAN-Scan-Table -- t2 = m:section(Table, {}, translate("<abbr title=\"Wireless Local Area Network\">WLAN</abbr>-Scan"), translate("Wifi networks in your local environment")) function scan.write(self, section) m.autoapply = false t2.render = t2._render local ifname = self.map:get(section, "ifname") local iwinfo = sys.wifi.getiwinfo(ifname) if iwinfo then local _, cell for _, cell in ipairs(iwinfo.scanlist) do t2.data[#t2.data+1] = { Quality = "%d/%d" %{ cell.quality, cell.quality_max }, ESSID = cell.ssid, Address = cell.bssid, Mode = cell.mode, ["Encryption key"] = cell.encryption.enabled and "On" or "Off", ["Signal level"] = "%d dBm" % cell.signal, ["Noise level"] = "%d dBm" % iwinfo.noise } end end end t2._render = t2.render t2.render = function() end t2:option(DummyValue, "Quality", translate("Link")) essid = t2:option(DummyValue, "ESSID", "ESSID") function essid.cfgvalue(self, section) return self.map:get(section, "ESSID") end t2:option(DummyValue, "Address", "BSSID") t2:option(DummyValue, "Mode", translate("Mode")) chan = t2:option(DummyValue, "channel", translate("Channel")) function chan.cfgvalue(self, section) return self.map:get(section, "Channel") or self.map:get(section, "Frequency") or "-" end t2:option(DummyValue, "Encryption key", translate("<abbr title=\"Encrypted\">Encr.</abbr>")) t2:option(DummyValue, "Signal level", translate("Signal")) t2:option(DummyValue, "Noise level", translate("Noise")) if #wifidevs < 1 then return m end -- Config Section -- s = m:section(NamedSection, wifidevs[1], "wifi-device", translate("Devices")) s.addremove = false en = s:option(Flag, "disabled", translate("enable")) en.rmempty = false en.enabled = "0" en.disabled = "1" function en.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end local hwtype = m:get(wifidevs[1], "type") if hwtype == "atheros" then mode = s:option(ListValue, "hwmode", translate("Mode")) mode.override_values = true mode:value("", "auto") mode:value("11b", "802.11b") mode:value("11g", "802.11g") mode:value("11a", "802.11a") mode:value("11bg", "802.11b+g") mode.rmempty = true end ch = s:option(Value, "channel", translate("Channel")) for i=1, 14 do ch:value(i, i .. " (2.4 GHz)") end s = m:section(TypedSection, "wifi-iface", translate("Local Network")) s.anonymous = true s.addremove = false s:option(Value, "ssid", translate("Network Name (<abbr title=\"Extended Service Set Identifier\">ESSID</abbr>)")) bssid = s:option(Value, "bssid", translate("<abbr title=\"Basic Service Set Identifier\">BSSID</abbr>")) local devs = {} luci.model.uci.cursor():foreach("wireless", "wifi-device", function (section) table.insert(devs, section[".name"]) end) if #devs > 1 then device = s:option(DummyValue, "device", translate("Device")) else s.defaults.device = devs[1] end mode = s:option(ListValue, "mode", translate("Mode")) mode.override_values = true mode:value("ap", translate("Provide (Access Point)")) mode:value("adhoc", translate("Independent (Ad-Hoc)")) mode:value("sta", translate("Join (Client)")) function mode.write(self, section, value) if value == "sta" then local oldif = m.uci:get("network", "wan", "ifname") if oldif and oldif ~= " " then m.uci:set("network", "wan", "_ifname", oldif) end m.uci:set("network", "wan", "ifname", " ") self.map:set(section, "network", "wan") else if m.uci:get("network", "wan", "_ifname") then m.uci:set("network", "wan", "ifname", m.uci:get("network", "wan", "_ifname")) end self.map:set(section, "network", "lan") end return ListValue.write(self, section, value) end encr = s:option(ListValue, "encryption", translate("Encryption")) encr.override_values = true encr:value("none", "No Encryption") encr:value("wep", "WEP") if hwtype == "atheros" or hwtype == "mac80211" then local supplicant = fs.access("/usr/sbin/wpa_supplicant") local hostapd = fs.access("/usr/sbin/hostapd") if hostapd and supplicant then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode") encr:value("wpa", "WPA-Radius", {mode="ap"}, {mode="sta"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}, {mode="sta"}) elseif hostapd and not supplicant then encr:value("psk", "WPA-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk2", "WPA2-PSK", {mode="ap"}, {mode="adhoc"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="ap"}, {mode="adhoc"}) encr:value("wpa", "WPA-Radius", {mode="ap"}) encr:value("wpa2", "WPA2-Radius", {mode="ap"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) elseif not hostapd and supplicant then encr:value("psk", "WPA-PSK", {mode="sta"}) encr:value("psk2", "WPA2-PSK", {mode="sta"}) encr:value("psk-mixed", "WPA-PSK/WPA2-PSK Mixed Mode", {mode="sta"}) encr:value("wpa", "WPA-EAP", {mode="sta"}) encr:value("wpa2", "WPA2-EAP", {mode="sta"}) encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) else encr.description = translate( "WPA-Encryption requires wpa_supplicant (for client mode) or hostapd (for AP " .. "and ad-hoc mode) to be installed." ) end elseif hwtype == "broadcom" then encr:value("psk", "WPA-PSK") encr:value("psk2", "WPA2-PSK") encr:value("psk+psk2", "WPA-PSK/WPA2-PSK Mixed Mode") end key = s:option(Value, "key", translate("Key")) key:depends("encryption", "wep") key:depends("encryption", "psk") key:depends("encryption", "psk2") key:depends("encryption", "psk+psk2") key:depends("encryption", "psk-mixed") key:depends({mode="ap", encryption="wpa"}) key:depends({mode="ap", encryption="wpa2"}) key.rmempty = true key.password = true server = s:option(Value, "server", translate("Radius-Server")) server:depends({mode="ap", encryption="wpa"}) server:depends({mode="ap", encryption="wpa2"}) server.rmempty = true port = s:option(Value, "port", translate("Radius-Port")) port:depends({mode="ap", encryption="wpa"}) port:depends({mode="ap", encryption="wpa2"}) port.rmempty = true if hwtype == "atheros" or hwtype == "mac80211" then nasid = s:option(Value, "nasid", translate("NAS ID")) nasid:depends({mode="ap", encryption="wpa"}) nasid:depends({mode="ap", encryption="wpa2"}) nasid.rmempty = true eaptype = s:option(ListValue, "eap_type", translate("EAP-Method")) eaptype:value("TLS") eaptype:value("TTLS") eaptype:value("PEAP") eaptype:depends({mode="sta", encryption="wpa"}) eaptype:depends({mode="sta", encryption="wpa2"}) cacert = s:option(FileUpload, "ca_cert", translate("Path to CA-Certificate")) cacert:depends({mode="sta", encryption="wpa"}) cacert:depends({mode="sta", encryption="wpa2"}) privkey = s:option(FileUpload, "priv_key", translate("Path to Private Key")) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkey:depends({mode="sta", eap_type="TLS", encryption="wpa"}) privkeypwd = s:option(Value, "priv_key_pwd", translate("Password of Private Key")) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa2"}) privkeypwd:depends({mode="sta", eap_type="TLS", encryption="wpa"}) auth = s:option(Value, "auth", translate("Authentication")) auth:value("PAP") auth:value("CHAP") auth:value("MSCHAP") auth:value("MSCHAPV2") auth:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) auth:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) auth:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) identity = s:option(Value, "identity", translate("Identity")) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) identity:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) identity:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) password = s:option(Value, "password", translate("Password")) password:depends({mode="sta", eap_type="PEAP", encryption="wpa2"}) password:depends({mode="sta", eap_type="PEAP", encryption="wpa"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa2"}) password:depends({mode="sta", eap_type="TTLS", encryption="wpa"}) end if hwtype == "atheros" or hwtype == "broadcom" then iso = s:option(Flag, "isolate", translate("AP-Isolation"), translate("Prevents Client to Client communication")) iso.rmempty = true iso:depends("mode", "ap") hide = s:option(Flag, "hidden", translate("Hide <abbr title=\"Extended Service Set Identifier\">ESSID</abbr>")) hide.rmempty = true hide:depends("mode", "ap") end if hwtype == "mac80211" or hwtype == "atheros" then bssid:depends({mode="adhoc"}) end if hwtype == "broadcom" then bssid:depends({mode="wds"}) bssid:depends({mode="adhoc"}) end return m
apache-2.0
peymankhanas8487/Horror-Avatar
plugins/banhammer.lua
294
10470
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end 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 if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
greasydeal/darkstar
scripts/zones/Windurst_Walls/npcs/Moan-Maon.lua
38
1408
----------------------------------- -- Area: Windurst Walls -- NPC: Moan-Maon -- Type: Standard NPC -- @pos 88.244 -6.32 148.912 239 ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,7) == false) then player:startEvent(0x01f1); else player:startEvent(0x0133); 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); if (csid == 0x01f1) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",7,true); end end;
gpl-3.0
greasydeal/darkstar
scripts/globals/weaponskills/dark_harvest.lua
29
1229
----------------------------------- -- Dark Harvest -- Scythe weapon skill -- Skill Level: 30 -- Delivers a dark elemental attack. Damage varies with TP. -- Aligned with the Aqua Gorget. -- Aligned with the Aqua Belt. -- Element: Dark -- Modifiers: STR:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_DARK; params.skill = SKILL_SYH; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
naclander/tome
game/modules/tome/data/gfx/particles/megaspeed.lua
3
1409
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org base_size = 64 return { generator = function() local pos = rng.range(-32, 32) local power = 32 - math.abs(pos) local life = power / 2 local size = rng.range(2, 5) local angle = math.rad(angle) return { trail = 1, life = life * 6, size = size, sizev = -0.02, sizea = 0, x = pos * math.cos(angle+math.rad(90)), xv = 0, xa = 0, y = pos * math.sin(angle+math.rad(90)), yv = 0, ya = 0, dir = angle, dirv = 0, dira = 0, vel = 8, velv = 0, vela = 0, r = 00, rv = 0, ra = 0, g = 0, gv = 0, ga = 0, b = 255, bv = 0, ba = 0, a = 1, av = -0.02, aa = 0, } end, }, function(self) self.ps:emit(20) end, 20 * 6
gpl-3.0
lbthomsen/openwrt-luci
modules/luci-compat/luasrc/model/network.lua
5
42342
-- Copyright 2009-2015 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local type, next, pairs, ipairs, loadfile, table, select = type, next, pairs, ipairs, loadfile, table, select local tonumber, tostring, math = tonumber, tostring, math local pcall, require, setmetatable = pcall, require, setmetatable local nxo = require "nixio" local nfs = require "nixio.fs" local ipc = require "luci.ip" local utl = require "luci.util" local uci = require "luci.model.uci" local lng = require "luci.i18n" local jsc = require "luci.jsonc" module "luci.model.network" IFACE_PATTERNS_VIRTUAL = { } IFACE_PATTERNS_IGNORE = { "^wmaster%d", "^wifi%d", "^hwsim%d", "^imq%d", "^ifb%d", "^mon%.wlan%d", "^sit%d", "^gre%d", "^gretap%d", "^ip6gre%d", "^ip6tnl%d", "^tunl%d", "^lo$" } IFACE_PATTERNS_WIRELESS = { "^wlan%d", "^wl%d", "^ath%d", "^%w+%.network%d" } IFACE_ERRORS = { CONNECT_FAILED = lng.translate("Connection attempt failed"), INVALID_ADDRESS = lng.translate("IP address is invalid"), INVALID_GATEWAY = lng.translate("Gateway address is invalid"), INVALID_LOCAL_ADDRESS = lng.translate("Local IP address is invalid"), MISSING_ADDRESS = lng.translate("IP address is missing"), MISSING_PEER_ADDRESS = lng.translate("Peer address is missing"), NO_DEVICE = lng.translate("Network device is not present"), NO_IFACE = lng.translate("Unable to determine device name"), NO_IFNAME = lng.translate("Unable to determine device name"), NO_WAN_ADDRESS = lng.translate("Unable to determine external IP address"), NO_WAN_LINK = lng.translate("Unable to determine upstream interface"), PEER_RESOLVE_FAIL = lng.translate("Unable to resolve peer host name"), PIN_FAILED = lng.translate("PIN code rejected") } protocol = utl.class() local _protocols = { } local _interfaces, _bridge, _switch, _tunnel, _swtopo local _ubusnetcache, _ubusdevcache, _ubuswificache local _uci function _filter(c, s, o, r) local val = _uci:get(c, s, o) if val then local l = { } if type(val) == "string" then for val in val:gmatch("%S+") do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci:set(c, s, o, table.concat(l, " ")) else _uci:delete(c, s, o) end elseif type(val) == "table" then for _, val in ipairs(val) do if val ~= r then l[#l+1] = val end end if #l > 0 then _uci:set(c, s, o, l) else _uci:delete(c, s, o) end end end end function _append(c, s, o, a) local val = _uci:get(c, s, o) or "" if type(val) == "string" then local l = { } for val in val:gmatch("%S+") do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci:set(c, s, o, table.concat(l, " ")) elseif type(val) == "table" then local l = { } for _, val in ipairs(val) do if val ~= a then l[#l+1] = val end end l[#l+1] = a _uci:set(c, s, o, l) end end function _stror(s1, s2) if not s1 or #s1 == 0 then return s2 and #s2 > 0 and s2 else return s1 end end function _get(c, s, o) return _uci:get(c, s, o) end function _set(c, s, o, v) if v ~= nil then if type(v) == "boolean" then v = v and "1" or "0" end return _uci:set(c, s, o, v) else return _uci:delete(c, s, o) end end local function _wifi_state() if not next(_ubuswificache) then _ubuswificache = utl.ubus("network.wireless", "status", {}) or {} end return _ubuswificache end local function _wifi_state_by_sid(sid) local t1, n1 = _uci:get("wireless", sid) if t1 == "wifi-iface" and n1 ~= nil then local radioname, radiostate for radioname, radiostate in pairs(_wifi_state()) do if type(radiostate) == "table" and type(radiostate.interfaces) == "table" then local netidx, netstate for netidx, netstate in ipairs(radiostate.interfaces) do if type(netstate) == "table" and type(netstate.section) == "string" then local t2, n2 = _uci:get("wireless", netstate.section) if t1 == t2 and n1 == n2 then return radioname, radiostate, netstate end end end end end end end local function _wifi_state_by_ifname(ifname) if type(ifname) == "string" then local radioname, radiostate for radioname, radiostate in pairs(_wifi_state()) do if type(radiostate) == "table" and type(radiostate.interfaces) == "table" then local netidx, netstate for netidx, netstate in ipairs(radiostate.interfaces) do if type(netstate) == "table" and type(netstate.ifname) == "string" and netstate.ifname == ifname then return radioname, radiostate, netstate end end end end end end function _wifi_iface(x) local _, p for _, p in ipairs(IFACE_PATTERNS_WIRELESS) do if x:match(p) then return true end end return (nfs.access("/sys/class/net/%s/phy80211" % x) == true) end local function _wifi_iwinfo_by_ifname(ifname, force_phy_only) local stat, iwinfo = pcall(require, "iwinfo") local iwtype = stat and type(ifname) == "string" and iwinfo.type(ifname) local is_nonphy_op = { bitrate = true, quality = true, quality_max = true, mode = true, ssid = true, bssid = true, assoclist = true, encryption = true } if iwtype then -- if we got a type but no real netdev, we're referring to a phy local phy_only = force_phy_only or (ipc.link(ifname).type ~= 1) return setmetatable({}, { __index = function(t, k) if k == "ifname" then return ifname elseif phy_only and is_nonphy_op[k] then return nil elseif iwinfo[iwtype][k] then return iwinfo[iwtype][k](ifname) end end }) end end local function _wifi_sid_by_netid(netid) if type(netid) == "string" then local radioname, netidx = netid:match("^(%w+)%.network(%d+)$") if radioname and netidx then local i, n = 0, nil netidx = tonumber(netidx) _uci:foreach("wireless", "wifi-iface", function(s) if s.device == radioname then i = i + 1 if i == netidx then n = s[".name"] return false end end end) return n end end end function _wifi_sid_by_ifname(ifn) local sid = _wifi_sid_by_netid(ifn) if sid then return sid end local _, _, netstate = _wifi_state_by_ifname(ifn) if netstate and type(netstate.section) == "string" then return netstate.section end end local function _wifi_netid_by_sid(sid) local t, n = _uci:get("wireless", sid) if t == "wifi-iface" and n ~= nil then local radioname = _uci:get("wireless", n, "device") if type(radioname) == "string" then local i, netid = 0, nil _uci:foreach("wireless", "wifi-iface", function(s) if s.device == radioname then i = i + 1 if s[".name"] == n then netid = "%s.network%d" %{ radioname, i } return false end end end) return netid, radioname end end end local function _wifi_netid_by_netname(name) local netid = nil _uci:foreach("wireless", "wifi-iface", function(s) local net for net in utl.imatch(s.network) do if net == name then netid = _wifi_netid_by_sid(s[".name"]) return false end end end) return netid end function _iface_virtual(x) local _, p for _, p in ipairs(IFACE_PATTERNS_VIRTUAL) do if x:match(p) then return true end end return false end function _iface_ignore(x) local _, p for _, p in ipairs(IFACE_PATTERNS_IGNORE) do if x:match(p) then return true end end return false end function init(cursor) _uci = cursor or _uci or uci.cursor() _interfaces = { } _bridge = { } _switch = { } _tunnel = { } _swtopo = { } _ubusnetcache = { } _ubusdevcache = { } _ubuswificache = { } -- read interface information local n, i for n, i in ipairs(nxo.getifaddrs()) do local name = i.name:match("[^:]+") if _iface_virtual(name) then _tunnel[name] = true end if _tunnel[name] or not (_iface_ignore(name) or _iface_virtual(name)) then _interfaces[name] = _interfaces[name] or { idx = i.ifindex or n, name = name, rawname = i.name, flags = { }, ipaddrs = { }, ip6addrs = { } } if i.family == "packet" then _interfaces[name].flags = i.flags _interfaces[name].stats = i.data _interfaces[name].macaddr = ipc.checkmac(i.addr) elseif i.family == "inet" then _interfaces[name].ipaddrs[#_interfaces[name].ipaddrs+1] = ipc.IPv4(i.addr, i.netmask) elseif i.family == "inet6" then _interfaces[name].ip6addrs[#_interfaces[name].ip6addrs+1] = ipc.IPv6(i.addr, i.netmask) end end end -- read bridge informaton local b, l for l in utl.execi("brctl show") do if not l:match("STP") then local r = utl.split(l, "%s+", nil, true) if #r == 4 then b = { name = r[1], id = r[2], stp = r[3] == "yes", ifnames = { _interfaces[r[4]] } } if b.ifnames[1] then b.ifnames[1].bridge = b end _bridge[r[1]] = b _interfaces[r[1]].bridge = b elseif b then b.ifnames[#b.ifnames+1] = _interfaces[r[2]] b.ifnames[#b.ifnames].bridge = b end end end -- read switch topology local boardinfo = jsc.parse(nfs.readfile("/etc/board.json") or "") if type(boardinfo) == "table" and type(boardinfo.switch) == "table" then local switch, layout for switch, layout in pairs(boardinfo.switch) do if type(layout) == "table" and type(layout.ports) == "table" then local _, port local ports = { } local nports = { } local netdevs = { } for _, port in ipairs(layout.ports) do if type(port) == "table" and type(port.num) == "number" and (type(port.role) == "string" or type(port.device) == "string") then local spec = { num = port.num, role = port.role or "cpu", index = port.index or port.num } if port.device then spec.device = port.device spec.tagged = port.need_tag netdevs[tostring(port.num)] = port.device end ports[#ports+1] = spec if port.role then nports[port.role] = (nports[port.role] or 0) + 1 end end end table.sort(ports, function(a, b) if a.role ~= b.role then return (a.role < b.role) end return (a.index < b.index) end) local pnum, role for _, port in ipairs(ports) do if port.role ~= role then role = port.role pnum = 1 end if role == "cpu" then port.label = "CPU (%s)" % port.device elseif nports[role] > 1 then port.label = "%s %d" %{ role:upper(), pnum } pnum = pnum + 1 else port.label = role:upper() end port.role = nil port.index = nil end _swtopo[switch] = { ports = ports, netdevs = netdevs } end end end return _M end function save(self, ...) _uci:save(...) _uci:load(...) end function commit(self, ...) _uci:commit(...) _uci:load(...) end function ifnameof(self, x) if utl.instanceof(x, interface) then return x:name() elseif utl.instanceof(x, protocol) then return x:ifname() elseif type(x) == "string" then return x:match("^[^:]+") end end function get_protocol(self, protoname, netname) local v = _protocols[protoname] if v then return v(netname or "__dummy__") end end function get_protocols(self) local p = { } local _, v for _, v in ipairs(_protocols) do p[#p+1] = v("__dummy__") end return p end function register_protocol(self, protoname) local proto = utl.class(protocol) function proto.__init__(self, name) self.sid = name end function proto.proto(self) return protoname end _protocols[#_protocols+1] = proto _protocols[protoname] = proto return proto end function register_pattern_virtual(self, pat) IFACE_PATTERNS_VIRTUAL[#IFACE_PATTERNS_VIRTUAL+1] = pat end function register_error_code(self, code, message) if type(code) == "string" and type(message) == "string" and not IFACE_ERRORS[code] then IFACE_ERRORS[code] = message return true end return false end function has_ipv6(self) return nfs.access("/proc/net/ipv6_route") end function add_network(self, n, options) local oldnet = self:get_network(n) if n and #n > 0 and n:match("^[a-zA-Z0-9_]+$") and not oldnet then if _uci:section("network", "interface", n, options) then return network(n) end elseif oldnet and oldnet:is_empty() then if options then local k, v for k, v in pairs(options) do oldnet:set(k, v) end end return oldnet end end function get_network(self, n) if n and _uci:get("network", n) == "interface" then return network(n) elseif n then local stat = utl.ubus("network.interface", "status", { interface = n }) if type(stat) == "table" and type(stat.proto) == "string" then return network(n, stat.proto) end end end function get_networks(self) local nets = { } local nls = { } _uci:foreach("network", "interface", function(s) nls[s['.name']] = network(s['.name']) end) local dump = utl.ubus("network.interface", "dump", { }) if type(dump) == "table" and type(dump.interface) == "table" then local _, net for _, net in ipairs(dump.interface) do if type(net) == "table" and type(net.proto) == "string" and type(net.interface) == "string" then if not nls[net.interface] then nls[net.interface] = network(net.interface, net.proto) end end end end local n for n in utl.kspairs(nls) do nets[#nets+1] = nls[n] end return nets end function del_network(self, n) local r = _uci:delete("network", n) if r then _uci:delete_all("luci", "ifstate", function(s) return (s.interface == n) end) _uci:delete_all("network", "alias", function(s) return (s.interface == n) end) _uci:delete_all("network", "route", function(s) return (s.interface == n) end) _uci:delete_all("network", "route6", function(s) return (s.interface == n) end) _uci:foreach("wireless", "wifi-iface", function(s) local net local rest = { } for net in utl.imatch(s.network) do if net ~= n then rest[#rest+1] = net end end if #rest > 0 then _uci:set("wireless", s['.name'], "network", table.concat(rest, " ")) else _uci:delete("wireless", s['.name'], "network") end end) local ok, fw = pcall(require, "luci.model.firewall") if ok then fw.init() fw:del_network(n) end end return r end function rename_network(self, old, new) local r if new and #new > 0 and new:match("^[a-zA-Z0-9_]+$") and not self:get_network(new) then r = _uci:section("network", "interface", new, _uci:get_all("network", old)) if r then _uci:foreach("network", "alias", function(s) if s.interface == old then _uci:set("network", s['.name'], "interface", new) end end) _uci:foreach("network", "route", function(s) if s.interface == old then _uci:set("network", s['.name'], "interface", new) end end) _uci:foreach("network", "route6", function(s) if s.interface == old then _uci:set("network", s['.name'], "interface", new) end end) _uci:foreach("wireless", "wifi-iface", function(s) local net local list = { } for net in utl.imatch(s.network) do if net == old then list[#list+1] = new else list[#list+1] = net end end if #list > 0 then _uci:set("wireless", s['.name'], "network", table.concat(list, " ")) end end) _uci:delete("network", old) end end return r or false end function get_interface(self, i) if _interfaces[i] or _wifi_iface(i) then return interface(i) else local netid = _wifi_netid_by_sid(i) return netid and interface(netid) end end function get_interfaces(self) local iface local ifaces = { } local nfs = { } -- find normal interfaces _uci:foreach("network", "interface", function(s) for iface in utl.imatch(s.ifname) do if not _iface_ignore(iface) and not _iface_virtual(iface) and not _wifi_iface(iface) then nfs[iface] = interface(iface) end end end) for iface in utl.kspairs(_interfaces) do if not (nfs[iface] or _iface_ignore(iface) or _iface_virtual(iface) or _wifi_iface(iface)) then nfs[iface] = interface(iface) end end -- find vlan interfaces _uci:foreach("network", "switch_vlan", function(s) if type(s.ports) ~= "string" or type(s.device) ~= "string" or type(_swtopo[s.device]) ~= "table" then return end local pnum, ptag for pnum, ptag in s.ports:gmatch("(%d+)([tu]?)") do local netdev = _swtopo[s.device].netdevs[pnum] if netdev then if not nfs[netdev] then nfs[netdev] = interface(netdev) end _switch[netdev] = true if ptag == "t" then local vid = tonumber(s.vid or s.vlan) if vid ~= nil and vid >= 0 and vid <= 4095 then local iface = "%s.%d" %{ netdev, vid } if not nfs[iface] then nfs[iface] = interface(iface) end _switch[iface] = true end end end end end) for iface in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[iface] end -- find wifi interfaces local num = { } local wfs = { } _uci:foreach("wireless", "wifi-iface", function(s) if s.device then num[s.device] = num[s.device] and num[s.device] + 1 or 1 local i = "%s.network%d" %{ s.device, num[s.device] } wfs[i] = interface(i) end end) for iface in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[iface] end return ifaces end function ignore_interface(self, x) return _iface_ignore(x) end function get_wifidev(self, dev) if _uci:get("wireless", dev) == "wifi-device" then return wifidev(dev) end end function get_wifidevs(self) local devs = { } local wfd = { } _uci:foreach("wireless", "wifi-device", function(s) wfd[#wfd+1] = s['.name'] end) local dev for _, dev in utl.vspairs(wfd) do devs[#devs+1] = wifidev(dev) end return devs end function get_wifinet(self, net) local wnet = _wifi_sid_by_ifname(net) if wnet then return wifinet(wnet) end end function add_wifinet(self, net, options) if type(options) == "table" and options.device and _uci:get("wireless", options.device) == "wifi-device" then local wnet = _uci:section("wireless", "wifi-iface", nil, options) return wifinet(wnet) end end function del_wifinet(self, net) local wnet = _wifi_sid_by_ifname(net) if wnet then _uci:delete("wireless", wnet) return true end return false end function get_status_by_route(self, addr, mask) local route_statuses = { } local _, object for _, object in ipairs(utl.ubus()) do local net = object:match("^network%.interface%.(.+)") if net then local s = utl.ubus(object, "status", {}) if s and s.route then local rt for _, rt in ipairs(s.route) do if not rt.table and rt.target == addr and rt.mask == mask then route_statuses[net] = s end end end end end return route_statuses end function get_status_by_address(self, addr) local _, object for _, object in ipairs(utl.ubus()) do local net = object:match("^network%.interface%.(.+)") if net then local s = utl.ubus(object, "status", {}) if s and s['ipv4-address'] then local a for _, a in ipairs(s['ipv4-address']) do if a.address == addr then return net, s end end end if s and s['ipv6-address'] then local a for _, a in ipairs(s['ipv6-address']) do if a.address == addr then return net, s end end end if s and s['ipv6-prefix-assignment'] then local a for _, a in ipairs(s['ipv6-prefix-assignment']) do if a and a['local-address'] and a['local-address'].address == addr then return net, s end end end end end end function get_wan_networks(self) local k, v local wan_nets = { } local route_statuses = self:get_status_by_route("0.0.0.0", 0) for k, v in pairs(route_statuses) do wan_nets[#wan_nets+1] = network(k, v.proto) end return wan_nets end function get_wan6_networks(self) local k, v local wan6_nets = { } local route_statuses = self:get_status_by_route("::", 0) for k, v in pairs(route_statuses) do wan6_nets[#wan6_nets+1] = network(k, v.proto) end return wan6_nets end function get_switch_topologies(self) return _swtopo end function network(name, proto) if name then local p = proto or _uci:get("network", name, "proto") local c = p and _protocols[p] or protocol return c(name) end end function protocol.__init__(self, name) self.sid = name end function protocol._get(self, opt) local v = _uci:get("network", self.sid, opt) if type(v) == "table" then return table.concat(v, " ") end return v or "" end function protocol._ubus(self, field) if not _ubusnetcache[self.sid] then _ubusnetcache[self.sid] = utl.ubus("network.interface.%s" % self.sid, "status", { }) end if _ubusnetcache[self.sid] and field then return _ubusnetcache[self.sid][field] end return _ubusnetcache[self.sid] end function protocol.get(self, opt) return _get("network", self.sid, opt) end function protocol.set(self, opt, val) return _set("network", self.sid, opt, val) end function protocol.ifname(self) local ifname if self:is_floating() then ifname = self:_ubus("l3_device") else ifname = self:_ubus("device") end if not ifname then ifname = _wifi_netid_by_netname(self.sid) end return ifname end function protocol.proto(self) return "none" end function protocol.get_i18n(self) local p = self:proto() if p == "none" then return lng.translate("Unmanaged") elseif p == "static" then return lng.translate("Static address") elseif p == "dhcp" then return lng.translate("DHCP client") else return lng.translate("Unknown") end end function protocol.type(self) return self:_get("type") end function protocol.name(self) return self.sid end function protocol.uptime(self) return self:_ubus("uptime") or 0 end function protocol.expires(self) local u = self:_ubus("uptime") local d = self:_ubus("data") if type(u) == "number" and type(d) == "table" and type(d.leasetime) == "number" then local r = (d.leasetime - (u % d.leasetime)) return r > 0 and r or 0 end return -1 end function protocol.metric(self) return self:_ubus("metric") or 0 end function protocol.zonename(self) local d = self:_ubus("data") if type(d) == "table" and type(d.zone) == "string" then return d.zone end return nil end function protocol.ipaddr(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and addrs[1].address end function protocol.ipaddrs(self) local addrs = self:_ubus("ipv4-address") local rv = { } if type(addrs) == "table" then local n, addr for n, addr in ipairs(addrs) do rv[#rv+1] = "%s/%d" %{ addr.address, addr.mask } end end return rv end function protocol.netmask(self) local addrs = self:_ubus("ipv4-address") return addrs and #addrs > 0 and ipc.IPv4("0.0.0.0/%d" % addrs[1].mask):mask():string() end function protocol.gwaddr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "0.0.0.0" and route.mask == 0 then return route.nexthop end end end function protocol.dnsaddrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if not addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.ip6addr(self) local addrs = self:_ubus("ipv6-address") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } else addrs = self:_ubus("ipv6-prefix-assignment") if addrs and #addrs > 0 then return "%s/%d" %{ addrs[1].address, addrs[1].mask } end end end function protocol.ip6addrs(self) local addrs = self:_ubus("ipv6-address") local rv = { } local n, addr if type(addrs) == "table" then for n, addr in ipairs(addrs) do rv[#rv+1] = "%s/%d" %{ addr.address, addr.mask } end end addrs = self:_ubus("ipv6-prefix-assignment") if type(addrs) == "table" then for n, addr in ipairs(addrs) do if type(addr["local-address"]) == "table" and type(addr["local-address"].mask) == "number" and type(addr["local-address"].address) == "string" then rv[#rv+1] = "%s/%d" %{ addr["local-address"].address, addr["local-address"].mask } end end end return rv end function protocol.gw6addr(self) local _, route for _, route in ipairs(self:_ubus("route") or { }) do if route.target == "::" and route.mask == 0 then return ipc.IPv6(route.nexthop):string() end end end function protocol.dns6addrs(self) local dns = { } local _, addr for _, addr in ipairs(self:_ubus("dns-server") or { }) do if addr:match(":") then dns[#dns+1] = addr end end return dns end function protocol.ip6prefix(self) local prefix = self:_ubus("ipv6-prefix") if prefix and #prefix > 0 then return "%s/%d" %{ prefix[1].address, prefix[1].mask } end end function protocol.errors(self) local _, err, rv local errors = self:_ubus("errors") if type(errors) == "table" then for _, err in ipairs(errors) do if type(err) == "table" and type(err.code) == "string" then rv = rv or { } rv[#rv+1] = IFACE_ERRORS[err.code] or lng.translatef("Unknown error (%s)", err.code) end end end return rv end function protocol.is_bridge(self) return (not self:is_virtual() and self:type() == "bridge") end function protocol.opkg_package(self) return nil end function protocol.is_installed(self) return true end function protocol.is_virtual(self) return false end function protocol.is_floating(self) return false end function protocol.is_dynamic(self) return (self:_ubus("dynamic") == true) end function protocol.is_auto(self) return (self:_get("auto") ~= "0") end function protocol.is_alias(self) local ifn, parent = nil, nil for ifn in utl.imatch(_uci:get("network", self.sid, "ifname")) do if #ifn > 1 and ifn:byte(1) == 64 then parent = ifn:sub(2) elseif parent ~= nil then parent = nil end end return parent end function protocol.is_empty(self) if self:is_floating() then return false else local empty = true if (self:_get("ifname") or ""):match("%S+") then empty = false end if empty and _wifi_netid_by_netname(self.sid) then empty = false end return empty end end function protocol.is_up(self) return (self:_ubus("up") == true) end function protocol.add_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wifi interface, change its network option local wif = _wifi_sid_by_ifname(ifname) if wif then _append("wireless", wif, "network", self.sid) -- add iface to our iface list else _append("network", self.sid, "ifname", ifname) end end end function protocol.del_interface(self, ifname) ifname = _M:ifnameof(ifname) if ifname and not self:is_floating() then -- if its a wireless interface, clear its network option local wif = _wifi_sid_by_ifname(ifname) if wif then _filter("wireless", wif, "network", self.sid) end -- remove the interface _filter("network", self.sid, "ifname", ifname) end end function protocol.get_interface(self) if self:is_virtual() then _tunnel[self:proto() .. "-" .. self.sid] = true return interface(self:proto() .. "-" .. self.sid, self) elseif self:is_bridge() then _bridge["br-" .. self.sid] = true return interface("br-" .. self.sid, self) else local ifn = self:_ubus("l3_device") or self:_ubus("device") if ifn then return interface(ifn, self) end for ifn in utl.imatch(_uci:get("network", self.sid, "ifname")) do ifn = ifn:match("^[^:/]+") return ifn and interface(ifn, self) end ifn = _wifi_netid_by_netname(self.sid) return ifn and interface(ifn, self) end end function protocol.get_interfaces(self) if self:is_bridge() or (self:is_virtual() and not self:is_floating()) then local ifaces = { } local ifn local nfs = { } for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("^[^:/]+") nfs[ifn] = interface(ifn, self) end for ifn in utl.kspairs(nfs) do ifaces[#ifaces+1] = nfs[ifn] end local wfs = { } _uci:foreach("wireless", "wifi-iface", function(s) if s.device then local net for net in utl.imatch(s.network) do if net == self.sid then ifn = _wifi_netid_by_sid(s[".name"]) if ifn then wfs[ifn] = interface(ifn, self) end end end end end) for ifn in utl.kspairs(wfs) do ifaces[#ifaces+1] = wfs[ifn] end return ifaces end end function protocol.contains_interface(self, ifname) ifname = _M:ifnameof(ifname) if not ifname then return false elseif self:is_virtual() and self:proto() .. "-" .. self.sid == ifname then return true elseif self:is_bridge() and "br-" .. self.sid == ifname then return true else local ifn for ifn in utl.imatch(self:get("ifname")) do ifn = ifn:match("[^:]+") if ifn == ifname then return true end end local wif = _wifi_sid_by_ifname(ifname) if wif then local n for n in utl.imatch(_uci:get("wireless", wif, "network")) do if n == self.sid then return true end end end end return false end function protocol.adminlink(self) local stat, dsp = pcall(require, "luci.dispatcher") return stat and dsp.build_url("admin", "network", "network", self.sid) end interface = utl.class() function interface.__init__(self, ifname, network) local wif = _wifi_sid_by_ifname(ifname) if wif then self.wif = wifinet(wif) self.ifname = self.wif:ifname() end self.ifname = self.ifname or ifname self.dev = _interfaces[self.ifname] self.network = network end function interface._ubus(self, field) if not _ubusdevcache[self.ifname] then _ubusdevcache[self.ifname] = utl.ubus("network.device", "status", { name = self.ifname }) end if _ubusdevcache[self.ifname] and field then return _ubusdevcache[self.ifname][field] end return _ubusdevcache[self.ifname] end function interface.name(self) return self.wif and self.wif:ifname() or self.ifname end function interface.mac(self) return ipc.checkmac(self:_ubus("macaddr")) end function interface.ipaddrs(self) return self.dev and self.dev.ipaddrs or { } end function interface.ip6addrs(self) return self.dev and self.dev.ip6addrs or { } end function interface.type(self) if self.ifname and self.ifname:byte(1) == 64 then return "alias" elseif self.wif or _wifi_iface(self.ifname) then return "wifi" elseif _bridge[self.ifname] then return "bridge" elseif _tunnel[self.ifname] then return "tunnel" elseif self.ifname:match("%.") then return "vlan" elseif _switch[self.ifname] then return "switch" else return "ethernet" end end function interface.shortname(self) if self.wif then return self.wif:shortname() else return self.ifname end end function interface.get_i18n(self) if self.wif then return "%s: %s %q" %{ lng.translate("Wireless Network"), self.wif:active_mode(), self.wif:active_ssid() or self.wif:active_bssid() or self.wif:id() or "?" } else return "%s: %q" %{ self:get_type_i18n(), self:name() } end end function interface.get_type_i18n(self) local x = self:type() if x == "alias" then return lng.translate("Alias Interface") elseif x == "wifi" then return lng.translate("Wireless Adapter") elseif x == "bridge" then return lng.translate("Bridge") elseif x == "switch" then return lng.translate("Ethernet Switch") elseif x == "vlan" then if _switch[self.ifname] then return lng.translate("Switch VLAN") else return lng.translate("Software VLAN") end elseif x == "tunnel" then return lng.translate("Tunnel Interface") else return lng.translate("Ethernet Adapter") end end function interface.adminlink(self) if self.wif then return self.wif:adminlink() end end function interface.ports(self) local members = self:_ubus("bridge-members") if members then local _, iface local ifaces = { } for _, iface in ipairs(members) do ifaces[#ifaces+1] = interface(iface) end return ifaces end end function interface.bridge_id(self) if self.dev and self.dev.bridge then return self.dev.bridge.id else return nil end end function interface.bridge_stp(self) if self.dev and self.dev.bridge then return self.dev.bridge.stp else return false end end function interface.is_up(self) local up = self:_ubus("up") if up == nil then up = (self:type() == "alias") end return up or false end function interface.is_bridge(self) return (self:type() == "bridge") end function interface.is_bridgeport(self) return self.dev and self.dev.bridge and (self.dev.bridge.name ~= self:name()) and true or false end function interface.tx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.tx_bytes or 0 end function interface.rx_bytes(self) local stat = self:_ubus("statistics") return stat and stat.rx_bytes or 0 end function interface.tx_packets(self) local stat = self:_ubus("statistics") return stat and stat.tx_packets or 0 end function interface.rx_packets(self) local stat = self:_ubus("statistics") return stat and stat.rx_packets or 0 end function interface.get_network(self) return self:get_networks()[1] end function interface.get_networks(self) if not self.networks then local nets = { } local _, net for _, net in ipairs(_M:get_networks()) do if net:contains_interface(self.ifname) or net:ifname() == self.ifname then nets[#nets+1] = net end end table.sort(nets, function(a, b) return a.sid < b.sid end) self.networks = nets return nets else return self.networks end end function interface.get_wifinet(self) return self.wif end wifidev = utl.class() function wifidev.__init__(self, name) local t, n = _uci:get("wireless", name) if t == "wifi-device" and n ~= nil then self.sid = n self.iwinfo = _wifi_iwinfo_by_ifname(self.sid, true) end self.sid = self.sid or name self.iwinfo = self.iwinfo or { ifname = self.sid } end function wifidev.get(self, opt) return _get("wireless", self.sid, opt) end function wifidev.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifidev.name(self) return self.sid end function wifidev.hwmodes(self) local l = self.iwinfo.hwmodelist if l and next(l) then return l else return { b = true, g = true } end end function wifidev.get_i18n(self) local t = self.iwinfo.hardware_name or "Generic" if self.iwinfo.type == "wl" then t = "Broadcom" end local m = "" local l = self:hwmodes() if l.a then m = m .. "a" end if l.b then m = m .. "b" end if l.g then m = m .. "g" end if l.n then m = m .. "n" end if l.ac then m = "ac" end return "%s 802.11%s Wireless Controller (%s)" %{ t, m, self:name() } end function wifidev.is_up(self) if _ubuswificache[self.sid] then return (_ubuswificache[self.sid].up == true) end return false end function wifidev.get_wifinet(self, net) if _uci:get("wireless", net) == "wifi-iface" then return wifinet(net) else local wnet = _wifi_sid_by_ifname(net) if wnet then return wifinet(wnet) end end end function wifidev.get_wifinets(self) local nets = { } _uci:foreach("wireless", "wifi-iface", function(s) if s.device == self.sid then nets[#nets+1] = wifinet(s['.name']) end end) return nets end function wifidev.add_wifinet(self, options) options = options or { } options.device = self.sid local wnet = _uci:section("wireless", "wifi-iface", nil, options) if wnet then return wifinet(wnet, options) end end function wifidev.del_wifinet(self, net) if utl.instanceof(net, wifinet) then net = net.sid elseif _uci:get("wireless", net) ~= "wifi-iface" then net = _wifi_sid_by_ifname(net) end if net and _uci:get("wireless", net, "device") == self.sid then _uci:delete("wireless", net) return true end return false end wifinet = utl.class() function wifinet.__init__(self, name, data) local sid, netid, radioname, radiostate, netstate -- lookup state by radio#.network# notation sid = _wifi_sid_by_netid(name) if sid then netid = name radioname, radiostate, netstate = _wifi_state_by_sid(sid) else -- lookup state by ifname (e.g. wlan0) radioname, radiostate, netstate = _wifi_state_by_ifname(name) if radioname and radiostate and netstate then sid = netstate.section netid = _wifi_netid_by_sid(sid) else -- lookup state by uci section id (e.g. cfg053579) radioname, radiostate, netstate = _wifi_state_by_sid(name) if radioname and radiostate and netstate then sid = name netid = _wifi_netid_by_sid(sid) else -- no state available, try to resolve from uci netid, radioname = _wifi_netid_by_sid(name) if netid and radioname then sid = name end end end end local iwinfo = (netstate and _wifi_iwinfo_by_ifname(netstate.ifname)) or (radioname and _wifi_iwinfo_by_ifname(radioname)) or { ifname = (netid or sid or name) } self.sid = sid or name self.wdev = iwinfo.ifname self.iwinfo = iwinfo self.netid = netid self._ubusdata = { radio = radioname, dev = radiostate, net = netstate } end function wifinet.ubus(self, ...) local n, v = self._ubusdata for n = 1, select('#', ...) do if type(v) == "table" then v = v[select(n, ...)] else return nil end end return v end function wifinet.get(self, opt) return _get("wireless", self.sid, opt) end function wifinet.set(self, opt, val) return _set("wireless", self.sid, opt, val) end function wifinet.mode(self) return self:ubus("net", "config", "mode") or self:get("mode") or "ap" end function wifinet.ssid(self) return self:ubus("net", "config", "ssid") or self:get("ssid") end function wifinet.bssid(self) return self:ubus("net", "config", "bssid") or self:get("bssid") end function wifinet.network(self) local net, networks = nil, { } for net in utl.imatch(self:ubus("net", "config", "network") or self:get("network")) do networks[#networks+1] = net end return networks end function wifinet.id(self) return self.netid end function wifinet.name(self) return self.sid end function wifinet.ifname(self) local ifname = self:ubus("net", "ifname") or self.iwinfo.ifname if not ifname or ifname:match("^wifi%d") or ifname:match("^radio%d") then ifname = self.netid end return ifname end function wifinet.get_device(self) local dev = self:ubus("radio") or self:get("device") return dev and wifidev(dev) or nil end function wifinet.is_up(self) local ifc = self:get_interface() return (ifc and ifc:is_up() or false) end function wifinet.active_mode(self) local m = self.iwinfo.mode or self:ubus("net", "config", "mode") or self:get("mode") or "ap" if m == "ap" then m = "Master" elseif m == "sta" then m = "Client" elseif m == "adhoc" then m = "Ad-Hoc" elseif m == "mesh" then m = "Mesh" elseif m == "monitor" then m = "Monitor" end return m end function wifinet.active_mode_i18n(self) return lng.translate(self:active_mode()) end function wifinet.active_ssid(self) return self.iwinfo.ssid or self:ubus("net", "config", "ssid") or self:get("ssid") end function wifinet.active_bssid(self) return self.iwinfo.bssid or self:ubus("net", "config", "bssid") or self:get("bssid") end function wifinet.active_encryption(self) local enc = self.iwinfo and self.iwinfo.encryption return enc and enc.description or "-" end function wifinet.assoclist(self) return self.iwinfo.assoclist or { } end function wifinet.frequency(self) local freq = self.iwinfo.frequency if freq and freq > 0 then return "%.03f" % (freq / 1000) end end function wifinet.bitrate(self) local rate = self.iwinfo.bitrate if rate and rate > 0 then return (rate / 1000) end end function wifinet.channel(self) return self.iwinfo.channel or self:ubus("dev", "config", "channel") or tonumber(self:get("channel")) end function wifinet.signal(self) return self.iwinfo.signal or 0 end function wifinet.noise(self) return self.iwinfo.noise or 0 end function wifinet.country(self) return self.iwinfo.country or self:ubus("dev", "config", "country") or "00" end function wifinet.txpower(self) local pwr = (self.iwinfo.txpower or 0) return pwr + self:txpower_offset() end function wifinet.txpower_offset(self) return self.iwinfo.txpower_offset or 0 end function wifinet.signal_level(self, s, n) if self:active_bssid() ~= "00:00:00:00:00:00" then local signal = s or self:signal() local noise = n or self:noise() if signal < 0 and noise < 0 then local snr = -1 * (noise - signal) return math.floor(snr / 5) else return 0 end else return -1 end end function wifinet.signal_percent(self) local qc = self.iwinfo.quality or 0 local qm = self.iwinfo.quality_max or 0 if qc > 0 and qm > 0 then return math.floor((100 / qm) * qc) else return 0 end end function wifinet.shortname(self) return "%s %q" %{ lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid() or self:id() } end function wifinet.get_i18n(self) return "%s: %s %q (%s)" %{ lng.translate("Wireless Network"), lng.translate(self:active_mode()), self:active_ssid() or self:active_bssid() or self:id(), self:ifname() } end function wifinet.adminlink(self) local stat, dsp = pcall(require, "luci.dispatcher") return dsp and dsp.build_url("admin", "network", "wireless", self.netid) end function wifinet.get_network(self) return self:get_networks()[1] end function wifinet.get_networks(self) local nets = { } local net for net in utl.imatch(self:ubus("net", "config", "network") or self:get("network")) do if _uci:get("network", net) == "interface" then nets[#nets+1] = network(net) end end table.sort(nets, function(a, b) return a.sid < b.sid end) return nets end function wifinet.get_interface(self) return interface(self:ifname()) end -- setup base protocols _M:register_protocol("static") _M:register_protocol("dhcp") _M:register_protocol("none") -- load protocol extensions local exts = nfs.dir(utl.libpath() .. "/model/network") if exts then local ext for ext in exts do if ext:match("%.lua$") then require("luci.model.network." .. ext:gsub("%.lua$", "")) end end end
apache-2.0
LegionXI/darkstar
scripts/zones/Bastok_Mines/npcs/Gregory.lua
14
1045
----------------------------------- -- Area: Bastok Mines -- NPC: Gregory -- Type: ENM -- @zone 234 -- @pos 51.530 -1 -83.940 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0100); 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
LegionXI/darkstar
scripts/zones/South_Gustaberg/npcs/qm1.lua
14
1424
----------------------------------- -- Area: South Gustaberg -- NPC: qm1 (???) -- Involved in Quest: The Cold Light of Day -- @pos 744 0 -671 107 ----------------------------------- package.loaded["scripts/zones/South_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/zones/South_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); gil = trade:getGil(); if ((trade:hasItemQty(4514,1) or trade:hasItemQty(5793,1)) and count == 1 and gil == 0) then if (GetMobAction(17215494) == 0) then SpawnMob(17215494); player:tradeComplete(); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MONSTER_TRACKS); 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
ibm2431/darkstar
scripts/zones/Port_San_dOria/npcs/Portaure.lua
9
1160
----------------------------------- -- Area: Port San d'Oria -- NPC: Portaure -- Standard Info NPC ----------------------------------- local ID = require("scripts/zones/Port_San_dOria/IDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getCharVar("tradePortaure") == 0) then player:messageSpecial(ID.text.PORTAURE_DIALOG); player:addCharVar("FFR", -1) player:setCharVar("tradePortaure",1); player:messageSpecial(ID.text.FLYER_ACCEPTED); player:messageSpecial(ID.text.FLYERS_HANDED,17 - player:getCharVar("FFR")); player:tradeComplete(); elseif (player:getCharVar("tradePortaure") ==1) then player:messageSpecial(ID.text.FLYER_ALREADY); end end end; function onTrigger(player,npc) player:startEvent(651); end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Temenos/bcnms/Central_Temenos_Basement.lua
13
1136
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[C_Temenos_Base]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1301),TEMENOS); HideTemenosDoor(GetInstanceRegion(1301)); player:setVar("Limbus_Trade_Item-T",0); if(GetMobAction(16929088) > 0)then DespawnMob(16928988);end end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[C_Temenos_Base]UniqueID")); player:setVar("LimbusID",1301); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if(leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
LegionXI/darkstar
scripts/zones/RaKaznar_Inner_Court/Zone.lua
33
1290
----------------------------------- -- -- Zone: Ra’Kanzar Inner Court (276) -- ----------------------------------- package.loaded["scripts/zones/RaKaznar_Inner_Court/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/RaKaznar_Inner_Court/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-476,-520.5,20,0); 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
LegionXI/darkstar
scripts/zones/La_Theine_Plateau/mobs/Poison_Funguar.lua
12
1099
----------------------------------- -- Area: La Theine Plateau -- MOB: Poison Funguar ----------------------------------- require("scripts/zones/La_Theine_Plateau/MobIDs"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkRegime(player,mob,71,2); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Tumbling_Truffle_PH[mobID] ~= nil) then -- printf("%u is a PH",mob); local TT_ToD = GetServerVariable("[POP]Tumbling_Truffle"); if (TT_ToD <= os.time(t) and GetMobAction(Tumbling_Truffle) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Tumbling_Truffle); GetMobByID(Tumbling_Truffle):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Tumbling_Truffle", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
siktirmirza/supergp
plugins/Fabanhammer.lua
14
11813
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 == "اخراج" 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 == 'بن' 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 == 'ان بن' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'کاربر '..user_id..' بن شد' elseif get_cmd == 'بن جهانی' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'حذف بن جهانی' 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() == 'ایدی' 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() == 'ایدی' 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() == 'حذفم کن' 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() == "لیست بن" 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() == 'بن' 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() == 'ان بن' 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_id..' از بن خارج شد' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ان بن', 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() == 'اخراج' 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 "شما نمیتوانید حذف کنید 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 = 'اخراج', 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() == 'بن جهانی' 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_id..' ] بن جهانی شد' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'بن جهانی', 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() == 'حذف بن جهانی' 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_id..' ] از بن جهانی خارج شد' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'حذف بن جهانی', 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() == "لیست بن جهانی" then -- Global ban list return banall_list() end end return { patterns = { "^(بن جهانی) (.*)$", "^[!/](بن جهانی)$", "^(لیست بن جهانی) (.*)$", "^(لیست بن)$", "^(لیست بن)$", "^(بن) (.*)$", "^(اخراج)$", "^(ان بن) (.*)$", "^(حذف بن جهانی) (.*)$", "^([حذف بن جهانی)$", "^(ان بن) (.*)$", "^(حذفم کن)$", "^([بن)$", "^([ان بن)$", "^(ایدی)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process --by shatel team }
gpl-2.0
greasydeal/darkstar
scripts/globals/spells/bluemagic/battery_charge.lua
10
1155
----------------------------------------- -- Spell: Battery Charge -- Gradually restores MP -- Spell cost: 50 MP -- Monster Type: Arcana -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: MP+10, MND+1 -- Level: 79 -- Casting Time: 5 seconds -- Recast Time: 75 seconds -- Spell Duration: 100 ticks, 300 Seconds (5 Minutes) -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) if(target:hasStatusEffect(EFFECT_REFRESH)) then target:delStatusEffect(EFFECT_REFRESH); end if(target:addStatusEffect(EFFECT_REFRESH,3,3,300)) then spell:setMsg(230); else spell:setMsg(75); -- no effect end return EFFECT_REFRESH; end;
gpl-3.0
ibm2431/darkstar
scripts/zones/AlTaieu/npcs/_0x2.lua
9
1738
----------------------------------- -- Area: Al'Taieu -- NPC: Rubious Crystal (West Tower) -- !pos -683.709 -6.250 -222.142 33 ----------------------------------- local ID = require("scripts/zones/AlTaieu/IDs"); require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if ( player:getCurrentMission(COP) == dsp.mission.id.cop.GARDEN_OF_ANTIQUITY and player:getCharVar("PromathiaStatus") == 2 and player:getCharVar("[SEA][AlTieu]WestTower") == 0 and player:getCharVar("[SEA][AlTieu]WestTowerCS") == 0 and not GetMobByID(ID.mob.AERNS_TOWER_WEST+0):isSpawned() and not GetMobByID(ID.mob.AERNS_TOWER_WEST+1):isSpawned() and not GetMobByID(ID.mob.AERNS_TOWER_WEST+2):isSpawned() ) then player:messageSpecial(ID.text.OMINOUS_SHADOW); SpawnMob(ID.mob.AERNS_TOWER_WEST+0):updateClaim(player); SpawnMob(ID.mob.AERNS_TOWER_WEST+1):updateClaim(player); SpawnMob(ID.mob.AERNS_TOWER_WEST+2):updateClaim(player); elseif ( player:getCurrentMission(COP) == dsp.mission.id.cop.GARDEN_OF_ANTIQUITY and player:getCharVar("PromathiaStatus") == 2 and player:getCharVar("[SEA][AlTieu]WestTower") == 1 and player:getCharVar("[SEA][AlTieu]WestTowerCS") == 0 ) then player:startEvent(162); else player:messageSpecial(ID.text.NOTHING_OF_INTEREST); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 162) then player:setCharVar("[SEA][AlTieu]WestTowerCS", 1); player:setCharVar("[SEA][AlTieu]WestTower", 0); end end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Travonce.lua
14
1060
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Travonce -- Type: Standard NPC -- @zone 26 -- @pos -89.068 -14.367 -0.030 -- -- 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(0x00d2); 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
creationix/nodemcu-firmware
app/cjson/tests/bench.lua
145
3247
#!/usr/bin/env lua -- This benchmark script measures wall clock time and should be -- run on an unloaded system. -- -- Your Mileage May Vary. -- -- Mark Pulford <mark@kyne.com.au> local json_module = os.getenv("JSON_MODULE") or "cjson" require "socket" local json = require(json_module) local util = require "cjson.util" local function find_func(mod, funcnames) for _, v in ipairs(funcnames) do if mod[v] then return mod[v] end end return nil end local json_encode = find_func(json, { "encode", "Encode", "to_string", "stringify", "json" }) local json_decode = find_func(json, { "decode", "Decode", "to_value", "parse" }) local function average(t) local total = 0 for _, v in ipairs(t) do total = total + v end return total / #t end function benchmark(tests, seconds, rep) local function bench(func, iter) -- Use socket.gettime() to measure microsecond resolution -- wall clock time. local t = socket.gettime() for i = 1, iter do func(i) end t = socket.gettime() - t -- Don't trust any results when the run lasted for less than a -- millisecond - return nil. if t < 0.001 then return nil end return (iter / t) end -- Roughly calculate the number of interations required -- to obtain a particular time period. local function calc_iter(func, seconds) local iter = 1 local rate -- Warm up the bench function first. func() while not rate do rate = bench(func, iter) iter = iter * 10 end return math.ceil(seconds * rate) end local test_results = {} for name, func in pairs(tests) do -- k(number), v(string) -- k(string), v(function) -- k(number), v(function) if type(func) == "string" then name = func func = _G[name] end local iter = calc_iter(func, seconds) local result = {} for i = 1, rep do result[i] = bench(func, iter) end -- Remove the slowest half (round down) of the result set table.sort(result) for i = 1, math.floor(#result / 2) do table.remove(result, 1) end test_results[name] = average(result) end return test_results end function bench_file(filename) local data_json = util.file_load(filename) local data_obj = json_decode(data_json) local function test_encode() json_encode(data_obj) end local function test_decode() json_decode(data_json) end local tests = {} if json_encode then tests.encode = test_encode end if json_decode then tests.decode = test_decode end return benchmark(tests, 0.1, 5) end -- Optionally load any custom configuration required for this module local success, data = pcall(util.file_load, ("bench-%s.lua"):format(json_module)) if success then util.run_script(data, _G) configure(json) end for i = 1, #arg do local results = bench_file(arg[i]) for k, v in pairs(results) do print(("%s\t%s\t%d"):format(arg[i], k, v)) end end -- vi:ai et sw=4 ts=4:
mit
Freezerburn/ld29-engine
LuaTest/lua/log.lua
2
3783
local log = { _AUTHOR = "Vincent 'Freezerburn Vinny' Kuyatt", _EMAIL = "vincentk@unlocked-doors.com", _VERSION = "log 0.1", _DESCRIPTION = "Simple logging for Lua", _URL = "None. Maybe Github after Ludum Dare?", _LICENSE = [[ MIT LICENSE Copyright (c) 2014 Vincent Kuyatt 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. ]] } log.LEVEL_CRITICAL = 0 log.LEVEL_ERROR = 1 log.LEVEL_WARNING = 2 log.LEVEL_INFO = 3 log.LEVEL_DEBUG = 4 local _logLevel = log.LEVEL_DEBUG function log.setLevel(level) _logLevel = level end function _parseTraceback() local tracebackInfos = {} for file, line, fun in string.gmatch(debug.traceback(), "/([a-zA-Z0-9]*[.]lua):([0-9]*): in function '(%a*)'") do tracebackInfos[#tracebackInfos + 1] = { file = file, line = line, f = fun } end return tracebackInfos end function log.critical(str, ...) if log.LEVEL_CRITICAL <= _logLevel then local tracebackInfos = _parseTraceback() local file = tracebackInfos[2].file local line = tracebackInfos[2].line local f = tracebackInfos[2].f print(string.format("[CRITICAL] %s:%s function %s: " .. str, file, line, f, ...)) end end function log.error(str, ...) if log.LEVEL_ERROR <= _logLevel then local tracebackInfos = _parseTraceback() local file = tracebackInfos[2].file local line = tracebackInfos[2].line local f = tracebackInfos[2].f print(string.format("[ERROR] %s:%s function %s: " .. str, file, line, f, ...)) end end function log.warning(str, ...) if log.LEVEL_WARNING <= _logLevel then local tracebackInfos = _parseTraceback() local file = tracebackInfos[2].file local line = tracebackInfos[2].line local f = tracebackInfos[2].f print(string.format("[WARNING] %s:%s function %s: " .. str, file, line, f, ...)) end end function log.info(str, ...) if log.LEVEL_INFO <= _logLevel then local tracebackInfos = _parseTraceback() local file = tracebackInfos[2].file local line = tracebackInfos[2].line local f = tracebackInfos[2].f print(string.format("[INFO] %s:%s function %s: " .. str, file, line, f, ...)) end end function log.debug(str, ...) if log.LEVEL_DEBUG <= _logLevel then local tracebackInfos = _parseTraceback() local file = tracebackInfos[2].file local line = tracebackInfos[2].line local f = tracebackInfos[2].f print(string.format("[DEBUG] %s:%s function %s: " .. str, file, line, f, ...)) end end return log
mit
naclander/tome
game/modules/tome/data/zones/norgos-lair/npcs.lua
3
5065
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Talents = require("engine.interface.ActorTalents") if not currentZone.is_invaded then load("/data/general/npcs/bear.lua", rarity(0)) load("/data/general/npcs/vermin.lua", rarity(3)) load("/data/general/npcs/canine.lua", rarity(1)) load("/data/general/npcs/snake.lua", rarity(0)) load("/data/general/npcs/plant.lua", rarity(0)) load("/data/general/npcs/all.lua", rarity(4, 35)) else load("/data/general/npcs/bear.lua", rarity(0)) load("/data/general/npcs/vermin.lua", rarity(3)) load("/data/general/npcs/canine.lua", rarity(1)) load("/data/general/npcs/snake.lua", rarity(0)) load("/data/general/npcs/shivgoroth.lua", function(e) if e.rarity and e.level_range then e.level_range[1] = e.level_range[1] - 9 e.start_level = e.start_level - 9 e.inc_damage = e.inc_damage or {} e.inc_damage.all = (e.inc_damage.all or 0) - 40 e.healing_factor = 0.4 e.combat_def = math.max(0, (e.combat_def or 0) - 12) end end) load("/data/general/npcs/all.lua", rarity(4, 35)) newEntity{ base="BASE_NPC_BEAR", define_as = "FROZEN_NORGOS", allow_infinite_dungeon = true, unique = true, name = "Norgos, the Frozen", display = "q", color=colors.VIOLET, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/animal_bear_norgos_the_frozen.png", display_h=2, display_y=-1}}}, desc = [[This ancient bear long guarded the western side of the forest, but as of late he started growing mad, attacking even the Thaloren. It seems to have fallen prey to the shivgoroth invading the area. Dead and frozen, it seems like a statue, animated by the elementals.]], killer_message = "and was turned into icicles", level_range = {7, nil}, exp_worth = 2, max_life = 200, life_rating = 17, fixed_rating = true, life_regen = 0, max_stamina = 85, max_mana = 1000, mana_regen = 10, stats = { str=15, dex=15, cun=8, mag=20, wil=20, con=20 }, tier1 = true, rank = 4, size_category = 5, infravision = 10, instakill_immune = 1, move_others=true, never_move = 1, combat = { dam=resolvers.levelup(17, 1, 0.8), atk=10, apr=9, dammod={str=1.2} }, resists = { [DamageType.COLD] = 20 }, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, resolvers.drops{chance=100, nb=1, {unique=true, not_properties={"lore"}} }, resolvers.drops{chance=100, nb=3, {tome_drops="boss"} }, resolvers.talents{ [Talents.T_FROST_GRAB]={base=1, every=6, max=6}, [Talents.T_ICE_STORM]={base=1, every=6, max=6}, }, autolevel = "caster", ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", }, on_die = function(self, who) game.player:resolveSource():setQuestStatus("start-thaloren", engine.Quest.COMPLETED, "norgos") game.player:resolveSource():setQuestStatus("start-thaloren", engine.Quest.COMPLETED, "norgos-invaded") end, } end newEntity{ base="BASE_NPC_BEAR", define_as = "NORGOS", allow_infinite_dungeon = true, unique = true, name = "Norgos, the Guardian", display = "q", color=colors.VIOLET, resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/animal_bear_norgos_the_guardian.png", display_h=2, display_y=-1}}}, desc = [[This ancient bear long guarded the western side of the forest, but as of late he started growing mad, attacking even the Thaloren.]], killer_message = "and was feasted upon by wolves", level_range = {7, nil}, exp_worth = 2, max_life = 200, life_rating = 17, fixed_rating = true, max_stamina = 85, max_mana = 200, stats = { str=25, dex=15, cun=8, mag=10, wil=20, con=20 }, tier1 = true, rank = 4, size_category = 5, infravision = 10, instakill_immune = 1, move_others=true, combat = { dam=resolvers.levelup(17, 1, 0.8), atk=10, apr=9, dammod={str=1.2} }, resists = { [DamageType.COLD] = 20 }, body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1 }, resolvers.drops{chance=100, nb=1, {unique=true, not_properties={"lore"}} }, resolvers.drops{chance=100, nb=3, {tome_drops="boss"} }, resolvers.talents{ [Talents.T_STUN]={base=1, every=6, max=6}, }, autolevel = "warrior", ai = "tactical", ai_state = { talent_in=2, ai_move="move_astar", }, ai_tactic = resolvers.tactic"melee", resolvers.inscriptions(1, "infusion"), on_die = function(self, who) game.player:resolveSource():setQuestStatus("start-thaloren", engine.Quest.COMPLETED, "norgos") end, }
gpl-3.0
greasydeal/darkstar
scripts/zones/Bastok_Mines/npcs/Sodragamm.lua
38
1086
----------------------------------- -- Area: Bastok Mines -- NPC: Sodragamm -- Type: Item Deliverer -- @zone: 234 -- @pos -24.741 -1 -64.944 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); 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
naclander/tome
game/modules/tome/data/general/grids/water.lua
3
10885
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org ------------------------------------------------------------ -- For inside the sea ------------------------------------------------------------ newEntity{ define_as = "WATER_FLOOR", type = "floor", subtype = "underwater", name = "underwater", image = "terrain/underwater/subsea_floor_02.png", display = '.', color=colors.LIGHT_BLUE, back_color=colors.DARK_BLUE, air_level = -5, air_condition="water", nice_tiler = { method="replace", base={"WATER_FLOOR", 10, 1, 5}}, } for i = 1, 5 do newEntity{ base="WATER_FLOOR", define_as = "WATER_FLOOR"..i, image = "terrain/underwater/subsea_floor_02"..string.char(string.byte('a')+i-1)..".png" } end newEntity{ define_as = "WATER_WALL", type = "wall", subtype = "underwater", name = "coral wall", image = "terrain/underwater/subsea_granite_wall1.png", display = '#', color=colors.AQUAMARINE, back_color=colors.DARK_BLUE, always_remember = true, can_pass = {pass_wall=1}, does_block_move = true, block_sight = true, air_level = -5, z = 3, nice_tiler = { method="wall3d", inner={"WATER_WALL", 100, 1, 5}, north={"WATER_WALL_NORTH", 100, 1, 5}, south={"WATER_WALL_SOUTH", 10, 1, 14}, north_south="WATER_WALL_NORTH_SOUTH", small_pillar="WATER_WALL_SMALL_PILLAR", pillar_2="WATER_WALL_PILLAR_2", pillar_8={"WATER_WALL_PILLAR_8", 100, 1, 5}, pillar_4="WATER_WALL_PILLAR_4", pillar_6="WATER_WALL_PILLAR_6" }, always_remember = true, does_block_move = true, can_pass = {pass_wall=1}, block_sight = true, air_level = -20, dig = "WATER_FLOOR", } for i = 1, 5 do newEntity{ base = "WATER_WALL", define_as = "WATER_WALL"..i, image = "terrain/underwater/subsea_granite_wall1_"..i..".png", z = 3} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_NORTH"..i, image = "terrain/underwater/subsea_granite_wall1_"..i..".png", z = 3, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_8"..i, image = "terrain/underwater/subsea_granite_wall1_"..i..".png", z = 3, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_8.png", z=18, display_y=-1}}} end newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_NORTH_SOUTH", image = "terrain/underwater/subsea_granite_wall2.png", z = 3, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_SOUTH", image = "terrain/underwater/subsea_granite_wall2.png", z = 3} for i = 1, 14 do newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_SOUTH"..i, image = "terrain/underwater/subsea_granite_wall2_"..i..".png", z = 3} end newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_SMALL_PILLAR", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_small.png",z=3}, class.new{image="terrain/underwater/subsea_granite_wall_pillar_small_top.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_6", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_3.png",z=3}, class.new{image="terrain/underwater/subsea_granite_wall_pillar_9.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_4", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_1.png",z=3}, class.new{image="terrain/underwater/subsea_granite_wall_pillar_7.png", z=18, display_y=-1}}} newEntity{ base = "WATER_WALL", define_as = "WATER_WALL_PILLAR_2", image = "terrain/underwater/subsea_floor_02.png", z=1, add_displays = {class.new{image="terrain/underwater/subsea_granite_wall_pillar_2.png",z=3}}} newEntity{ define_as = "WATER_DOOR", type = "wall", subtype = "underwater", name = "door", image = "terrain/underwater/subsea_stone_wall_door_closed.png", display = '+', color_r=238, color_g=154, color_b=77, back_color=colors.DARK_UMBER, nice_tiler = { method="door3d", north_south="WATER_DOOR_VERT", west_east="WATER_DOOR_HORIZ" }, notice = true, always_remember = true, block_sight = true, air_level = -5, air_condition="water", is_door = true, door_opened = "WATER_DOOR_OPEN", dig = "WATER_FLOOR", } newEntity{ define_as = "WATER_DOOR_OPEN", type = "wall", subtype = "underwater", name = "open door", image="terrain/underwater/subsea_granite_door1_open.png", display = "'", color_r=238, color_g=154, color_b=77, back_color=colors.DARK_GREY, always_remember = true, air_level = -5, air_condition="water", is_door = true, door_closed = "WATER_DOOR", } newEntity{ base = "WATER_DOOR", define_as = "WATER_DOOR_HORIZ", image = "terrain/underwater/subsea_stone_wall_door_closed.png", add_displays = {class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}, door_opened = "WATER_DOOR_HORIZ_OPEN"} newEntity{ base = "WATER_DOOR_OPEN", define_as = "WATER_DOOR_HORIZ_OPEN", image = "terrain/underwater/subsea_floor_02.png", add_displays = {class.new{image="terrain/underwater/subsea_stone_store_open.png", z=17}, class.new{image="terrain/underwater/subsea_granite_wall3.png", z=18, display_y=-1}}, door_closed = "WATER_DOOR_HORIZ"} newEntity{ base = "WATER_DOOR", define_as = "WATER_DOOR_VERT", image = "terrain/underwater/subsea_floor_02.png", add_displays = {class.new{image="terrain/underwater/subsea_granite_door1_vert.png", z=17}, class.new{image="terrain/underwater/subsea_granite_door1_vert_north.png", z=18, display_y=-1}}, door_opened = "WATER_DOOR_OPEN_VERT", dig = "WATER_DOOR_OPEN_VERT"} newEntity{ base = "WATER_DOOR_OPEN", define_as = "WATER_DOOR_OPEN_VERT", image = "terrain/underwater/subsea_floor_02.png", add_displays = {class.new{image="terrain/underwater/subsea_granite_door1_open_vert.png", z=17}, class.new{image="terrain/underwater/subsea_granite_door1_open_vert_north.png", z=18, display_y=-1}}, door_closed = "WATER_DOOR_VERT"} newEntity{ define_as = "WATER_FLOOR_BUBBLE", name = "underwater air bubble", image = "terrain/underwater/subsea_floor_bubbles.png", desc = "#LIGHT_BLUE#Replenishes air level when standing inside.#LAST#", show_tooltip = true, display = ':', color=colors.LIGHT_BLUE, back_color=colors.DARK_BLUE, air_level = 15, nb_charges = resolvers.rngrange(4, 7), force_clone = true, on_stand = function(self, x, y, who) if ((who.can_breath.water and who.can_breath.water <= 0) or not who.can_breath.water) and not who:attr("no_breath") then self.nb_charges = self.nb_charges - 1 if self.nb_charges <= 0 then game.logSeen(who, "#AQUAMARINE#The air bubbles are depleted!") local g = game.zone:makeEntityByName(game.level, "terrain", "WATER_FLOOR") game.zone:addEntity(game.level, g, "terrain", x, y) end end end, } ------------------------------------------------------------ -- For outside ------------------------------------------------------------ newEntity{ define_as = "WATER_BASE", type = "floor", subtype = "water", name = "deep water", image = "terrain/water_floor.png", display = '~', color=colors.AQUAMARINE, back_color=colors.DARK_BLUE, always_remember = true, special_minimap = colors.BLUE, shader = "water", } ----------------------------------------- -- Water/grass ----------------------------------------- newEntity{ base="WATER_BASE", define_as = "DEEP_WATER", image="terrain/water_grass_5_1.png", air_level = -5, air_condition="water", } ----------------------------------------- -- Water(ocean)/grass ----------------------------------------- newEntity{ base="WATER_BASE", define_as = "DEEP_OCEAN_WATER", image = "terrain/ocean_water_grass_5_1.png", air_level = -5, air_condition="water", } ----------------------------------------- -- Poison water ----------------------------------------- newEntity{ define_as = "POISON_DEEP_WATER", type = "floor", subtype = "water", name = "poisoned deep water", image = "terrain/poisoned_water_01.png", display = '~', color=colors.YELLOW_GREEN, back_color=colors.DARK_GREEN, -- add_displays = class:makeWater(true, "poison_"), always_remember = true, air_level = -5, air_condition="water", mindam = resolvers.mbonus(10, 25), maxdam = resolvers.mbonus(20, 50), on_stand = function(self, x, y, who) if self.faction and who:reactionToward(self.faction) >= 0 then return end local DT = engine.DamageType local dam = DT:get(DT.POISON).projector(self, x, y, DT.POISON, rng.range(self.mindam, self.maxdam)) self.x, self.y = x, y if dam > 0 and who.player then self:logCombat(who, "#Source# poisons #Target#!") end end, combatAttack = function(self) return rng.range(self.mindam, self.maxdam) end, nice_tiler = { method="replace", base={"POISON_DEEP_WATER", 100, 1, 6}}, shader = "water", } for i = 1, 6 do newEntity{ base="POISON_DEEP_WATER", define_as = "POISON_DEEP_WATER"..i, image = "terrain/poisoned_water_0"..i..".png" } end ----------------------------------------- -- Dungeony exits ----------------------------------------- newEntity{ define_as = "WATER_UP_WILDERNESS", name = "exit to the worldmap", image = "terrain/underwater/subsea_floor_02.png", add_mos = {{image="terrain/underwater/subsea_stair_up_wild.png"}}, display = '<', color_r=255, color_g=0, color_b=255, always_remember = true, notice = true, change_level = 1, change_zone = "wilderness", air_level = -5, air_condition="water", } newEntity{ define_as = "WATER_UP", image = "terrain/underwater/subsea_floor_02.png", add_mos = {{image="terrain/underwater/subsea_stair_up.png"}}, name = "previous level", display = '<', color_r=255, color_g=255, color_b=0, notice = true, always_remember = true, change_level = -1, air_level = -5, air_condition="water", } newEntity{ define_as = "WATER_DOWN", image = "terrain/underwater/subsea_floor_02.png", add_mos = {{image="terrain/underwater/subsea_stair_down_03_64.png"}}, name = "next level", display = '>', color_r=255, color_g=255, color_b=0, notice = true, always_remember = true, change_level = 1, air_level = -5, air_condition="water", }
gpl-3.0
greasydeal/darkstar
scripts/globals/items/pot_of_honey.lua
35
1143
----------------------------------------- -- ID: 4370 -- Item: pot_of_honey -- Food Effect: 5Min, All Races ----------------------------------------- -- Magic Regen While Healing 1 ----------------------------------------- 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,300,4370); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
naclander/tome
game/modules/tome/data/general/objects/egos/rings.lua
1
19074
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Stats = require "engine.interface.ActorStats" local Talents = require "engine.interface.ActorTalents" local DamageType = require "engine.DamageType" --load("/data/general/objects/egos/charged-attack.lua") --load("/data/general/objects/egos/charged-defensive.lua") --load("/data/general/objects/egos/charged-utility.lua") -- Immunity/Resist rings newEntity{ power_source = {arcane=true}, name = " of sensing", suffix=true, instant_resolve=true, keywords = {sensing=true}, level_range = {1, 50}, rarity = 4, cost = 2, wielder = { see_invisible = resolvers.mbonus_material(20, 5), see_stealth = resolvers.mbonus_material(20, 5), blind_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {psionic=true}, name = " of clarity", suffix=true, instant_resolve=true, keywords = {clarity=true}, level_range = {1, 50}, rarity = 4, cost = 2, wielder = { combat_mentalresist = resolvers.mbonus_material(10, 5), confusion_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {technique=true}, name = " of tenacity", suffix=true, instant_resolve=true, keywords = {tenacity=true}, level_range = {1, 50}, rarity = 4, cost = 5, wielder = { max_life=resolvers.mbonus_material(30, 20), pin_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), knockback_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), disarm_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {technique=true}, name = " of perseverance", suffix=true, instant_resolve=true, keywords = {perseverance =true}, level_range = {1, 50}, rarity = 4, cost = 5, wielder = { life_regen = resolvers.mbonus_material(40, 8, function(e, v) v=v/10 return 0, v end), stun_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {arcane=true}, name = " of arcana(#REGEN#)", suffix=true, instant_resolve=true, keywords = {arcana=true}, level_range = {1, 50}, rarity = 6, cost = 3, wielder = { mana_regen = resolvers.mbonus_material(30, 10, function(e, v) v=v/100 return 0, v end), silence_immune = resolvers.mbonus_material(30, 20, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {nature=true}, name = " of fire (#RESIST#)", suffix=true, instant_resolve=true, keywords = {fire=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.FIRE] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.FIRE] = (e.wielder.resists[engine.DamageType.FIRE] or 0) + (e.wielder.inc_damage[engine.DamageType.FIRE]*2) end), } newEntity{ power_source = {nature=true}, name = " of frost (#RESIST#)", suffix=true, instant_resolve=true, keywords = {frost=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.COLD] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.COLD] = (e.wielder.resists[engine.DamageType.COLD] or 0) + (e.wielder.inc_damage[engine.DamageType.COLD]*2) end), } newEntity{ power_source = {nature=true}, name = " of nature (#RESIST#)", suffix=true, instant_resolve=true, keywords = {nature=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.NATURE] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.NATURE] = (e.wielder.resists[engine.DamageType.NATURE] or 0) + (e.wielder.inc_damage[engine.DamageType.NATURE]*2) end), } newEntity{ power_source = {nature=true}, name = " of lightning (#RESIST#)", suffix=true, instant_resolve=true, keywords = {lightning=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.LIGHTNING] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.LIGHTNING] = (e.wielder.resists[engine.DamageType.LIGHTNING] or 0) + (e.wielder.inc_damage[engine.DamageType.LIGHTNING]*2) end), } newEntity{ power_source = {arcane=true}, name = " of light (#RESIST#)", suffix=true, instant_resolve=true, keywords = {light=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.LIGHT] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.LIGHT] = (e.wielder.resists[engine.DamageType.LIGHT] or 0) + (e.wielder.inc_damage[engine.DamageType.LIGHT]*2) end), } newEntity{ power_source = {arcane=true}, name = " of darkness (#RESIST#)", suffix=true, instant_resolve=true, keywords = {darkness=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.DARKNESS] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.DARKNESS] = (e.wielder.resists[engine.DamageType.DARKNESS] or 0) + (e.wielder.inc_damage[engine.DamageType.DARKNESS]*2) end), } newEntity{ power_source = {nature=true}, name = " of corrosion (#RESIST#)", suffix=true, instant_resolve=true, keywords = {corrosion=true}, level_range = {1, 50}, rarity = 6, cost = 2, wielder = { inc_damage = { [DamageType.ACID] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.ACID] = (e.wielder.resists[engine.DamageType.ACID] or 0) + (e.wielder.inc_damage[engine.DamageType.ACID]*2) end), } -- rare resists newEntity{ power_source = {arcane=true}, name = " of aether (#RESIST#)", suffix=true, instant_resolve=true, keywords = {aether=true}, level_range = {1, 50}, rarity = 24, cost = 2, wielder = { inc_damage = { [DamageType.ARCANE] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.ARCANE] = (e.wielder.resists[engine.DamageType.ARCANE] or 0) + (e.wielder.inc_damage[engine.DamageType.ARCANE]) end), } newEntity{ power_source = {arcane=true}, name = " of blight (#RESIST#)", suffix=true, instant_resolve=true, keywords = {blight=true}, level_range = {1, 50}, rarity = 12, cost = 2, wielder = { inc_damage = { [DamageType.BLIGHT] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.BLIGHT] = (e.wielder.resists[engine.DamageType.BLIGHT] or 0) + (e.wielder.inc_damage[engine.DamageType.BLIGHT]) end), } newEntity{ power_source = {nature=true}, name = " of the mountain (#RESIST#)", suffix=true, instant_resolve=true, keywords = {mountain=true}, level_range = {1, 50}, rarity = 24, cost = 2, wielder = { inc_damage = { [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.PHYSICAL] = (e.wielder.resists[engine.DamageType.PHYSICAL] or 0) + (e.wielder.inc_damage[engine.DamageType.PHYSICAL]) end), } newEntity{ power_source = {psionic=true}, name = " of the mind (#RESIST#)", suffix=true, instant_resolve=true, keywords = {mind=true}, level_range = {1, 50}, rarity = 12, cost = 2, wielder = { inc_damage = { [DamageType.MIND] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.MIND] = (e.wielder.resists[engine.DamageType.MIND] or 0) + (e.wielder.inc_damage[engine.DamageType.MIND]) end), } newEntity{ power_source = {arcane=true}, name = " of time (#RESIST#)", suffix=true, instant_resolve=true, keywords = {time=true}, level_range = {1, 50}, rarity = 24, cost = 2, wielder = { inc_damage = { [DamageType.TEMPORAL] = resolvers.mbonus_material(10, 10) }, resists = {}, }, resolvers.genericlast(function(e) e.wielder.resists[engine.DamageType.TEMPORAL] = (e.wielder.resists[engine.DamageType.TEMPORAL] or 0) + (e.wielder.inc_damage[engine.DamageType.TEMPORAL]) end), } -- The rest newEntity{ power_source = {arcane=true}, name = " of power", suffix=true, instant_resolve=true, keywords = {power=true}, level_range = {1, 50}, rarity = 4, cost = 4, wielder = { combat_spellpower = resolvers.mbonus_material(10, 5), combat_dam = resolvers.mbonus_material(10, 5), combat_mindpower = resolvers.mbonus_material(10, 5), }, } newEntity{ power_source = {technique=true}, name = "savior's ", prefix=true, instant_resolve=true, keywords = {savior=true}, level_range = {1, 50}, rarity = 10, cost = 10, wielder = { combat_mentalresist = resolvers.mbonus_material(12, 6), combat_physresist = resolvers.mbonus_material(12, 6), combat_spellresist = resolvers.mbonus_material(12, 6), }, } newEntity{ power_source = {technique=true}, name = "warrior's ", prefix=true, instant_resolve=true, keywords = {warrior=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { inc_stats = { [Stats.STAT_STR] = resolvers.mbonus_material(8, 2) }, }, resolvers.genericlast(function(e) e.wielder.combat_armor = (e.wielder.combat_armor or 0) + (e.wielder.inc_stats[engine.interface.ActorStats.STAT_STR]*2) end), } newEntity{ power_source = {technique=true}, name = "rogue's ", prefix=true, instant_resolve=true, keywords = {rogue=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { inc_stats = { [Stats.STAT_CUN] = resolvers.mbonus_material(8, 2) }, }, resolvers.genericlast(function(e) e.wielder.combat_def = (e.wielder.combat_def or 0) + (e.wielder.inc_stats[engine.interface.ActorStats.STAT_CUN]*2) end), } newEntity{ power_source = {technique=true}, name = "marksman's ", prefix=true, instant_resolve=true, keywords = {marskman=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { inc_stats = { [Stats.STAT_DEX] = resolvers.mbonus_material(8, 2) }, }, resolvers.genericlast(function(e) e.wielder.combat_atk = (e.wielder.combat_atk or 0) + (e.wielder.inc_stats[engine.interface.ActorStats.STAT_DEX]*2) end), } newEntity{ power_source = {nature=true}, name = "titan's ", prefix=true, instant_resolve=true, keywords = {titan=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { inc_stats = { [Stats.STAT_CON] = resolvers.mbonus_material(8, 2) }, }, resolvers.genericlast(function(e) e.wielder.combat_physresist = (e.wielder.combat_physresist or 0) + (e.wielder.inc_stats[engine.interface.ActorStats.STAT_CON]*2) end), } newEntity{ power_source = {arcane=true}, name = "wizard's ", prefix=true, instant_resolve=true, keywords = {wizard=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { inc_stats = { [Stats.STAT_MAG] = resolvers.mbonus_material(8, 2) }, }, resolvers.genericlast(function(e) e.wielder.combat_spellresist = (e.wielder.combat_spellresist or 0) + (e.wielder.inc_stats[engine.interface.ActorStats.STAT_MAG]*2) end), } newEntity{ power_source = {psionic=true}, name = "psionicist's ", prefix=true, instant_resolve=true, keywords = {psionic=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { inc_stats = { [Stats.STAT_WIL] = resolvers.mbonus_material(8, 2) }, }, resolvers.genericlast(function(e) e.wielder.combat_mentalresist = (e.wielder.combat_mentalresist or 0) + (e.wielder.inc_stats[engine.interface.ActorStats.STAT_WIL]*2) end), } newEntity{ power_source = {technique=true}, name = "sneakthief's ", prefix=true, instant_resolve=true, keywords = {sneakthief=true}, level_range = {15, 50}, greater_ego = 1, rarity = 12, cost = 20, wielder = { combat_atk = resolvers.mbonus_material(10, 5), inc_stats = { [Stats.STAT_DEX] = resolvers.mbonus_material(6, 4), [Stats.STAT_CUN] = resolvers.mbonus_material(6, 4), }, }, } newEntity{ power_source = {technique=true}, name = "gladiator's ", prefix=true, instant_resolve=true, keywords = {gladiator=true}, level_range = {15, 50}, greater_ego = 1, rarity = 12, cost = 20, wielder = { combat_dam = resolvers.mbonus_material(10, 5), inc_stats = { [Stats.STAT_STR] = resolvers.mbonus_material(6, 4), [Stats.STAT_CON] = resolvers.mbonus_material(6, 4), }, }, } newEntity{ power_source = {arcane=true}, name = "conjurer's ", prefix=true, instant_resolve=true, keywords = {conjurer=true}, level_range = {15, 50}, greater_ego = 1, rarity = 12, cost = 20, wielder = { combat_spellpower = resolvers.mbonus_material(10, 5), inc_stats = { [Stats.STAT_MAG] = resolvers.mbonus_material(4, 4), [Stats.STAT_WIL] = resolvers.mbonus_material(4, 4), }, }, } newEntity{ power_source = {psionic=true}, name = "solipsist's ", prefix=true, instant_resolve=true, keywords = {solipsist=true}, level_range = {15, 50}, greater_ego = 1, rarity = 12, cost = 20, wielder = { combat_mindpower = resolvers.mbonus_material(10, 5), inc_stats = { [Stats.STAT_CUN] = resolvers.mbonus_material(4, 4), [Stats.STAT_WIL] = resolvers.mbonus_material(4, 4), }, }, } newEntity{ power_source = {technique=true}, name = "mule's ", prefix=true, instant_resolve=true, keywords = {mule=true}, level_range = {1, 50}, rarity = 7, cost = 6, wielder = { max_encumber = resolvers.mbonus_material(20, 20), fatigue = resolvers.mbonus_material(6, 4, function(e, v) return 0, -v end), }, } newEntity{ power_source = {nature=true}, name = " of life", suffix=true, instant_resolve=true, keywords = {life=true}, level_range = {30, 50}, greater_ego = 1, rarity = 12, cost = 50, wielder = { max_life=resolvers.mbonus_material(60, 40), life_regen = resolvers.mbonus_material(15, 5, function(e, v) v=v/10 return 0, v end), healing_factor = resolvers.mbonus_material(20, 10, function(e, v) v=v/100 return 0, v end), }, } newEntity{ power_source = {technique=true}, name = "painweaver's ", prefix=true, instant_resolve=true, keywords = {painweaver=true}, level_range = {30, 50}, rarity = 20, cost = 60, wielder = { combat_spellpower = resolvers.mbonus_material(15, 5), combat_dam = resolvers.mbonus_material(15, 5), combat_mindpower = resolvers.mbonus_material(15, 5), inc_damage = { all = resolvers.mbonus_material(4, 4) }, }, } newEntity{ power_source = {technique=true}, name = "savage's ", prefix=true, instant_resolve=true, keywords = {savage=true}, level_range = {10, 50}, greater_ego = 1, rarity = 15, cost = 40, wielder = { inc_stats = { [Stats.STAT_CON] = resolvers.mbonus_material(5, 1), }, combat_spellresist = resolvers.mbonus_material(10, 10), max_stamina = resolvers.mbonus_material(30, 10), }, } newEntity{ power_source = {nature=true}, name = "treant's ", prefix=true, instant_resolve=true, keywords = {treant=true}, level_range = {10, 50}, greater_ego = 1, rarity = 15, cost = 40, wielder = { resists={ [DamageType.NATURE] = resolvers.mbonus_material(10, 5), }, poison_immune = resolvers.mbonus_material(15, 10, function(e, v) v=v/100 return 0, v end), disease_immune = resolvers.mbonus_material(15, 10, function(e, v) v=v/100 return 0, v end), combat_physresist = resolvers.mbonus_material(10, 10), }, } newEntity{ power_source = {psionic=true}, name = " of misery", suffix=true, instant_resolve=true, keywords = {misery=true}, level_range = {20, 50}, greater_ego = 1, rarity = 20, cost = 40, resolvers.charmt(Talents.T_BLEEDING_EDGE, {2,3,4}, 20), wielder = { melee_project = { [DamageType.BLEED] = resolvers.mbonus_material(20, 20), [DamageType.RANDOM_GLOOM] = resolvers.mbonus_material(10, 10), }, inc_stats = { [Stats.STAT_CUN] = resolvers.mbonus_material(9, 1), }, hate_on_crit = resolvers.mbonus_material(2, 1), max_hate = resolvers.mbonus_material(10, 5), }, } newEntity{ power_source = {arcane=true}, name = " of warding", suffix=true, instant_resolve=true, keywords = {warding=true}, level_range = {30, 50}, greater_ego = 1, rarity = 30, cost = 60, wielder = { resists={ [DamageType.ACID] = resolvers.mbonus_material(20, 10), [DamageType.LIGHTNING] = resolvers.mbonus_material(20, 10), [DamageType.FIRE] = resolvers.mbonus_material(20, 10), [DamageType.COLD] = resolvers.mbonus_material(20, 10), }, }, } newEntity{ power_source = {technique=true}, name = " of focus", suffix=true, instant_resolve=true, keywords = {focus=true}, level_range = {40, 50}, greater_ego = 1, rarity = 30, cost = 100, resolvers.charmt(Talents.T_GREATER_WEAPON_FOCUS, {2,3,4}, 20), wielder = { resists_pen = { [DamageType.PHYSICAL] = resolvers.mbonus_material(10, 5), }, }, } newEntity{ power_source = {technique=true}, name = " of pilfering", suffix=true, instant_resolve=true, keywords = {pilfering=true}, level_range = {10, 50}, greater_ego = 1, rarity = 15, cost = 30, resolvers.charmt(Talents.T_DISENGAGE, 2, 30), wielder = { combat_atk = resolvers.mbonus_material(10, 7), combat_apr = resolvers.mbonus_material(10, 7), combat_def = resolvers.mbonus_material(10, 7), }, } newEntity{ power_source = {technique=true}, name = " of speed", suffix=true, instant_resolve=true, keywords = {speed=true}, level_range = {30, 50}, greater_ego = 1, rarity = 40, cost = 140, resolvers.charmt(Talents.T_BLINDING_SPEED, {2,3,4}, 40), wielder = { movement_speed = resolvers.mbonus_material(15, 10, function(e, v) v=v/100 return 0, v end), combat_atk = resolvers.mbonus_material(10, 5), combat_def = resolvers.mbonus_material(10, 5), }, } newEntity{ power_source = {arcane=true}, name = " of blinding strikes", suffix=true, instant_resolve=true, keywords = {strikes=true}, level_range = {10, 50}, greater_ego = 1, rarity = 30, cost = 60, wielder = { melee_project = { [DamageType.LIGHTNING] = resolvers.mbonus_material(12, 3), [DamageType.PHYSICAL] = resolvers.mbonus_material(12, 3), [DamageType.RANDOM_BLIND] = resolvers.mbonus_material(12, 3), }, on_melee_hit = { [DamageType.LIGHTNING] = resolvers.mbonus_material(12, 3), [DamageType.PHYSICAL] = resolvers.mbonus_material(12, 3), [DamageType.RANDOM_BLIND] = resolvers.mbonus_material(12, 3), }, }, }
gpl-3.0
greasydeal/darkstar
scripts/globals/abilities/pets/stone_iv.lua
20
1151
--------------------------------------------------- -- Stone 4 --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local spell = getSpell(162); --calculate raw damage local dmg = calculateMagicDamage(381,2,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, 2); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = mobAddBonuses(pet,spell,target,dmg, 2); --add on TP bonuses local tp = skill:getTP(); if tp < 100 then tp = 100; end dmg = dmg * tp / 100; --add in final adjustments dmg = finalMagicAdjustments(pet,target,spell,dmg); return dmg; end
gpl-3.0
naclander/tome
game/engines/default/engine/interface/ActorTemporaryEffects.lua
1
6387
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" --- Handles actors temporary effects (temporary boost of a stat, ...) module(..., package.seeall, class.make) _M.tempeffect_def = {} --- Defines actor temporary effects -- Static! function _M:loadDefinition(file, env) local f, err = util.loadfilemods(file, setmetatable(env or { DamageType = require "engine.DamageType", TemporaryEffects = self, newEffect = function(t) self:newEffect(t) end, load = function(f) self:loadDefinition(f, getfenv(2)) end }, {__index=_G})) if not f and err then error(err) end f() end --- Defines one effect -- Static! function _M:newEffect(t) assert(t.name, "no effect name") assert(t.desc, "no effect desc") assert(t.type, "no effect type") t.name = t.name:upper() t.activation = t.activation or function() end t.deactivation = t.deactivation or function() end t.parameters = t.parameters or {} t.type = t.type or "physical" t.status = t.status or "detrimental" t.decrease = t.decrease or 1 self.tempeffect_def["EFF_"..t.name] = t t.id = "EFF_"..t.name self["EFF_"..t.name] = "EFF_"..t.name end function _M:init(t) self.tmp = self.tmp or {} end --- Counts down timed effects, call from your actors "act" method -- @param filter if not nil a function that gets passed the effect and its parameters, must return true to handle the effect function _M:timedEffects(filter) local todel = {} local def for eff, p in pairs(self.tmp) do def = _M.tempeffect_def[eff] if not filter or filter(def, p) then if p.dur <= 0 then todel[#todel+1] = eff else if def.on_timeout then if p.src then p.src.__project_source = p end -- intermediate projector source if def.on_timeout(self, p) then todel[#todel+1] = eff end if p.src then p.src.__project_source = nil end end end p.dur = p.dur - def.decrease end end while #todel > 0 do self:removeEffect(table.remove(todel)) end end --- Sets a timed effect on the actor -- @param eff_id the effect to set -- @param dur the number of turns to go on -- @param p a table containing the effects parameters -- @parm silent true to suppress messages function _M:setEffect(eff_id, dur, p, silent) local had = self.tmp[eff_id] -- Beware, setting to 0 means removing if dur <= 0 then return self:removeEffect(eff_id) end dur = math.floor(dur) for k, e in pairs(_M.tempeffect_def[eff_id].parameters) do if not p[k] then p[k] = e end end p.dur = dur p.effect_id = eff_id self:check("on_set_temporary_effect", eff_id, _M.tempeffect_def[eff_id], p) if p.dur <= 0 then return self:removeEffect(eff_id) end -- If we already have it, we check if it knows how to "merge", or else we remove it and re-add it if self:hasEffect(eff_id) then if _M.tempeffect_def[eff_id].on_merge then self.tmp[eff_id] = _M.tempeffect_def[eff_id].on_merge(self, self.tmp[eff_id], p) self.changed = true return else self:removeEffect(eff_id, true, true) end end self.tmp[eff_id] = p if _M.tempeffect_def[eff_id].on_gain then local ret, fly = _M.tempeffect_def[eff_id].on_gain(self, p) if not silent and not had then if ret then game.logSeen(self, ret:gsub("#Target#", self.name:capitalize()):gsub("#target#", self.name)) end if fly and game.flyers and self.x and self.y and game.level.map.seens(self.x, self.y) then local sx, sy = game.level.map:getTileToScreen(self.x, self.y) if game.level.map.seens(self.x, self.y) then game.flyers:add(sx, sy, 20, (rng.range(0,2)-1) * 0.5, -3, fly, {255,100,80}) end end end end if _M.tempeffect_def[eff_id].activate then _M.tempeffect_def[eff_id].activate(self, p) end self.changed = true self:check("on_temporary_effect_added", eff_id, _M.tempeffect_def[eff_id], p) end --- Check timed effect -- @param eff_id the effect to check for -- @return either nil or the parameters table for the effect function _M:hasEffect(eff_id) return self.tmp[eff_id] end --- Removes the effect function _M:removeEffect(eff, silent, force) local p = self.tmp[eff] if not p then return end if _M.tempeffect_def[eff].no_remove and not force then return end self.tmp[eff] = nil self.changed = true if _M.tempeffect_def[eff].on_lose then local ret, fly = _M.tempeffect_def[eff].on_lose(self, p) if not silent then if ret then game.logSeen(self, ret:gsub("#Target#", self.name:capitalize()):gsub("#target#", self.name)) end if fly and game.flyers and self.x and self.y then local sx, sy = game.level.map:getTileToScreen(self.x, self.y) if game.level.map.seens(self.x, self.y) then game.flyers:add(sx, sy, 20, (rng.range(0,2)-1) * 0.5, -3, fly, {255,100,80}) end end end end if p.__tmpvals then for i = 1, #p.__tmpvals do self:removeTemporaryValue(p.__tmpvals[i][1], p.__tmpvals[i][2]) end end if _M.tempeffect_def[eff].deactivate then _M.tempeffect_def[eff].deactivate(self, p) end self:check("on_temporary_effect_removed", eff, _M.tempeffect_def[eff], p) end --- Removes the effect function _M:removeAllEffects() local todel = {} for eff, p in pairs(self.tmp) do todel[#todel+1] = eff end while #todel > 0 do self:removeEffect(table.remove(todel)) end end --- Helper function to add temporary values and not have to remove them manualy function _M:effectTemporaryValue(eff, k, v) if not eff.__tmpvals then eff.__tmpvals = {} end eff.__tmpvals[#eff.__tmpvals+1] = {k, self:addTemporaryValue(k, v)} end --- Trigger an effect method function _M:callEffect(eff_id, name, ...) local e = _M.tempeffect_def[eff_id] local p = self.tmp[eff_id] name = name or "trigger" if e[name] and p then return e[name](self, p, ...) end end
gpl-3.0
ibm2431/darkstar
scripts/commands/takexp.lua
22
1123
--------------------------------------------------------------------------------------------------- -- func: takexp <amount> <player> -- desc: Removes experience points from the target player. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "is" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!takexp <amount> {player}"); end; function onTrigger(player, amount, target) -- validate amount if (amount == nil or amount < 1) then error(player, "Invalid amount."); return; end -- validate target local targ; if (target == nil) then targ = player; else targ = GetPlayerByName(target); if (targ == nil) then error(player, string.format("Player named '%s' not found!", target)); return; end end -- take xp targ:delExp(amount); player:PrintToPlayer( string.format( "Removed %i exp from %s. They are now level %i.", amount, targ:getName(), targ:getMainLvl() )); end;
gpl-3.0
Geigerkind/DPSMateTBC
DPSMate/libs/LibStub.lua
184
1367
-- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info -- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS! local LibStub = _G[LIBSTUB_MAJOR] if not LibStub or LibStub.minor < LIBSTUB_MINOR then LibStub = LibStub or {libs = {}, minors = {} } _G[LIBSTUB_MAJOR] = LibStub LibStub.minor = LIBSTUB_MINOR function LibStub:NewLibrary(major, minor) assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)") minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.") local oldminor = self.minors[major] if oldminor and oldminor >= minor then return nil end self.minors[major], self.libs[major] = minor, self.libs[major] or {} return self.libs[major], oldminor end function LibStub:GetLibrary(major, silent) if not self.libs[major] and not silent then error(("Cannot find a library instance of %q."):format(tostring(major)), 2) end return self.libs[major], self.minors[major] end function LibStub:IterateLibraries() return pairs(self.libs) end setmetatable(LibStub, { __call = LibStub.GetLibrary }) end
gpl-3.0
ibm2431/darkstar
scripts/zones/Nashmau/npcs/Fhe_Maksojha.lua
9
1768
----------------------------------- -- Area: Nashmau -- NPC: Fhe Maksojha -- Type: Standard NPC -- !pos 19.084 -7 71.287 53 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); local ID = require("scripts/zones/Nashmau/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local notmeanttobe = player:getQuestStatus(AHT_URHGAN,dsp.quest.id.ahtUrhgan.NOT_MEANT_TO_BE); local notMeantToBeProg = player:getCharVar("notmeanttobeCS"); if (notmeanttobe == QUEST_AVAILABLE) then player:startEvent(293); elseif (notMeantToBeProg == 1) then player:startEvent(295); elseif (notMeantToBeProg == 2) then player:startEvent(294); elseif (notMeantToBeProg == 3) then player:startEvent(296); elseif (notMeantToBeProg == 5) then player:startEvent(297); elseif (notmeanttobe == QUEST_COMPLETED) then player:startEvent(298); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 293) then player:setCharVar("notmeanttobeCS",1); player:addQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.NOT_MEANT_TO_BE); elseif (csid == 294) then player:setCharVar("notmeanttobeCS",3); elseif (csid == 297) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINEDX,2187,3); else player:setCharVar("notmeanttobeCS",0); player:addItem(2187,3); player:messageSpecial(ID.text.ITEM_OBTAINEDX,2187,3); player:completeQuest(AHT_URHGAN,dsp.quest.id.ahtUrhgan.NOT_MEANT_TO_BE); end end end;
gpl-3.0
greasydeal/darkstar
scripts/globals/spells/Vital_Etude.lua
11
1611
----------------------------------------- -- Spell: Vital Etude -- Static VIT Boost, BRD 70 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 416) then power = 12; elseif((sLvl+iLvl >= 417) and (sLvl+iLvl <= 445)) then power = 13; elseif((sLvl+iLvl >= 446) and (sLvl+iLvl <= 474)) then power = 14; elseif(sLvl+iLvl >= 475) then power = 15; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,10,duration,caster:getID(), MOD_VIT, 2)) then spell:setMsg(75); end return EFFECT_ETUDE; end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Windurst_Woods/npcs/HomePoint#1.lua
27
1278
----------------------------------- -- Area: Windurst Woods -- NPC: HomePoint#1 -- @pos -98.588 0.001 -183.416 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 25); 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); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
LegionXI/darkstar
scripts/globals/items/anthos_xiphos.lua
41
1078
----------------------------------------- -- ID: 17750 -- Item: Anthos Xiphos -- Additional Effect: Water Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(4,11); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0); dmg = adjustForTarget(target,dmg,ELE_WATER); dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_WATER_DAMAGE,message,dmg; end end;
gpl-3.0
greasydeal/darkstar
scripts/globals/spells/aisha_ichi.lua
11
1595
----------------------------------------- -- Spell: Aisha: Ichi ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_ATTACK_DOWN; -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local resist = applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Base power is 15 and is not affected by resistaces. local power = 15; --Calculates Resist Chance if(resist >= 0.125) then local duration = 120 * resist; if(duration >= 50) then -- Erases a weaker attack down and applies the stronger one local attackdown = target:getStatusEffect(effect); if(attackdown ~= nil) then if(attackdown:getPower() < power) then target:delStatusEffect(effect); target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); else -- no effect spell:setMsg(75); end else target:addStatusEffect(effect,power,0,duration); spell:setMsg(237); end else spell:setMsg(85); end else spell:setMsg(284); end return effect; end;
gpl-3.0
LegionXI/darkstar
scripts/globals/spells/foe_requiem_iv.lua
26
1631
----------------------------------------- -- Spell: Foe Requiem IV ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_REQUIEM; local duration = 111; local power = 4; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,SINGING_SKILL,0); if (resm < 0.5) then spell:setMsg(85);--resist message return 1; end local iBoost = caster:getMod(MOD_REQUIEM_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Try to overwrite weaker slow / haste if (canOverwrite(target, effect, power)) then -- overwrite them target:delStatusEffect(effect); target:addStatusEffect(effect,power,3,duration); spell:setMsg(237); else spell:setMsg(75); -- no effect end return effect; end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Port_Bastok/npcs/Tete.lua
17
1303
----------------------------------- -- Area: Port Bastok -- NPC: Tete -- Continues Quest: The Wisdom Of Elders ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ------------------------------------ require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,THE_WISDOM_OF_ELDERS) == QUEST_ACCEPTED) then player:startEvent(0x00af); else player:startEvent(0x0023); 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); if (csid == 0x00af) then player:setVar("TheWisdomVar",2); end end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Selbina/npcs/Gabwaleid.lua
14
1534
----------------------------------- -- Area: Selbina -- NPC: Gabwaleid -- Involved in Quest: Riding on the Clouds -- @pos -17 -7 11 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 4) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0258); 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
LegionXI/darkstar
scripts/globals/abyssea.lua
17
10151
----------------------------------- -- Abyssea functions, vars, tables -- DO NOT mess with the order -- or change things to "elseif"! ----------------------------------- require("scripts/globals/keyitems"); -- weaponskills for red weakness local red_weakness = { --light 37, 161, 149, 180, --dark 22, 133, 98, --fire 34, --earth 178, --wind 20, 148, --ice 51, --thunder 144 } local yellow_weakness = { --fire [0] = { 146, 147, 176, 204, 591, 321, 455 }, --earth [1] = { 161, 162, 191, 210, 555, 330, 458 }, --water [2] = { 171, 172, 201, 515, 336, 454 }, --wind [3] = { 156, 157, 186, 208, 534, 327, 457 }, --ice [4] = { 151, 152, 181, 206, 531, 324, 456 }, --ltng [5] = { 166, 167, 196, 212, 644, 333, 459 }, --light [6] = { 29, 30, 38, 39, 21, 112, 565, 461 }, --dark [7] = { 247, 245, 231, 260, 557, 348, 460 } } local blue_weakness = { --6-14 {196, 197, 198, 199, 212, 213, 214, 215, 18, 23, 24, 25, 118, 119, 120}, --14-22 {40, 41, 42, 135, 136, 71, 72, 103, 104, 87, 88, 151, 152, 55, 56}, --22-6 {165, 166, 167, 168, 169, 5, 6, 7, 8, 9, 176, 181, 182, 183, 184} } ----------------------------------- -- getMaxTravStones -- returns Traverser Stone KI cap ----------------------------------- function getMaxTravStones(player) local MaxTravStones = 3; if (player:hasKeyItem(VIRIDIAN_ABYSSITE_OF_AVARICE)) then MaxTravStones = MaxTravStones + 1; end if (player:hasKeyItem(IVORY_ABYSSITE_OF_AVARICE)) then MaxTravStones = MaxTravStones + 1; end if (player:hasKeyItem(VERMILLION_ABYSSITE_OF_AVARICE)) then MaxTravStones = MaxTravStones + 1; end return MaxTravStones; end; ----------------------------------- -- getTravStonesTotal -- returns total Traverser Stone KI -- (NOT the reserve value from currency menu) ----------------------------------- function getTravStonesTotal(player) local STONES = 0; if (player:hasKeyItem(TRAVERSER_STONE1)) then STONES = STONES + 1; end if (player:hasKeyItem(TRAVERSER_STONE2)) then STONES = STONES + 1; end if (player:hasKeyItem(TRAVERSER_STONE3)) then STONES = STONES + 1; end if (player:hasKeyItem(TRAVERSER_STONE4)) then STONES = STONES + 1; end if (player:hasKeyItem(TRAVERSER_STONE5)) then STONES = STONES + 1; end if (player:hasKeyItem(TRAVERSER_STONE6)) then STONES = STONES + 1; end return STONES; end; ----------------------------------- -- spendTravStones -- removes Traverser Stone KIs ----------------------------------- function spendTravStones(player,spentstones) if (spentstones == 4) then if (player:hasKeyItem(TRAVERSER_STONE6)) then spentstones = 3; player:delKeyItem(TRAVERSER_STONE6); elseif (player:hasKeyItem(TRAVERSER_STONE5)) then spentstones = 3; player:delKeyItem(TRAVERSER_STONE5); elseif (player:hasKeyItem(TRAVERSER_STONE4)) then spentstones = 3; player:delKeyItem(TRAVERSER_STONE4); elseif (player:hasKeyItem(TRAVERSER_STONE3)) then spentstones = 3; player:delKeyItem(TRAVERSER_STONE3); elseif (player:hasKeyItem(TRAVERSER_STONE2)) then spentstones = 3; player:delKeyItem(TRAVERSER_STONE2); elseif (player:hasKeyItem(TRAVERSER_STONE1)) then spentstones = 3; player:delKeyItem(TRAVERSER_STONE1); end end if (spentstones == 3) then if (player:hasKeyItem(TRAVERSER_STONE6)) then spentstones = 2; player:delKeyItem(TRAVERSER_STONE6); elseif (player:hasKeyItem(TRAVERSER_STONE5)) then spentstones = 2; player:delKeyItem(TRAVERSER_STONE5); elseif (player:hasKeyItem(TRAVERSER_STONE4)) then spentstones = 2; player:delKeyItem(TRAVERSER_STONE4); elseif (player:hasKeyItem(TRAVERSER_STONE3)) then spentstones = 2; player:delKeyItem(TRAVERSER_STONE3); elseif (player:hasKeyItem(TRAVERSER_STONE2)) then spentstones = 2; player:delKeyItem(TRAVERSER_STONE2); elseif (player:hasKeyItem(TRAVERSER_STONE1)) then spentstones = 2; player:delKeyItem(TRAVERSER_STONE1); end end if (spentstones == 2) then if (player:hasKeyItem(TRAVERSER_STONE6)) then spentstones = 1; player:delKeyItem(TRAVERSER_STONE6); elseif (player:hasKeyItem(TRAVERSER_STONE5)) then spentstones = 1; player:delKeyItem(TRAVERSER_STONE5); elseif (player:hasKeyItem(TRAVERSER_STONE4)) then spentstones = 1; player:delKeyItem(TRAVERSER_STONE4); elseif (player:hasKeyItem(TRAVERSER_STONE3)) then spentstones = 1; player:delKeyItem(TRAVERSER_STONE3); elseif (player:hasKeyItem(TRAVERSER_STONE2)) then spentstones = 1; player:delKeyItem(TRAVERSER_STONE2); elseif (player:hasKeyItem(TRAVERSER_STONE1)) then spentstones = 1; player:delKeyItem(TRAVERSER_STONE1); end end if (spentstones == 1) then if (player:hasKeyItem(TRAVERSER_STONE6)) then player:delKeyItem(TRAVERSER_STONE6); elseif (player:hasKeyItem(TRAVERSER_STONE5)) then player:delKeyItem(TRAVERSER_STONE5); elseif (player:hasKeyItem(TRAVERSER_STONE4)) then player:delKeyItem(TRAVERSER_STONE4); elseif (player:hasKeyItem(TRAVERSER_STONE3)) then player:delKeyItem(TRAVERSER_STONE3); elseif (player:hasKeyItem(TRAVERSER_STONE2)) then player:delKeyItem(TRAVERSER_STONE2); elseif (player:hasKeyItem(TRAVERSER_STONE1)) then player:delKeyItem(TRAVERSER_STONE1); end end end; ----------------------------------- -- getAbyssiteTotal -- returns total "Abyssite of <thing>" ----------------------------------- function getAbyssiteTotal(player,Type) local SOJOURN = 0; local FURTHERANCE = 0; local MERIT = 0; if (Type == "SOJOURN") then if (player:hasKeyItem(IVORY_ABYSSITE_OF_SOJOURN)) then SOJOURN = SOJOURN + 1; end if (player:hasKeyItem(SCARLET_ABYSSITE_OF_SOJOURN)) then SOJOURN = SOJOURN + 1; end if (player:hasKeyItem(JADE_ABYSSITE_OF_SOJOURN)) then SOJOURN = SOJOURN + 1; end if (player:hasKeyItem(SAPPHIRE_ABYSSITE_OF_SOJOURN)) then SOJOURN = SOJOURN + 1; end if (player:hasKeyItem(INDIGO_ABYSSITE_OF_SOJOURN)) then SOJOURN = SOJOURN + 1; end if (player:hasKeyItem(EMERALD_ABYSSITE_OF_SOJOURN)) then SOJOURN = SOJOURN + 1; end return SOJOURN; elseif (Type == "FURTHERANCE") then if (player:hasKeyItem(SCARLET_ABYSSITE_OF_FURTHERANCE)) then FURTHERANCE = FURTHERANCE + 1; end if (player:hasKeyItem(SAPPHIRE_ABYSSITE_OF_FURTHERANCE)) then FURTHERANCE = FURTHERANCE + 1; end if (player:hasKeyItem(IVORY_ABYSSITE_OF_FURTHERANCE)) then FURTHERANCE = FURTHERANCE + 1; end return FURTHERANCE; elseif (Type == "MERIT") then if (player:hasKeyItem(AZURE_ABYSSITE_OF_MERIT)) then MERIT = MERIT + 1; end if (player:hasKeyItem(VIRIDIAN_ABYSSITE_OF_MERIT)) then MERIT = MERIT + 1; end if (player:hasKeyItem(JADE_ABYSSITE_OF_MERIT)) then MERIT = MERIT + 1; end if (player:hasKeyItem(SAPPHIRE_ABYSSITE_OF_MERIT)) then MERIT = MERIT + 1; end if (player:hasKeyItem(IVORY_ABYSSITE_OF_MERIT)) then MERIT = MERIT + 1; end if (player:hasKeyItem(INDIGO_ABYSSITE_OF_MERIT)) then MERIT = MERIT + 1; end return MERIT; end end; ----------------------------------- -- getDemiluneAbyssite -- returns total value of Demulune KeyItems ----------------------------------- function getDemiluneAbyssite(player) local Demilune = 0; -- Todo: change this into proper bitmask if (player:hasKeyItem(CLEAR_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 1; end if (player:hasKeyItem(COLORFUL_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 2; end if (player:hasKeyItem(SCARLET_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 4; end if (player:hasKeyItem(AZURE_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 8; end if (player:hasKeyItem(VIRIDIAN_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 16; end if (player:hasKeyItem(JADE_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 32; end if (player:hasKeyItem(SAPPHIRE_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 64; end if (player:hasKeyItem(CRIMSON_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 128; end if (player:hasKeyItem(EMERALD_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 256; end if (player:hasKeyItem(VERMILLION_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 512; end if (player:hasKeyItem(INDIGO_DEMILUNE_ABYSSITE)) then Demilune = Demilune + 1024; end return Demilune; end; function getNewYellowWeakness(mob) local day = VanadielDayElement() local weakness = math.random(day-1, day+1) if weakness < 0 then weakness = 7 elseif weakness > 7 then weakness = 0 end return yellow_weakness[weakness][math.random(#yellow_weakness[weakness])] end function getNewRedWeakness(mob) return red_weakness[math.random(#red_weakness)] end function getNewBlueWeakness(mob) local time = VanadielHour() local table = 3 if time >= 6 and time < 14 then table = 1 elseif time >= 14 and time < 22 then table = 2 end return blue_weakness[table][math.random(#blue_weakness[table])] end
gpl-3.0
LegionXI/darkstar
scripts/globals/mobskills/Sweeping_Flail.lua
39
1067
--------------------------------------------------- -- Sweeping Flail -- Family: Bahamut -- Description: Spins around to deal physical damage to enemies behind user. Additional effect: Knockback -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: 20' cone -- Notes: Used when someone pulls hate from behind Bahamut. --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:isBehind(mob, 55) == false) then return 1; else return 0; end; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW); target:delHP(dmg); return dmg; end;
gpl-3.0
greasydeal/darkstar
scripts/globals/items/tiny_goldfish.lua
17
1322
----------------------------------------- -- ID: 4310 -- Item: tiny_goldfish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local 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,4310); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Abyssea-Misareaux/npcs/qm13.lua
14
1548
----------------------------------- -- Zone: Abyssea-Misareaux -- NPC: qm13 (???) -- Spawns Cirein-Croin -- @pos ? ? ? 216 ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/status"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17662481) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(GLISTENING_OROBON_LIVER) and player:hasKeyItem(DOFFED_POROGGO_HAT)) then player:startEvent(1021, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Ask if player wants to use KIs else player:startEvent(1020, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1021 and option == 1) then SpawnMob(17662481):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(GLISTENING_OROBON_LIVER); player:delKeyItem(DOFFED_POROGGO_HAT); end end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Thierride.lua
14
3302
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Thierride -- @zone 80 -- @pos -124 -2 14 ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- Item 1019 = Lufet Salt -- Had to use setVar because you have to trade Salts one at a time according to the wiki. -- Lufet Salt can be obtained by killing Crabs in normal West Ronfaure. ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local lufetSalt = trade:hasItemQty(1019,1); local cnt = trade:getItemCount(); local beansAhoy = player:getQuestStatus(CRYSTAL_WAR,BEANS_AHOY); if (lufetSalt and cnt == 1 and beansAhoy == QUEST_ACCEPTED) then if (player:getVar("BeansAhoy") == 0 == true) then player:startEvent(0x0151); -- Traded the Correct Item Dialogue (NOTE: You have to trade the Salts one at according to wiki) elseif (player:needsToZone() == false) then player:startEvent(0x0154); -- Quest Complete Dialogue end else player:startEvent(0x0153); -- Wrong Item Traded end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local beansAhoy = player:getQuestStatus(CRYSTAL_WAR,BEANS_AHOY); if (beansAhoy == QUEST_AVAILABLE) then player:startEvent(0x014E); -- Quest Start elseif (beansAhoy == QUEST_ACCEPTED) then player:startEvent(0x014F); -- Quest Active, NPC Repeats what he says but as normal 'text' instead of cutscene. elseif (beansAhoy == QUEST_COMPLETED and getConquestTally() ~= player:getVar("BeansAhoy_ConquestWeek")) then player:startEvent(0x0156); elseif (beansAhoy == QUEST_COMPLETED) then player:startEvent(0x0155); else player:startEvent(0x014D); -- Default Dialogue 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); if (csid == 0x014E) then player:addQuest(CRYSTAL_WAR,BEANS_AHOY); elseif (csid == 0x0151) then player:tradeComplete(); player:setVar("BeansAhoy",1); player:needsToZone(true); elseif (csid == 0x0154 or csid == 0x0156) then if (player:hasItem(5704,1) or player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,5704) else player:addItem(5704,1); player:messageSpecial(ITEM_OBTAINED,5704); player:setVar("BeansAhoy_ConquestWeek",getConquestTally()); if (csid == 0x0154) then player:completeQuest(CRYSTAL_WAR,BEANS_AHOY); player:setVar("BeansAhoy",0); player:tradeComplete(); end end end end;
gpl-3.0
ricker75/Global-Server
data/npc/scripts/Imbul.lua
2
2004
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) -- OTServ event handling functions start function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- OTServ event handling functions end keywordHandler:addKeyword({'passage'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = "I can bring you either to the east end of Port Hope or to the centre of the town, where would you like to go?"}) -- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions! local travelNode = keywordHandler:addKeyword({'east'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you seek a passage to the east end of Port Hope for free?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 0, cost = 0, destination = {x=32679, y=32777, z=7} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Maybe another time.'}) local travelNode = keywordHandler:addKeyword({'centre'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you seek a passage to the centre of Port Hope for free?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = false, level = 0, cost = 0, destination = {x=32628, y=32771, z=7} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Maybe another time.'}) npcHandler:addModule(FocusModule:new())
gpl-2.0
SIfoxDevTeam/wireshark
test/lua/pcre_sets.lua
35
6911
-- See Copyright Notice in the file lrexlib.h local luatest = require "luatest" local N = luatest.NT local function norm(a) return a==nil and N or a end local function fill (n, m) local t = {} for i = n, m, -1 do table.insert (t, i) end return t end local function set_named_subpatterns (lib, flg) return { Name = "Named Subpatterns", Func = function (subj, methodname, patt, name1, name2) local r = lib.new (patt) local _,_,caps = r[methodname] (r, subj) return norm(caps[name1]), norm(caps[name2]) end, --{} N.B. subject is always first element { {"abcd", "tfind", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} }, { {"abcd", "exec", "(?P<dog>.)b.(?P<cat>d)", "dog", "cat"}, {"a","d"} }, } end local function set_f_find (lib, flg) local cp1251 = "ÀÁÂÃÄŨÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖרÙÜÛÚÝÞßàáâãä叿çèéêëìíîïðñòóôõö÷øùüûúýþÿ" local loc = "Russian_Russia.1251" return { Name = "Function find", Func = lib.find, --{subj, patt, st,cf,ef,lo}, { results } { {"abcd", ".+", 5}, { N } }, -- failing st { {"abcd", ".*?"}, { 1,0 } }, -- non-greedy { {"abc", "aBC", N,flg.CASELESS}, { 1,3 } }, -- cf { {"abc", "aBC", N,"i" }, { 1,3 } }, -- cf { {"abc", "bc", N,flg.ANCHORED}, { N } }, -- cf { {"abc", "bc", N,N,flg.ANCHORED}, { N } }, -- ef --{ {cp1251, "[[:upper:]]+", N,N,N, loc}, { 1,33} }, -- locale --{ {cp1251, "[[:lower:]]+", N,N,N, loc}, {34,66} }, -- locale } end local function set_f_match (lib, flg) return { Name = "Function match", Func = lib.match, --{subj, patt, st,cf,ef,lo}, { results } { {"abcd", ".+", 5}, { N }}, -- failing st { {"abcd", ".*?"}, { "" }}, -- non-greedy { {"abc", "aBC", N,flg.CASELESS}, {"abc" }}, -- cf { {"abc", "aBC", N,"i" }, {"abc" }}, -- cf { {"abc", "bc", N,flg.ANCHORED}, { N }}, -- cf { {"abc", "bc", N,N,flg.ANCHORED}, { N }}, -- ef } end local function set_f_gmatch (lib, flg) -- gmatch (s, p, [cf], [ef]) local pCSV = "(^[^,]*)|,([^,]*)" local F = false 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 } { {"a\0c", "." }, {{"a",N},{"\0",N},{"c",N}} },--nuls in subj { {"", pCSV}, {{"",F}} }, { {"12", pCSV}, {{"12",F}} }, { {",", pCSV}, {{"", F},{F,""}} }, { {"12,,45", pCSV}, {{"12",F},{F,""},{F,"45"}} }, { {",,12,45,,ab,", pCSV}, {{"",F},{F,""},{F,"12"},{F,"45"},{F,""},{F,"ab"},{F,""}} }, } 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 } { {"a,\0,c", ","}, {{"a",",",N},{"\0",",",N},{"c",N,N}, } },--nuls in subj { {"ab", "$"}, {{"ab","",N}, {"",N,N}, } }, { {"ab", "^|$"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } }, { {"ab45ab","(?<=ab).*?"}, {{"ab","",N}, {"45ab","",N},{"",N,N}, } }, { {"ab", "\\b"}, {{"", "", N}, {"ab","",N}, {"",N,N}, } }, } end local function set_m_exec (lib, flg) return { Name = "Method exec", Method = "exec", --{patt,cf,lo}, {subj,st,ef} { results } { {".+"}, {"abcd",5}, { N } }, -- failing st { {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy { {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf { {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf { {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf { {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef } end local function set_m_tfind (lib, flg) return { Name = "Method tfind", Method = "tfind", --{patt,cf,lo}, {subj,st,ef} { results } { {".+"}, {"abcd",5}, { N } }, -- failing st { {".*?"}, {"abcd"}, {1,0,{}} }, -- non-greedy { {"aBC",flg.CASELESS}, {"abc"}, {1,3,{}} }, -- cf { {"aBC","i" }, {"abc"}, {1,3,{}} }, -- cf { {"bc",flg.ANCHORED}, {"abc"}, { N } }, -- cf { {"bc"}, {"abc",N, flg.ANCHORED}, { N } }, -- ef } end local function set_m_dfa_exec (lib, flg) return { Name = "Method dfa_exec", Method = "dfa_exec", --{patt,cf,lo}, {subj,st,ef,os,ws} { results } { {".+"}, {"abcd"}, {1,{4,3,2,1},4} }, -- [none] { {".+"}, {"abcd",2}, {2,{4,3,2}, 3} }, -- positive st { {".+"}, {"abcd",-2}, {3,{4,3}, 2} }, -- negative st { {".+"}, {"abcd",5}, {N } }, -- failing st { {".*"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- [none] { {".*?"}, {"abcd"}, {1,{4,3,2,1,0},5}}, -- non-greedy { {"aBC",flg.CASELESS}, {"abc"}, {1,{3},1} }, -- cf { {"aBC","i" }, {"abc"}, {1,{3},1} }, -- cf { {"bc"}, {"abc"}, {2,{3},1} }, -- [none] { {"bc",flg.ANCHORED}, {"abc"}, {N } }, -- cf { {"bc"}, {"abc",N, flg.ANCHORED}, {N } }, -- ef { { "(.)b.(d)"}, {"abcd"}, {1,{4},1} }, --[captures] { {"abc"}, {"ab"}, {N } }, { {"abc"}, {"ab",N,flg.PARTIAL}, {1,{2},flg.ERROR_PARTIAL} }, { {".+"}, {string.rep("a",50),N,N,50,50}, {1, fill(50,26), 0}},-- small ovecsize } end return function (libname, isglobal) local lib = isglobal and _G[libname] or require (libname) local flags = lib.flags () local sets = { set_f_match (lib, flags), set_f_find (lib, flags), set_f_gmatch (lib, flags), set_f_split (lib, flags), set_m_exec (lib, flags), set_m_tfind (lib, flags), } if flags.MAJOR >= 4 then table.insert (sets, set_named_subpatterns (lib, flags)) end if flags.MAJOR >= 6 then table.insert (sets, set_m_dfa_exec (lib, flags)) end return sets end
gpl-2.0
LegionXI/darkstar
scripts/zones/Western_Adoulin/npcs/Marjoirelle.lua
14
1308
----------------------------------- -- Area: Western Adoulin -- NPC: Majoirelle -- Type: Standard NPC and Quest NPC -- Involved With Quest: 'Order Up' -- @zone 256 -- @pos 127 4 -81 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Order_Up = player:getQuestStatus(ADOULIN, ORDER_UP); local Order_Marjoirelle = player:getMaskBit(player:getVar("Order_Up_NPCs"), 8); if ((Order_Up == QUEST_ACCEPTED) and (not Order_Marjoirelle)) then -- Progresses Quest: 'Order Up' player:startEvent(0x0044); else -- Standard Dialogue player:startEvent(0x021A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0044) then -- Progresses Quest: 'Order Up' player:setMaskBit("Order_Up_NPCs", 8, true); end end;
gpl-3.0
ibm2431/darkstar
scripts/zones/West_Sarutabaruta_[S]/IDs.lua
9
1556
----------------------------------- -- Area: West_Sarutabaruta_[S] ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.WEST_SARUTABARUTA_S] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. HARVESTING_IS_POSSIBLE_HERE = 7069, -- Harvesting is possible here if you have <item>. FISHING_MESSAGE_OFFSET = 7076, -- You can't fish here. DOOR_OFFSET = 7434, -- The door is sealed shut... COMMON_SENSE_SURVIVAL = 9258, -- It appears that you have arrived at a new survival guide provided by the Servicemen's Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. }, mob = { JEDUAH_PH = { [17166542] = 17166543, -- 113.797 -0.8 -310.342 }, RAMPONNEAU_PH = { [17166701] = 17166705, -- 78.836 -0.109 -199.204 }, }, npc = { HARVESTING = { 17167162, 17167163, 17167164, 17167165, 17167166, 17167167, }, }, } return zones[dsp.zone.WEST_SARUTABARUTA_S]
gpl-3.0
greasydeal/darkstar
scripts/zones/Dynamis-Bastok/npcs/qm1.lua
19
1256
----------------------------------- -- Area: Dynamis Bastok -- NPC: qm1 (???) -- Notes: Spawns when Megaboss is defeated ----------------------------------- package.loaded["scripts/zones/Dynamis-Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Dynamis-Bastok/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(HYDRA_CORPS_EYEGLASS) == false) then player:setVar("DynaBastok_Win",1); player:addKeyItem(HYDRA_CORPS_EYEGLASS); player:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_EYEGLASS); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
ibm2431/darkstar
scripts/zones/Apollyon/mobs/Dark_Elemental.lua
9
2103
----------------------------------- -- Area: Apollyon SW -- Mob: Dark Elemental ----------------------------------- require("scripts/globals/limbus"); ----------------------------------- function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) local mobID = mob:getID(); print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); local elementalday = GetServerVariable("[SW_Apollyon]ElementalTrigger"); local correctelement=false; switch (elementalday): caseof { [1] = function (x) if (mobID==16932913 or mobID==16932921 or mobID==16932929) then correctelement=true; end end , [2] = function (x) if (mobID==16932912 or mobID==16932920 or mobID==16932928 ) then correctelement=true; end end , [3] = function (x) if (mobID==16932916 or mobID==16932924 or mobID==16932932 ) then correctelement=true; end end , [4] = function (x) if (mobID==16932910 or mobID==16932918 or mobID==16932926 ) then correctelement=true; end end , [5] = function (x) if (mobID==16932914 or mobID==16932922 or mobID==16932930 ) then correctelement=true; end end , [6] = function (x) if (mobID==16932917 or mobID==16932925 or mobID==16932933 ) then correctelement=true; end end , [7] = function (x) if (mobID==16932931 or mobID==16932915 or mobID==16932923 ) then correctelement=true; end end , [8] = function (x) if (mobID==16932911 or mobID==16932919 or mobID==16932927 ) then correctelement=true; end end , }; if (correctelement==true and IselementalDayAreDead() == true) then GetNPCByID(16932864+313):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+313):setStatus(dsp.status.NORMAL); end end;
gpl-3.0
moteus/lua-spylog
src/config/filters/rdp-nxlog.lua
1
1364
-- When use NTLM auth event 4625 has no IP address -- so we should use different event but this event can not -- be forwarded by SNMP so we have to use some external tool. -- -- Forward eventlogs using nxlog (http://nxlog.co) -- -- <Input eventlog> -- Module im_msvistalog -- SavePos TRUE -- ReadFromLast TRUE -- Channel "Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational" -- <QueryXML> -- <QueryList> -- <Query Id="0" Path="Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational"> -- <Select Path="Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational">*[System[(EventID=140)]]</Select> -- </Query> -- </QueryList> -- </QueryXML> -- </Input> -- -- <Output spylog> -- Module om_udp -- Host 127.0.0.1 -- Port 614 -- Exec $raw_event = "EventID: " + $EventID + "; " + $Message; -- </Output> -- -- <Route 1> -- Path eventlog => spylog -- </Route> -- FILTER{ "rdp-fail-access-140-nxlog"; enabled = false; source = "nxlog"; exclude = WHITE_IP; hint = "EventID: 140;"; failregex = { "^EventID: 140; A connection from the client computer with an IP address of ([%d%.:]+)"; -- UTF8 "^EventID: 140; Не удалось подключить клиентский компьютер с IP%-адресом ([%d%.:]+)"; }; };
mit
greasydeal/darkstar
scripts/globals/items/dish_of_spaghetti_nero_di_seppia_+1.lua
36
1731
----------------------------------------- -- ID: 5202 -- Item: Dish of Spaghetti Nero Di Seppia +1 -- Food Effect: 60 Mins, All Races ----------------------------------------- -- HP % 17 (cap 140) -- Dexterity 3 -- Vitality 2 -- Agility -1 -- Mind -2 -- Charisma -1 -- Double Attack 1 -- Store TP 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) 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,3600,5202); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 17); target:addMod(MOD_FOOD_HP_CAP, 140); target:addMod(MOD_DEX, 3); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, -1); target:addMod(MOD_MND, -2); target:addMod(MOD_CHR, -1); target:addMod(MOD_DOUBLE_ATTACK, 1); target:addMod(MOD_STORETP, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 17); target:delMod(MOD_FOOD_HP_CAP, 140); target:delMod(MOD_DEX, 3); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, -1); target:delMod(MOD_MND, -2); target:delMod(MOD_CHR, -1); target:delMod(MOD_DOUBLE_ATTACK, 1); target:delMod(MOD_STORETP, 6); end;
gpl-3.0
Igalia/snabbswitch
lib/pflua/src/pf/selection.lua
11
18901
-- This module implements an "instruction selection" pass over the -- SSA IR and produces pseudo-instructions for register allocation -- and code generation. -- -- This uses a greed matching algorithm over the tree. -- -- This generates an array of pseudo-instructions like this: -- -- { { "load", "r1", 12, 2 } } -- { "add", "r1", "r3" } } -- -- The instructions available are: -- * cmp -- * mov -- * mov64 -- * load -- * add -- * add-i -- * sub -- * sub-i -- * mul -- * mul-i -- * div -- * and -- * and-i -- * or -- * or-i -- * xor -- * xor-i -- * shl -- * shl-i -- * shr -- * shr-i -- * ntohs -- * ntohl -- * uint32 -- * cjmp -- * jmp -- * ret-true, ret-false -- * nop (inserted by register allocation) module(...,package.seeall) local utils = require("pf.utils") local verbose = os.getenv("PF_VERBOSE"); local negate_op = { ["="] = "!=", ["!="] = "=", [">"] = "<=", ["<"] = ">=", [">="] = "<", ["<="] = ">" } -- this maps numeric operations that we handle in a generic way -- because the instruction selection is very similar local numop_map = { ["+"] = "add", ["-"] = "sub", ["*"] = "mul", ["*64"] = "mul", ["&"] = "and", ["|"] = "or", ["^"] = "xor" } -- extract a number from an SSA IR label function label_num(label) return tonumber(string.match(label, "L(%d+)")) end -- Convert a block to a sequence of pseudo-instructions -- -- Virtual registers are given names prefixed with "r" as in "r1". -- SSA variables remain prefixed with "v" local function select_block(block, new_register, instructions, next_label, jmp_map) local this_label = block.label local control = block.control local bindings = block.bindings local function emit(instr) table.insert(instructions, instr) end -- emit a jmp, looking up the next block and replace the jump target if -- the next block would immediately jmp anyway (via a return statement) local function emit_jmp(target_label, condition) -- if the target label is one that was deleted by the return processing -- pass, then patch the jump up as appropriate local jmp_entry = jmp_map[target_label] if jmp_entry then if condition then emit({ "cjmp", condition, jmp_entry }) else emit({ "jmp", jmp_entry }) end return end if condition then emit({ "cjmp", condition, label_num(target_label) }) else emit({ "jmp", label_num(target_label) }) end end local function emit_cjmp(condition, target_label) emit_jmp(target_label, condition) end local function emit_label() local max = instructions.max_label local num = label_num(this_label) if num > max then instructions.max_label = num end emit({ "label", num }) end -- do instruction selection on an arithmetic expression -- returns the destination register or immediate local function select_arith(expr) if type(expr) == "number" then if expr > (2 ^ 31) - 1 then tmp = new_register() emit({ "mov64", tmp, expr}) return tmp else return expr end elseif type(expr) == "string" then return expr elseif expr[1] == "[]" then local reg = new_register() local reg2 = select_arith(expr[2]) emit({ "load", reg, reg2, expr[3] }) return reg elseif numop_map[expr[1]] then local reg2 = select_arith(expr[2]) local reg3 = select_arith(expr[3]) local op = numop_map[expr[1]] local op_i = string.format("%s-i", op) -- both arguments in registers if type(reg2) ~= "number" and type(reg3) ~= "number" then local tmp = new_register() emit({ "mov", tmp, reg2 }) emit({ op, tmp, reg3 }) return tmp -- cases with one or more immediate arguments elseif type(reg2) == "number" then local tmp3 = new_register() -- if op is commutative, we can re-arrange to save registers if op ~= "sub" then emit({ "mov", tmp3, reg3 }) emit({ op_i, tmp3, reg2 }) return tmp3 else local tmp2 = new_register() emit({ "mov", tmp2, reg2 }) emit({ "mov", tmp3, reg3 }) emit({ op, tmp2, tmp3 }) return tmp2 end elseif type(reg3) == "number" then local tmp = new_register() emit({ "mov", tmp, reg2 }) emit({ op_i, tmp, reg3 }) return tmp end elseif expr[1] == "/" then local reg2 = select_arith(expr[2]) local rhs = expr[3] local tmp = new_register() if type(rhs) == "number" then -- if dividing by a power of 2, do a shift if rhs ~= 0 and bit.band(rhs, rhs-1) == 0 then local imm = 0 rhs = bit.rshift(rhs, 1) while rhs ~= 0 do rhs = bit.rshift(rhs, 1) imm = imm + 1 end emit({ "mov", tmp, reg2 }) emit({ "shr-i", tmp, imm }) else local tmp3 = new_register() local reg3 = select_arith(expr[3]) emit({ "mov", tmp, reg2 }) emit({ "mov", tmp3, reg3 }) emit({ "div", tmp, tmp3 }) end else local reg3 = select_arith(expr[3]) emit({ "mov", tmp, reg2 }) emit({ "div", tmp, reg3 }) end return tmp elseif expr[1] == "<<" then -- with immediate if type(expr[2]) == "number" then local reg3 = select_arith(expr[3]) local tmp = new_register() local tmp2 = new_register() emit({ "mov", tmp, reg3 }) emit({ "mov", tmp2, expr[2] }) emit({ "shl", tmp, tmp2 }) return tmp elseif type(expr[3]) == "number" then local reg2 = select_arith(expr[2]) local imm = expr[3] local tmp = new_register() emit({ "mov", tmp, reg2 }) emit({ "shl-i", tmp, imm }) return tmp else local reg2 = select_arith(expr[2]) local reg3 = select_arith(expr[3]) local tmp1 = new_register() local tmp2 = new_register() emit({ "mov", tmp1, reg2 }) emit({ "mov", tmp2, reg3 }) emit({ "shl", tmp1, tmp2 }) return tmp1 end elseif expr[1] == ">>" then -- with immediate if type(expr[2]) == "number" then local reg3 = select_arith(expr[3]) local tmp = new_register() local tmp2 = new_register() emit({ "mov", tmp, reg3 }) emit({ "mov", tmp2, expr[2] }) emit({ "shr", tmp, tmp2 }) return tmp elseif type(expr[3]) == "number" then local reg2 = select_arith(expr[2]) local imm = expr[3] local tmp = new_register() emit({ "mov", tmp, reg2 }) emit({ "shr-i", tmp, imm }) return tmp else local reg2 = select_arith(expr[2]) local reg3 = select_arith(expr[3]) local tmp1 = new_register() local tmp2 = new_register() emit({ "mov", tmp1, reg2 }) emit({ "mov", tmp2, reg3 }) emit({ "shr", tmp1, tmp2 }) return tmp1 end elseif expr[1] == "ntohs" then local reg = select_arith(expr[2]) local tmp = new_register() emit({ "mov", tmp, reg }) emit({ "ntohs", tmp }) return tmp elseif expr[1] == "ntohl" then local reg = select_arith(expr[2]) local tmp = new_register() emit({ "mov", tmp, reg }) emit({ "ntohl", tmp }) return tmp elseif expr[1] == "uint32" then local reg = select_arith(expr[2]) local tmp = new_register() emit({ "mov", tmp, reg }) emit({ "uint32", tmp }) return tmp else error(string.format("NYI op %s", expr[1])) end end local function select_bool(expr) local reg1 = select_arith(expr[2]) local reg2 = select_arith(expr[3]) -- cmp can't have an immediate on the lhs, but sometimes unoptimized -- pf expressions will have such a comparison which requires an extra -- mov instruction if type(reg1) == "number" then local tmp = new_register() emit({ "mov", tmp, reg1 }) reg1 = tmp end emit({ "cmp", reg1, reg2 }) end local function select_bindings() for _, binding in ipairs(bindings) do local rhs = binding.value local reg = select_arith(rhs) emit({ "mov", binding.name, reg }) end end if control[1] == "return" then local result = control[2] -- For the first two branches, only record necessity of constructing the -- label. The blocks are dropped since these returns can just be replaced -- by directly jumping to the true or false return labels at the end if result[1] == "false" then emit_false = true elseif result[1] == "true" then emit_true = true else emit_label() select_bindings() select_bool(result) emit({ "cjmp", result[1], "true-label" }) emit({ "jmp", "false-label" }) emit_true = true emit_false = true end elseif control[1] == "if" then local cond = control[2] local then_label = control[3] local else_label = control[4] emit_label() select_bindings() select_bool(cond) if next_label == then_label then emit_cjmp(negate_op[cond[1]], else_label) emit_jmp(then_label) else emit_cjmp(cond[1], then_label) emit_jmp(else_label) end else error(string.format("NYI op %s", control[1])) end end local function make_new_register(reg_num) return function() local new_var = string.format("r%d", reg_num) reg_num = reg_num + 1 return new_var end end -- printing instruction IR for debugging function print_selection(ir) utils.pp({ "instructions", ir }) end -- removes blocks that just return constant true/false and return a new -- SSA order (with returns removed), a map for redirecting jmps, and two -- booleans indicating whether to produce true/false return code local function process_returns(ssa) -- these control whether to emit pseudo-instructions for doing -- 'return true' or 'return false' at the very end. -- (since they may not be needed if the result is always true or false) local emit_true, emit_false = false, false local return_map = {} -- clone to ease testing without side effects local order = utils.dup(ssa.order) local blocks = ssa.blocks local len = #order -- proceed in reverse order to allow easy deletion for i=1, len do local idx = len - i + 1 local label = order[idx] local block = blocks[label] local control = block.control if control[1] == "return" then if control[2][1] == "true" then emit_true = true return_map[label] = "true-label" table.remove(order, idx) elseif control[2][1] == "false" then emit_false = true return_map[label] = "false-label" table.remove(order, idx) else -- a return block with a non-trivial expression requires both -- true and false return labels emit_true = true emit_false = true end end end return order, return_map, emit_true, emit_false end function select(ssa) local blocks = ssa.blocks local instructions = { max_label = 0 } local reg_num = 1 local new_register = make_new_register(reg_num) local order, jmp_map, emit_true, emit_false = process_returns(ssa) for idx, label in pairs(order) do local next_label = order[idx+1] select_block(blocks[label], new_register, instructions, next_label, jmp_map) end if emit_false then table.insert(instructions, { "ret-false" }) end if emit_true then table.insert(instructions, { "ret-true" }) end if verbose then print_selection(instructions) end return instructions end function selftest() local utils = require("pf.utils") -- test on a whole set of blocks local function test(block, expected) local instructions = select(block) utils.assert_equals(instructions, expected) end test(-- `arp` { start = "L1", order = { "L1", "L4", "L5" }, blocks = { L1 = { label = "L1", bindings = {}, control = { "if", { ">=", "len", 14}, "L4", "L5" } }, L4 = { label = "L4", bindings = {}, control = { "return", { "=", { "[]", 12, 2}, 1544 } } }, L5 = { label = "L5", bindings = {}, control = { "return", { "false" } } } } }, { { "label", 1 }, { "cmp", "len", 14 }, { "cjmp", "<", "false-label"}, { "jmp", 4 }, { "label", 4 }, { "load", "r1", 12, 2 }, { "cmp", "r1", 1544 }, { "cjmp", "=", "true-label" }, { "jmp", "false-label" }, { "ret-false" }, { "ret-true" }, max_label = 4 }) test(-- `tcp` { start = "L1", order = { "L1", "L4", "L6", "L7", "L8", "L10", "L12", "L13", "L14", "L16", "L17", "L15", "L11", "L9", "L5" }, blocks = { L1 = { label = "L1", bindings = {}, control = { "if", { ">=", "len", 34 }, "L4", "L5" } }, L4 = { label = "L4", bindings = { { name = "v1", value = { "[]", 12, 2 } } }, control = { "if", { "=", "v1", 8 }, "L6", "L7" }, idom = "L1" }, L6 = { label = "L6", bindings = {}, control = { "return", { "=", { "[]", 23, 1 }, 6 } }, idom = "L4" }, L7 = { label = "L7", bindings = {}, control = { "if", { ">=", "len", 54 }, "L8", "L9" }, idom = "L7" }, L8 = { label = "L8", bindings = {}, control = { "if", { "=", "v1", 56710 }, "L10", "L11" }, idom = "L7" }, L10 = { label = "L10", bindings = { { name = "v2", value = { "[]", 20, 1 } } }, control = { "if", { "=", "v2", 6 }, "L12", "L13" }, idom = "L9" }, L12 = { label = "L12", bindings = {}, control = { "return", { "true" } }, idom = "L10" }, L13 = { label = "L13", bindings = {}, control = { "if", { ">=", "len", 55 }, "L14", "L15" } }, L14 = { label = "L14", bindings = {}, control = { "if", { "=", "v2", 44 }, "L16", "L17" } }, L16 = { label = "L16", bindings = {}, control = { "return", { "=", { "[]", 54, 1 }, 6 } } }, L17 = { label = "L17", bindings = {}, control = { "return", { "false" } } }, L15 = { label = "L15", bindings = {}, control = { "return", { "false" } } }, L11 = { label = "L11", bindings = {}, control = { "return", { "false" } } }, L9 = { label = "L9", bindings = {}, control = { "return", { "false" } } }, L5 = { label = "L5", bindings = {}, control = { "return", { "false" } } } } }, { { "label", 1 }, { "cmp", "len", 34 }, { "cjmp", "<", "false-label" }, { "jmp", 4 }, { "label", 4 }, { "load", "r1", 12, 2 }, { "mov", "v1", "r1" }, { "cmp", "v1", 8 }, { "cjmp", "!=", 7 }, { "jmp", 6 }, { "label", 6 }, { "load", "r2", 23, 1 }, { "cmp", "r2", 6 }, { "cjmp", "=", "true-label" }, { "jmp", "false-label" }, { "label", 7 }, { "cmp", "len", 54 }, { "cjmp", "<", "false-label" }, { "jmp", 8 }, { "label", 8 }, { "cmp", "v1", 56710 }, { "cjmp", "!=", "false-label" }, { "jmp", 10 }, { "label", 10 }, { "load", "r3", 20, 1 }, { "mov", "v2", "r3" }, { "cmp", "v2", 6 }, { "cjmp", "=", "true-label" }, { "jmp", 13 }, { "label", 13 }, { "cmp", "len", 55 }, { "cjmp", "<", "false-label" }, { "jmp", 14 }, { "label", 14 }, { "cmp", "v2", 44 }, { "cjmp", "!=", "false-label" }, { "jmp", 16 }, { "label", 16 }, { "load", "r4", 54, 1 }, { "cmp", "r4", 6 }, { "cjmp", "=", "true-label" }, { "jmp", "false-label" }, { "ret-false" }, { "ret-true" }, max_label = 16 }) test(-- randomly generated by tests { start = "L1", order = { "L1", "L4", "L5" }, blocks = { L1 = { control = { "if", { ">=", "len", 4 }, "L4", "L5" }, bindings = {}, label = "L1", }, L4 = { control = { "return", { ">", { "ntohs", { "[]", 0, 4 } }, 0 } }, bindings = {}, label = "L4", }, L5 = { control = { "return", { "false" } }, bindings = {}, label = "L5", } } }, { { "label", 1 }, { "cmp", "len", 4 }, { "cjmp", "<", "false-label" }, { "jmp", 4 }, { "label", 4 }, { "load", "r1", 0, 4 }, { "mov", "r2", "r1" }, { "ntohs", "r2" }, { "cmp", "r2", 0 }, { "cjmp", ">", "true-label" }, { "jmp", "false-label" }, { "ret-false" }, { "ret-true" }, max_label = 4 }) end
apache-2.0
pokemoncentral/wiki-lua-modules
EffTipi-6.lua
1
8351
-- Calcolo efficacia tipi, ad uso esclusivamente interno local et = {} local tab = require('Wikilib-tables') --[[ Tabella contenente i valori di efficacia. Il livello esterno è il tipo attaccante, il livello interno il difensore. Ad esempio, normale.fuoco è l'efficacia di un attacco di tipo normale che colpisce un tipo fuoco puro --]] local eff = {} eff.normale = {normale = 1, fuoco = 1, acqua = 1, elettro = 1, erba = 1, ghiaccio = 1, lotta = 1, veleno = 1, terra = 1, volante = 1, psico = 1, coleottero = 1, roccia = 0.5, spettro = 0, drago = 1, buio = 1, acciaio = 0.5, folletto = 1} eff.fuoco = {normale = 1, fuoco = 0.5, acqua = 0.5, elettro = 1, erba = 2, ghiaccio = 2, lotta = 1, veleno = 1, terra = 1, volante = 1, psico = 1, coleottero = 2, roccia = 0.5, spettro = 1, drago = 0.5, buio = 1, acciaio = 2, folletto = 1} eff.acqua = {normale = 1, fuoco = 2, acqua = 0.5, elettro = 1, erba = 0.5, ghiaccio = 1, lotta = 1, veleno = 1, terra = 2, volante = 1, psico = 1, coleottero = 1, roccia = 2, spettro = 1, drago = 0.5, buio = 1, acciaio = 1, folletto = 1} eff.elettro = {normale = 1, fuoco = 1, acqua = 2, elettro = 0.5, erba = 0.5, ghiaccio = 1, lotta = 1, veleno = 1, terra = 0, volante = 2, psico = 1, coleottero = 1, roccia = 1, spettro = 1, drago = 0.5, buio = 1, acciaio = 1, folletto = 1} eff.erba = {normale = 1, fuoco = 0.5, acqua = 2, elettro = 1, erba = 0.5, ghiaccio = 1, lotta = 1, veleno = 0.5, terra = 2, volante = 0.5, psico = 1, coleottero = 0.5, roccia = 2, spettro = 1, drago = 0.5, buio = 1, acciaio = 0.5, folletto = 1} eff.ghiaccio = {normale = 1, fuoco = 0.5, acqua = 0.5, elettro = 1, erba = 2, ghiaccio = 0.5, lotta = 1, veleno = 1, terra = 2, volante = 2, psico = 1, coleottero = 1, roccia = 1, spettro = 1, drago = 2, buio = 1, acciaio = 0.5, folletto = 1} eff.lotta = {normale = 2, fuoco = 1, acqua = 1, elettro = 1, erba = 1, ghiaccio = 2, lotta = 1, veleno = 0.5, terra = 1, volante = 0.5, psico = 0.5, coleottero = 0.5, roccia = 2, spettro = 0, drago = 1, buio = 2, acciaio = 2, folletto = 0.5} eff.veleno = {normale = 1, fuoco = 1, acqua = 1, elettro = 1, erba = 2, ghiaccio = 1, lotta = 1, veleno = 0.5, terra = 0.5, volante = 1, psico = 1, coleottero = 1, roccia = 0.5, spettro = 0.5, drago = 1, buio = 1, acciaio = 0, folletto = 2} eff.terra = {normale = 1, fuoco = 2, acqua = 1, elettro = 2, erba = 0.5, ghiaccio = 1, lotta = 1, veleno = 2, terra = 1, volante = 0, psico = 1, coleottero = 0.5, roccia = 2, spettro = 1, drago = 1, buio = 1, acciaio = 2, folletto = 1} eff.volante = {normale = 1, fuoco = 1, acqua = 1, elettro = 0.5, erba = 2, ghiaccio = 1, lotta = 2, veleno = 1, terra = 1, volante = 1, psico = 1, coleottero = 2, roccia = 0.5, spettro = 1, drago = 1, buio = 1, acciaio = 0.5, folletto = 1} eff.psico = {normale = 1, fuoco = 1, acqua = 1, elettro = 1, erba = 1, ghiaccio = 1, lotta = 2, veleno = 2, terra = 1, volante = 1, psico = 0.5, coleottero = 1, roccia = 1, spettro = 1, drago = 1, buio = 0, acciaio = 0.5, folletto = 1} eff.coleottero = {normale = 1, fuoco = 0.5, acqua = 1, elettro = 1, erba = 2, ghiaccio = 1, lotta = 0.5, veleno = 0.5, terra = 1, volante = 0.5, psico = 2, coleottero = 1, roccia = 1, spettro = 0.5, drago = 1, buio = 2, acciaio = 0.5, folletto = 0.5} eff.roccia = {normale = 1, fuoco = 2, acqua = 1, elettro = 1, erba = 1, ghiaccio = 2, lotta = 0.5, veleno = 1, terra = 0.5, volante = 2, psico = 1, coleottero = 2, roccia = 1, spettro = 1, drago = 1, buio = 1, acciaio = 0.5, folletto = 1} eff.spettro = {normale = 0, fuoco = 1, acqua = 1, elettro = 1, erba = 1, ghiaccio = 1, lotta = 1, veleno = 1, terra = 1, volante = 1, psico = 2, coleottero = 1, roccia = 1, spettro = 2, drago = 1, buio = 0.5, acciaio = 1, folletto = 1} eff.drago = {normale = 1, fuoco = 1, acqua = 1, elettro = 1, erba = 1, ghiaccio = 1, lotta = 1, veleno = 1, terra = 1, volante = 1, psico = 1, coleottero = 1, roccia = 1, spettro = 1, drago = 2, buio = 1, acciaio = 0.5, folletto = 0} eff.buio = {normale = 1, fuoco = 1, acqua = 1, elettro = 1, erba = 1, ghiaccio = 1, lotta = 0.5, veleno = 1, terra = 1, volante = 1, psico = 2, coleottero = 1, roccia = 1, spettro = 2, drago = 1, buio = 0.5, acciaio = 1, folletto = 0.5} eff.acciaio = {normale = 1, fuoco = 0.5, acqua = 0.5, elettro = 0.5, erba = 1, ghiaccio = 2, lotta = 1, veleno = 1, terra = 1, volante = 1, psico = 1, coleottero = 1, roccia = 2, spettro = 1, drago = 1, buio = 1, acciaio = 0.5, folletto = 2} eff.folletto = {normale = 1, fuoco = 0.5, acqua = 1, elettro = 1, erba = 1, ghiaccio = 1, lotta = 2, veleno = 0.5, terra = 1, volante = 1, psico = 1, coleottero = 1, roccia = 1, spettro = 1, drago = 2, buio = 2, acciaio = 0.5, folletto = 1} eff.coleot = eff.coleottero for a in pairs(eff) do eff[a].coleot = eff[a].coleottero end --[[ Le abilità che alterano l'efficacia dei tipi: il primo indice è il nome dell'abilità, il secondo il tipo alterato e il valore associato sarà moltiplicato all'efficacia calcolata solo con i tipi. Per esempio, all'indice grassospess corrispondono i due tipi fuoco e ghiaccio, entrambi con valore 0.5, perché l'abilità dimezza l'efficacia di questi due tipi. Filtro, Solidroccia e Magidifesa sono trattate a parte. --]] local ability = {} ability.levitazione = {terra = 0} ability.grassospesso = {fuoco = 0.5, ghiaccio = 0.5} ability.antifuoco = {fuoco = 0.5} ability.fuocardore = {fuoco = 0} ability.pellearsa = {fuoco = 1.25, acqua = 0} ability.acquascolo = {acqua = 0} ability.assorbacqua = ability.acquascolo ability.parafulmine = {elettro = 0} ability.elettrorapid = ability.parafulmine ability.assorbivolt = ability.parafulmine ability.mangiaerba = {erba = 0} ability['mare primordiale'] = ability.fuocardore ability['terra estrema'] = ability.acquascolo ability['flusso delta'] = {elettro = 0.5, ghiaccio = 0.5, roccia = 0.5} --[[ Creazione dinamica di una table contenente tutte le abilità che influenzano l'efficacia tipi, ad oguna delle quali è associata una table con i tipi da essa influenzati. Le abilità sono gli indici e i tipi influenzati gli elementi associati, es: all'indice pellearsa corrisponde una table contenente i tipi fuoco e acqua. Fanno eccezione Magidifesa, Filtro e Solidroccia, che non hanno tipi associati fissi --]] et.modTypesAbil = {magidifesa = {}, filtro = {}, solidroccia = {}} for abil, types in pairs(ability) do et.modTypesAbil[abil] = {} for Type, eff in pairs(types) do table.insert(et.modTypesAbil[abil], Type) end end --[[ Creazione dinamica di una table con i tipi che hanno immunità, con associati i tipi a cui sono immuni. I primi sono gli indici, i secondi gli elementi di una table ad essi associata, es: all'indice spettro è associata una table contenente i tipi lotta e normale --]] et.typesHaveImm = {} for atk, defs in pairs(eff) do for def, eff in pairs(defs) do if eff == 0 then if type(et.typesHaveImm[def]) ~= 'table' then et.typesHaveImm[def] = {} end table.insert(et.typesHaveImm[def], atk) end end end --[[ Calcola l'efficacia di un attacco; si aspetta i nomi dei tipi e dell'abilità, tutti in minuscolo --]] et.efficacia = function(atk, def1, def2, abil) -- Efficacia base con due tipi local e = eff[atk][def1] if def2 ~= def1 then e = e * eff[atk][def2] end -- Abilità standard if ability[abil] and ability[abil][atk] then return e * ability[abil][atk] -- Filtro e solidroccia elseif e >= 2 and (abil == 'filtro' or abil == 'solidroccia') then return e * 0.75 -- Magidifesa elseif e < 2 and abil == 'magidifesa' then return 0 end return e end --[[ Cerca tutti i tipi che soddisfano una condizione data. Il parametro test è una funzione che si aspetta un solo argomento (vedere gli esempi dopo per chiarimenti). --]] local cerca_tipi = function(test) local t = {} for k in pairs(eff) do if k ~= 'coleottero' and test(k) then table.insert(t, k) end end return t end --[[ Trova tutti i tipi che attaccando tipo1 e tipo2, con abilità abil, hanno efficacia eff --]] et.difesa = function(eff, tipo1, tipo2, abil) return cerca_tipi(function (x) return et.efficacia(x, tipo1, tipo2, abil) == eff end) end -- Trova tutti i tipi su cui tipo ha efficacia eff et.attacco = function(eff, tipo) return cerca_tipi(function (x) return et.efficacia(tipo, x, x, 'Tanfo') == eff end) end return et
cc0-1.0
atheurer/MoonGen
examples/pcap/pcap-test.lua
2
2375
--! @file pcap-test.lua --! @brief This is a simple test for MoonGen's pcap import and export functionality local mg = require "dpdk" local memory = require "memory" local device = require "device" local log = require "log" local ts = require "timestamping" local pcap = require "pcap" function master(source, sink) source = source or "-" sink = sink or "test-sink.pcap" if source == '--help' then return log:info([[ Usage: [source pcap] [sink pcap] Reads UDP packets from the source pcap to the sink pcap. if source is set to '-', some random UDP packets are generated and written to sink. The default value for source is '-'. The default value for sink is test-sink.pcap. ]]) end source = source or "-" sink = sink or "test-sink.pcap" -- test demonstration without usage of network interfaces simplePcapStoreAndLoadTestSlave(source, sink) mg.waitForSlaves() end --! @brief most simpliest test; just store a packet from buffer to pcap file, and read it again function simplePcapStoreAndLoadTestSlave(source, sink) -- allocate mempool with generator for udp packets with random src port local mem = memory.createMemPool(function(buf) buf:getUdpPacket():fill({udpSrc=math.floor(math.random()*65535)}) end) local bufs = mem:bufArray(12) bufs:alloc(124) local rx = 0 -- read packets from a pcap if the user provided one if source ~= '-' then local pcapReader = pcapReader:newPcapReader(source) rx = pcapReader:readPkt(bufs) for i = 1,rx do print(i..' Read UDP packet with src port '..bufs[i]:getUdpPacket().udp:getSrcPortString()) end pcapReader:close() -- log randomly generated packets instead else print("Simple test: Generating random packets, writing to "..sink.." and reading back from "..sink) for i = 1,#bufs do print(i..' Generated UDP packet with src port '..bufs[i]:getUdpPacket().udp:getSrcPortString()) end end -- write the packets print("Writing packets to "..sink) local pcapWriter = pcapWriter:newPcapWriter(sink) pcapWriter:write(bufs) pcapWriter:close() -- read back local pcapReader = pcapReader:newPcapReader(sink) -- yes, open sink, not source local pktidx = 1 while not pcapReader.done do rx = pcapReader:readPkt(bufs) for i = 1,rx do print(pktidx..' Read back UDP packet with src port '..bufs[i]:getUdpPacket().udp:getSrcPortString()) pktidx = pktidx +1 end end end
mit
chanko08/KillerLibrarian2
lib/tiny.lua
3
23223
--[[ Copyright (c) 2015 Calvin Rose 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. ]] --- @module tiny-ecs -- @author Calvin Rose -- @license MIT -- @copyright 2015 local tiny = { _VERSION = "1.1-7" } -- Local versions of standard lua functions local tinsert = table.insert local tremove = table.remove local tsort = table.sort local pairs = pairs local setmetatable = setmetatable local type = type local select = select -- Local versions of the library functions local tiny_manageEntities local tiny_manageSystems local tiny_addEntity local tiny_addSystem local tiny_add local tiny_removeEntity local tiny_removeSystem local tiny_remove --- Filter functions. -- A Filter is a function that selects which Entities apply to a System. -- Filters take two parameters, the System and the Entity, and return a boolean -- value indicating if the Entity should be processed by the System. -- -- Filters must be added to Systems by setting the `filter` field of the System. -- Filter's returned by tiny-ecs's Filter functions are immutable and can be -- used by multiple Systems. -- -- local f1 = tiny.requireAll("position", "velocity", "size") -- local f2 = tiny.requireAny("position", "velocity", "size") -- -- local e1 = { -- position = {2, 3}, -- velocity = {3, 3}, -- size = {4, 4} -- } -- -- local entity2 = { -- position = {4, 5}, -- size = {4, 4} -- } -- -- local e3 = { -- position = {2, 3}, -- velocity = {3, 3} -- } -- -- print(f1(nil, e1), f1(nil, e2), f1(nil, e3)) -- prints true, false, false -- print(f2(nil, e1), f2(nil, e2), f2(nil, e3)) -- prints true, true, true -- -- Filters can also be passed as arguments to other Filter constructors. This is -- a powerful way to create complex, custom Filters that select a very specific -- set of Entities. -- -- -- Selects Entities with an "image" Component, but not Entities with a -- -- "Player" or "Enemy" Component. -- filter = tiny.requireAll("image", tiny.rejectAny("Player", "Enemy")) -- -- @section Filter --- Makes a Filter that selects Entities with all specified Components and -- Filters. function tiny.requireAll(...) local components = {...} local len = #components return function(system, e) local c for i = 1, len do c = components[i] if type(c) == 'function' then if not c(system, e) then return false end elseif e[c] == nil then return false end end return true end end --- Makes a Filter that selects Entities with at least one of the specified -- Components and Filters. function tiny.requireAny(...) local components = {...} local len = #components return function(system, e) local c for i = 1, len do c = components[i] if type(c) == 'function' then if c(system, e) then return true end elseif e[c] ~= nil then return true end end return false end end --- Makes a Filter that rejects Entities with all specified Components and -- Filters, and selects all other Entities. function tiny.rejectAll(...) local components = {...} local len = #components return function(system, e) local c for i = 1, len do c = components[i] if type(c) == 'function' then if not c(system, e) then return true end elseif e[c] == nil then return true end end return false end end --- Makes a Filter that rejects Entities with at least one of the specified -- Components and Filters, and selects all other Entities. function tiny.rejectAny(...) local components = {...} local len = #components return function(system, e) local c for i = 1, len do c = components[i] if type(c) == 'function' then if c(system, e) then return false end elseif e[c] ~= nil then return false end end return true end end --- System functions. -- A System is a wrapper around function callbacks for manipulating Entities. -- Systems are implemented as tables that contain at least one method; -- an update function that takes parameters like so: -- -- * `function system:update(dt)`. -- -- There are also a few other optional callbacks: -- -- * `function system:filter(entity)` - Returns true if this System should -- include this Entity, otherwise should return false. If this isn't specified, -- no Entities are included in the System. -- * `function system:onAdd(entity)` - Called when an Entity is added to the -- System. -- * `function system:onRemove(entity)` - Called when an Entity is removed -- from the System. -- * `function system:onModify(dt)` - Called when the System is modified by -- adding or removing Entities from the System. -- -- For Filters, it is convenient to use `tiny.requireAll` or `tiny.requireAny`, -- but one can write their own filters as well. Set the Filter of a System like -- so: -- system.filter = tiny.requireAll("a", "b", "c") -- or -- function system:filter(entity) -- return entity.myRequiredComponentName ~= nil -- end -- -- All Systems also have a few important fields that are initialized when the -- system is added to the World. A few are important, and few should be less -- commonly used. -- -- * The `world` field points to the World that the System belongs to. Useful -- for adding and removing Entities from the world dynamically via the System. -- * The `active` flag is whether or not the System is updated automatically. -- Inactive Systems should be updated manually or not at all via -- `system:update(dt)`. Defaults to true. -- * The `entities` field is an ordered list of Entities in the System. This -- list can be used to quickly iterate through all Entities in a System. -- * The `interval` field is an optional field that makes Systems update at -- certain intervals using buffered time, regardless of World update frequency. -- For example, to make a System update once a second, set the System's interval -- to 1. -- * The `index` field is the System's index in the World. Lower indexed -- Systems are processed before higher indices. The `index` is a read only -- field; to set the `index`, use `tiny.setSystemIndex(world, system)`. -- * The `indices` field is a table of Entity keys to their indices in the -- `entities` list. Most Systems can ignore this. -- * The `modified` flag is an indicator if the System has been modified in -- the last update. If so, the `onModify` callback will be called on the System -- in the next update, if it has one. This is usually managed by tiny-ecs, so -- users should mostly ignore this, too. -- -- @section System -- Use an empty table as a key for identifying Systems. Any table that contains -- this key is considered a System rather than an Entity. local systemTableKey = { "SYSTEM_TABLE_KEY" } -- Checks if a table is a System. local function isSystem(table) return table[systemTableKey] end -- Update function for all Processing Systems. local function processingSystemUpdate(system, dt) local entities = system.entities local preProcess = system.preProcess local process = system.process local postProcess = system.postProcess local entity if preProcess then preProcess(system, dt) end if process then local len = #entities for i = 1, len do entity = entities[i] process(system, entity, dt) end end if postProcess then postProcess(system, dt) end end -- Sorts Systems by a function system.sort(entity1, entity2) on modify. local function sortedSystemOnModify(system, dt) local entities = system.entities local indices = system.indices local sortDelegate = system.sortDelegate if not sortDelegate then local compare = system.compare sortDelegate = function(e1, e2) return compare(system, e1, e2) end system.sortDelegate = sortDelegate end tsort(entities, sortDelegate) for i = 1, #entities do local entity = entities[i] indices[entity] = i end end --- Creates a new System or System class from the supplied table. If `table` is -- nil, creates a new table. function tiny.system(table) table = table or {} table[systemTableKey] = true return table end --- Creates a new Processing System or Processing System class. Processing -- Systems process each entity individual, and are usually what is needed. -- Processing Systems have three extra callbacks besides those inheritted from -- vanilla Systems. -- -- function system:preProcess(entities, dt) -- Called before iteration. -- function system:process(entities, dt) -- Process each entity. -- function system:postProcess(entity, dt) -- Called after iteration. -- -- Processing Systems have their own `update` method, so don't implement a -- a custom `update` callback for Processing Systems. -- @see system function tiny.processingSystem(table) table = table or {} table[systemTableKey] = true table.update = processingSystemUpdate return table end --- Creates a new Sorted System or Sorted System class. Sorted Systems sort -- their Entities according to a user-defined method, `system:compare(e1, e2)`, -- which should return true if `e1` should come before `e2` and false otherwise. -- Sorted Systems also override the default System's `onModify` callback, so be -- careful if defining a custom callback. However, for processing the sorted -- entities, consider `tiny.sortedProcessingSystem(table)`. -- @see system function tiny.sortedSystem(table) table = table or {} table[systemTableKey] = true table.onModify = sortedSystemOnModify return table end --- Creates a new Sorted Processing System or Sorted Processing System class. -- Sorted Processing Systems have both the aspects of Processing Systems and -- Sorted Systems. -- @see system -- @see processingSystem -- @see sortedSystem function tiny.sortedProcessingSystem(table) table = table or {} table[systemTableKey] = true table.update = processingSystemUpdate table.onModify = sortedSystemOnModify return table end --- World functions. -- A World is a container that manages Entities and Systems. Typically, a -- program uses one World at a time. -- -- For all World functions except `tiny.world(...)`, object-oriented syntax can -- be used instead of the documented syntax. For example, -- `tiny.add(world, e1, e2, e3)` is the same as `world:add(e1, e2, e3)`. -- @section World -- Forward declaration local worldMetaTable --- Creates a new World. -- Can optionally add default Systems and Entities. Returns the new World along -- with default Entities and Systems. function tiny.world(...) local ret = { -- List of Entities to add entitiesToAdd = {}, -- List of Entities to remove entitiesToRemove = {}, -- List of Entities to add systemsToAdd = {}, -- List of Entities to remove systemsToRemove = {}, -- Set of Entities entities = {}, -- Number of Entities in World entityCount = 0, -- List of Systems systems = {} } tiny_add(ret, ...) tiny_manageSystems(ret) tiny_manageEntities(ret) return setmetatable(ret, worldMetaTable), ... end --- Adds an Entity to the world. -- Also call this on Entities that have changed Components such that they -- match different Filters. Returns the Entity. function tiny.addEntity(world, entity) local e2a = world.entitiesToAdd e2a[#e2a + 1] = entity if world.entities[entity] then tiny_removeEntity(world, entity) end return entity end tiny_addEntity = tiny.addEntity --- Adds a System to the world. Returns the System. function tiny.addSystem(world, system) local s2a = world.systemsToAdd s2a[#s2a + 1] = system return system end tiny_addSystem = tiny.addSystem --- Shortcut for adding multiple Entities and Systems to the World. Returns all -- added Entities and Systems. function tiny.add(world, ...) local obj for i = 1, select("#", ...) do obj = select(i, ...) if obj then if isSystem(obj) then tiny_addSystem(world, obj) else -- Assume obj is an Entity tiny_addEntity(world, obj) end end end return ... end tiny_add = tiny.add --- Removes an Entity to the World. Returns the Entity. function tiny.removeEntity(world, entity) local e2r = world.entitiesToRemove e2r[#e2r + 1] = entity return entity end tiny_removeEntity = tiny.removeEntity --- Removes a System from the world. Returns the System. function tiny.removeSystem(world, system) local s2r = world.systemsToRemove s2r[#s2r + 1] = system return system end tiny_removeSystem = tiny.removeSystem --- Shortcut for removing multiple Entities and Systems from the World. Returns -- all removed Systems and Entities function tiny.remove(world, ...) local obj for i = 1, select("#", ...) do obj = select(i, ...) if obj then if isSystem(obj) then tiny_removeSystem(world, obj) else -- Assume obj is an Entity tiny_removeEntity(world, obj) end end end return ... end tiny_remove = tiny.remove -- Adds and removes Systems that have been marked from the World. function tiny_manageSystems(world) local s2a, s2r = world.systemsToAdd, world.systemsToRemove -- Early exit if #s2a == 0 and #s2r == 0 then return end local entities = world.entities local systems = world.systems local system, index, filter local entityList, entityIndices, entityIndex, onRemove, onAdd -- Remove Systems for i = 1, #s2r do system = s2r[i] index = system.index if system.world == world then onRemove = system.onRemove if onRemove then entityList = system.entities for j = 1, #entityList do onRemove(system, entityList[j]) end end tremove(systems, index) for j = index, #systems do systems[j].index = j end end s2r[i] = nil -- Clean up System system.world = nil system.entities = nil system.indices = nil system.index = nil end -- Add Systems for i = 1, #s2a do system = s2a[i] if systems[system.index] ~= system then entityList = {} entityIndices = {} system.entities = entityList system.indices = entityIndices if system.active == nil then system.active = true end system.modified = true system.world = world index = #systems + 1 system.index = index systems[index] = system -- Try to add Entities onAdd = system.onAdd filter = system.filter if filter then for entity in pairs(entities) do if filter(system, entity) then entityIndex = #entityList + 1 entityList[entityIndex] = entity entityIndices[entity] = entityIndex if onAdd then onAdd(system, entity) end end end end end s2a[i] = nil end end -- Adds and removes Entities that have been marked. function tiny_manageEntities(world) local e2a, e2r = world.entitiesToAdd, world.entitiesToRemove -- Early exit if #e2a == 0 and #e2r == 0 then return end local entities = world.entities local systems = world.systems local entityCount = world.entityCount local entity, system, index local onRemove, onAdd, ses, seis, filter, tmpEntity -- Remove Entities for i = 1, #e2r do entity = e2r[i] if entities[entity] then entities[entity] = nil entityCount = entityCount - 1 for j = 1, #systems do system = systems[j] ses = system.entities seis = system.indices index = seis[entity] if index then system.modified = true tmpEntity = ses[#ses] ses[index] = tmpEntity seis[tmpEntity] = index seis[entity] = nil ses[#ses] = nil onRemove = system.onRemove if onRemove then onRemove(system, entity) end end end end e2r[i] = nil end -- Add Entities for i = 1, #e2a do entity = e2a[i] if not entities[entity] then entities[entity] = true entityCount = entityCount + 1 for j = 1, #systems do system = systems[j] ses = system.entities seis = system.indices filter = system.filter if filter and filter(system, entity) then system.modified = true index = #ses + 1 ses[index] = entity seis[entity] = index onAdd = system.onAdd if onAdd then onAdd(system, entity) end end end end e2a[i] = nil end -- Update Entity count world.entityCount = entityCount end --- Manages Entities and Systems marked for deletion or addition. Call this -- before modifying Systems and Entities outside of a call to `tiny.update`. -- Do not call this within a call to `tiny.update`. function tiny.refresh(world) tiny_manageSystems(world) tiny_manageEntities(world) end --- Updates the World by dt (delta time). Takes an optional parameter, `filter`, -- which is a Filter that selects Systems from the World, and updates only those -- Systems. If `filter` is not supplied, all Systems are updated. Put this -- function in your main loop. function tiny.update(world, dt, filter) tiny_manageSystems(world) tiny_manageEntities(world) local systems = world.systems local system, update, interval, onModify -- Iterate through Systems IN ORDER for i = 1, #systems do system = systems[i] if system.active and ((not filter) or filter(world, system)) then -- Call the modify callback on Systems that have been modified. onModify = system.onModify if onModify and system.modified then onModify(system, dt) end -- Update Systems that have an update method (most Systems) update = system.update if update then interval = system.interval if interval then local bufferedTime = (system.bufferedTime or 0) + dt while bufferedTime >= interval do bufferedTime = bufferedTime - interval if update then update(system, interval) end end system.bufferedTime = bufferedTime else update(system, dt) end end system.modified = false end end end --- Removes all Entities from the World. function tiny.clearEntities(world) for e in pairs(world.entities) do tiny_removeEntity(world, e) end end --- Removes all Systems from the World. function tiny.clearSystems(world) local systems = world.systems for i = #systems, 1, -1 do tiny_removeSystem(world, systems[i]) end end --- Gets number of Entities in the World. function tiny.getEntityCount(world) return world.entityCount end --- Gets number of Systems in World. function tiny.getSystemCount(world) return #(world.systems) end --- Gets the index of the System in the World. -- A simpler alternative is `system.index`. function tiny.getSystemIndex(world, system) return system.index end --- Sets the index of a System in the World, and returns the old index. Changes -- the order in which they Systems processed, because lower indexed Systems are -- processed first. Returns the old system.index. function tiny.setSystemIndex(world, system, index) local oldIndex = system.index local systems = world.systems tremove(systems, oldIndex) tinsert(systems, index, system) for i = oldIndex, index, index >= oldIndex and 1 or -1 do systems[i].index = i end return oldIndex end -- Construct world metatable. worldMetaTable = { __index = { add = tiny.add, addEntity = tiny.addEntity, addSystem = tiny.addSystem, remove = tiny.remove, removeEntity = tiny.removeEntity, removeSystem = tiny.removeSystem, refresh = tiny.refresh, update = tiny.update, clearEntities = tiny.clearEntities, clearSystems = tiny.clearSystems, getEntityCount = tiny.getEntityCount, getSystemCount = tiny.getSystemCount, getSystemIndex = tiny.getSystemIndex, setSystemIndex = tiny.setSystemIndex } } return tiny
mit
LegionXI/darkstar
scripts/zones/Port_Windurst/npcs/Kumama.lua
17
1712
----------------------------------- -- Area: Port Windurst -- NPC: Kumama -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,KUMAMA_SHOP_DIALOG); stock = { 0x3239, 2268,1, --Linen Slops 0x32b9, 1462,1, --Holly Clogs 0x3004, 4482,1, --Mahogany Shield 0x3218, 482,2, --Leather Trousers 0x3231, 9936,2, --Cotton Brais 0x3298, 309,2, --Leather Highboots 0x32c0, 544,2, --Solea 0x32b1, 6633,2, --Cotton Gaiters 0x3002, 556,2, --Maple Shield 0x3230, 1899,3, --Brais 0x3238, 172,3, --Slops 0x32b0, 1269,3, --Gaiters 0x32b8, 111,3, --Ash Clogs 0x3001, 110,3 --Lauan Shield } showNationShop(player, NATION_WINDURST, 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
LegionXI/darkstar
scripts/zones/Sea_Serpent_Grotto/npcs/_4w3.lua
14
2876
----------------------------------- -- Area: Sea Serpent Grotto -- NPC: Mythril Beastcoin Door -- @zone 176 -- @pos 40 8.6 20.012 ----------------------------------- package.loaded["scripts/zones/Sea_Serpent_Grotto/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Sea_Serpent_Grotto/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(749,1) and trade:getItemCount() == 1) then if (player:getVar("SSG_MythrilDoor") == 7) then npc:openDoor(5) --Open the door if a mythril beastcoin has been traded after checking the door the required number of times end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) X = player:getXPos(); Z = player:getZPos(); MythrilDoorCheck = player:getVar("SSG_MythrilDoor"); if (X >= 40 and Z >= 15) then if (MythrilDoorCheck == 0) then --Door has never been checked player:messageSpecial(FIRST_CHECK); player:setVar("SSG_MythrilDoor",1); elseif (MythrilDoorCheck == 1) then --Door has been checked once player:messageSpecial(SECOND_CHECK); player:setVar("SSG_MythrilDoor",2); elseif (MythrilDoorCheck == 2) then --Door has been checked twice player:messageSpecial(THIRD_CHECK); player:setVar("SSG_MythrilDoor",3); elseif (MythrilDoorCheck == 3) then --Door has been checked three times player:messageSpecial(FOURTH_CHECK); player:setVar("SSG_MythrilDoor",4); elseif (MythrilDoorCheck == 4) then --Door has been checked four times player:messageSpecial(FIFTH_CHECK); player:setVar("SSG_MythrilDoor",5); elseif (MythrilDoorCheck == 5) then --Door has been checked five times player:messageSpecial(MYTHRIL_CHECK); player:setVar("SSG_MythrilDoor",6); elseif (MythrilDoorCheck == 6 or MythrilDoorCheck == 7) then --Door has been checked six or more times player:messageSpecial(COMPLETED_CHECK,749); player:setVar("SSG_MythrilDoor",7); end return 1 --Keep the door closed elseif (X < 40 and Z < 24) then return -1 --Open the door if coming from the "inside" 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
greasydeal/darkstar
scripts/zones/Temenos/bcnms/Central_Temenos_4th_Floor.lua
13
1399
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[C_Temenos_4th]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1306),TEMENOS); HideTemenosDoor(GetInstanceRegion(1306)); player:setVar("Limbus_Trade_Item-T",0); if(GetMobAction(16928986) > 0)then DespawnMob(16928986);end if(GetMobAction(16928987) > 0)then DespawnMob(16928987);end if(GetMobAction(16928988) > 0)then DespawnMob(16928988);end for n=16928991,16929003,1 do if(GetMobAction(n) > 0)then DespawnMob(n);end end --print("spawn_coffer"); SpawnCofferTemenosCFloor4(); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[C_Temenos_4th]UniqueID")); player:setVar("LimbusID",1306); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if(leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Caedarva_Mire/npcs/Nahshib.lua
12
1969
----------------------------------- -- Area: Caedarva Mire -- NPC: Nahshib -- Type: Assault -- @pos -274.334 -9.287 -64.255 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local IPpoint = player:getCurrency("imperial_standing"); if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES) then if(player:hasKeyItem(SUPPLIES_PACKAGE))then player:startEvent(0x0005); elseif(player:getVar("TOAUM2") == 1)then player:startEvent(0x0006); end elseif(player:getCurrentMission(TOAU) >= PRESIDENT_SALAHEEM)then if(player:hasKeyItem(PERIQIA_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then player:startEvent(0x0094,50,IPpoint); else player:startEvent(0x0007); -- player:delKeyItem(ASSAULT_ARMBAND); end else player:startEvent(0x0004); 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); if(csid == 0x0094 and option == 1) then player:delCurrency("imperial_standing", 50); player:addKeyItem(ASSAULT_ARMBAND); player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND); elseif(csid == 0x0005 and option == 1)then player:delKeyItem(SUPPLIES_PACKAGE); player:setVar("TOAUM2",1); end end;
gpl-3.0
LegionXI/darkstar
scripts/globals/mobskills/Crystal_Weapon.lua
37
1031
--------------------------------------------- -- Crystal Weapon -- -- Description: Invokes the power of a crystal to deal magical damage of a random element to a single target. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown -- Notes: Can be Fire, Earth, Wind, or Water element. Functions even at a distance (outside of melee range). --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local element = math.random(6,9); local dmgmod = 1; local accmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 5,accmod,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,element,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
LegionXI/darkstar
scripts/zones/Western_Altepa_Desert/TextIDs.lua
7
1562
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6383; -- You cannot obtain the <item>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6393; -- You obtain <param2 number> <param1 item>! NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here. -- ZM4 dialog CANNOT_REMOVE_FRAG = 7341; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed... ALREADY_OBTAINED_FRAG = 7342; -- You have already obtained this monument's ALREADY_HAVE_ALL_FRAGS = 7343; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine! FOUND_ALL_FRAGS = 7344; -- You now have all 8 fragments of light! ZILART_MONUMENT = 7345; -- It is an ancient Zilart monument. -- Other dialog THE_DOOR_IS_LOCKED = 7324; -- The door is locked. DOES_NOT_RESPOND = 7325; -- It does not respond. -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results... --chocobo digging DIG_THROW_AWAY = 7217; -- You dig up$, but your inventory is full. You regretfully throw the # away. FIND_NOTHING = 7219; -- You dig and you dig, but find nothing.
gpl-3.0
greasydeal/darkstar
scripts/zones/Port_Windurst/npcs/Erabu-Fumulubu.lua
53
1835
----------------------------------- -- Area: Port Windurst -- NPC: Erabu-Fumulubu -- Type: Fishing Synthesis Image Support -- @pos -178.900 -2.789 76.200 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,5); local SkillCap = getCraftSkillCap(player,SKILL_FISHING); local SkillLevel = player:getSkillLevel(SKILL_FISHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),19194,4031,0); end else player:startEvent(0x271C); -- Standard Dialogue 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); if (csid == 0x271C and option == 1) then player:messageSpecial(FISHING_SUPPORT,0,0,1); player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600); end end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Temenos/mobs/Airi.lua
17
1277
----------------------------------- -- Area: Temenos Central 1floor -- NPC: Airi ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if(IsMobDead(16929047)==true)then mob:addStatusEffect(EFFECT_REGAIN,7,3,0); mob:addStatusEffect(EFFECT_REGEN,50,3,0); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if(IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true)then GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ); GetNPCByID(16928768+71):setStatus(STATUS_NORMAL); GetNPCByID(16928770+471):setStatus(STATUS_NORMAL); end end;
gpl-3.0
naclander/tome
game/modules/tome/data/chats/ring-of-blood-win.lua
3
1160
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newChat{ id="welcome", text = [[So, you tasted blood? Liked it? I am sure you did; you are just that kind of people. Anyway, I suppose you deserve your reward. You can always participate again for fun, if you've got the gold to spare.]], answers = { {"Thanks, it was fun!", action=function(npc, player) player:hasQuest("ring-of-blood"):reward(player) end}, } } return "welcome"
gpl-3.0
greasydeal/darkstar
scripts/zones/Korroloka_Tunnel/MobIDs.lua
65
1094
----------------------------------- -- Area: Korroloka Tunnel (173) -- Comments: -- posX, posY, posZ -- (Taken from 'mob_spawn_points' table) ----------------------------------- -- Cargo_Crab_Colin Cargo_Crab_Colin=17485980; Cargo_Crab_Colin_PH={ [17486002] = '1', -- -30.384, 1.000, -33.277 [17486095] = '1' -- -85.000, -0.500, -37.000 }; -- Dame_Blanche Dame_Blanche=17486129; Dame_Blanche_PH={ [17486128] = '1', -- -345.369, 0.716, 119.486 [17486127] = '1', -- -319.266, -0.244, 130.650 [17486126] = '1', -- -319.225, -0.146, 109.776 [17486124] = '1', -- -296.821, -3.207, 131.239 [17486125] = '1', -- -292.487, -5.993, 141.408 [17486119] = '1', -- -277.338, -9.352, 139.763 [17486118] = '1' -- -276.713, -9.954, 135.353 }; -- Falcatus_Aranei Falcatus_Aranei=17486031; Falcatus_Aranei_PH={ [17486033] = '1', -- -68.852, -5.029, 141.069 [17486032] = '1', -- -94.545, -6.095, 136.480 [17486034] = '1', -- -79.827, -6.046, 133.982 [17486027] = '1', -- -25.445, -6.073, 142.192 [17486028] = '1' -- -33.446, -6.038, 141.987 };
gpl-3.0
LegionXI/darkstar
scripts/zones/Yhoator_Jungle/npcs/qm3.lua
14
1845
----------------------------------- -- Area: Davoi -- NPC: ??? (qm3) -- Involved in Quest: True will -- @pos 203 0.1 82 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Yhoator_Jungle/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(OUTLANDS,TRUE_WILL) == QUEST_ACCEPTED and player:hasKeyItem(OLD_TRICK_BOX) == false) then if (player:getVar("trueWillKilledNM") >= 1) then if (GetMobAction(17285544) == 0 and GetMobAction(17285545) == 0 and GetMobAction(17285546) == 0) then player:addKeyItem(OLD_TRICK_BOX); player:messageSpecial(KEYITEM_OBTAINED,OLD_TRICK_BOX); player:setVar("trueWillKilledNM",0); end else SpawnMob(17285544):updateClaim(player); -- Kappa Akuso SpawnMob(17285545):updateClaim(player); -- Kappa Bonze SpawnMob(17285546):updateClaim(player); -- Kappa Biwa end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
naclander/tome
game/modules/tome/data/texts/message-last-hope.lua
3
2327
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- 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/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local delivered_staff = game.player:resolveSource():isQuestStatus("staff-absorption", engine.Quest.COMPLETED, "survived-ukruk") if delivered_staff then return [[@playername@, this message is of utmost importance. The staff you left at Last Hope is gone. A raid of orcs ambushed the guards that were transporting it to a secret vault. Our troops managed to capture one of the orcs and made him talk. He did not know much, but he did speak about "masters" in the Far East. He spoke about Golbug -- this seems to be a warmaster in Reknor -- leading a raid to send a "package" through a portal. This calls for urgency; should you find this Golbug or the portal, please investigate. #GOLD#-- Tolak, King of the Allied Kingdoms]] else return [[@playername@, this message is of utmost importance. Our elders searched the old texts looking for clues about the staff of which you spoke. It turns out to be a powerful object indeed, able to absorb the power of places, and beings. This must not fall in the wrong hands, which certainly include orcish hands. While you were gone, one of our patrols met a group of orcs led by Ukruk. We could not stop them, but we managed to capture one of them. He did not know much, but he did speak about "masters" in the Far East. He spoke about meeting with Golbug -- this seems to be a warmaster in Reknor -- to send a "package" through a portal. This calls for urgency; should you find this Golbug or the portal, please investigate. #GOLD#-- Tolak, King of the Allied Kingdoms]] end
gpl-3.0
ibm2431/darkstar
scripts/zones/Beadeaux/npcs/_43b.lua
11
1312
----------------------------------- -- Area: Beadeaux -- NPC: Jail Door -- Involved in Quests: The Rescue -- !pos 56 0.1 -23 147 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); local ID = require("scripts/zones/Beadeaux/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.THE_RESCUE) == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TRADERS_SACK) == false) then if (trade:hasItemQty(495,1) == true and trade:getItemCount() == 1) then player:startEvent(1000); end end end; function onTrigger(player,npc) if (player:getQuestStatus(OTHER_AREAS_LOG,dsp.quest.id.otherAreas.THE_RESCUE) == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TRADERS_SACK) == false) then player:messageSpecial(ID.text.LOCKED_DOOR_QUADAV_HAS_KEY); else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY); end return 1; end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 1000) then player:addKeyItem(dsp.ki.TRADERS_SACK); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.TRADERS_SACK); end end;
gpl-3.0
greasydeal/darkstar
scripts/zones/Jugner_Forest_[S]/Zone.lua
17
1510
----------------------------------- -- -- Zone: Jugner_Forest_[S] (82) -- ----------------------------------- package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Jugner_Forest_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(621.865,-6.665,300.264,149); end if(player:getQuestStatus(CRYSTAL_WAR,CLAWS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("ClawsOfGriffonProg") == 0) then return 200; else return cs; end 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
greasydeal/darkstar
scripts/globals/items/skewer_of_m&p_chicken.lua
36
1336
----------------------------------------- -- ID: 5639 -- Item: Skewer of M&P Chicken -- Food Effect: 3Min, All Races ----------------------------------------- -- Strength 5 -- Intelligence -5 -- Attack % 25 -- Attack Cap 154 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) 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,180,5639); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_INT, -5); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 154); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_INT, -5); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 154); end;
gpl-3.0
ibm2431/darkstar
scripts/zones/Port_San_dOria/npcs/Vounebariont.lua
11
1647
----------------------------------- -- Area: Port San d'Oria -- NPC: Vounebariont -- Starts and Finishes Quest: Thick Shells ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); local ID = require("scripts/zones/Port_San_dOria/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS) ~= QUEST_AVAILABLE) then if (trade:hasItemQty(889,5) and trade:getItemCount() == 5) then -- Trade Beetle Shell player:startEvent(514); end end end; function onTrigger(player,npc) if (player:getFameLevel(SANDORIA) >= 2) then player:startEvent(516); else player:startEvent(568); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 516) then if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS) == QUEST_AVAILABLE) then player:addQuest(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS); end elseif (csid == 514) then if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS) == QUEST_ACCEPTED) then player:completeQuest(SANDORIA,dsp.quest.id.sandoria.THICK_SHELLS); player:addFame(SANDORIA,30); else player:addFame(SANDORIA,5); end player:tradeComplete(); player:addTitle(dsp.title.BUG_CATCHER); player:addGil(GIL_RATE*750); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*750) end end;
gpl-3.0
lbthomsen/openwrt-luci
applications/luci-app-coovachilli/luasrc/model/cbi/coovachilli_network.lua
79
1459
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local sys = require"luci.sys" local ip = require "luci.ip" m = Map("coovachilli") -- tun s1 = m:section(TypedSection, "tun") s1.anonymous = true s1:option( Flag, "usetap" ) s1:option( Value, "tundev" ).optional = true s1:option( Value, "txqlen" ).optional = true net = s1:option( Value, "net" ) for _, route in ipairs(ip.routes({ family = 4, type = 1 })) do if route.dest:prefix() > 0 and route.dest:prefix() < 32 then net:value( route.dest:string() ) end end s1:option( Value, "dynip" ).optional = true s1:option( Value, "statip" ).optional = true s1:option( Value, "dns1" ).optional = true s1:option( Value, "dns2" ).optional = true s1:option( Value, "domain" ).optional = true s1:option( Value, "ipup" ).optional = true s1:option( Value, "ipdown" ).optional = true s1:option( Value, "conup" ).optional = true s1:option( Value, "condown" ).optional = true -- dhcp config s2 = m:section(TypedSection, "dhcp") s2.anonymous = true dif = s2:option( Value, "dhcpif" ) for _, nif in ipairs(sys.net.devices()) do if nif ~= "lo" then dif:value(nif) end end s2:option( Value, "dhcpmac" ).optional = true s2:option( Value, "lease" ).optional = true s2:option( Value, "dhcpstart" ).optional = true s2:option( Value, "dhcpend" ).optional = true s2:option( Flag, "eapolenable" ) return m
apache-2.0
greasydeal/darkstar
scripts/zones/Castle_Oztroja/npcs/_47x.lua
17
1245
----------------------------------- -- Area: Castle Oztroja -- NPC: _47x (Handle) -- Notes: Opens door _477 -- @pos -99 -71 -41 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorID = npc:getID() - 1; local DoorA = GetNPCByID(DoorID):getAnimation(); if(player:getZPos() > -45) then if(DoorA == 9 and npc:getAnimation() == 9) then npc:openDoor(6.5); -- Should be a ~1 second delay here before the door opens GetNPCByID(DoorID):openDoor(4.5); end 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); end;
gpl-3.0