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
AlexandreCA/update
scripts/zones/Upper_Jeuno/npcs/Paya-Sabya.lua
17
1335
----------------------------------- -- 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
AlexandreCA/update
scripts/zones/Tavnazian_Safehold/Zone.lua
19
3150
----------------------------------- -- -- Zone: Tavnazian_Safehold (26) -- ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -5, -24, 18, 5, -20, 27); zone:registerRegion(2, 104, -42, -88, 113, -38, -77); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(27.971,-14.068,43.735,66); end if (player:getCurrentMission(COP) == AN_INVITATION_WEST) then if (player:getVar("PromathiaStatus") == 1) then cs = 0x0065; end elseif (player:getCurrentMission(COP) == SHELTERING_DOUBT and player:getVar("PromathiaStatus") == 0) then cs = 0x006B; elseif (player:getCurrentMission(COP) == CHAINS_AND_BONDS and player:getVar("PromathiaStatus") == 1) then cs = 0x0072; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) if (player:getCurrentMission(COP) == AN_ETERNAL_MELODY and player:getVar("PromathiaStatus") == 2) then player:startEvent(0x0069); end end, [2] = function (x) if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0070); end end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(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); if (csid == 0x0065) then player:completeMission(COP,AN_INVITATION_WEST); player:addMission(COP,THE_LOST_CITY); player:setVar("PromathiaStatus",0); elseif (csid == 0x0069) then player:setVar("PromathiaStatus",0); player:completeMission(COP,AN_ETERNAL_MELODY); player:addMission(COP,ANCIENT_VOWS); elseif (csid == 0x006B) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0070) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0072) then player:setVar("PromathiaStatus",2); end end;
gpl-3.0
jstewart-amd/premake-core
modules/d/tools/dmd.lua
7
8729
-- -- d/tools/dmd.lua -- Provides dmd-specific configuration strings. -- Copyright (c) 2013-2015 Andrew Gough, Manu Evans, and the Premake project -- local tdmd = {} local project = premake.project local config = premake.config local d = premake.modules.d -- -- Set default tools -- tdmd.gcc = {} tdmd.gcc.dc = "dmd" tdmd.optlink = {} tdmd.optlink.dc = "dmd" -- ///////////////////////////////////////////////////////////////////////// -- dmd + GCC toolchain -- ///////////////////////////////////////////////////////////////////////// -- -- Return a list of LDFLAGS for a specific configuration. -- tdmd.gcc.ldflags = { architecture = { x86 = { "-m32" }, x86_64 = { "-m64" }, }, kind = { SharedLib = "-shared", StaticLib = "-lib", } } function tdmd.gcc.getldflags(cfg) local flags = config.mapFlags(cfg, tdmd.gcc.ldflags) return flags end -- -- Return a list of decorated additional libraries directories. -- tdmd.gcc.libraryDirectories = { architecture = { x86 = "-L-L/usr/lib", x86_64 = "-L-L/usr/lib64", } } function tdmd.gcc.getLibraryDirectories(cfg) local flags = config.mapFlags(cfg, tdmd.gcc.libraryDirectories) -- Scan the list of linked libraries. If any are referenced with -- paths, add those to the list of library search paths for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do table.insert(flags, '-L-L' .. project.getrelative(cfg.project, dir)) end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function tdmd.gcc.getlinks(cfg, systemonly) local result = {} local links if not systemonly then links = config.getlinks(cfg, "siblings", "object") for _, link in ipairs(links) do -- skip external project references, since I have no way -- to know the actual output target path if not link.project.external then if link.kind == premake.STATICLIB then -- Don't use "-l" flag when linking static libraries; instead use -- path/libname.a to avoid linking a shared library of the same -- name if one is present table.insert(result, "-L" .. project.getrelative(cfg.project, link.linktarget.abspath)) else table.insert(result, "-L-l" .. link.linktarget.basename) end end end end -- The "-l" flag is fine for system libraries links = config.getlinks(cfg, "system", "fullpath") for _, link in ipairs(links) do if path.isframework(link) then table.insert(result, "-framework " .. path.getbasename(link)) elseif path.isobjectfile(link) then table.insert(result, "-L" .. link) else table.insert(result, "-L-l" .. path.getbasename(link)) end end return result end -- ///////////////////////////////////////////////////////////////////////// -- tdmd + OPTLINK toolchain -- ///////////////////////////////////////////////////////////////////////// -- -- Return a list of LDFLAGS for a specific configuration. -- tdmd.optlink.ldflags = { architecture = { x86 = { "-m32" }, x86_64 = { "-m64" }, }, kind = { SharedLib = "-shared", StaticLib = "-lib", } } function tdmd.optlink.getldflags(cfg) local flags = config.mapFlags(cfg, tdmd.optlink.ldflags) return flags end -- -- Return a list of decorated additional libraries directories. -- function tdmd.optlink.getLibraryDirectories(cfg) local flags = {} -- Scan the list of linked libraries. If any are referenced with -- paths, add those to the list of library search paths for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do table.insert(flags, '-Llib "' .. project.getrelative(cfg.project, dir) .. '"') end return flags end -- -- Returns a list of linker flags for library names. -- function tdmd.optlink.getlinks(cfg) local result = {} local links = config.getlinks(cfg, "dependencies", "object") for _, link in ipairs(links) do -- skip external project references, since I have no way -- to know the actual output target path if not link.project.externalname then local linkinfo = config.getlinkinfo(link) if link.kind == premake.STATICLIB then table.insert(result, project.getrelative(cfg.project, linkinfo.abspath)) end end end -- The "-l" flag is fine for system libraries links = config.getlinks(cfg, "system", "basename") for _, link in ipairs(links) do if path.isobjectfile(link) then table.insert(result, link) elseif path.hasextension(link, premake.systems[cfg.system].staticlib.extension) then table.insert(result, link) end end return result end -- ///////////////////////////////////////////////////////////////////////// -- common dmd code (either toolchain) -- ///////////////////////////////////////////////////////////////////////// -- if we are compiling on windows, we need to specialise to OPTLINK as the linker -- OR!!! if cfg.system ~= premake.WINDOWS then if string.match( os.getversion().description, "Windows" ) ~= nil then -- TODO: on windows, we may use OPTLINK or MSLINK (for Win64)... -- printf("TODO: select proper linker for 32/64 bit code") premake.tools.dmd = tdmd.optlink else premake.tools.dmd = tdmd.gcc end local dmd = premake.tools.dmd -- -- Returns list of D compiler flags for a configuration. -- dmd.dflags = { architecture = { x86 = "-m32", x86_64 = "-m64", }, flags = { CodeCoverage = "-cov", Deprecated = "-d", Documentation = "-D", FatalWarnings = "-w", GenerateHeader = "-H", GenerateJSON = "-X", GenerateMap = "-map", NoBoundsCheck = "-noboundscheck", Profile = "-profile", Quiet = "-quiet", -- Release = "-release", RetainPaths = "-op", SymbolsLikeC = "-gc", UnitTest = "-unittest", Verbose = "-v", }, floatingpoint = { None = "-nofloat", }, optimize = { On = "-O -inline", Full = "-O -inline", Size = "-O -inline", Speed = "-O -inline", }, pic = { On = "-fPIC", }, warnings = { Default = "-wi", Extra = "-wi", }, symbols = { On = "-g", } } function dmd.getdflags(cfg) local flags = config.mapFlags(cfg, dmd.dflags) if config.isDebugBuild(cfg) then table.insert(flags, "-debug") else table.insert(flags, "-release") end -- TODO: When DMD gets CRT options, map StaticRuntime and DebugRuntime if cfg.flags.Documentation then if cfg.docname then table.insert(flags, "-Df" .. premake.quoted(cfg.docname)) end if cfg.docdir then table.insert(flags, "-Dd" .. premake.quoted(cfg.docdir)) end end if cfg.flags.GenerateHeader then if cfg.headername then table.insert(flags, "-Hf" .. premake.quoted(cfg.headername)) end if cfg.headerdir then table.insert(flags, "-Hd" .. premake.quoted(cfg.headerdir)) end end return flags end -- -- Decorate versions for the DMD command line. -- function dmd.getversions(versions, level) local result = {} for _, version in ipairs(versions) do table.insert(result, '-version=' .. version) end if level then table.insert(result, '-version=' .. level) end return result end -- -- Decorate debug constants for the DMD command line. -- function dmd.getdebug(constants, level) local result = {} for _, constant in ipairs(constants) do table.insert(result, '-debug=' .. constant) end if level then table.insert(result, '-debug=' .. level) end return result end -- -- Decorate import file search paths for the DMD command line. -- function dmd.getimportdirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Returns the target name specific to compiler -- function dmd.gettarget(name) return "-of" .. name end -- -- Returns makefile-specific configuration rules. -- dmd.makesettings = { } function dmd.getmakesettings(cfg) local settings = config.mapFlags(cfg, dmd.makesettings) return table.concat(settings) end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "dc" for the D compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- dmd.tools = { -- dmd will probably never support any foreign architectures...? } function dmd.gettoolname(cfg, tool) local names = dmd.tools[cfg.architecture] or dmd.tools[cfg.system] or {} local name = names[tool] return name or dmd[tool] end
bsd-3-clause
AlexandreCA/update
scripts/globals/items/ulbukan_lobster.lua
18
1342
----------------------------------------- -- ID: 5960 -- Item: Ulbukan Lobster -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity -3 -- Vitality 1 -- Defense +9% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5960); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -3); target:addMod(MOD_VIT, 1); target:addMod(MOD_DEFP, 9); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -3); target:delMod(MOD_VIT, 1); target:delMod(MOD_DEFP, 9); end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm8.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm8 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED2); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED2); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); 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); end;
gpl-3.0
incinirate/Riko4
scripts/usr/bin/edit.lua
1
5615
--HELP: \b6Usage: \b16edit \b7<\b16file\b7> \n -- \b6Description: \b7Opens \b16file \b7in a code editor local args = {...} if #args < 1 then if shell then print("Syntax: edit <file> [line]\n", 9) return else error("Syntax: edit <file> [line]", 2) end end local running = true local myPath = fs.getLastFile() local workingDir = myPath:match(".+%/") .. "edit/" addRequirePath(workingDir) local editorTheme = { bg = 1, -- black text = 16, -- white selBar = 2, -- dark blue selChar = 10, -- yellow highlight = 3, -- maroon scrollBar = 7, -- light gray lineNumbers = 7, -- light gray caret = 9 -- orange } local syntaxTheme = { keyword = 13, -- purple specialKeyword = 12, -- light blue func = 12, -- light blue string = 8, -- red stringEscape = 10, -- yellow primitive = 9, -- orange comment = 6, -- dark gray catch = 16 -- everything else is white } local context = require("context").new() context:set("mediator", context:get("mediator")()) local rif = require("rif") local mposx, mposy = -5, -5 local cur, ibar cur = rif.createImage(workingDir .. "curs.rif") ibar = rif.createImage(workingDir .. "ibar.rif") local filename = args[1] if not fs.exists(filename) and not fs.isDir(filename) then if fs.exists(filename .. ".lua") then filename = filename .. ".lua" elseif fs.exists(filename .. ".rlua") then filename = filename .. ".rlua" elseif not filename:match("%..+$") then filename = filename .. ".rlua" end end if fs.isDir(filename) then print("'" .. filename .. "' is a directory", 8) return end local eventPriorityQueue local insertionQueue = {} local editor = context:get "editor" editor.init({ editorTheme = editorTheme, syntaxTheme = syntaxTheme, viewportWidth = gpu.width, viewportHeight = gpu.height - 10, initialLine = tonumber(args[2]) }) local menu = context:get "menu" menu.init({ editorTheme = editorTheme, filename = filename, quitFunc = function() running = false end, attacher = function(obj) insertionQueue[#insertionQueue + 1] = obj end, detacher = function(obj) for i = 1, #eventPriorityQueue do if eventPriorityQueue[i] == obj then table.remove(eventPriorityQueue, i) break end end end }) local function fsLines(fn) local handle = fs.open(fn, "rb") local i = 1 return function() local c = handle:read("*l") i = i + 1 if c then return c else handle:close() return nil end end end do local content = {} if fs.exists(filename) then for line in fsLines(filename) do if line then content[#content + 1] = line end end end if #content == 0 then content[#content + 1] = "" end editor.setText(content) end local eventModifiers = { key = { ctrl = false, shift = false, alt = false } } eventPriorityQueue = { editor, menu } local function drawContent() gpu.clear(editorTheme.bg) editor.draw() menu.draw() local cursorName = "default" for i = 1, #eventPriorityQueue do local eventTarget = eventPriorityQueue[i] if eventTarget.assignMouseIcon then cursorName = eventTarget.assignMouseIcon(mposx, mposy) or cursorName end end if cursorName == "default" then cur:render(mposx, mposy) elseif cursorName == "ibar" then ibar:render(mposx, mposy - 4) end end local function update(dt) menu.update(dt) end local function capitalize(str) return str:sub(1, 1):upper() .. str:sub(2) end local function processEvent(e, p1, p2) if e == "key" then if p1 == "leftCtrl" or p1 == "rightCtrl" then eventModifiers.key.ctrl = true elseif p1 == "leftShift" or p1 == "rightShift" then eventModifiers.key.shift = true elseif p1 == "leftAlt" or p1 == "rightAlt" then eventModifiers.key.alt = true end elseif e == "keyUp" then if p1 == "leftCtrl" or p1 == "rightCtrl" then eventModifiers.key.ctrl = false elseif p1 == "leftShift" or p1 == "rightShift" then eventModifiers.key.shift = false elseif p1 == "leftAlt" or p1 == "rightAlt" then eventModifiers.key.alt = false end end local propName = "on" .. capitalize(e) for i = 1, #eventPriorityQueue do local eventTarget = eventPriorityQueue[i] if eventTarget[propName] then local capture, promote = eventTarget[propName](eventTarget, eventModifiers or {}, p1, p2) if promote ~= nil then table.remove(eventPriorityQueue, i) if promote then table.insert(eventPriorityQueue, 1, eventTarget) else local newIndex = i + 1 newIndex = (newIndex - 1 > #eventPriorityQueue) and newIndex - 1 or newIndex table.insert(eventPriorityQueue, newIndex, eventTarget) end break end if capture then break end end end for i = #insertionQueue, 1, -1 do table.insert(eventPriorityQueue, 1, insertionQueue[i]) insertionQueue[i] = nil end if e == "mouseMoved" then mposx, mposy = p1, p2 end end local eventQueue = {} local lastTime = os.clock() drawContent() while running do while true do local e, p1, p2 = coroutine.yield() if not e then break end table.insert(eventQueue, {e, p1, p2}) end while #eventQueue > 0 do processEvent(unpack(eventQueue[1])) table.remove(eventQueue, 1) end if not running then break end update(os.clock() - lastTime) lastTime = os.clock() gpu.clear() drawContent() gpu.swap() end
mit
AlexandreCA/darkstar
scripts/zones/Kazham/npcs/Balih_Chavizaai.lua
15
1055
----------------------------------- -- Area: Kazham -- NPC: Balih Chavizaai -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00A0); -- scent from Blue Rafflesias else player:startEvent(0x0028); 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
AlexandreCA/update
scripts/globals/items/sleep_bolt.lua
4
1214
----------------------------------------- -- ID: 18149 -- Item: Sleep Bolt -- Additional Effect: Sleep ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 95; if (target:getMainLvl() > player:getMainLvl()) then chance = chance - 5 * (target:getMainLvl() - player:getMainLvl()) chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance) then return 0,0,0; else local duration = 25; if (target:getMainLvl() > player:getMainLvl()) then duration = duration - (target:getMainLvl() - player:getMainLvl()) end duration = utils.clamp(duration,1,25); duration = duration * applyResistanceAddEffect(player,target,ELE_LIGHT,0); if (not target:hasStatusEffect(EFFECT_SLEEP_I)) then target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration); end return SUBEFFECT_SLEEP, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_SLEEP_I; end end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/chocolate_cake.lua
36
1186
----------------------------------------- -- ID: 5633 -- Item: Chocolate Cake -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- MP +3% -- MP Recovered while healing +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,10800,5633); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPP, 3); target:addMod(MOD_MPHEAL, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPP, 3); target:delMod(MOD_MPHEAL, 6); end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Attohwa_Chasm/npcs/qm1.lua
13
1613
----------------------------------- -- Area: Attohwa Chasm -- NPC: ??? (qm1) -- @pos -402.574 3.999 -202.750 7 ----------------------------------- package.loaded["scripts/zones/Attohwa_Chasm/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Attohwa_Chasm/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) -- Antlion Trap: ID 1825 -- Alastor Antlion: ID 16806248 -- UPDATE `mob_spawn_points` SET `pos_x`='-402.574', `pos_y`='3.999', `pos_z`='-202.75', `pos_rot`='7' WHERE (`mobid`='16806242') local feelerID =16806242; local feelerAntlion = GetMobByID(feelerID); local npcX = npc:getXPos(); local npcY = npc:getYPos(); local npcZ = npc:getZPos(); feelerAntlion:setSpawn(npcX-3,npcY-2,npcZ-1); if (GetMobAction(feelerID) == 0 and trade:hasItemQty(1825,1) and trade:getItemCount() == 1) then player:tradeComplete(); SpawnMob(feelerID,120):updateClaim(player); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(OCCASIONAL_LUMPS); 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
AlexandreCA/update
scripts/zones/Port_San_dOria/npcs/HomePoint#1.lua
17
1263
----------------------------------- -- Area: Port San dOria -- NPC: HomePoint#1 -- @pos -67.963 -4.000 -105.023 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 6); 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
lucgagnon/ntopng
scripts/lua/get_user_info.lua
8
5905
-- -- (C) 2014-15-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" require "flow_utils" sendHTTPHeader('text/html; charset=iso-8859-1') ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc") page = _GET["page"] if(page == nil) then page = "UserApps" end dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua") user_key = _GET["user"] host_key = _GET["host"] application = _GET["application"] if(user_key == nil) then print("<div class=\"alert alert-danger\"><img src=".. ntop.getHttpPrefix() .. "/img/warning.png> Missing user name</div>") else if(host_key ~= nil) then name = ntop.getResolvedAddress(host_key) if (name == nil) then name = host_key end end print [[ <nav class="navbar navbar-default" role="navigation"> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="#"><i class="fa fa-user fa-lg"></i> ]] print(user_key) if(host_key ~= nil) then print(' - <i class="fa fa-building fa-lg"></i> '..name) end print [[ </a></li> ]] if(page == "UserApps") then active=' class="active"' else active = "" end print('<li'..active..'><a href="?user='.. user_key) if(host_key ~= nil) then print("&host="..host_key) end print('&page=UserApps">Applications</a></li>\n') if(page == "UserProtocols") then active=' class="active"' else active = "" end print('<li'..active..'><a href="?user='.. user_key) if(host_key ~= nil) then print("&host="..host_key) end print('&page=UserProtocols">Protocols</a></li>\n') if(page == "Flows") then active=' class="active"' else active = "" end print('<li'..active..'><a href="?user='.. user_key) if(host_key ~= nil) then print("&host="..host_key) end print('&page=Flows">Flow</a></li>\n') print('</ul>\n\t</div>\n\t\t</nav>\n') if(page == "UserApps") then print [[ <table class="table table-bordered table-striped"> <tr><th class="text-center"> <h4>Top Applications</h4> <td><div class="pie-chart" id="topApps"></div></td> </th> </tr>]] print [[ </table> <script type='text/javascript'> window.onload=function() { var refresh = 3000 /* ms */; do_pie("#topApps", ']] print (ntop.getHttpPrefix()) print [[/lua/user_stats.lua', { user: "]] print(user_key) print [[", mode: "apps" ]] if (host_key ~= nil) then print(", host: \""..host_key.."\"") end print [[ }, "", refresh); } </script> ]] elseif(page == "UserProtocols") then print [[ <br> <!-- Left Tab --> <div class="tabbable tabs-left"> <ul class="nav nav-tabs"> <li class="active"><a href="#l7" data-toggle="tab">L7 Protocols</a></li> <li><a href="#l4" data-toggle="tab">L4 Protocols</a></li> </ul> <!-- Tab content--> <div class="tab-content"> <div class="tab-pane active" id="l7"> <table class="table table-bordered table-striped"> <tr> <th class="text-center">Top L7 Protocols</th> <td><div class="pie-chart" id="topL7"></div></td> </tr> </table> </div> <!-- Tab l7--> <div class="tab-pane" id="l4"> <table class="table table-bordered table-striped"> <tr> <th class="text-center">Top L4 Protocols</th> <td><div class="pie-chart" id="topL4"></div></td> </tr> </table> </div> <!-- Tab l4--> </div> <!-- End Tab content--> </div> <!-- End Left Tab --> ]] print [[ </table> <script type='text/javascript'> window.onload=function() { var refresh = 3000 /* ms */; do_pie("#topL7", ']] print (ntop.getHttpPrefix()) print [[/lua/user_stats.lua', { user: "]] print(user_key) print [[", mode: "l7" ]] if (host_key ~= nil) then print(", host: \""..host_key.."\"") end print [[ }, "", refresh); do_pie("#topL4", ']] print (ntop.getHttpPrefix()) print [[/lua/user_stats.lua', { user: "]] print(user_key) print [[", mode: "l4" ]] if (host_key ~= nil) then print(", host: \""..host_key.."\"") end print [[ }, "", refresh); } </script> ]] elseif(page == "Flows") then stats = interface.getnDPIStats() num_param = 0 print [[ <div id="table-hosts"></div> <script> $("#table-hosts").datatable({ url: "]] print (ntop.getHttpPrefix()) print [[/lua/get_flows_data.lua]] if(application ~= nil) then print("?application="..application) num_param = num_param + 1 end if(user_key ~= nil) then if (num_param > 0) then print("&") else print("?") end print("user="..user_key) num_param = num_param + 1 end if(host_key ~= nil) then if (num_param > 0) then print("&") else print("?") end print("host="..host_key) num_param = num_param + 1 end print [[", showPagination: true, buttons: [ '<div class="btn-group"><button class="btn btn-link dropdown-toggle" data-toggle="dropdown">Applications<span class="caret"></span></button> <ul class="dropdown-menu" id="flow_dropdown">]] print('<li><a href="'..ntop.getHttpPrefix()..'/lua/get_user_info.lua?user='.. user_key) if(host_key ~= nil) then print("&host="..host_key) end print('&page=Flows">All Proto</a></li>') for key, value in pairsByKeys(stats["ndpi"], asc) do class_active = '' if(key == application) then class_active = ' class="active"' end print('<li '..class_active..'><a href="'..ntop.getHttpPrefix()..'/lua/get_user_info.lua?user='.. user_key) if(host_key ~= nil) then print("&host="..host_key) end print('&page=Flows&application=' .. key..'">'..key..'</a></li>') end print("</ul> </div>' ],\n") ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/sflows_stats_top.inc") prefs = ntop.getPrefs() ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/sflows_stats_bottom.inc") end -- If page end dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
gpl-3.0
AlexandreCA/darkstar
scripts/globals/weaponskills/uriel_blade.lua
11
1417
----------------------------------- -- Uriel Blade -- Sword weapon skill -- Skill Level: N/A -- Description: Delivers an area attack that deals light elemental damage. Damage varies with TP. Additional effect Flash. -- AoE range ??. -- Only available during Campaign Battle while wielding a Griffinclaw. -- Aligned with the Thunder Gorget & Breeze Gorget. -- Aligned with Thunder Belt & Breeze Belt. -- Modifiers: STR: 32% MND:32% -- 100%TP 200%TP 300%TP -- 4.50 6.00 7.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.ftp100 = 4.5; params.ftp200 = 6; params.ftp300 = 7.5; params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.32; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_SWD; params.includemab = true; local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary); if (damage > 0 and target:hasStatusEffect(EFFECT_FLASH) == false) then target:addStatusEffect(EFFECT_FLASH, 200, 0, 15); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
dani-sj/evillbot
plugins/stats.lua
168
4001
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'creedbot' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /creedbot ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "creedbot" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (creedbot)",-- Put everything you like :) "^[!/]([Cc]reedbot)"-- Put everything you like :) }, run = run } end
gpl-2.0
AlexandreCA/darkstar
scripts/commands/additem.lua
11
1309
--------------------------------------------------------------------------------------------------- -- func: @additem <itemId> <quantity> <aug1> <v1> <aug2> <v2> <aug3> <v3> <aug4> <v4> <trial> -- desc: Adds an item to the GMs inventory. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "iiiiiiiiiii" }; function onTrigger(player, itemId, quantity, aug0, aug0val, aug1, aug1val, aug2, aug2val, aug3, aug3val, trialId) -- Load needed text ids for players current zone.. local TextIDs = "scripts/zones/" .. player:getZoneName() .. "/TextIDs"; package.loaded[TextIDs] = nil; require(TextIDs); -- Ensure item id was given.. if (itemId == nil or tonumber(itemId) == nil or tonumber(itemId) == 0) then player:PrintToPlayer( "You must enter a valid item id." ); return; end -- Ensure the GM has room to obtain the item... if (player:getFreeSlotsCount() == 0) then player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, itemId ); return; end -- Give the GM the item... player:addItem( itemId, quantity, aug0, aug0val, aug1, aug1val, aug2, aug2val, aug3, aug3val, trialId ); player:messageSpecial( ITEM_OBTAINED, itemId ); end
gpl-3.0
AlexandreCA/update
scripts/globals/spells/hunters_prelude.lua
18
1490
----------------------------------------- -- Spell: Hunter's Prelude -- Gives party members ranged attack accuracy ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- 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 = 5; if (sLvl+iLvl > 85) then power = power + math.floor((sLvl+iLvl-300) / 10); end if (power >= 30) then power = 30; end local iBoost = caster:getMod(MOD_PRELUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); if (iBoost > 0) then power = power + 1 + (iBoost-1)*3; end 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_PRELUDE,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_PRELUDE; end;
gpl-3.0
lucgagnon/ntopng
scripts/lua/get_alerts_data.lua
10
1870
-- -- (C) 2013-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" sendHTTPHeader('text/html; charset=iso-8859-1') currentPage = _GET["currentPage"] perPage = _GET["perPage"] if(currentPage == nil) then currentPage = 1 else currentPage = tonumber(currentPage) end if(perPage == nil) then perPage = getDefaultTableSize() else perPage = tonumber(perPage) end initial_idx = (currentPage-1)*perPage alerts = ntop.getQueuedAlerts(initial_idx, perPage) print ("{ \"currentPage\" : " .. currentPage .. ",\n \"data\" : [\n") total = 0 for _key,_value in pairs(alerts) do if(total > 0) then print(",\n") end values = split(string.gsub(_value, "\n", ""), "|") column_id = "<form class=form-inline style='margin-bottom: 0px;' method=get action='"..ntop.getHttpPrefix().."/lua/show_alerts.lua'><input type=hidden name=id_to_delete value="..(initial_idx+tonumber(_key)).."><input type=hidden name=currentPage value=".. currentPage .."><input type=hidden name=perPage value=".. perPage .."><button class='btn btn-default btn-xs' type='submit'><input id=csrf name=csrf type=hidden value='"..ntop.getRandomCSRFValue().."' /><i type='submit' class='fa fa-trash-o'></i></button></form>" column_date = os.date("%c", values[1]) column_severity = alertSeverityLabel(tonumber(values[2])) column_type = alertTypeLabel(tonumber(values[3])) column_msg = values[4] print('{ "column_key" : "'..column_id..'", "column_date" : "'..column_date..'", "column_severity" : "'..column_severity..'", "column_type" : "'..column_type..'", "column_msg" : "'..column_msg..'" }') total = total + 1 end -- for print ("\n], \"perPage\" : " .. perPage .. ",\n") print ("\"sort\" : [ [ \"\", \"\" ] ],\n") print ("\"totalRows\" : " .. ntop.getNumQueuedAlerts() .. " \n}")
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Yuhtunga_Jungle/TextIDs.lua
15
1884
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. BEASTMEN_BANNER = 7126; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7546; -- You can't fish here. -- Conquest CONQUEST = 7213; -- You've earned conquest points! -- Logging LOGGING_IS_POSSIBLE_HERE = 7688; -- Logging is possible here if you have HARVESTING_IS_POSSIBLE_HERE = 7695; -- Harvesting is possible here if you have -- ZM4 Dialog CANNOT_REMOVE_FRAG = 7667; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed... ALREADY_OBTAINED_FRAG = 7668; -- You have already obtained this monument's ALREADY_HAVE_ALL_FRAGS = 7669; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine! FOUND_ALL_FRAGS = 7670; -- You now have all 8 fragments of light! ZILART_MONUMENT = 7671; -- It is an ancient Zilart monument. -- Rafflesia Scent FLOWER_BLOOMING = 7647; -- A large flower is blooming. FOUND_NOTHING_IN_FLOWER = 7650; -- You find nothing inside the flower. FEEL_DIZZY = 7651; -- You feel slightly dizzy. You must have breathed in too much of the pollen. -- Other NOTHING_HAPPENS = 119; -- Nothing happens... -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results... -- chocobo digging DIG_THROW_AWAY = 7559; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full. FIND_NOTHING = 7561; -- You dig and you dig, but find nothing.
gpl-3.0
AlexandreCA/update
scripts/zones/Northern_San_dOria/npcs/Miageau.lua
17
2459
----------------------------------- -- Area: Northern San d'Oria -- NPC: Miageau -- Type: Quest Giver NPC -- @zone: 231 -- @pos 115 0 108 -- -- Starts and Finishes: Waters of Cheval ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED) then if (trade:getItemCount() == 1 and trade:hasItemQty(603, 1)) then player:startEvent(0x0203); end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) watersOfTheCheval = player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL); if (watersOfTheCheval == QUEST_ACCEPTED) then if (player:hasItem(602) == true) then player:startEvent(0x0200); else player:startEvent(0x0207); end; elseif (watersOfTheCheval == QUEST_AVAILABLE) then player:startEvent(0x01f8); else player:startEvent(0x0205); 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 == 0x0203) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 13183); else player:tradeComplete(); player:addItem(13183); player:messageSpecial(ITEM_OBTAINED, 13183); player:addFame(SANDORIA,SAN_FAME*30); player:addTitle(THE_PURE_ONE); player:completeQuest(SANDORIA,WATER_OF_THE_CHEVAL); end; elseif (csid == 0x01f8) then player:addQuest(SANDORIA, WATER_OF_THE_CHEVAL); end; end;
gpl-3.0
focusworld/ffocus
plugins/ingroup.lua
527
44020
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
samihacker/xx
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
we20/sss
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
Maxsteam/mer
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
AlexandreCA/darkstar
scripts/zones/Toraimarai_Canal/TextIDs.lua
15
1157
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6425; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6430; -- Obtained: <item>. GIL_OBTAINED = 6431; -- Obtained <number> gil. KEYITEM_OBTAINED = 6433; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7250; -- You can't fish here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7352; -- You unlock the chest! CHEST_FAIL = 7353; -- Fails to open the chest. CHEST_TRAP = 7354; -- The chest was trapped! CHEST_WEAK = 7355; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7356; -- The chest was a mimic! CHEST_MOOGLE = 7357; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7358; -- The chest was but an illusion... CHEST_LOCKED = 7359; -- The chest appears to be locked. -- Quest dialog SEALED_SHUT = 3; -- It's sealed shut with incredibly strong magic. CHEST_IS_LOCKED = 7345; -- This chest is locked. It can be opened with -- conquest Base CONQUEST_BASE = 7091; -- Tallying conquest results...
gpl-3.0
AlexandreCA/update
scripts/zones/Castle_Oztroja/npcs/_47f.lua
17
1240
----------------------------------- -- Area: Castle Oztroja -- NPC: _47f (Handle) -- Notes: Opens door _471 -- @pos -182 -15 -19 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) -- To be implemented (This is temporary) local DoorID = npc:getID() - 2; local DoorA = GetNPCByID(DoorID):getAnimation(); if (DoorA == 9 and npc:getAnimation() == 9) then npc:openDoor(8); -- Should be a 1 second delay here before the door opens GetNPCByID(DoorID):openDoor(6); 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
AlexandreCA/darkstar
scripts/zones/Chateau_dOraguille/npcs/Mistaravant.lua
13
1064
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Mistaravant -- Type: Standard NPC -- @zone: 233 -- @pos 7.097 -3.999 67.988 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x020c); 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
AlexandreCA/darkstar
scripts/zones/Kuftal_Tunnel/TextIDs.lua
15
1264
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7306; -- You unlock the chest! CHEST_FAIL = 7307; -- Fails to open the chest. CHEST_TRAP = 7308; -- The chest was trapped! CHEST_WEAK = 7309; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7310; -- The chest was a mimic! CHEST_MOOGLE = 7311; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7312; -- The chest was but an illusion... CHEST_LOCKED = 7313; -- The chest appears to be locked. -- Other Dialog FELL = 7324; -- The piece of wood fell off the cliff! EVIL = 7325; -- You sense an evil presence... FISHBONES = 7339; -- Fish bones lie scattered about the area... -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Cloister_of_Tides/npcs/Water_Protocrystal.lua
13
1940
----------------------------------- -- Area: Cloister of Tides -- NPC: Water Protocrystal -- Involved in Quests: Trial by Water, Trial Size Trial by Water -- @pos 560 36 560 211 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Tides/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); require("scripts/zones/Cloister_of_Tides/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:getVar("ASA4_Cerulean") == 1) then player:startEvent(0x0002); elseif (EventTriggerBCNM(player,npc)) then return; else player:messageSpecial(PROTOCRYSTAL); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid==0x0002) then player:delKeyItem(DOMINAS_CERULEAN_SEAL); player:addKeyItem(CERULEAN_COUNTERSEAL); player:messageSpecial(KEYITEM_OBTAINED,CERULEAN_COUNTERSEAL); player:setVar("ASA4_Cerulean","2"); elseif (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
dani-sj/evillbot
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
AlexandreCA/update
scripts/zones/AlTaieu/mobs/Jailer_of_Justice.lua
23
1460
----------------------------------- -- Area: Al'Taieu -- NM: Jailer of Justice ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local popTime = mob:getLocalVar("lastPetPop"); -- ffxiclopedia says 30 sec, bgwiki says 1-2 min.. -- Going with 60 seconds until I see proof of retails timing. if (os.time() - popTime > 60) then local alreadyPopped = false; for Xzomit = mob:getID()+1, mob:getID()+6 do if (alreadyPopped == true) then break; else if (GetMobAction(Xzomit) == ACTION_NONE or GetMobAction(Xzomit) == ACTION_SPAWN) then SpawnMob(Xzomit, 300):updateEnmity(target); mob:setLocalVar("lastPetPop", os.time()); alreadyPopped = true; end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) end;
gpl-3.0
exercism/xlua
exercises/practice/list-ops/list-ops_spec.lua
2
2972
local map = require('list-ops').map local reduce = require('list-ops').reduce local filter = require('list-ops').filter describe('list-ops', function() local function should_not_be_called() error('unexpected call') end describe('map', function() local function identity(x) return x end local function square(x) return x * x end it('should return an empty array and not call f when the input is an empty array', function() assert.same({}, map({}, should_not_be_called)) end) it('should return an array identical to the input when f is identity', function() assert.same({ 1, 2, 3, 4 }, map({ 1, 2, 3, 4 }, identity)) end) it('should return an array of the same length where each element in the output is f(x_i)', function() assert.same({ 1, 4, 9, 16 }, map({ 1, 2, 3, 4 }, square)) end) it('should not mutate the input', function() local xs = { 1, 2, 3, 4 } map(xs, square) assert.same({ 1, 2, 3, 4 }, xs) end) end) describe('reduce', function() local function sum(x, acc) return x + acc end local function first_even(x, acc) return (acc % 2 == 0) and acc or x end it('should reduce the input array using the provided accumulator and reduction function', function() assert.equal(10, reduce({ 1, 2, 3, 4 }, 0, sum)) end) it('should begin reduction with the provided initial value', function() assert.equal(15, reduce({ 1, 2, 3, 4 }, 5, sum)) end) it('should reduce from left to right', function() assert.equal(2, reduce({ 1, 2, 3, 4 }, 1, first_even)) end) it('should return the initial accumulator and not call the reduction function when the array is empty', function() assert.equal(55, reduce({}, 55, should_not_be_called)) end) it('should not mutate the input', function() local xs = { 1, 2, 3, 4 } reduce(xs, 0, sum) assert.same({ 1, 2, 3, 4 }, xs) end) end) describe('filter', function() local function always_true() return true end local function always_false() return false end local function is_even(x) return x % 2 == 0 end it('should return an empty array and not call the predicate when the input is an empty array', function() assert.same({}, filter({}, should_not_be_called)) end) it('should return the entire input when the predicate is always true', function() assert.same({ 1, 2, 3, 4 }, filter({ 1, 2, 3, 4 }, always_true)) end) it('should return an empty array when the predicate is always false', function() assert.same({}, filter({ 1, 2, 3, 4 }, always_false)) end) it('should filter out elements for which the predicate is false', function() assert.same({ 2, 4 }, filter({ 1, 2, 3, 4 }, is_even)) end) it('should not mutate the input', function() local xs = { 1, 2, 3, 4 } filter(xs, is_even) assert.same({ 1, 2, 3, 4 }, xs) end) end) end)
mit
AlexandreCA/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Romaa_Mihgo.lua
13
1062
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Romaa Mihgo -- Type: Standard NPC -- @zone: 94 -- @pos -1.967 -3 -26.337 -- -- 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(0x000b); 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
AlexandreCA/darkstar
scripts/globals/items/serving_of_golden_royale.lua
18
1474
----------------------------------------- -- ID: 5558 -- Item: Serving of Golden Royale -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10 -- MP +10 -- Intelligence +2 -- HP Recoverd while healing 2 -- MP Recovered while healing 2 ----------------------------------------- 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,14400,5558); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_INT, 2); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_INT, 2); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
martolini/Vana
scripts/npcs/NLC_HairVip.lua
1
3528
--[[ Copyright (C) 2008-2015 Vana Development Team 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; version 2 of the License. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] -- Mani (VIP hair and color - NLC) dofile("scripts/utils/beautyHelper.lua"); dofile("scripts/utils/npcHelper.lua"); validHairs = getHairStyles(getGenderStyles({ ["male"] = {30730, 30280, 30220, 30410, 30200, 30050, 30230, 30160, 30110, 30250}, ["female"] = {31730, 31310, 31470, 31150, 31160, 31300, 31260, 31220, 31410, 31270}, })); vipHairItem = 5150031; vipHairColour = 5151026; vipMembershipItem = 5420001; choices = { makeChoiceHandler(" Haircut(VIP coupon)", function() addText("I can totally change up your hairstyle and make it look so good. "); addText("Why don't you change it up a bit? "); addText("If you have " .. blue(itemRef(vipHairItem)) .. " I'll change it for you. "); addText("Choose the one to your liking~"); return {validHairs, vipHairItem, true}; end), makeChoiceHandler(" Dye your hair(VIP coupon)", function() addText("I can totally change your haircolor and make it look so good. "); addText("Why don't you change it up a bit? "); addText("With " .. blue(itemRef(vipHairColour)) .. " I'll change it for you. "); addText("Choose the one to your liking."); return {getHairColours(hair_all), vipHairColour, false}; end), -- TODO FIXME beauty -- Verify the choices for this option if possible, might be lost data but I'm not sure that the choices would be consistent with regular VIP makeChoiceHandler(" Change Hairstyle (VIP Membership Coupon)", function() addText("I can totally change up your hairstyle and make it look so good. "); addText("Why don't you change it up a bit? "); addText("If you have " .. blue(itemRef(vipMembershipItem)) .. " I'll change it for you. "); addText("With this coupon, you have the power to change your hairstyle to something totally new, as often as you want, for ONE MONTH! "); addText("Now, please choose the hairstyle of your liking."); return {validHairs, vipMembershipItem, true}; end), }; addText("I'm the head of this hair salon Mani. "); addText("If you have " .. blue(itemRef(vipHairItem)) .. ", " .. blue(itemRef(vipHairColour)) .. " or " .. blue(itemRef(vipMembershipItem)) .. ", allow me to take care of your hairdo. "); addText("Please choose the one you want.\r\n"); addText(blue(choiceRef(choices))); choice = askChoice(); data = selectChoice(choices, choice); choices, itemId, isHaircut = data[1], data[2], data[3]; choice = askStyle(choices); if (itemId == vipMembershipItem and getItemAmount(itemId) > 0) or giveItem(itemId, -1) then setStyle(selectChoice(choices, choice)); addText("Enjoy your new and improved hairstyle!"); sendOk(); else addText("Hmmm...it looks like you don't have our designated coupon..."); addText("I'm afraid I can't "); if isHaircut then addText("give you a haircut "); else addText("dye your hair "); end addText("without it. "); addText("I'm sorry."); sendNext(); end
gpl-2.0
AlexandreCA/darkstar
scripts/zones/Bhaflau_Thickets/npcs/Daswil.lua
18
2118
----------------------------------- -- Area: Bhaflau Thickets -- NPC: Daswil -- Type: Assault -- @pos -208.720 -12.889 -779.713 52 ----------------------------------- package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bhaflau_Thickets/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); ----------------------------------- -- 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(5); elseif (player:getVar("AhtUrganStatus") == 1) then player:startEvent(6); end elseif (player:getCurrentMission(TOAU) >= PRESIDENT_SALAHEEM) then if (player:hasKeyItem(MAMOOL_JA_ASSAULT_ORDERS) and player:hasKeyItem(ASSAULT_ARMBAND) == false) then player:startEvent(512,50,IPpoint); else player:startEvent(7); -- player:delKeyItem(ASSAULT_ARMBAND); end else player:startEvent(4); 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 == 5 and option == 1) then player:delKeyItem(SUPPLIES_PACKAGE); player:setVar("AhtUrganStatus",1); elseif (csid == 512 and option == 1) then player:delCurrency("imperial_standing", 50); player:addKeyItem(ASSAULT_ARMBAND); player:messageSpecial(KEYITEM_OBTAINED,ASSAULT_ARMBAND); end end;
gpl-3.0
AlexandreCA/update
scripts/zones/The_Shrouded_Maw/bcnms/darkness_named.lua
17
2518
----------------------------------- -- Area: The_Shrouded_Maw -- Name: darkness_named ----------------------------------- package.loaded["scripts/zones/The_Shrouded_Maw/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/The_Shrouded_Maw/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) local inst = player:getBattlefieldID(); if (inst == 1) then local TileOffset = 16818258; for i = TileOffset, TileOffset+7 do local TileOffsetA = GetNPCByID(i):getAnimation(); if (TileOffsetA == 8) then GetNPCByID(i):setAnimation(9); end end elseif (inst == 2) then local TileOffset = 16818266; for i = TileOffset, TileOffset+7 do local TileOffsetA = GetNPCByID(i):getAnimation(); if (TileOffsetA == 8) then GetNPCByID(i):setAnimation(9); end end elseif (inst == 3) then local TileOffset = 16818274; for i = TileOffset, TileOffset+7 do local TileOffsetA = GetNPCByID(i):getAnimation(); if (TileOffsetA == 8) then GetNPCByID(i):setAnimation(9); end end end end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:addExp(1000); if (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 2) then player:addTitle(TRANSIENT_DREAMER); player:setVar("PromathiaStatus",3); player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Sea_Serpent_Grotto/npcs/Grounds_Tome.lua
30
1109
----------------------------------- -- Area: Sea Serpent Grotto -- 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_SEA_SERPENT_GROTTO,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,804,805,806,807,808,809,810,811,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,804,805,806,807,808,809,810,811,0,0,GOV_MSG_SEA_SERPENT_GROTTO); end;
gpl-3.0
AlexandreCA/update
scripts/zones/Dynamis-Valkurm/bcnms/dynamis_Valkurm.lua
22
2129
----------------------------------- -- Area: dynamis_Valkurm -- Name: dynamis_Valkurm ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaValkurm]UniqueID",player:getDynamisUniqueID(1286)); SetServerVariable("[DynaValkurm]Boss_Trigger",0); SetServerVariable("[DynaValkurm]Already_Received",0); local RNDpositionTable=TimerStatueRandomPos; local X=0; local Y=0; local Z=0; local statueID = {16937287,16937262,16937237,16937212}; --spawn random timer statue local statueRND = math.random(1,4); local SpawnStatueID= statueID[statueRND]; --printf("timer_statue_ID = %u",SpawnStatueID); local F={2,4,6,8}; --printf("position_type = %u",statueRND); X=RNDpositionTable[F[statueRND]][1]; --printf("X = %u",X); Y=RNDpositionTable[F[statueRND]][2]; --printf("Y = %u",Y); Z=RNDpositionTable[F[statueRND]][3]; --printf("Z = %u",Z); SpawnMob(SpawnStatueID); GetMobByID(SpawnStatueID):setPos(X,Y,Z); GetMobByID(SpawnStatueID):setSpawn(X,Y,Z); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaValkurm]UniqueID")); local realDay = os.time(); if (DYNA_MIDNIGHT_RESET == true) then realDay = getMidnight() - 86400; end local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis 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 SetServerVariable("[DynaValkurm]UniqueID",0); end end;
gpl-3.0
martolini/Vana
scripts/instances/kerningToCbdTrip.lua
1
1142
--[[ Copyright (C) 2008-2015 Vana Development Team 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; version 2 of the License. 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, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. --]] function beginInstance() addInstanceMap(540010101); end function timerEnd(name, fromTimer) if name == instance_timer then if getInstancePlayerCount() > 0 then moveAllPlayers(540010000); removeAllInstancePlayers(); end end end function changeMap(playerId, newMap, oldMap, isPartyLeader) if not isInstanceMap(newMap) then removeInstancePlayer(playerId); elseif not isInstanceMap(oldMap) then addInstancePlayer(playerId); end end
gpl-2.0
AlexandreCA/update
scripts/zones/East_Sarutabaruta/npcs/Heih_Porhiaap.lua
34
1064
----------------------------------- -- Area: East Sarutabaruta -- NPC: Heih Porhiaap -- @pos -118.876 -4.088 -515.731 116 ----------------------------------- package.loaded["scripts/zones/East_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/zones/East_Sarutabaruta/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,HEIH_PORHIAAP_DIALOG); 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
paly2/minetest-minetestforfun-server
mods/lavatemple/nodes.lua
10
1326
minetest.register_node("lavatemple:brick", { description = "Darkbrick", tiles = {"lavatemple_brick.png"}, groups = {dark=1}, sounds = default.node_sound_stone_defaults(), }) stairs.register_stair_and_slab( "lavatemple_brick", "lavatemple:brick", {dark=1}, {"lavatemple_brick.png"}, "Darkbrick Stair", "Darkbrick Slab", default.node_sound_stone_defaults() ) minetest.register_node("lavatemple:ladder", { description = "Darkbrick Ladder", drawtype = "nodebox", tiles = {"lavatemple_ladder.png"}, inventory_image = "lavatemple_ladder_inv.png", wield_image = "lavatemple_ladder_inv.png", paramtype = "light", sunlight_propagates = true, paramtype2 = "wallmounted", climbable = true, walkable = true, node_box = { type = "wallmounted", wall_top = {-0.375, 0.4375, -0.5, 0.375, 0.5, 0.5}, wall_bottom = {-0.375, -0.5, -0.5, 0.375, -0.4375, 0.5}, wall_side = {-0.5, -0.5, -0.375, -0.4375, 0.5, 0.375}, }, selection_box = {type = "wallmounted"}, legacy_wallmounted = true, groups = {dark=1, cracky = 1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("lavatemple:fence_brick", { description = "Darkbrick fence", drawtype = "fencelike", paramtype = "light", tiles = {"lavatemple_brick.png"}, groups = {dark=1}, sounds = default.node_sound_stone_defaults(), })
unlicense
AlexandreCA/update
scripts/zones/Lower_Jeuno/npcs/Shashan-Mishan.lua
59
1043
----------------------------------- -- Area: Lower Jeuno -- NPC: Shashan-Mishan -- Type: Weather Reporter ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x8271C,0,0,0,0,0,0,0,VanadielTime()); 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
AlexandreCA/update
scripts/zones/The_Garden_of_RuHmet/mobs/Aw_aern.lua
13
2386
----------------------------------- -- Area: The Garden of Ru'Hmet -- NPC: Aw_aern PH (Ix'Aern DRK and DRG) ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/zones/The_Garden_of_RuHmet/MobIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) local IxAernDRG_PH = GetServerVariable("[SEA]IxAernDRG_PH"); -- Should be be the ID of the mob that spawns the actual PH -- Pick the Ix'Aern (DRG) PH if the server doesn't have one, and the if the actual PH/NM isn't up. Then, set it. if (GetMobAction(IxAernDRG) == 0 and GetServerVariable("[SEA]IxAernDRG_PH") == 0) then -- This should be cleared when the mob is killed. IxAernDRG_PH = AwAernDRGGroups[math.random(1, #AwAernDRGGroups)] + math.random(0, 2); -- The 4th mobid in each group is a pet. F that son SetServerVariable("[SEA]IxAernDRG_PH", IxAernDRG_PH); end; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) local currentMobID = mob:getID(); -- Ix'Aern (DRG) Placeholder mobs local IxAernDRG_PH = GetServerVariable("[SEA]IxAernDRG_PH"); -- Should be be the ID of the mob that spawns the actual PH. -- If the mob killed was the randomized PH, then Ix'Aern (DRG) in the specific spot, unclaimed and not aggroed. if (IxAernDRG_PH == currentMobID) then -- Select spawn location based on ID if (currentMobID >= 16920777 and currentMobID < 16920781) then GetMobByID(IxAernDRG):setSpawn(-520, 5, -520, 225); -- Bottom Left elseif (currentMobID >= 16920781 and currentMobID < 16920785) then GetMobByID(IxAernDRG):setSpawn(-520, 5, -359, 30); -- Top Left elseif (currentMobID >= 16920785 and currentMobID < 16920789) then GetMobByID(IxAernDRG):setSpawn(-319, 5, -359, 95); -- Top Right elseif (currentMobID >= 16920789 and currentMobID < 16920783) then GetMobByID(IxAernDRG):setSpawn(-319, 5, -520, 156); -- Bottom Right end; SpawnMob(IxAernDRG); SetServerVariable("[SEA]IxAernDRG_PH", 0); -- Clear the variable because it is spawned! end; end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Riverne-Site_B01/npcs/_0t2.lua
13
1348
----------------------------------- -- Area: Riverne Site #B01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_B01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x16); else player:messageSpecial(SD_VERY_SMALL); end; return 1; 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
AlexandreCA/darkstar
scripts/globals/magic.lua
2
45757
require("scripts/globals/magicburst"); require("scripts/globals/status"); require("scripts/globals/weather"); require("scripts/globals/utils"); require("scripts/globals/settings"); MMSG_BUFF_FAIL = 75; DIVINE_MAGIC_SKILL = 32; HEALING_MAGIC_SKILL = 33; ENHANCING_MAGIC_SKILL = 34; ENFEEBLING_MAGIC_SKILL = 35; ELEMENTAL_MAGIC_SKILL = 36; DARK_MAGIC_SKILL = 37; NINJUTSU_SKILL = 39; SUMMONING_SKILL = 38; SINGING_SKILL = 40; STRING_SKILL = 41; WIND_SKILL = 42; BLUE_SKILL = 43; FIRESDAY = 0; EARTHSDAY = 1; WATERSDAY = 2; WINDSDAY = 3; ICEDAY = 4; LIGHTNINGDAY = 5; LIGHTSDAY = 6; DARKSDAY = 7; ELE_NONE = 0; ELE_FIRE = 1; ELE_EARTH = 2; ELE_WATER = 3; ELE_WIND = 4; ELE_ICE = 5; ELE_LIGHTNING = 6; -- added both because monsterstpmoves calls it thunder ELE_THUNDER = 6; ELE_LIGHT = 7; ELE_DARK = 8; dayStrong = {FIRESDAY, EARTHSDAY, WATERSDAY, WINDSDAY, ICEDAY, LIGHTNINGDAY, LIGHTSDAY, DARKSDAY}; dayWeak = {WATERSDAY, WINDSDAY, LIGHTNINGDAY, ICEDAY, FIRESDAY, EARTHSDAY, DARKSDAY, LIGHTSDAY}; singleWeatherStrong = {WEATHER_HOT_SPELL, WEATHER_DUST_STORM, WEATHER_RAIN, WEATHER_WIND, WEATHER_SNOW, WEATHER_THUNDER, WEATHER_AURORAS, WEATHER_GLOOM}; doubleWeatherStrong = {WEATHER_HEAT_WAVE, WEATHER_SAND_STORM, WEATHER_SQUALL, WEATHER_GALES, WEATHER_BLIZZARDS, WEATHER_THUNDERSTORMS, WEATHER_STELLAR_GLARE, WEATHER_DARKNESS}; singleWeatherWeak = {WEATHER_RAIN, WEATHER_WIND, WEATHER_THUNDER, WEATHER_SNOW, WEATHER_HOT_SPELL, WEATHER_DUST_STORM, WEATHER_GLOOM, WEATHER_AURORAS}; doubleWeatherWeak = {WEATHER_SQUALL, WEATHER_GALES, WEATHER_THUNDERSTORMS, WEATHER_BLIZZARDS, WEATHER_HEAT_WAVE, WEATHER_SAND_STORM, WEATHER_DARKNESS, WEATHER_STELLAR_GLARE}; elementalObi = {MOD_FORCE_FIRE_DWBONUS, MOD_FORCE_EARTH_DWBONUS, MOD_FORCE_WATER_DWBONUS, MOD_FORCE_WIND_DWBONUS, MOD_FORCE_ICE_DWBONUS, MOD_FORCE_LIGHTNING_DWBONUS, MOD_FORCE_LIGHT_DWBONUS, MOD_FORCE_DARK_DWBONUS}; elementalObiWeak = {MOD_FORCE_WATER_DWBONUS, MOD_FORCE_WIND_DWBONUS, MOD_FORCE_LIGHTNING_DWBONUS, MOD_FORCE_ICE_DWBONUS, MOD_FORCE_FIRE_DWBONUS, MOD_FORCE_EARTH_DWBONUS, MOD_FORCE_DARK_DWBONUS, MOD_FORCE_LIGHT_DWBONUS}; spellAcc = {MOD_FIREACC, MOD_EARTHACC, MOD_WATERACC, MOD_WINDACC, MOD_ICEACC, MOD_THUNDERACC, MOD_LIGHTACC, MOD_DARKACC}; strongAffinityDmg = {MOD_FIRE_AFFINITY_DMG, MOD_EARTH_AFFINITY_DMG, MOD_WATER_AFFINITY_DMG, MOD_WIND_AFFINITY_DMG, MOD_ICE_AFFINITY_DMG, MOD_THUNDER_AFFINITY_DMG, MOD_LIGHT_AFFINITY_DMG, MOD_DARK_AFFINITY_DMG}; strongAffinityAcc = {MOD_FIRE_AFFINITY_ACC, MOD_EARTH_AFFINITY_ACC, MOD_WATER_AFFINITY_ACC, MOD_WIND_AFFINITY_ACC, MOD_ICE_AFFINITY_ACC, MOD_THUNDER_AFFINITY_ACC, MOD_LIGHT_AFFINITY_ACC, MOD_DARK_AFFINITY_ACC}; resistMod = {MOD_FIRERES, MOD_EARTHRES, MOD_WATERRES, MOD_WINDRES, MOD_ICERES, MOD_THUNDERRES, MOD_LIGHTRES, MOD_DARKRES}; defenseMod = {MOD_FIREDEF, MOD_EARTHDEF, MOD_WATERDEF, MOD_WINDDEF, MOD_ICEDEF, MOD_THUNDERDEF, MOD_LIGHTDEF, MOD_DARKDEF}; absorbMod = {MOD_FIRE_ABSORB, MOD_EARTH_ABSORB, MOD_WATER_ABSORB, MOD_WIND_ABSORB, MOD_ICE_ABSORB, MOD_LTNG_ABSORB, MOD_LIGHT_ABSORB, MOD_DARK_ABSORB}; nullMod = {MOD_FIRE_NULL, MOD_EARTH_NULL, MOD_WATER_NULL, MOD_WIND_NULL, MOD_ICE_NULL, MOD_LTNG_NULL, MOD_LIGHT_NULL, MOD_DARK_NULL}; blmMerit = {MERIT_FIRE_MAGIC_POTENCY, MERIT_EARTH_MAGIC_POTENCY, MERIT_WATER_MAGIC_POTENCY, MERIT_WIND_MAGIC_POTENCY, MERIT_ICE_MAGIC_POTENCY, MERIT_LIGHTNING_MAGIC_POTENCY}; rdmMerit = {MERIT_FIRE_MAGIC_ACCURACY, MERIT_EARTH_MAGIC_ACCURACY, MERIT_WATER_MAGIC_ACCURACY, MERIT_WIND_MAGIC_ACCURACY, MERIT_ICE_MAGIC_ACCURACY, MERIT_LIGHTNING_MAGIC_ACCURACY}; blmAMIIMerit = {MERIT_FLARE_II, MERIT_QUAKE_II, MERIT_FLOOD_II, MERIT_TORNADO_II, MERIT_FREEZE_II, MERIT_BURST_II}; barSpells = {EFFECT_BARFIRE, EFFECT_BARSTONE, EFFECT_BARWATER, EFFECT_BARAERO, EFFECT_BARBLIZZARD, EFFECT_BARTHUNDER}; -- USED FOR DAMAGING MAGICAL SPELLS (Stages 1 and 2 in Calculating Magic Damage on wiki) --Calculates magic damage using the standard magic damage calc. --Does NOT handle resistance. -- Inputs: -- V - The base damage of the spell -- M - The INT multiplier of the spell -- skilltype - The skill ID of the spell. -- atttype - The attribute type (usually MOD_INT , except for things like Banish which is MOD_MND) -- hasMultipleTargetReduction - true ifdamage is reduced on AoE. False otherwise (e.g. Charged Whisker vs -ga3 spells) -- -- Output: -- The total damage, before resistance and before equipment (so no HQ staff bonus worked out here). SOFT_CAP = 60; --guesstimated HARD_CAP = 120; --guesstimated function calculateMagicDamage(V,M,player,spell,target,skilltype,atttype,hasMultipleTargetReduction) local dint = player:getStat(atttype) - target:getStat(atttype); local dmg = V; if (dint<=0) then --ifdINT penalises, it's always M=1 dmg = dmg + dint; if (dmg <= 0) then --dINT penalty cannot result in negative damage (target absorption) return 0; end elseif (dint > 0 and dint <= SOFT_CAP) then --The standard calc, most spells hit this dmg = dmg + (dint*M); elseif (dint > 0 and dint > SOFT_CAP and dint < HARD_CAP) then --After SOFT_CAP, INT is only half effective dmg = dmg + SOFT_CAP*M + ((dint-SOFT_CAP)*M)/2; elseif (dint > 0 and dint > SOFT_CAP and dint >= HARD_CAP) then --After HARD_CAP, INT has no effect. dmg = dmg + HARD_CAP*M; end if (skilltype == DIVINE_MAGIC_SKILL and target:isUndead()) then -- 150% bonus damage dmg = dmg * 1.5; end -- printf("dmg: %d dint: %d\n", dmg, dint); return dmg; end; function doBoostGain(caster,target,spell,effect) local duration = 300; if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end --calculate potency local magicskill = target:getSkillLevel(ENHANCING_MAGIC_SKILL); local potency = math.floor((magicskill - 300) / 10) + 5; if (potency > 25) then potency = 25; elseif (potency < 5) then potency = 5; end --printf("BOOST-GAIN: POTENCY = %d", potency); --Only one Boost Effect can be active at once, so if the player has any we have to cancel & overwrite local effectOverwrite = {80, 81, 82, 83, 84, 85, 86}; for i, effect in ipairs(effectOverwrite) do --printf("BOOST-GAIN: CHECKING FOR EFFECT %d...",effect); if (caster:hasStatusEffect(effect)) then --printf("BOOST-GAIN: HAS EFFECT %d, DELETING...",effect); caster:delStatusEffect(effect); end end if (target:addStatusEffect(effect,potency,0,duration)) then spell:setMsg(230); else spell:setMsg(75); end end; function doEnspell(caster,target,spell,effect) if (effect==EFFECT_BLOOD_WEAPON) then target:addStatusEffect(EFFECT_BLOOD_WEAPON,1,0,30); return; end local duration = 180; if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end --calculate potency local magicskill = target:getSkillLevel(ENHANCING_MAGIC_SKILL); local potency = 3 + math.floor((6*magicskill)/100); if (magicskill>200) then potency = 5 + math.floor((5*magicskill)/100); end if (target:addStatusEffect(effect,potency,0,duration)) then spell:setMsg(230); else spell:setMsg(75); end end; --------------------------------- -- getCurePower returns the caster's cure power -- getCureFinal returns the final cure amount -- Source: http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html --------------------------------- function getCurePower(caster,isBlueMagic) local MND = caster:getStat(MOD_MND); local VIT = caster:getStat(MOD_VIT); local skill = caster:getSkillLevel(HEALING_MAGIC_SKILL) + caster:getMod(MOD_HEALING); local power = math.floor(MND/2) + math.floor(VIT/4) + skill; return power; end; function getCurePowerOld(caster) local MND = caster:getStat(MOD_MND); local VIT = caster:getStat(MOD_VIT); local skill = caster:getSkillLevel(HEALING_MAGIC_SKILL) + caster:getMod(MOD_HEALING);--it's healing magic skill for the BLU cures as well local power = ((3 * MND) + VIT + (3 * math.floor(skill/5))); return power; end; function getBaseCure(power,divisor,constant,basepower) return ((power - basepower) / divisor) + constant; end; function getBaseCureOld(power,divisor,constant) return (power / 2) / divisor + constant; end; function getCureFinal(caster,spell,basecure,minCure,isBlueMagic) if (basecure < minCure) then basecure = minCure; end local potency = 1 + (caster:getMod(MOD_CURE_POTENCY) / 100); if (potency > 1.5) then potency = 1.5; end local dSeal = 1; if (caster:hasStatusEffect(EFFECT_DIVINE_SEAL)) then dSeal = 2; end local rapture = 1; if (isBlueMagic == false) then --rapture doesn't affect BLU cures as they're not white magic if (caster:hasStatusEffect(EFFECT_RAPTURE)) then rapture = 1.5 + caster:getMod(MOD_RAPTURE_AMOUNT)/100; caster:delStatusEffectSilent(EFFECT_RAPTURE); end end local dayWeatherBonus = 1; local ele = spell:getElement(); local castersWeather = caster:getWeather(); if (castersWeather == singleWeatherStrong[ele]) then if (caster:getMod(MOD_IRIDESCENCE) >= 1) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end end if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end elseif (castersWeather == singleWeatherWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus - 0.10; end elseif (castersWeather == doubleWeatherStrong[ele]) then if (caster:getMod(MOD_IRIDESCENCE) >= 1) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end end if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.25; end elseif (castersWeather == doubleWeatherWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus - 0.25; end end local dayElement = VanadielDayElement(); if (dayElement == dayStrong[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end elseif (dayElement == dayWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus - 0.10; end end if (dayWeatherBonus > 1.4) then dayWeatherBonus = 1.4; end local final = math.floor(math.floor(math.floor(math.floor(basecure) * potency) * dayWeatherBonus) * rapture) * dSeal; return final; end; function getCureAsNukeFinal(caster,spell,power,divisor,constant,basepower) return getCureFinal(caster,spell,power,divisor,constant,basepower); end; ----------------------------------- -- Returns the staff bonus for the caster and spell. ----------------------------------- -- affinities that strengthen/weaken the index element function AffinityBonusDmg(caster,ele) local affinity = caster:getMod(strongAffinityDmg[ele]); local bonus = 1.00 + affinity * 0.05; -- 5% per level of affinity -- print(bonus); return bonus; end; function AffinityBonusAcc(caster,ele) local affinity = caster:getMod(strongAffinityAcc[ele]); local bonus = 0 + affinity * 10; -- 10 acc per level of affinity -- print(bonus); return bonus; end; -- USED FOR DAMAGING MAGICAL SPELLS. Stage 3 of Calculating Magic Damage on wiki -- Reduces damage ifit resists. -- -- Output: -- The factor to multiply down damage (1/2 1/4 1/8 1/16) - In this format so this func can be used for enfeebs on duration. function applyResistance(player,spell,target,diff,skill,bonus) return applyResistanceEffect(player, spell, target, diff, skill, bonus, nil); end; -- USED FOR Status Effect Enfeebs (blind, slow, para, etc.) -- Output: -- The factor to multiply down duration (1/2 1/4 1/8 1/16) function applyResistanceEffect(player,spell,target,diff,skill,bonus,effect) -- If Stymie is active, as long as the mob is not immune then the effect is not resisted if (effect ~= nil) then -- Dispel's script doesn't have an "effect" to send here, nor should it. if (skill == ENFEEBLING_MAGIC_SKILL and player:hasStatusEffect(EFFECT_STYMIE) and target:canGainStatusEffect(effect)) then player:delStatusEffect(EFFECT_STYMIE); return 1; end end if (skill == SINGING_SKILL and player:hasStatusEffect(EFFECT_TROUBADOUR)) then if (math.random(0,99) < player:getMerit(MERIT_TROUBADOUR)-25) then return 1.0; end end local element = spell:getElement(); local percentBonus = 0; local magicaccbonus = getSpellBonusAcc(player, target, spell); if (diff > 10) then magicaccbonus = magicaccbonus + 10 + (diff - 10)/2; else magicaccbonus = magicaccbonus + diff; end if (bonus ~= nil) then magicaccbonus = magicaccbonus + bonus; end if(effect ~= nil) then percentBonus = percentBonus - getEffectResistance(target, effect); end local p = getMagicHitRate(player, target, skill, element, percentBonus, magicaccbonus); return getMagicResist(p); end; -- Applies resistance for things that may not be spells - ie. Quick Draw function applyResistanceAbility(player,target,element,skill,bonus) local p = getMagicHitRate(player, target, skill, element, 0, bonus); return getMagicResist(p); end; -- Applies resistance for additional effects function applyResistanceAddEffect(player,target,element,bonus) local p = getMagicHitRate(player, target, 0, element, 0, bonus); return getMagicResist(p); end; function getMagicHitRate(caster, target, skillType, element, percentBonus, bonusAcc) -- resist everything if magic shield is active if (target:hasStatusEffect(EFFECT_MAGIC_SHIELD, 0)) then return 0; end local magiceva = 0; if (bonusAcc == nil) then bonusAcc = 0; end -- Get the base acc (just skill + skill mod (79 + skillID = ModID) + magic acc mod) local magicacc = caster:getMod(MOD_MACC) + caster:getILvlMacc(); if (skillType ~= 0) then magicacc = magicacc + caster:getSkillLevel(skillType) + caster:getMod(79 + skillType); else -- for mob skills / additional effects which don't have a skill magicacc = magicacc + utils.getSkillLvl(1, caster:getMainLvl()); end local resMod = 0; -- Some spells may possibly be non elemental, but have status effects. if (element ~= ELE_NONE) then resMod = target:getMod(resistMod[element]); -- Add acc for elemental affinity accuracy and element specific accuracy local affinityBonus = AffinityBonusAcc(caster, element); local elementBonus = caster:getMod(spellAcc[element]); -- print(elementBonus); bonusAcc = bonusAcc + affinityBonus + elementBonus; end -- Base magic evasion (base magic evasion plus resistances(players), plus elemental defense(mobs) local magiceva = target:getMod(MOD_MEVA) + resMod; magicacc = magicacc + bonusAcc; return calculateMagicHitRate(magicacc, magiceva, percentBonus, caster:getMainLvl(), target:getMainLvl()); end function calculateMagicHitRate(magicacc, magiceva, percentBonus, casterLvl, targetLvl) local p = 0; --add a scaling bonus or penalty based on difference of targets level from caster local levelDiff = utils.clamp(casterLvl - targetLvl, -5, 5); p = 70 - 0.5 * (magiceva - magicacc) + levelDiff * 3 + percentBonus; -- printf("P: %f, macc: %f, meva: %f, bonus: %d%%, leveldiff: %d", p, magicacc, magiceva, percentBonus, levelDiff); return utils.clamp(p, 5, 95); end -- Returns resistance value from given magic hit rate (p) function getMagicResist(magicHitRate) local p = magicHitRate / 100; local resist = 1; -- Resistance thresholds based on p. A higher p leads to lower resist rates, and a lower p leads to higher resist rates. local half = (1 - p); local quart = ((1 - p)^2); local eighth = ((1 - p)^3); local sixteenth = ((1 - p)^4); -- print("HALF: "..half); -- print("QUART: "..quart); -- print("EIGHTH: "..eighth); -- print("SIXTEENTH: "..sixteenth); local resvar = math.random(); -- Determine final resist based on which thresholds have been crossed. if (resvar <= sixteenth) then resist = 0.0625; --printf("Spell resisted to 1/16!!! Threshold = %u",sixteenth); elseif (resvar <= eighth) then resist = 0.125; --printf("Spell resisted to 1/8! Threshold = %u",eighth); elseif (resvar <= quart) then resist = 0.25; --printf("Spell resisted to 1/4. Threshold = %u",quart); elseif (resvar <= half) then resist = 0.5; --printf("Spell resisted to 1/2. Threshold = %u",half); else resist = 1.0; --printf("1.0"); end return resist; end -- Returns the amount of resistance the -- target has to the given effect (stun, sleep, etc..) function getEffectResistance(target, effect) local effectres = 0; if (effect == EFFECT_SLEEP_I or effect == EFFECT_SLEEP_II) then effectres = MOD_SLEEPRES; elseif(effect == EFFECT_LULLABY) then effectres = MOD_LULLABYRES; elseif (effect == EFFECT_POISON) then effectres = MOD_POISONRES; elseif (effect == EFFECT_PARALYZE) then effectres = MOD_PARALYZERES; elseif (effect == EFFECT_BLINDNESS) then effectres = MOD_BLINDRES elseif (effect == EFFECT_SILENCE) then effectres = MOD_SILENCERES; elseif (effect == EFFECT_PLAGUE or effect == EFFECT_DISEASE) then effectres = MOD_VIRUSRES; elseif (effect == EFFECT_PETRIFICATION) then effectres = MOD_PETRIFYRES; elseif (effect == EFFECT_BIND) then effectres = MOD_BINDRES; elseif (effect == EFFECT_CURSE_I or effect == EFFECT_CURSE_II or effect == EFFECT_BANE) then effectres = MOD_CURSERES; elseif (effect == EFFECT_WEIGHT) then effectres = MOD_GRAVITYRES; elseif (effect == EFFECT_SLOW or effect == EFFECT_ELEGY) then effectres = MOD_SLOWRES; elseif (effect == EFFECT_STUN) then effectres = MOD_STUNRES; elseif (effect == EFFECT_CHARM) then effectres = MOD_CHARMRES; elseif (effect == EFFECT_AMNESIA) then effectres = MOD_AMNESIARES; end if (effectres ~= 0) then return target:getMod(effectres); end return 0; end; -- Returns the bonus magic accuracy for any spell function getSpellBonusAcc(caster, target, spell) local magicAccBonus = 0; local spellId = spell:getID(); local element = spell:getElement(); local castersWeather = caster:getWeather(); local skill = spell:getSkillType(); local spellGroup = spell:getSpellGroup(); if caster:hasStatusEffect(EFFECT_ALTRUISM) and spellGroup == SPELLGROUP_WHITE then magicAccBonus = magicAccBonus + caster:getStatusEffect(EFFECT_ALTRUISM):getPower(); end if caster:hasStatusEffect(EFFECT_FOCALIZATION) and spellGroup == SPELLGROUP_BLACK then magicAccBonus = magicAccBonus + caster:getStatusEffect(EFFECT_FOCALIZATION):getPower(); end local skillchainTier, skillchainCount = FormMagicBurst(element, target); --add acc for BLM AMII spells if (spellId == 205 or spellId == 207 or spellId == 209 or spellId == 211 or spellId == 213 or spellId == 215) then -- no bonus if the caster has zero merit investment - don't want to give them a negative bonus if (caster:getMerit(blmAMIIMerit[element]) ~= 0) then -- bonus value granted by merit is 1; subtract 1 since unlock doesn't give an accuracy bonus magicAccBonus = magicAccBonus + (caster:getMerit(blmAMIIMerit[element]) - 1) * 5; end end --add acc for skillchains if (skillchainTier > 0) then magicAccBonus = magicAccBonus + 25; end --Add acc for klimaform if (caster:hasStatusEffect(EFFECT_KLIMAFORM) and (castersWeather == singleWeatherStrong[element] or castersWeather == doubleWeatherStrong[element])) then magicAccBonus = magicAccBonus + 15; end --Add acc for dark seal if (skill == DARK_MAGIC_SKILL and caster:hasStatusEffect(EFFECT_DARK_SEAL)) then magicAccBonus = magicAccBonus + 256; end --add acc for RDM group 1 merits if (element > 0 and element <= 6) then magicAccBonus = magicAccBonus + caster:getMerit(rdmMerit[element]); end -- BLU mag acc merits - nuke acc is handled in bluemagic.lua if (skill == BLUE_SKILL) then magicAccBonus = magicAccBonus + caster:getMerit(MERIT_MAGICAL_ACCURACY); end return magicAccBonus; end; function handleAfflatusMisery(caster, spell, dmg) if (caster:hasStatusEffect(EFFECT_AFFLATUS_MISERY)) then local misery = caster:getMod(MOD_AFFLATUS_MISERY); local miseryMax = caster:getMaxHP() / 4; -- BGwiki puts the boost capping at 200% bonus at 1/4th max HP. if (misery > miseryMax) then misery = miseryMax; end; -- Damage is 2x at boost cap. local boost = 1 + (misery / miseryMax); dmg = math.floor(dmg * boost); -- printf("AFFLATUS MISERY: Damage boosted by %f to %d", boost, dmg); --Afflatus Mod is Used Up... caster:setMod(MOD_AFFLATUS_MISERY, 0) end return dmg; end; function finalMagicAdjustments(caster,target,spell,dmg) --Handles target's HP adjustment and returns UNSIGNED dmg (absorb message is set in this function) -- handle multiple targets if (caster:isSpellAoE(spell:getID())) then local total = spell:getTotalTargets(); if (total > 9) then -- ga spells on 10+ targets = 0.4 dmg = dmg * 0.4; elseif (total > 1) then -- -ga spells on 2 to 9 targets = 0.9 - 0.05T where T = number of targets dmg = dmg * (0.9 - 0.05 * total); end -- kill shadows -- target:delStatusEffect(EFFECT_COPY_IMAGE); -- target:delStatusEffect(EFFECT_BLINK); else -- this logic will eventually be moved here -- dmg = utils.takeShadows(target, dmg, 1); -- if (dmg == 0) then -- spell:setMsg(31); -- return 1; -- end end local skill = spell:getSkillType(); if (skill == ELEMENTAL_MAGIC_SKILL) then dmg = dmg * ELEMENTAL_POWER; elseif (skill == DARK_MAGIC_SKILL) then dmg = dmg * DARK_POWER; elseif (skill == NINJUTSU_SKILL) then dmg = dmg * NINJUTSU_POWER; elseif (skill == DIVINE_MAGIC_SKILL) then dmg = dmg * DIVINE_POWER; end dmg = target:magicDmgTaken(dmg); if (dmg > 0) then dmg = dmg - target:getMod(MOD_PHALANX); dmg = utils.clamp(dmg, 0, 99999); end --handling stoneskin dmg = utils.stoneskin(target, dmg); dmg = utils.clamp(dmg, -99999, 99999); if (dmg < 0) then dmg = target:addHP(-dmg); spell:setMsg(7); else target:delHP(dmg); target:handleAfflatusMiseryDamage(dmg); target:updateEnmityFromDamage(caster,dmg); -- Only add TP if the target is a mob if (target:getObjType() ~= TYPE_PC) then target:addTP(100); end end return dmg; end; function finalMagicNonSpellAdjustments(caster,target,ele,dmg) --Handles target's HP adjustment and returns SIGNED dmg (negative values on absorb) dmg = target:magicDmgTaken(dmg); if (dmg > 0) then dmg = dmg - target:getMod(MOD_PHALANX); dmg = utils.clamp(dmg, 0, 99999); end --handling stoneskin dmg = utils.stoneskin(target, dmg); dmg = utils.clamp(dmg, -99999, 99999); if (dmg < 0) then dmg = -(target:addHP(-dmg)); else target:delHP(dmg); end --Not updating enmity from damage, as this is primarily used for additional effects (which don't generate emnity) -- in the case that updating enmity is needed, do it manually after calling this --target:updateEnmityFromDamage(caster,dmg); return dmg; end; function adjustForTarget(target,dmg,ele) if (dmg > 0 and math.random(0,99) < target:getMod(absorbMod[ele])) then return -dmg; end if (math.random(0,99) < target:getMod(nullMod[ele])) then return 0; end --Moved non element specific absorb and null mod checks to core --TODO: update all lua calls to magicDmgTaken with appropriate element and remove this function return dmg; end; function calculateMagicBurst(caster, spell, target) local burst = 1.0; if (spell:getSpellGroup() == 3 and not caster:hasStatusEffect(EFFECT_BURST_AFFINITY)) then return burst; end local skillchainTier, skillchainCount = FormMagicBurst(spell:getElement(), target); if (skillchainTier > 0) then if (skillchainCount == 1) then burst = 1.3; elseif (skillchainCount == 2) then burst = 1.35; elseif (skillchainCount == 3) then burst = 1.40; elseif (skillchainCount == 4) then burst = 1.45; elseif (skillchainCount == 5) then burst = 1.50; else -- Something strange is going on if this occurs. burst = 1.0; end --add burst bonus for BLM AMII spells if (spell:getID() == 205 or spell:getID() == 207 or spell:getID() == 209 or spell:getID() == 211 or spell:getID() == 213 or spell:getID() == 215) then if (caster:getMerit(blmAMIIMerit[spell:getElement()]) ~= 0) then -- no bonus if the caster has zero merit investment - don't want to give them a negative bonus burst = burst + (caster:getMerit(blmAMIIMerit[spell:getElement()]) - 1) * 0.03; -- bonus value granted by merit is 1; subtract 1 since unlock doesn't give a magic burst bonus -- print((caster:getMerit(blmAMIIMerit[spell:getElement()]) - 1) * 0.03) end end end -- Add in Magic Burst Bonus Modifier if (burst > 1) then burst = burst + (caster:getMod(MOD_MAG_BURST_BONUS) / 100); end return burst; end; function addBonuses(caster, spell, target, dmg, bonusmab) local ele = spell:getElement(); local affinityBonus = AffinityBonusDmg(caster, ele); dmg = math.floor(dmg * affinityBonus); if (bonusmab == nil) then bonusmab = 0; end local magicDefense = getElementalDamageReduction(target, ele); dmg = math.floor(dmg * magicDefense); local dayWeatherBonus = 1.00; local weather = caster:getWeather(); if (weather == singleWeatherStrong[ele]) then if (caster:getMod(MOD_IRIDESCENCE) >= 1) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus + 0.10; end end if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus + 0.10; end elseif (caster:getWeather() == singleWeatherWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus - 0.10; end elseif (weather == doubleWeatherStrong[ele]) then if (caster:getMod(MOD_IRIDESCENCE) >= 1) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus + 0.10; end end if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus + 0.25; end elseif (weather == doubleWeatherWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus - 0.25; end end local dayElement = VanadielDayElement(); if (dayElement == dayStrong[ele]) then dayWeatherBonus = dayWeatherBonus + caster:getMod(MOD_DAY_NUKE_BONUS)/100; -- sorc. tonban(+1)/zodiac ring if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus + 0.10; end elseif (dayElement == dayWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1 or isHelixSpell(spell)) then dayWeatherBonus = dayWeatherBonus - 0.10; end end if dayWeatherBonus > 1.4 then dayWeatherBonus = 1.4; end dmg = math.floor(dmg * dayWeatherBonus); local burst = calculateMagicBurst(caster, spell, target); if (burst > 1.0) then spell:setMsg(spell:getMagicBurstMessage()); -- "Magic Burst!" end dmg = math.floor(dmg * burst); local mabbonus = 0; if (spell:getID() >= 245 and spell:getID() <= 248) then -- Drain/Aspir (II) mabbonus = 1 + caster:getMod(MOD_ENH_DRAIN_ASPIR)/100; -- print(mabbonus); else local mab = caster:getMod(MOD_MATT) + bonusmab; local mab_crit = caster:getMod(MOD_MAGIC_CRITHITRATE); if( math.random(1,100) < mab_crit ) then mab = mab + ( 10 + caster:getMod(MOD_MAGIC_CRIT_DMG_INCREASE ) ); end local mdefBarBonus = 0; if (ele > 0 and ele <= 6) then mab = mab + caster:getMerit(blmMerit[ele]); if (target:hasStatusEffect(barSpells[ele])) then -- bar- spell magic defense bonus mdefBarBonus = target:getStatusEffect(barSpells[ele]):getSubPower(); end end mabbonus = (100 + mab) / (100 + target:getMod(MOD_MDEF) + mdefBarBonus); end if (mabbonus < 0) then mabbonus = 0; end dmg = math.floor(dmg * mabbonus); if (caster:hasStatusEffect(EFFECT_EBULLIENCE)) then dmg = dmg * 1.2 + caster:getMod(MOD_EBULLIENCE_AMOUNT)/100; caster:delStatusEffectSilent(EFFECT_EBULLIENCE); end dmg = math.floor(dmg); -- print(affinityBonus); -- print(speciesReduction); -- print(dayWeatherBonus); -- print(burst); -- print(mab); -- print(magicDmgMod); return dmg; end; function addBonusesAbility(caster, ele, target, dmg, params) local affinityBonus = AffinityBonusDmg(caster, ele); dmg = math.floor(dmg * affinityBonus); local magicDefense = getElementalDamageReduction(target, ele); dmg = math.floor(dmg * magicDefense); local dayWeatherBonus = 1.00; local weather = caster:getWeather(); if (weather == singleWeatherStrong[ele]) then if (caster:getMod(MOD_IRIDESCENCE) >= 1) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end end if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end elseif (caster:getWeather() == singleWeatherWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus - 0.10; end elseif (weather == doubleWeatherStrong[ele]) then if (caster:getMod(MOD_IRIDESCENCE) >= 1) then if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end end if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.25; end elseif (weather == doubleWeatherWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus - 0.25; end end local dayElement = VanadielDayElement(); if (dayElement == dayStrong[ele]) then dayWeatherBonus = dayWeatherBonus + caster:getMod(MOD_DAY_NUKE_BONUS)/100; -- sorc. tonban(+1)/zodiac ring if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus + 0.10; end elseif (dayElement == dayWeak[ele]) then if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1) then dayWeatherBonus = dayWeatherBonus - 0.10; end end if dayWeatherBonus > 1.4 then dayWeatherBonus = 1.4; end dmg = math.floor(dmg * dayWeatherBonus); local mab = 1; local mdefBarBonus = 0; if (ele > 0 and ele <= 6 and target:hasStatusEffect(barSpells[ele])) then -- bar- spell magic defense bonus mdefBarBonus = target:getStatusEffect(barSpells[ele]):getSubPower(); end if (params ~= nil and params.bonusmab ~= nil and params.includemab == true) then mab = (100 + caster:getMod(MOD_MATT) + params.bonusmab) / (100 + target:getMod(MOD_MDEF) + mdefBarBonus); elseif (params == nil or (params ~= nil and params.includemab == true)) then mab = (100 + caster:getMod(MOD_MATT)) / (100 + target:getMod(MOD_MDEF) + mdefBarBonus); end if (mab < 0) then mab = 0; end dmg = math.floor(dmg * mab); -- print(affinityBonus); -- print(speciesReduction); -- print(dayWeatherBonus); -- print(burst); -- print(mab); -- print(magicDmgMod); return dmg; end; -- get elemental damage reduction function getElementalDamageReduction(target, element) local defense = 1; if (element > 0) then defense = 1 - (target:getMod(defenseMod[element]) / 256); return utils.clamp(defense, 0.0, 2.0); end return defense; end --------------------------------------------------------------------- -- Elemental Debuff Potency functions --------------------------------------------------------------------- function getElementalDebuffDOT(INT) local DOT = 0; if (INT<= 39) then DOT = 1; elseif (INT <= 69) then DOT = 2; elseif (INT <= 99) then DOT = 3; elseif (INT <= 149) then DOT = 4; else DOT = 5; end return DOT; end; function getElementalDebuffStatDownFromDOT(dot) local stat_down = 0; if (dot == 1) then stat_down = 5; elseif (dot == 2) then stat_down = 7; elseif (dot == 3) then stat_down = 9; elseif (dot == 4) then stat_down = 11; else stat_down = 13; end return stat_down; end; function getHelixDuration(caster) --Dark Arts will further increase Helix duration, but testing is ongoing. local casterLevel = caster:getMainLvl(); local duration = 30; --fallthrough if (casterLevel <= 39) then duration = 30; elseif (casterLevel <= 59) then duration = 60; elseif (casterLevel <= 99) then duration = 90; end return duration; end; function isHelixSpell(spell) --Dark Arts will further increase Helix duration, but testing is ongoing. local id = spell:getID(); if id >= 278 and id <= 285 then return true; end return false; end; function handleThrenody(caster, target, spell, basePower, baseDuration, modifier) -- Process resitances local staff = AffinityBonusAcc(caster, spell:getElement()); -- print("staff=" .. staff); local dCHR = (caster:getStat(MOD_CHR) - target:getStat(MOD_CHR)); -- print("dCHR=" .. dCHR); local resm = applyResistance(caster, spell, target, dCHR, SINGING_SKILL, staff); -- print("rsem=" .. resm); if (resm < 0.5) then -- print("resm resist"); spell:setMsg(85); return EFFECT_THRENODY; end -- Remove previous Threnody target:delStatusEffect(EFFECT_THRENODY); local iBoost = caster:getMod(MOD_THRENODY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); local power = basePower + iBoost*5; local duration = baseDuration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Set spell message and apply status effect target:addStatusEffect(EFFECT_THRENODY, power, 0, duration, 0, modifier, 0); return EFFECT_THRENODY; end; function handleNinjutsuDebuff(caster, target, spell, basePower, baseDuration, modifier) -- Add new target:addStatusEffectEx(EFFECT_NINJUTSU_ELE_DEBUFF, 0, basePower, 0, baseDuration, 0, modifier, 0); return EFFECT_NINJUTSU_ELE_DEBUFF; end; -- Returns true if you can overwrite the effect -- Example: canOverwrite(target, EFFECT_SLOW, 25) function canOverwrite(target, effect, power, mod) mod = mod or 1; local statusEffect = target:getStatusEffect(effect); -- effect not found so overwrite if (statusEffect == nil) then return true; end -- overwrite if its weaker if (statusEffect:getPower()*mod > power) then return false; end return true; end function doElementalNuke(caster, spell, target, spellParams) local DMG = 0; local V = 0; local M = 0; local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local hasMultipleTargetReduction = spellParams.hasMultipleTargetReduction; --still unused!!! local resistBonus = spellParams.resistBonus; local mDMG = caster:getMod(MOD_MAGIC_DAMAGE); --[[ Calculate base damage: D = mDMG + V + (dINT × M) D is then floored For dINT reduce by amount factored into the V value (example: at 134 INT, when using V100 in the calculation, use dINT = 134-100 = 34) ]] if (dINT <= 49) then V = spellParams.V0; M = spellParams.M0; DMG = math.floor(DMG + mDMG + V + (dINT * M)); if (DMG <= 0) then return 0; end elseif (dINT >= 50 and dINT <= 99) then V = spellParams.V50; M = spellParams.M50; DMG = math.floor(DMG + mDMG + V + ((dINT - 50) * M)); elseif (dINT >= 100 and dINT <= 199) then V = spellParams.V100; M = spellParams.M100; DMG = math.floor(DMG + mDMG + V + ((dINT - 100) * M)); elseif (dINT > 199) then V = spellParams.V200; M = spellParams.M200; DMG = math.floor(DMG + mDMG + V + ((dINT - 200) * M)); end --get resist multiplier (1x if no resist) local diff = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistance(caster, spell, target, diff, ELEMENTAL_MAGIC_SKILL, resistBonus); --get the resisted damage DMG = DMG * resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) DMG = addBonuses(caster, spell, target, DMG); --add in target adjustment local ele = spell:getElement(); DMG = adjustForTarget(target, DMG, ele); --add in final adjustments DMG = finalMagicAdjustments(caster, target, spell, DMG); return DMG; end function doDivineNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) return doNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus,DIVINE_MAGIC_SKILL,MOD_MND); end function doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus,mabBonus) mabBonus = mabBonus or 0; mabBonus = mabBonus + caster:getMod(MOD_NIN_NUKE_BONUS); -- "enhances ninjutsu damage" bonus if (caster:hasStatusEffect(EFFECT_INNIN) and caster:isBehind(target, 23)) then -- Innin mag atk bonus from behind, guesstimating angle at 23 degrees mabBonus = mabBonus + caster:getStatusEffect(EFFECT_INNIN):getPower(); end return doNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus,NINJUTSU_SKILL,MOD_INT,mabBonus); end function doNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus,skill,modStat,mabBonus) --calculate raw damage local dmg = calculateMagicDamage(V,M,caster,spell,target,skill,modStat,hasMultipleTargetReduction); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(modStat)-target:getStat(modStat),skill,resistBonus); --get the resisted damage dmg = dmg*resist; if (skill == NINJUTSU_SKILL) then if (caster:getMainJob() == JOB_NIN) then -- NIN main gets a bonus to their ninjutsu nukes local ninSkillBonus = 100; if (spell:getID() % 3 == 2) then -- ichi nuke spell ids are 320, 323, 326, 329, 332, and 335 ninSkillBonus = 100 + math.floor((caster:getSkillLevel(SKILL_NIN) - 50)/2); -- getSkillLevel includes bonuses from merits and modifiers (ie. gear) elseif (spell:getID() % 3 == 0) then -- ni nuke spell ids are 1 more than their corresponding ichi spell ninSkillBonus = 100 + math.floor((caster:getSkillLevel(SKILL_NIN) - 125)/2); else -- san nuke spell, also has ids 1 more than their corresponding ni spell ninSkillBonus = 100 + math.floor((caster:getSkillLevel(SKILL_NIN) - 275)/2); end ninSkillBonus = utils.clamp(ninSkillBonus, 100, 200); -- bonus caps at +100%, and does not go negative dmg = dmg * ninSkillBonus/100; end -- boost with Futae if (caster:hasStatusEffect(EFFECT_FUTAE)) then dmg = math.floor(dmg * 1.50); caster:delStatusEffect(EFFECT_FUTAE); end end --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,mabBonus); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); return dmg; end function doDivineBanishNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local skill = DIVINE_MAGIC_SKILL; local modStat = MOD_MND; --calculate raw damage local dmg = calculateMagicDamage(V,M,caster,spell,target,skill,modStat,hasMultipleTargetReduction); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(modStat)-target:getStat(modStat),skill,resistBonus); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --handling afflatus misery dmg = handleAfflatusMisery(caster, spell, dmg); --add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); return dmg; end function calculateDurationForLvl(duration, spellLvl, targetLvl) if (targetLvl < spellLvl) then return duration * targetLvl / spellLvl; end return duration; end function calculateBarspellPower(caster,enhanceSkill) local meritBonus = caster:getMerit(MERIT_BAR_SPELL_EFFECT); local equipBonus = caster:getMod(MOD_BARSPELL_AMOUNT); --printf("Barspell: Merit Bonus +%d", meritBonus); if (enhanceSkill == nil or enhanceSkill < 0) then enhanceSkill = 0; end local power = 40 + 0.2 * enhanceSkill + meritBonus + equipBonus; return power; end -- Output magic hit rate for all levels function outputMagicHitRateInfo() for casterLvl = 1, 75 do printf(""); printf("-------- CasterLvl: %d", casterLvl); for lvlMod = -5, 20 do local targetLvl = casterLvl + lvlMod; if(targetLvl >= 0) then -- assume BLM spell, A+ local magicAcc = utils.getSkillLvl(6, casterLvl); -- assume default monster magic eva, D local magicEvaRank = 3; local rate = 0; local magicEva = utils.getMobSkillLvl(magicEvaRank, targetLvl); local dINT = (lvlMod + 1) * -1; if (dINT > 10) then magicAcc = magicAcc + 10 + (dINT - 10)/2; else magicAcc = magicAcc + dINT; end local magicHitRate = calculateMagicHitRate(magicAcc, magicEva, 0, casterLvl, targetLvl); printf("Lvl: %d vs %d, %d%%, MA: %d, ME: %d", casterLvl, targetLvl, magicHitRate, magicAcc, magicEva); end end end end; -- outputMagicHitRateInfo();
gpl-3.0
AlexandreCA/update
scripts/zones/Phomiuna_Aqueducts/npcs/_0rs.lua
17
1623
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: Oil lamp -- @pos -60 -23 60 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID(); player:messageSpecial(LAMP_OFFSET+1); -- earth lamp npc:openDoor(7); -- lamp animation local element = VanadielDayElement(); --printf("element: %u",element); if (element == 3) then -- wind day if (GetNPCByID(DoorOffset+1):getAnimation() == 8) then -- lamp wind open? GetNPCByID(DoorOffset-7):openDoor(15); -- Open Door _0rk end elseif (element == 1) then -- earth day if (GetNPCByID(DoorOffset-3):getAnimation() == 8) then -- lamp lightning open? GetNPCByID(DoorOffset-7):openDoor(15); -- Open Door _0rk end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/darkstar
scripts/globals/items/galette_des_rois.lua
18
1349
----------------------------------------- -- ID: 5875 -- Item: Galette Des Rois -- Food Effect: 180 Min, All Races ----------------------------------------- -- MP % 1 -- Intelligence +2 -- Random Jewel ----------------------------------------- require("scripts/globals/status"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD)) then result = 246; end if (target:getFreeSlotsCount() == 0) then result = 308; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5875); local rand = math.random(784,815); target:addItem(rand); -- Random Jewel end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPP, 1); target:addMod(MOD_INT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPP, 1); target:delMod(MOD_INT, 2); end;
gpl-3.0
paly2/minetest-minetestforfun-server
minetestforfun_game/mods/farming/compatibility.lua
4
4773
-- is Ethereal mod installed? local eth = minetest.get_modpath("ethereal") or nil -- Banana if eth then minetest.register_alias("farming_plus:banana_sapling", "ethereal:banana_tree_sapling") minetest.register_alias("farming_plus:banana_leaves", "ethereal:bananaleaves") minetest.register_alias("farming_plus:banana", "ethereal:banana") else minetest.register_alias("farming_plus:banana_sapling", "default:sapling") minetest.register_alias("farming_plus:banana_leaves", "default:leaves") minetest.register_alias("farming_plus:banana", "default:apple") end -- Carrot minetest.register_alias("farming_plus:carrot_seed", "farming:carrot") minetest.register_alias("farming_plus:carrot_1", "farming:carrot_1") minetest.register_alias("farming_plus:carrot_2", "farming:carrot_4") minetest.register_alias("farming_plus:carrot_3", "farming:carrot_6") minetest.register_alias("farming_plus:carrot", "farming:carrot_8") -- Cocoa minetest.register_alias("farming_plus:cocoa_sapling", "farming:cocoa_beans") minetest.register_alias("farming_plus:cocoa_leaves", "default:leaves") minetest.register_alias("farming_plus:cocoa", "default:apple") minetest.register_alias("farming_plus:cocoa_bean", "farming:cocoa_beans") -- Orange minetest.register_alias("farming_plus:orange_1", "farming:tomato_1") minetest.register_alias("farming_plus:orange_2", "farming:tomato_4") minetest.register_alias("farming_plus:orange_3", "farming:tomato_6") minetest.register_alias("farming_plus:orange", "farming:tomato_8") if eth then minetest.register_alias("farming_plus:orange_item", "ethereal:orange") minetest.register_alias("farming_plus:orange_seed", "ethereal:orange_tree_sapling") else minetest.register_alias("farming_plus:orange_item", "default:apple") minetest.register_alias("farming_plus:orange_seed", "default:sapling") end -- Potato minetest.register_alias("farming_plus:potato_item", "farming:potato") minetest.register_alias("farming_plus:potato_1", "farming:potato_1") minetest.register_alias("farming_plus:potato_2", "farming:potato_2") minetest.register_alias("farming_plus:potato", "farming:potato_3") minetest.register_alias("farming_plus:potato_seed", "farming:potato") -- Pumpkin minetest.register_alias("farming:pumpkin_seed", "farming:pumpkin_slice") minetest.register_alias("farming:pumpkin_face", "farming:pumpkin") minetest.register_alias("farming:pumpkin_face_light", "farming:jackolantern") minetest.register_alias("farming:big_pumpkin", "farming:pumpkin") minetest.register_alias("farming:big_pumpkin_side", "air") minetest.register_alias("farming:big_pumpkin_corner", "air") minetest.register_alias("farming:big_pumpkin_top", "air") minetest.register_alias("farming:scarecrow", "farming:pumpkin") minetest.register_alias("farming:scarecrow_bottom", "default:fence_wood") minetest.register_alias("farming:scarecrow_light", "farming:jackolantern") minetest.register_alias("farming:pumpkin_flour", "farming:pumpkin_dough") -- Rhubarb minetest.register_alias("farming_plus:rhubarb_seed", "farming:rhubarb") minetest.register_alias("farming_plus:rhubarb_1", "farming:rhubarb_1") minetest.register_alias("farming_plus:rhubarb_2", "farming:rhubarb_2") minetest.register_alias("farming_plus:rhubarb", "farming:rhubarb_3") minetest.register_alias("farming_plus:rhubarb_item", "farming:rhubarb") -- Strawberry if eth then minetest.register_alias("farming_plus:strawberry_item", "ethereal:strawberry") minetest.register_alias("farming_plus:strawberry_seed", "ethereal:strawberry") minetest.register_alias("farming_plus:strawberry_1", "ethereal:strawberry_1") minetest.register_alias("farming_plus:strawberry_2", "ethereal:strawberry_3") minetest.register_alias("farming_plus:strawberry_3", "ethereal:strawberry_5") minetest.register_alias("farming_plus:strawberry", "ethereal:strawberry_7") else minetest.register_alias("farming_plus:strawberry_item", "farming:raspberries") minetest.register_alias("farming_plus:strawberry_seed", "farming:raspberries") minetest.register_alias("farming_plus:strawberry_1", "farming:raspberry_1") minetest.register_alias("farming_plus:strawberry_2", "farming:raspberry_2") minetest.register_alias("farming_plus:strawberry_3", "farming:raspberry_3") minetest.register_alias("farming_plus:strawberry", "farming:raspberry_4") end -- Tomato minetest.register_alias("farming_plus:tomato_seed", "farming:tomato") minetest.register_alias("farming_plus:tomato_item", "farming:tomato") minetest.register_alias("farming_plus:tomato_1", "farming:tomato_2") minetest.register_alias("farming_plus:tomato_2", "farming:tomato_4") minetest.register_alias("farming_plus:tomato_3", "farming:tomato_6") minetest.register_alias("farming_plus:tomato", "farming:tomato_8") -- Weed minetest.register_alias("farming:weed", "default:grass_2")
unlicense
jstewart-amd/premake-core
tests/actions/vstudio/vc2010/test_manifest.lua
6
1122
-- -- tests/actions/vstudio/vc2010/test_manifest.lua -- Validate generation of Manifest block in Visual Studio 201x C/C++ projects. -- Copyright (c) 2009-2013 Jason Perkins and the Premake project -- local suite = test.declare("vs2010_manifest") local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- Setup -- local wks, prj function suite.setup() premake.action.set("vs2010") wks, prj = test.createWorkspace() kind "ConsoleApp" end local function prepare(platform) local cfg = test.getconfig(prj, "Debug", platform) vc2010.manifest(cfg) end -- -- Check the basic element structure with default settings. -- function suite.defaultSettings() files { "source/test.manifest" } prepare() test.capture [[ <Manifest> <AdditionalManifestFiles>source/test.manifest %(AdditionalManifestFiles)</AdditionalManifestFiles> </Manifest> ]] end -- -- Check that there is no manifest when using static lib -- function suite.staticLib() kind "StaticLib" files { "test.manifest" } prepare() test.isemptycapture() end
bsd-3-clause
AlexandreCA/darkstar
scripts/zones/Riverne-Site_A01/npcs/_0u4.lua
13
1348
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x20); else player:messageSpecial(SD_VERY_SMALL); end; return 1; 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
lucgagnon/ntopng
scripts/lua/examples/debug.lua
13
3427
-- -- (C) 2013 - ntop.org -- -- debug lua example -- Set package.path information to be able to require lua module dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" -- Here you can choose the type of your HTTP message {'text/html','application/json',...}. There are two main function that you can use: -- function sendHTTPHeaderIfName(mime, ifname, maxage) -- function sendHTTPHeader(mime) -- For more information please read the scripts/lua/modules/lua_utils.lua file. sendHTTPHeader('text/html; charset=iso-8859-1') ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc") dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua") print('<html><head><title>debug Lua example</title></head>') print('<body>') print('<h1>How to debug your lua scripts</h1>') print('<br><h2>How to print debug information</h2>') print('<p><h4>ntopng Lua library comes with a standard trace event features:</h4></p>') print('<p>There are five type of event:</p>') print('<ul>') print('<li> TRACE_ERROR </li>') print('<li> TRACE_WARNING </li>') print('<li> TRACE_NORMAL </li>') print('<li> TRACE_INFO </li>') print('<li> TRACE_DEBUG </li>') print('</ul>') print('<p>Use the following function to modify the current trace level.</p>') print('<pre><code>setTraceLevel(p_trace_level)</br>resetTraceLevel()</code></pre></br>') print('<p>There are two type of trace:</p>') print('<ul>') print('<li> TRACE_CONSOLE </li>') print('<li> TRACE_WEB </li>') print('</ul>') print('<p>Default: Only the TRACE_ERROR is printed.</p></br>') print('<p><h4>There are two way to print some debug information:</h4></p>') print('<ul>') print('<li> <a href="?trace=console">Trace event on the console.</a></li>') print('<li> <a href="?trace=web">Trace event on the web.</a></li>') print('</ul>') if(_GET["trace"] == "console") then print('<p><b>Code:</b><p>') print('<pre><code>traceError(TRACE_DEBUG,TRACE_CONSOLE, "Trace: ".._GET["trace"])</code></pre>') end if(_GET["trace"] == "web") then print('<p><b>Code:</b><p>') print('<pre><code>traceError(TRACE_DEBUG,TRACE_WEB, "Trace: ".._GET["trace"])</code></pre>') end if(_GET["trace"] == "console") then print('<p><b>Output:</b><p>') print('<ul><li> <b>Show ntopng console</b></li></ul>') traceError(TRACE_ERROR,TRACE_CONSOLE, "Trace: ".._GET["trace"]) end if(_GET["trace"] == "web") then print('<p><b>Output:</b><p>') print('<ul><li>') traceError(TRACE_ERROR,TRACE_WEB, "Trace: ".._GET["trace"]) print('</li></ul>') end print('</br><p><h4>Output format:</h4></p>') print('<pre><code>#date #time [#calling_function] [#filename:#currentline] #trace_level: #message</code></pre>') print('<p>NB: #calling_function will be show only if it is different from #filename:#currentline<p>') print('<br><h2>How to read and print the _GET variables</h2>') print('<p>Any lua scripts can be executed by passing one or more parameters. The simple way to get an input variable is "variable_name = _GET["variable_name"]".<br><br>Try with this: <a href="?host=192.168.1.10&myparam=myparam&var=123456">/lua/examples/debug.lua?host=192.168.1.10&myparam=myparam&var=123456</a></p>') -- Print _GET variable print('<p>') for key, value in pairs(_GET) do print(key.."="..value.."<br>") end -- printGETParameters(_GET) print('</p>') dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
gpl-3.0
jstewart-amd/premake-core
src/base/semver.lua
22
6948
local semver = { _VERSION = '1.2.1', _DESCRIPTION = 'semver for Lua', _URL = 'https://github.com/kikito/semver.lua', _LICENSE = [[ MIT LICENSE Copyright (c) 2015 Enrique García Cota Permission is hereby granted, free of charge, to any person obtaining a copy of tother 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 tother 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. ]] } local function checkPositiveInteger(number, name) assert(number >= 0, name .. ' must be a valid positive number') assert(math.floor(number) == number, name .. ' must be an integer') end local function present(value) return value and value ~= '' end -- splitByDot("a.bbc.d") == {"a", "bbc", "d"} local function splitByDot(str) str = str or "" local t, count = {}, 0 str:gsub("([^%.]+)", function(c) count = count + 1 t[count] = c end) return t end local function parsePrereleaseAndBuildWithSign(str) local prereleaseWithSign, buildWithSign = str:match("^(-[^+]+)(+.+)$") if not (prereleaseWithSign and buildWithSign) then prereleaseWithSign = str:match("^(-.+)$") buildWithSign = str:match("^(+.+)$") end assert(prereleaseWithSign or buildWithSign, ("The parameter %q must begin with + or - to denote a prerelease or a build"):format(str)) return prereleaseWithSign, buildWithSign end local function parsePrerelease(prereleaseWithSign) if prereleaseWithSign then local prerelease = prereleaseWithSign:match("^-(%w[%.%w-]*)$") assert(prerelease, ("The prerelease %q is not a slash followed by alphanumerics, dots and slashes"):format(prereleaseWithSign)) return prerelease end end local function parseBuild(buildWithSign) if buildWithSign then local build = buildWithSign:match("^%+(%w[%.%w-]*)$") assert(build, ("The build %q is not a + sign followed by alphanumerics, dots and slashes"):format(buildWithSign)) return build end end local function parsePrereleaseAndBuild(str) if not present(str) then return nil, nil end local prereleaseWithSign, buildWithSign = parsePrereleaseAndBuildWithSign(str) local prerelease = parsePrerelease(prereleaseWithSign) local build = parseBuild(buildWithSign) return prerelease, build end local function parseVersion(str) local sMajor, sMinor, sPatch, sPrereleaseAndBuild = str:match("^(%d+)%.?(%d*)%.?(%d*)(.-)$") assert(type(sMajor) == 'string', ("Could not extract version number(s) from %q"):format(str)) local major, minor, patch = tonumber(sMajor), tonumber(sMinor), tonumber(sPatch) local prerelease, build = parsePrereleaseAndBuild(sPrereleaseAndBuild) return major, minor, patch, prerelease, build end -- return 0 if a == b, -1 if a < b, and 1 if a > b local function compare(a,b) return a == b and 0 or a < b and -1 or 1 end local function compareIds(myId, otherId) if myId == otherId then return 0 elseif not myId then return -1 elseif not otherId then return 1 end local selfNumber, otherNumber = tonumber(myId), tonumber(otherId) if selfNumber and otherNumber then -- numerical comparison return compare(selfNumber, otherNumber) -- numericals are always smaller than alphanums elseif selfNumber then return -1 elseif otherNumber then return 1 else return compare(myId, otherId) -- alphanumerical comparison end end local function smallerIdList(myIds, otherIds) local myLength = #myIds local comparison for i=1, myLength do comparison = compareIds(myIds[i], otherIds[i]) if comparison ~= 0 then return comparison == -1 end -- if comparison == 0, continue loop end return myLength < #otherIds end local function smallerPrerelease(mine, other) if mine == other or not mine then return false elseif not other then return true end return smallerIdList(splitByDot(mine), splitByDot(other)) end local methods = {} function methods:nextMajor() return semver(self.major + 1, 0, 0) end function methods:nextMinor() return semver(self.major, self.minor + 1, 0) end function methods:nextPatch() return semver(self.major, self.minor, self.patch + 1) end local mt = { __index = methods } function mt:__eq(other) return self.major == other.major and self.minor == other.minor and self.patch == other.patch and self.prerelease == other.prerelease -- notice that build is ignored for precedence in semver 2.0.0 end function mt:__lt(other) if self.major ~= other.major then return self.major < other.major end if self.minor ~= other.minor then return self.minor < other.minor end if self.patch ~= other.patch then return self.patch < other.patch end return smallerPrerelease(self.prerelease, other.prerelease) -- notice that build is ignored for precedence in semver 2.0.0 end -- This works like the "pessimisstic operator" in Rubygems. -- if a and b are versions, a ^ b means "b is backwards-compatible with a" -- in other words, "it's safe to upgrade from a to b" function mt:__pow(other) if self.major == 0 then return self == other end return self.major == other.major and self.minor <= other.minor end function mt:__tostring() local buffer = { ("%d.%d.%d"):format(self.major, self.minor, self.patch) } if self.prerelease then table.insert(buffer, "-" .. self.prerelease) end if self.build then table.insert(buffer, "+" .. self.build) end return table.concat(buffer) end local function new(major, minor, patch, prerelease, build) assert(major, "At least one parameter is needed") if type(major) == 'string' then major,minor,patch,prerelease,build = parseVersion(major) end patch = patch or 0 minor = minor or 0 checkPositiveInteger(major, "major") checkPositiveInteger(minor, "minor") checkPositiveInteger(patch, "patch") local result = {major=major, minor=minor, patch=patch, prerelease=prerelease, build=build} return setmetatable(result, mt) end setmetatable(semver, { __call = function(_, ...) return new(...) end }) semver._VERSION= semver(semver._VERSION) return semver
bsd-3-clause
AlexandreCA/darkstar
scripts/zones/Selbina/npcs/Quelpia.lua
13
1782
----------------------------------- -- Area: Selbina -- NPC: Quelpia -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,QUELPIA_SHOP_DIALOG); stock = {0x1202,585, -- Scroll of Cure II 0x1203,3261, -- Scroll of Cure III 0x1208,10080, -- Scroll of Curaga II 0x120C,5178, -- Scroll of Raise 0x1215,31500, -- Scroll of Holy 0x1218,10080, -- Scroll of Dia II 0x121D,8100, -- Scroll of Banish II 0x122C,6366, -- Scroll of Protect II 0x1231,15840, -- Scroll of Shell II 0x1239,18000, -- Scroll of Haste 0x1264,4644, -- Scroll of Enfire 0x1265,3688, -- Scroll of Enblizzard 0x1266,2250, -- Scroll of Enaero 0x1267,1827, -- Scroll of Enstone 0x1268,1363, -- Scroll of Enthunder 0x1269,6366} -- Scroll of Enwater showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AlexandreCA/update
scripts/zones/Dragons_Aery/npcs/relic.lua
38
1837
----------------------------------- -- Area: Dragon's Aery -- NPC: <this space intentionally left blank> -- @pos -20 -2 61 154 ----------------------------------- package.loaded["scripts/zones/Dragons_Aery/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Dragons_Aery/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece if (player:getVar("RELIC_IN_PROGRESS") == 18275 and trade:getItemCount() == 4 and trade:hasItemQty(18275,1) and trade:hasItemQty(1573,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then player:startEvent(3,18276); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 3) then if (player:getFreeSlotsCount() < 2) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18276); player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453); else player:tradeComplete(); player:addItem(18276); player:addItem(1453,30); player:messageSpecial(ITEM_OBTAINED,18276); player:messageSpecial(ITEMS_OBTAINED,1453,30); player:setVar("RELIC_IN_PROGRESS",0); end end end;
gpl-3.0
JiessieDawn/skynet
lualib/http/internal.lua
3
4777
local table = table local type = type local sockethelper = require "http.sockethelper" local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end if #header > LIMIT then return end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end function M.request(interface, method, host, url, recvheader, header, content) local is_ws = interface.websocket local read = interface.read local write = interface.write local header_content = "" if header then if not header.host then header.host = host end for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end else header_content = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n", method, url, header_content, #content) write(data) write(content) else local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content) write(request_header) end local tmpline = {} local body = M.recvheader(read, tmpline, "") if not body then error(sockethelper.socket_error) end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = M.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = M.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end elseif code == 204 or code == 304 or code < 200 then body = "" -- See https://stackoverflow.com/questions/15991173/is-the-content-length-header-required-for-a-http-1-0-response elseif is_ws and code == 101 then -- if websocket handshake success return code, body else -- no content-length, read all body = body .. interface.readall() end end return code, body end return M
mit
AlexandreCA/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/_0rw.lua
13
1295
----------------------------------- -- Area: Phomiuna_Aqueducts -- NPC: _0rw (Oil Lamp) -- Notes: Opens south door at J-9 from inside. -- @pos 103.703 -26.180 83.000 27 ----------------------------------- package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Phomiuna_Aqueducts/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 1; if (GetNPCByID(DoorOffset):getAnimation() == 9) then if (player:getZPos() < 85) then npc:openDoor(7); -- torch animation GetNPCByID(DoorOffset):openDoor(7); -- _0rh end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
elfinlazz/melia
system/scripts/npc/dungeon/id_catacomb_01.lua
1
3196
addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", -243, 955, -3206, 18, "npc_dummy") addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", -125, 935, -2422, 18, "npc_dummy") addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", -188, 935, -1148, 18, "npc_dummy") addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", 1126, 935, -730, 18, "npc_dummy") addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", 1661.212, 887.7891, -766.8322, 18, "npc_dummy") addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", 49, 915, 1178, 18, "npc_dummy") addnpc(45132, "QUEST_LV_0200_20150317_000504", "id_catacomb_01", 454, 940, 1889, 18, "npc_dummy") addnpc(147469, "ETC_20150323_010413", "id_catacomb_01", -229.1274, 935.6871, -2565.841, 45, "npc_dummy") addnpc(147469, "ETC_20150323_010413", "id_catacomb_01", -142.8405, 936.2567, -1030.828, 45, "npc_dummy") addnpc(147366, "ETC_20150323_010414", "id_catacomb_01", -242.2459, 935.6871, -261.4104, 45, "npc_dummy") addnpc(20135, "ETC_20150323_010415", "id_catacomb_01", 1658.325, 887.5892, -621.8292, -45, "npc_dummy") addnpc(147363, "ETC_20150323_010414", "id_catacomb_01", 1658.122, 887.7968, -731.7316, 45, "npc_dummy") addnpc(147392, "ETC_20150323_010416", "id_catacomb_01", -217.5575, 960.6872, -1804.256, 0, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", -535.9864, 955.0643, 867.0446, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", -470.9926, 933.4761, 1145.751, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", -525.5616, 952.1689, 1413.986, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", -235.3258, 935.6871, 826.0167, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", -225.3825, 915.6871, 1121.134, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", -216.222, 935.6871, 1359.507, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", 44.46272, 916.152, 866.0585, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", 47.69323, 919.1976, 1128.774, 45, "npc_dummy") addnpc(20026, "ETC_20150323_010417", "id_catacomb_01", 79.6908, 937.0817, 1415.757, 45, "npc_dummy") addnpc(147366, "ETC_20150323_010414", "id_catacomb_01", -258.7648, 935.6871, 655.3992, 45, "npc_dummy") addnpc(147366, "ETC_20150323_010414", "id_catacomb_01", -243.6189, 955.6871, -3426.757, 45, "npc_dummy") addnpc(40120, "QUEST_20150317_000002", "id_catacomb_01", 1344.74, 887.0438, -1033.726, 45, "npc_dummy") addnpc(152009, "QUEST_20150428_001948", "id_catacomb_01", 1611.627, 868.5986, -955.1895, -45, "npc_dummy") addnpc(152009, "QUEST_20150428_001948", "id_catacomb_01", -641.7699, 935.6871, -615.2181, -45, "npc_dummy") addnpc(147463, "QUEST_20150428_001948", "id_catacomb_01", 995.5764, 915.9975, 2860.073, 45, "npc_dummy") addnpc(40070, "QUEST_20150317_000560", "id_catacomb_01", -174.0962, 935.6871, -2942.402, 0, "npc_dummy") addnpc(147463, "QUEST_20150428_001948", "id_catacomb_01", 99.65654, 935.6872, 1985.888, 45, "npc_dummy") addnpc(147392, "ETC_20150317_009100", "id_catacomb_01", 180.11, 935.79, -523.76, 45, "npc_dummy")
gpl-3.0
samboy/Oblige
attic/v4_walls.lua
1
15565
---------------------------------------------------------------- -- V4 WALL Layouting ---------------------------------------------------------------- -- -- Oblige Level Maker -- -- Copyright (C) 2006-2011 Andrew Apted -- -- 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 2 -- 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. -- ---------------------------------------------------------------- --[[ *** CLASS INFORMATION *** class EDGE { K, side -- identification real_len -- real length of edge corn_L, corn_R : CORNER long_L, long_R -- length allocated to corners deep_L, deep_R -- depth (sticking out) at corners usage : USAGE -- primary usage (door, window, etc) spans[] : SPAN -- allocated stuff on this edge } class SPAN { long1, long2 -- length range along edge deep1, deep2 -- depth (sticking out) FIXME: usage stuff } class CORNER { K, side -- identification concave -- true for 270 degree corners horiz, vert -- connecting sizes usage : USAGE -- primary usage } class MIDDLE { K -- section usage : USAGE } ----------------------------------------------------------------]] require 'defs' require 'util' ---- --- MINIMUM SIZES --- ------------- --- --- Door / Window / Important @ EDGE --> 192 x 64 (64 walk) --- --- Item / Switch @ MIDDLE --> 128 x 128 (64 walk) --- --- Basic wall --> 32 thick --- --- Basic corner --> 32 x 32 -- -- -- Straddlers are architecture which sits across two rooms. -- Currently there are only two kinds: DOORS and WINDOWS. -- -- The prefab to use (and hence their size) are decided before -- everything else. The actual prefab and heights will be -- decided later in the normal layout code. -- function Layout_inner_outer_tex(skin, K, K2) assert(K) if not K2 then return end local R = K.room local N = K2.room if N.kind == "REMOVED" then return end skin.wall = R.skin.wall skin.outer = N.skin.wall if R.outdoor and not N.outdoor then skin.wall = N.facade or skin.outer elseif N.outdoor and not R.outdoor then skin.outer = R.facade or skin.wall end end function Layout_add_span(E, long1, long2, deep) -- stderrf("********** add_span %s @ %s : %d\n", kind, E.K:tostr(), E.side) assert(long2 > long1) -- check if valid assert(long1 >= 16) assert(long2 <= E.real_len - 16) -- corner check if E.long_L then assert(long1 >= E.long_L) end if E.long_R then assert(long2 <= E.long_R) end for _,SP in ipairs(E.spans) do if (long2 <= SP.long1) or (long1 >= SP.long2) then -- OK else error("Layout_add_span: overlaps existing one!") end end -- create and add it local SPAN = { long1 = long1, long2 = long2, deep1 = deep, deep2 = deep, } table.insert(E.spans, SPAN) -- keep them sorted if #E.spans > 1 then table.sort(E.spans, function(A, B) return A.long1 < B.long1 end) end return SPAN end function Layout_used_walls(R) local function is_minimal_edge(skin) if not skin._long then return false end if not skin._deep then return false end return skin._long <= 192 and skin._deep <= 64 end local function possible_doors(E) local list, lock, key local C = E.usage.conn if C.lock and C.lock.kind == "KEY" then list = THEME.lock_doors lock = C.lock key = lock.key elseif C.lock and C.lock.kind == "SWITCH" then list = THEME.switch_doors lock = C.lock elseif rand.odds(20) then list = THEME.doors else list = THEME.arches end E.usage.edge_fabs = Layout_possible_prefab_from_list(list, "edge", key) end local function possible_windows(E) if E.usage.K1.room.outdoor and E.usage.K2.room.outdoor then list = THEME.fences else list = THEME.windows end E.usage.edge_fabs = Layout_possible_prefab_from_list(list, "edge") end local function create_span(E, skin, extra_skins) local long = assert(skin._long) local deep = assert(skin._deep) local long1 = int(E.real_len - long) / 2 local long2 = int(E.real_len + long) / 2 local SP = Layout_add_span(E, long1, long2, deep, prefab) if E.usage.FOOBIE then return end E.usage.FOOBIE = true if R.skin then table.insert(extra_skins, 1, R.skin) end local skins = table.copy(extra_skins) table.insert(skins, skin) local fab = Fab_create(skin._prefab) Fab_apply_skins(fab, skins) fab.room = R table.insert(R.prefabs, fab) SP.fab = fab SP.extra_skins = extra_skins local back = 0 if E.usage.kind == "window" or E.usage.kind == "door" then back = -deep -- add the straddler prefab to the other room too local N = E.K:neighbor(E.side) fab.straddler = { E = E, R2 = N.room } table.insert(N.room.prefabs, fab) end local T = Trans.edge_transform(E.K.x1, E.K.y1, E.K.x2, E.K.y2, 0, E.side, long1, long2, back, deep) Fab_transform_XY(fab, T) end local function initial_edge(E) if E.usage.kind == "door" then possible_doors(E) elseif E.usage.kind == "window" then possible_windows(E) end local fabs = assert(E.usage.edge_fabs) if fabs == "SWITCH" then fabs = assert(E.usage.lock.switches) end local fabs2 = table.copy(fabs) for name,_ in pairs(fabs) do local skin = GAME.SKINS[name] if not skin then error("No such skin: " .. tostring(name)) end if is_minimal_edge(skin) then gui.printf(" minimal_fab @ %s:%d ---> %s\n", E.K:tostr(), E.side, name) else fabs2[name] = nil end end if table.empty(fabs2) then gui.printf("E.usage =\n%s\n", table.tostr(E.usage, 2)) error("Lacking minimal prefab for: " .. tostring(E.usage.kind)) end local name = rand.key_by_probs(fabs2) E.minimal = { skin=GAME.SKINS[name] } if E.usage.kind == "door" and E.usage.conn.lock and E.usage.conn.lock.kind == "SWITCH" then E.usage.conn.lock.switches = assert(E.minimal.skin._switches) end local extra_skins = {} --!!!!!! local CRUD = { item="none", outer="COMPBLUE",track="_ERROR",frame="_ERROR", rail="STEPTOP", metal="METAL", } table.insert(extra_skins, CRUD) local in_out = {} Layout_inner_outer_tex(in_out, E.K, E.K:neighbor(E.side)) table.insert(extra_skins, in_out) if E.usage.kind == "door" and E.usage.conn.lock then local lock = E.usage.conn.lock if lock.tag then table.insert(extra_skins, { tag = lock.tag, targetname = "sw" .. tostring(lock.tag) }) end end if E.usage.kind == "important" and E.usage.lock and E.usage.lock.kind == "KEY" then table.insert(extra_skins, { item = E.usage.lock.key }) end if E.usage.kind == "important" and E.usage.lock and E.usage.lock.kind == "SWITCH" then local lock = E.usage.lock table.insert(extra_skins, { tag = lock.tag, targetname = "sw" .. tostring(lock.tag) }) end if E.usage.sub == "EXIT" and GAME.format == "quake" then table.insert(extra_skins, { next_map = LEVEL.next_map }) end create_span(E, E.minimal.skin, extra_skins) end ---| Layout_used_walls |--- for pass = 1,2 do for _,K in ipairs(R.sections) do for _,E in pairs(K.edges) do -- do doors before everything else, since switched doors -- control what switches will be available. local is_door = sel(E.usage and E.usage.kind == "door", 1, 2) if E.usage and pass == is_door then initial_edge(E) end end end end end function Layout_make_corners(R) -- -- this function decides what to place in every corner of the room, -- including concave (270 degree) corners. This is done before the -- edges, determining the sides of each edge so that the edges will -- merely need to fill in the gap(s). -- local function find_edges(C) local side_L = geom.LEFT_45 [C.side] local side_R = geom.RIGHT_45[C.side] local H -- edge connecting Horizontally local V -- edge connecting Vertically if C.concave then local K1 = C.K:neighbor(side_L) local K2 = C.K:neighbor(side_R) H = K1.edges[side_R] V = K2.edges[side_L] else H = C.K.edges[side_R] V = C.K.edges[side_L] end if C.side == 1 or C.side == 9 then H, V = V, H end assert(H and V) return H, V end local function edge_max_depth(E) -- NOTE: assumes no more than one span on any edge local SP = E.spans[1] if SP then return math.max(SP.deep1, SP.deep2, 64) end return 64 end local function corner_length(C, E) if C.concave then return 64 end local SP = E.spans[1] if SP then -- FIXME: assumes span is centered local long = SP.long2 - SP.long1 return (E.real_len - long) / 2 end return E.real_len / 2 - 48 end local function make_corner(C) local H, V = find_edges(C) local long_H = corner_length(C, H) local long_V = corner_length(C, V) local deep_H = edge_max_depth(H) local deep_V = edge_max_depth(V) H.max_deep = deep_H V.max_deep = deep_V gui.debugf("Corner @ %s:%d : long_H:%d long_V:%d deep_H:%d deep_V:%d\n", C.K:tostr(), C.side, long_H, long_V, deep_H, deep_V) -- long_H,V are the upper limit on the size of the corner -- FIXME!!! look for a prefab that fits in that limit, -- and test if it fits OK (no overlapping e.g. walk brushes) if true then long_V = 64 long_H = 64 end C.horiz = long_H C.vert = long_V H.max_deep = math.max(long_V, deep_H) V.max_deep = math.max(long_H, deep_V) -- the EDGE long_L,R and deep_L,R fields are done in flesh_out_walls() local skin = {} local neighbor = C.K:neighbor(C.side) if R.outdoor then local A = C.K:neighbor(geom.RIGHT_45[C.side]) local B = C.K:neighbor(geom. LEFT_45[C.side]) if A and A.room and not A.room.outdoor then neighbor = A end if B and B.room and not B.room.outdoor then neighbor = B end end Layout_inner_outer_tex(skin, C.K, neighbor) local fab_name = "CORNER" if GAME.format == "quake" and not C.concave and not R.outdoor then fab_name = "CORNER_DIAG_W_TORCH" end -- build something local T = Trans.corner_transform(C.K.x1, C.K.y1, C.K.x2, C.K.y2, nil, C.side, C.horiz, C.vert) local fab = Fab_create(fab_name) Fab_apply_skins(fab, { R.skin or {}, skin }) Fab_transform_XY(fab, T) fab.room = R table.insert(R.prefabs, fab) end ---| Layout_make_corners |--- for _,K in ipairs(R.sections) do for _,C in pairs(K.corners) do make_corner(C) end end end -- FIXME: TEMP CRUD - REMOVE function geom.horiz_sel(A, B, C) return geom.vert_sel(A, C, B) end function Layout_picture_hack(R) -- FIXME: TEMP HACK : add some picture prefabs local function do_edge(E) if E.spans[1] then return end if not THEME.piccies then return end if R.outdoor then return end if not rand.odds(30) then return end if not R.pic_name then -- FIXME: use possible_prefabs ?? R.pic_name = rand.key_by_probs(THEME.piccies) end local skin = assert(GAME.SKINS[R.pic_name]) -- FIXME: similar code to create_span() -- check if can merge them local long = skin._long local deep = skin._deep local long1 = int(E.real_len - long) / 2 local long2 = int(E.real_len + long) / 2 Layout_add_span(E, long1, long2, deep) local skins = { } if R.skin then table.insert(skins, R.skin) end table.insert(skins, skin) local fab = Fab_create(skin._prefab) Fab_apply_skins(fab, skins) fab.room = R table.insert(R.prefabs, fab) local T = Trans.edge_transform(E.K.x1, E.K.y1, E.K.x2, E.K.y2, 0, E.side, long1, long2, 0, deep) Fab_transform_XY(fab, T) end for _,K in ipairs(R.sections) do for _,E in pairs(K.edges) do do_edge(E) end end end function Layout_flesh_out_walls(R) -- -- the goal of this function is to fill in the gaps along walls -- with either prefabs or trapezoid-shaped brushes. -- local function edge_extents(E) E.long_L = 0 E.deep_L = 64 if E.corn_L and not E.corn_L.concave then -- FIXME: SHOULD BE vert_sel : WHAT IS WRONG ??? E.long_L = geom.horiz_sel(E.side, E.corn_L.vert, E.corn_L.horiz) E.deep_L = geom.horiz_sel(E.side, E.corn_L.horiz, E.corn_L.vert) end E.long_R = 0 -- temporarily use offset from right, fixed soon E.deep_R = 64 if E.corn_R and not E.corn_R.concave then E.long_R = geom.horiz_sel(E.side, E.corn_R.vert, E.corn_R.horiz) E.deep_R = geom.horiz_sel(E.side, E.corn_R.horiz, E.corn_R.vert) end E.long_R = E.real_len - E.long_R end local function flesh_out_range(E, long1, deep1, long2, deep2) if long1 >= long2 then return end -- FIXME: handle small gaps local my = int((deep1 + deep2) / 2) --- if (long2 - long1) >= 360 then --- local mx = int((long1 + long2) / 2) --- RECURSIVE SUB-DIVISION --- end gui.debugf("flesh_out_range @ %s:%d : (%d %d) .. (%d %d)\n", E.K:tostr(), E.side, long1, deep1, long2, deep2) local deep if true then deep = 16 else deep = math.max(deep1, deep2) end local skin = {} Layout_inner_outer_tex(skin, E.K, E.K:neighbor(E.side)) -- build something local T = Trans.edge_transform(E.K.x1, E.K.y1, E.K.x2, E.K.y2, nil, E.side, long1, long2, 0, deep) local fab = Fab_create("WALL") Fab_apply_skins(fab, { R.skin or {}, skin }) Fab_transform_XY(fab, T) fab.room = R table.insert(R.prefabs, fab) end local function flesh_out_edge(E) -- NOTE: assumes no more than one span so far local SP = E.spans[1] if SP then local span_L = SP.long1 local span_R = SP.long2 -- FIXME: key stuff / torches on either side of door flesh_out_range(E, E.long_L, E.deep_L, span_L, SP.deep1) flesh_out_range(E, span_R, SP.deep2, E.long_R, E.deep_R) else flesh_out_range(E, E.long_L, E.deep_L, E.long_R, E.deep_R) end end ---| Layout_flesh_out_walls |--- for _,K in ipairs(R.sections) do for _,E in pairs(K.edges) do edge_extents(E) flesh_out_edge(E) end end end function Layout_all_walls() for _,R in ipairs(LEVEL.all_rooms) do Layout_used_walls(R) end for _,R in ipairs(LEVEL.all_rooms) do Layout_picture_hack(R) Layout_make_corners(R) Layout_flesh_out_walls(R) end end function Layout_build_walls(R) for _,fab in ipairs(R.prefabs) do if fab.room == R and not fab.rendered then if not fab.bumped then local z = fab.air_z or R.floor_max_h assert(z) Fab_transform_Z(fab, { add_z = z }) end Fab_render(fab) end end end
gpl-2.0
AlexandreCA/darkstar
scripts/zones/Southern_San_dOria/npcs/Luthiaque.lua
13
1426
----------------------------------- -- Area: Southern San d'Oria -- NPC: Luthiaque -- General Info NPC ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0292); 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
LuaDist2/gimlet-cocktail
gimlet/init.lua
2
2819
local dispatch do local _obj_0 = require("gimlet.dispatcher") dispatch = _obj_0.dispatch end local gimlet_cache = { } local runner runner = function(gimlet_cls) local gimlet = gimlet_cache[gimlet_cls] if not (gimlet) then if type(gimlet_cls) == "string" then gimlet = require(gimlet_cls)() elseif gimlet_cls.__base then gimlet = gimlet_cls() else gimlet = gimlet_cls end gimlet_cache[gimlet_cls] = gimlet end return dispatch(gimlet) end local mixin mixin = function(self, cls, ...) for key, val in pairs(cls.__base) do if not key:match("^__") then self[key] = val end end return cls.__init(self, ...) end local Logger do local _obj_0 = require("gimlet.logger") Logger = _obj_0.Logger end local Router do local _obj_0 = require("gimlet.router") Router = _obj_0.Router end local Static do local _obj_0 = require("gimlet.static") Static = _obj_0.Static end local validate_handler do local _obj_0 = require("gimlet.utils") validate_handler = _obj_0.validate_handler end local Gimlet do local _base_0 = { handlers = function(self, ...) self._handlers = { } for _, h in pairs({ ... }) do self:use(h) end end, set_action = function(self, handler) validate_handler(handler) self.action = handler end, use = function(self, handler) validate_handler(handler) return table.insert(self._handlers, handler) end, map = function(self, name, value) self._mapped[name] = value end, run = function(self) return runner(self) end } _base_0.__index = _base_0 local _class_0 = setmetatable({ __init = function(self) self.action = function(self) end self._handlers = { } self._mapped = { gimlet = self } end, __base = _base_0, __name = "Gimlet" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Gimlet = _class_0 end local Classic do local _base_0 = { } _base_0.__index = _base_0 local _class_0 = setmetatable({ __init = function(self, log) if log == nil then log = io.stdout end mixin(self, Gimlet) mixin(self, Router) self:use(Logger(log)) self:use(Static("/public", { log = log })) return self:set_action(self.handle) end, __base = _base_0, __name = "Classic" }, { __index = _base_0, __call = function(cls, ...) local _self_0 = setmetatable({}, _base_0) cls.__init(_self_0, ...) return _self_0 end }) _base_0.__class = _class_0 Classic = _class_0 end return { Gimlet = Gimlet, Classic = Classic }
mit
jstewart-amd/premake-core
tests/api/test_containers.lua
16
1895
-- -- tests/api/test_containers.lua -- Tests the API's workspace() and project() container definitions. -- Copyright (c) 2013-2014 Jason Perkins and the Premake project -- local suite = test.declare("api_containers") local api = premake.api -- -- Setup and teardown -- local wks function suite.setup() wks = workspace("MyWorkspace") end -- -- The first time a name is encountered, a new container should be created. -- function suite.workspace_createsOnFirstUse() test.isnotnil(premake.global.getWorkspace("MyWorkspace")) end function suite.project_createsOnFirstUse() project("MyProject") test.isnotnil(test.getproject(wks, "MyProject")) end -- -- When a container is created, it should become the active scope. -- function suite.workspace_setsActiveScope() test.issame(api.scope.workspace, wks) end function suite.project_setsActiveScope() local prj = project("MyProject") test.issame(api.scope.project, prj) end -- -- When container function is called with no arguments, that should -- become the current scope. -- function suite.workspace_setsActiveScope_onNoArgs() project("MyProject") group("MyGroup") workspace() test.issame(wks, api.scope.workspace) test.isnil(api.scope.project) test.isnil(api.scope.group) end function suite.project_setsActiveScope_onNoArgs() local prj = project("MyProject") group("MyGroup") project() test.issame(prj, api.scope.project) end -- -- The "*" name should activate the parent scope. -- function suite.workspace_onStar() project("MyProject") group("MyGroup") filter("Debug") workspace("*") test.isnil(api.scope.workspace) test.isnil(api.scope.project) test.isnil(api.scope.group) end function suite.project_onStar() project("MyProject") group("MyGroup") filter("Debug") project "*" test.issame(wks, api.scope.workspace) test.isnil(api.scope.project) end
bsd-3-clause
AlexandreCA/update
scripts/globals/mobskills/Gregale_Wing.lua
18
1239
--------------------------------------------- -- Gregale Wing -- -- Description: An icy wind deals Ice damage to enemies within a very wide area of effect. Additional effect: Paralyze -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Jormungand and Isgebind --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then return 1; elseif (mob:AnimationSub() == 1) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_PARALYSIS; MobStatusEffectMove(mob, target, typeEffect, 40, 0, 120); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_ICE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
techtonik/wesnoth
data/ai/micro_ais/cas/ca_recruit_random.lua
26
4781
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require("ai/lua/ai_helper.lua") local LS = wesnoth.dofile "lua/location_set.lua" local recruit_type local ca_recruit_random = {} function ca_recruit_random:evaluation(ai, cfg) -- Random recruiting from all the units the side has -- Check if leader is on keep local leader = wesnoth.get_units { side = wesnoth.current.side, canrecruit = 'yes' }[1] if (not leader) or (not wesnoth.get_terrain_info(wesnoth.get_terrain(leader.x, leader.y)).keep) then return 0 end -- Find all connected castle hexes local castle_map = LS.of_pairs({ { leader.x, leader.y } }) local width, height, border = wesnoth.get_map_size() local new_castle_hex_found = true while new_castle_hex_found do new_castle_hex_found = false local new_hexes = {} castle_map:iter(function(x, y) for xa,ya in H.adjacent_tiles(x, y) do if (not castle_map:get(xa, ya)) and (xa >= 1) and (xa <= width) and (ya >= 1) and (ya <= height) then local is_castle = wesnoth.get_terrain_info(wesnoth.get_terrain(xa, ya)).castle if is_castle then table.insert(new_hexes, { xa, ya }) new_castle_hex_found = true end end end end) for _,hex in ipairs(new_hexes) do castle_map:insert(hex[1], hex[2]) end end -- Check if there is space left for recruiting local no_space = true castle_map:iter(function(x, y) local unit = wesnoth.get_unit(x, y) if (not unit) then no_space = false end end) if no_space then return 0 end -- Set up the probability array local probabilities, probability_sum = {}, 0 -- Go through all the types listed in [probability] tags (which can be comma-separated lists) -- Types and probabilities are put into cfg.type and cfg.prob arrays by micro_ai_wml_tag.lua for ind,types in ipairs(cfg.type) do types = AH.split(types, ",") for _,typ in ipairs(types) do -- 'type' is a reserved keyword in Lua -- If this type is in the recruit list, add it for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do if (recruit == typ) then probabilities[typ] = { value = cfg.prob[ind] } probability_sum = probability_sum + cfg.prob[ind] break end end end end -- Now we add in all the unit types not listed in [probability] tags for _,recruit in ipairs(wesnoth.sides[wesnoth.current.side].recruit) do if (not probabilities[recruit]) then probabilities[recruit] = { value = 1 } probability_sum = probability_sum + 1 end end -- Now eliminate all those that are too expensive (unless cfg.skip_low_gold_recruiting is set) if cfg.skip_low_gold_recruiting then for typ,probability in pairs(probabilities) do -- 'type' is a reserved keyword in Lua if (wesnoth.unit_types[typ].cost > wesnoth.sides[wesnoth.current.side].gold) then probability_sum = probability_sum - probability.value probabilities[typ] = nil end end end -- Now set up the cumulative probability values for each type -- Both min and max need to be set as the order of pairs() is not guaranteed local cum_prob = 0 for typ,probability in pairs(probabilities) do probabilities[typ].p_i = cum_prob cum_prob = cum_prob + probability.value probabilities[typ].p_f = cum_prob end -- We always call the exec function, no matter if the selected unit is affordable -- The point is that this will blacklist the CA if an unaffordable recruit was -- chosen -> no cheaper recruits will be selected in subsequent calls if (cum_prob > 0) then local rand_prob = math.random(cum_prob) for typ,probability in pairs(probabilities) do if (probability.p_i < rand_prob) and (rand_prob <= probability.p_f) then recruit_type = typ break end end else recruit_type = wesnoth.sides[wesnoth.current.side].recruit[1] end return cfg.ca_score end function ca_recruit_random:execution(ai, cfg) -- Let this function blacklist itself if the chosen recruit is too expensive if wesnoth.unit_types[recruit_type].cost <= wesnoth.sides[wesnoth.current.side].gold then AH.checked_recruit(ai, recruit_type) end end return ca_recruit_random
gpl-2.0
AlexandreCA/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/King_Zagan.lua
2
1559
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: King Zagan ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if (mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 2048; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if (Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330177); -- Dynamis Lord GetMobByID(17330183):setSpawn(-364,-35.661,17.254); -- Set Ying and Yang's spawn points to their initial spawn point. GetMobByID(17330184):setSpawn(-364,-35.974,24.254); SpawnMob(17330183); SpawnMob(17330184); activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if (Animate_Trigger == 32767) then ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Selbina/npcs/Explorer_Moogle.lua
13
1835
----------------------------------- -- Area: Selbina -- NPC: Explorer Moogle ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/teleports"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) accept = 0; event = 0x046f; if (player:getGil() < 300) then accept = 1; end if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then event = event + 1; end player:startEvent(event,player:getZoneID(),0,accept); 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); local price = 300; if (csid == 0x046f) then if (option == 1 and player:delGil(price)) then toExplorerMoogle(player,231); elseif (option == 2 and player:delGil(price)) then toExplorerMoogle(player,234); elseif (option == 3 and player:delGil(price)) then toExplorerMoogle(player,240); elseif (option == 4 and player:delGil(price)) then toExplorerMoogle(player,248); elseif (option == 5 and player:delGil(price)) then toExplorerMoogle(player,249); end end end;
gpl-3.0
stefano-m/lua-dbus_proxy
tests/proxy_spec.lua
1
21447
-- Works with the 'busted' framework. -- http://olivinelabs.com/busted/ local table = table local os = os local unpack = unpack or table.unpack -- luacheck: globals unpack require("busted") local GLib = require("lgi").GLib local GVariant = GLib.Variant local p = require("dbus_proxy") local Bus = p.Bus local Proxy = p.Proxy local variant = p.variant local monitored = p.monitored -- See dbus-shared.h local DBUS_NAME_FLAG_REPLACE_EXISTING = 2 describe("The Bus table", function () it("does not allow to set values", function () assert.has_error(function () Bus.something = 1 end, "Cannot set values") end) it("can get the SYSTEM bus", function () assert.equals("userdata", type(Bus.SYSTEM)) assert.equals("Gio.DBusConnection", Bus.SYSTEM._name) end) it("can get the SESSION bus", function () assert.equals("userdata", type(Bus.SESSION)) assert.equals("Gio.DBusConnection", Bus.SESSION._name) end) it("returns a nil with a wrong DBus address", function () assert.is_nil(Bus.wrong_thing) end) it("can get the bus from an address", function () local address = os.getenv("DBUS_SESSION_BUS_ADDRESS") local bus = Bus[address] assert.equals("userdata", type(bus)) assert.equals("Gio.DBusConnection", bus._name) end) end) describe("Stripping GVariant of its type", function () it("works on boolean types", function () local v = GVariant("b", true) assert.is_true(variant.strip(v)) end) it("works on byte types", function () local v = GVariant("y", 1) assert.equals(1, variant.strip(v)) end) it("works on int16 types", function () local v = GVariant("n", -32768) assert.equals(-32768, variant.strip(v)) end) it("works on uint16 types", function () local v = GVariant("q", 65535) assert.equals(65535, variant.strip(v)) end) it("works on int32 types", function () local v = GVariant("i", -2147483648) assert.equals(-2147483648, variant.strip(v)) end) it("works on uint32 types", function () local v = GVariant("u", 4294967295) assert.equals(4294967295, variant.strip(v)) end) it("works on int64 types", function () local v = GVariant("x", -14294967295) assert.equals(-14294967295, variant.strip(v)) end) it("works on uint64 types", function () local v = GVariant("t", 14294967295) assert.equals(14294967295, variant.strip(v)) end) it("works on double types", function () local v = GVariant("d", 1.54) assert.equals(1.54, variant.strip(v)) end) it("works on string types", function () local v = GVariant("s", "Hello, Lua!") assert.equals("Hello, Lua!", variant.strip(v)) end) it("works on object path types", function () local v = GVariant("o", "/some/path") assert.equals("/some/path", variant.strip(v)) end) it("works on simple variant types", function () local v = GVariant("v", GVariant("s", "in a variant")) assert.equals("in a variant", variant.strip(v)) end) it("works on simple array types", function () local v = GVariant("ai", {4, 1, 2, 3}) assert.same({4, 1, 2, 3}, variant.strip(v)) end) it("works on simple nested array types", function () local v = GVariant("aai", {{1, 2, 3}, {4, 1, 2, 3}}) assert.same({{1, 2, 3}, {4, 1, 2, 3}}, variant.strip(v)) end) it("works on array types of variant types", function () local v = GVariant("av", {GVariant("s", "Hello"), GVariant("i", 8383), GVariant("b", true)}) assert.same({"Hello", 8383, true}, variant.strip(v)) end) it("works on simple tuple types", function () -- AKA "struct" in DBus local v = GVariant("(is)", {4, "Hello"}) assert.same({4, "Hello"}, variant.strip(v)) end) it("works on simple nested tuple types", function () local v = GVariant("(i(si))", {4, {"Hello", 2}}) assert.same({4, {"Hello", 2}}, variant.strip(v)) end) it("works on tuple types with Variants", function () local v = GVariant("(iv)", {4, GVariant("s", "Hello")}) assert.same({4, "Hello"}, variant.strip(v)) end) it("works on simple dictionary types", function () local v = GVariant("a{ss}", {one = "Hello", two = "Lua!", n = "Yes"}) assert.same({one = "Hello", two = "Lua!", n = "Yes"}, variant.strip(v)) end) it("works on nested dictionary types", function () local v = GVariant("a{sa{ss}}", {one = {nested1 = "Hello"}, two = {nested2 = "Lua!"}}) assert.same({one = {nested1 = "Hello"}, two = {nested2 = "Lua!"}}, variant.strip(v)) end) it("works on dictionary types with Variants", function () local v = GVariant("a{sv}", {one = GVariant("i", 123), two = GVariant("s", "Lua!")}) assert.same({one = 123, two = "Lua!"}, variant.strip(v)) end) it("works on tuples of dictionaries", function () local v = GVariant( "(a{sv})", { { one = GVariant("s", "hello"), two = GVariant("i", 123) } } ) local actual = variant.strip(v) assert.is_true(#actual == 1) assert.same( {one = "hello", two = 123}, actual[1]) end) end) describe("DBus Proxy objects", function () it("can be created", function () local proxy = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) assert.equals("Gio.DBusProxy", proxy._proxy._name) -- g-* properties assert.equals("org.freedesktop.DBus", proxy.interface) assert.equals("/org/freedesktop/DBus", proxy.object_path) assert.equals("org.freedesktop.DBus", proxy.name) assert.equals(Bus.SESSION, proxy.connection) assert.same({NONE = true}, proxy.flags) assert.equals("org.freedesktop.DBus", proxy.name_owner) -- generated methods assert.is_function(proxy.Introspect) assert.equals("<!DOCTYPE", proxy:Introspect():match("^<!DOCTYPE")) assert.is_table(proxy:ListNames()) assert.has_error( function () proxy:Hello("wrong") end, "Expected 0 parameters but got 1") assert.equals( 1, proxy:RequestName("com.example.Test1", DBUS_NAME_FLAG_REPLACE_EXISTING) ) end) it("reports an error if a call fails", function () local errfn = function() Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.some.name", path= "/org/freedesktop/Some/Path", interface = "org.freedesktop.some.interface" } ) end assert.has_error(errfn, "Failed to introspect object 'org.freedesktop.some.name'\n" .. "error: GDBus.Error:org.freedesktop.DBus.Error.ServiceUnknown: " .. "The name org.freedesktop.some.name was not provided by any .service files\n" .. "code: SERVICE_UNKNOWN") end) it("can access properties", function () local proxy = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) -- https://dbus.freedesktop.org/doc/dbus-specification.html#message-bus-properties assert.is_table(proxy.Features) assert.is_table(proxy.Interfaces) assert.has_error( function () proxy.Features = 1 end, "Property 'Features' is not writable") end) it("can handle signals", function () local proxy = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) local ctx = GLib.MainLoop():get_context() local called = false local received_proxy local received_params local function callback(proxy_obj, ...) -- don't do assertions in here because a failure -- would just print an "Lgi-WARNING" message called = true received_proxy = proxy_obj received_params = {...} end -- this signal is also used when *new* owners appear local signal_name = "NameOwnerChanged" local sender_name = nil -- any sender proxy:connect_signal(callback, signal_name, sender_name) local bus_name = "com.example.Test2" assert.equals( 1, proxy:RequestName(bus_name, DBUS_NAME_FLAG_REPLACE_EXISTING) ) -- Run an iteration of the loop (blocking) -- to ensure that the signal is emitted. assert.is_true(ctx:iteration(true)) assert.is_true(called) assert.equals(proxy, received_proxy) assert.equals(3, #received_params) local owned_name, old_owner, new_owner = unpack(received_params) assert.equals(bus_name, owned_name) assert.equals('', old_owner) assert.is_string(new_owner) end) it("errors when connecting to an invalid signal", function () local proxy = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) assert.has_error( function () proxy:connect_signal(function() end, "NotValid") end, "Invalid signal: NotValid") end) it("can call async methods", function () local dbus = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) local ctx = GLib.MainLoop():get_context() local name = "com.example.Test7" local test_data = { called = false, has_owner = false, err = false } local callback = function(_, user_data, result, err) user_data.called = true user_data.has_owner = result user_data.err = err end assert.equals( 1, dbus:RequestName(name, DBUS_NAME_FLAG_REPLACE_EXISTING) ) assert.is_true(ctx:iteration(true)) dbus:NameHasOwnerAsync(callback, test_data, name) assert.equals(false, test_data.called) assert.equals(false, test_data.has_owner) assert.is_true(ctx:iteration(true)) assert.equals(true, test_data.called) assert.equals(true, test_data.has_owner) assert.equals(nil, test_data.err) end) it("can get errors with async methods", function () local dbus = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) local ctx = GLib.MainLoop():get_context() local name = "org.freedesktop.DBus" local test_data = { called = false, has_owner = false, err = nil } local callback = function(_, user_data, result, err) user_data.called = true user_data.has_owner = result user_data.err = err end dbus:RequestNameAsync(callback, test_data, name, DBUS_NAME_FLAG_REPLACE_EXISTING) assert.equals(false, test_data.called) assert.equals(false, test_data.has_owner) assert.is_true(ctx:iteration(true)) assert.equals(true, test_data.called) assert.equals(nil, test_data.has_owner) assert.equals("userdata", type(test_data.err)) end) it("can deal with methods and properties with the same name #skipci", -- TODO: how can I make it work in CI? function () local proxy = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.systemd1", interface = "org.freedesktop.systemd1.Unit", path = "/org/freedesktop/systemd1/unit/redshift_2eservice" } ) assert.is_function(proxy.Restart) assert.is_table(proxy.accessors._Restart) local spy_getter = spy.on(proxy.accessors._Restart, "getter") assert.is_nil(proxy._Restart) -- actual value of the property assert.spy(spy_getter).was.called() assert.has_error(function () proxy._Restart = 1 end, "Property 'Restart' is not writable") end) end) describe("Monitored proxy objects", function () local ctx = GLib.MainLoop():get_context() local dbus = Proxy:new( { bus = Bus.SESSION, name = "org.freedesktop.DBus", path= "/org/freedesktop/DBus", interface = "org.freedesktop.DBus" } ) it("can validate the options", function () local options = { "bus", "name", "interface", "path" } local correct_options = { bus = Bus.SESSION, name = "com.example.Test2", path = "/com/example/Test2", interface = "com.example.Test2" } for _, option in ipairs(options) do local opts = {} for k, v in pairs(correct_options) do if k ~= option then opts[k] = v end assert.has_error(function () local _ = monitored.new(opts) end) end end end) it("can be disconnected", function () local name = "com.example.Test3" local opts = { bus = Bus.SESSION, name = name, interface = name, path = "/com/example/Test3" } assert.equals( 1, dbus:RequestName(name, DBUS_NAME_FLAG_REPLACE_EXISTING) ) assert.is_true(ctx:iteration(true)) assert.equals( 1, dbus:ReleaseName(name) ) assert.is_true(ctx:iteration(true)) local proxy = monitored.new(opts) assert.is_true(ctx:iteration(true)) assert.is_false(proxy.is_connected) assert.has_error( function () local _ = proxy.Metadata end, name .. " disconnected") end) it("can be connected", function () local bus_name = "com.example.Test4" local opts = { bus = Bus.SESSION, name = bus_name, interface = bus_name, path = "/com/example/Test4", } assert.equals( 1, dbus:RequestName(bus_name, DBUS_NAME_FLAG_REPLACE_EXISTING) ) assert.is_true(ctx:iteration(true)) local proxy = monitored.new(opts) assert.is_true(ctx:iteration(true)) assert.is_true(proxy.is_connected) end) it("will run the callback when disconnected", function () local name = "com.example.Test5" local opts = { bus = Bus.SESSION, name = name, interface = name, path = "/com/example/Test5", } assert.equals( 1, dbus:RequestName(name, DBUS_NAME_FLAG_REPLACE_EXISTING) ) assert.is_true(ctx:iteration(true)) local params = {} local function callback(proxy, appeared) if not appeared then assert.is_false(proxy.is_connected) end params.proxy = proxy params.appeared = appeared end local proxy = monitored.new(opts, callback) assert.is_true(ctx:iteration(true)) assert.equals( 1, dbus:ReleaseName(name) ) assert.is_true(ctx:iteration(true)) assert.equals(params.proxy, proxy) assert.is_false(params.appeared) end) it("will run the callback when connected", function () local name = "com.example.Test6" local opts = { bus = Bus.SESSION, name = name, interface = name, path = "/com/example/Test6", } assert.equals( 1, dbus:RequestName(name, DBUS_NAME_FLAG_REPLACE_EXISTING) ) assert.is_true(ctx:iteration(true)) local params = {} local function callback(proxy, appeared) if appeared then assert.is_true(proxy.is_connected) end params.proxy = proxy params.appeared = appeared end local proxy = monitored.new(opts, callback) assert.is_true(ctx:iteration(true)) assert.equals(params.proxy, proxy) assert.is_true(params.appeared) end) end)
apache-2.0
AlexandreCA/update
scripts/zones/Metalworks/npcs/Romero.lua
24
1858
----------------------------------- -- Area: Metalworks -- NPC: Romero -- Type: Smithing Synthesis Image Support -- @pos -106.336 2.000 26.117 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,8); local SkillCap = getCraftSkillCap(player,SKILL_SMITHING); local SkillLevel = player:getSkillLevel(SKILL_SMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then player:startEvent(0x0069,SkillCap,SkillLevel,2,207,player:getGil(),0,0,0); else player:startEvent(0x0069,SkillCap,SkillLevel,2,207,player:getGil(),7127,0,0); end else player:startEvent(0x0069); -- 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 == 0x0069 and option == 1) then player:messageSpecial(SMITHING_SUPPORT,0,2,2); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,1,0,120); end end;
gpl-3.0
AlexandreCA/update
scripts/zones/Sealions_Den/mobs/Omega.lua
16
1290
----------------------------------- -- Area: Sealions Den -- NPC: Omega ----------------------------------- require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) killer:addTitle(OMEGA_OSTRACIZER); killer:startEvent(0x000b); end; function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x000b) then local instance = player:getVar("bcnm_instanceid") --Players are healed in between the fights, but their TP is set to 0 player:setHP(player:getMaxHP()); player:setMP(player:getMaxMP()); player:setTP(0); if (instance == 1) then player:setPos(-779, -103, -80); SpawnMob(16908295); --ultima1 elseif (instance == 2) then player:setPos(-140, -23, -440); SpawnMob(16908302); --ultima2 else player:setPos(499, 56, -802); SpawnMob(16908309); --ultima3 end end end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/broiled_trout.lua
35
1292
----------------------------------------- -- ID: 4587 -- Item: Broiled Trout -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 4 -- Mind -1 -- Ranged ATT % 14 ----------------------------------------- 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,3600,4587); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -1); target:addMod(MOD_RATTP, 14); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -1); target:delMod(MOD_RATTP, 14); end;
gpl-3.0
AlexandreCA/update
scripts/zones/Caedarva_Mire/mobs/Lamia_Idolater.lua
4
1722
----------------------------------- -- Area: Arrapago Reef -- NPC: Lamia Idolator ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob, target) local swapTimer = mob:getLocalVar("swapTime"); if (os.time() > swapTimer) then if (mob:AnimationSub() == 1) then -- swap from fists to second weapon mob:AnimationSub(2); mob:setLocalVar("swapTime", os.time() + 60) elseif (mob:AnimationSub() == 2) then -- swap from second weapon to fists mob:AnimationSub(1); mob:setLocalVar("swapTime", os.time() + 60) end end end; ----------------------------------- -- onCriticalHit ----------------------------------- function onCriticalHit(mob) if (math.random(100) < 10) then -- 10% change to break the weapon on crit if (mob:AnimationSub() == 0) then -- first weapon mob:AnimationSub(1); mob:setLocalVar("swapTime", os.time() + 60) -- start the timer for swapping between fists and the second weapon elseif (mob:AnimationSub() == 2) then -- second weapon mob:AnimationSub(3); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) end;
gpl-3.0
annulen/premake-annulen
src/actions/vstudio/vs2010_vcxproj_filters.lua
17
2473
-- -- vs2010_vcxproj_filters.lua -- Generate a Visual Studio 2010 C/C++ filters file. -- Copyright (c) 2009-2011 Jason Perkins and the Premake project -- local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- The first portion of the filters file assigns unique IDs to each -- directory or virtual group. Would be cool if we could automatically -- map vpaths like "**.h" to an <Extensions>h</Extensions> element. -- function vc2010.filteridgroup(prj) local filters = { } local filterfound = false for file in project.eachfile(prj) do -- split the path into its component parts local folders = string.explode(file.vpath, "/", true) local path = "" for i = 1, #folders - 1 do -- element is only written if there *are* filters if not filterfound then filterfound = true _p(1,'<ItemGroup>') end path = path .. folders[i] -- have I seen this path before? if not filters[path] then filters[path] = true _p(2, '<Filter Include="%s">', path) _p(3, '<UniqueIdentifier>{%s}</UniqueIdentifier>', os.uuid()) _p(2, '</Filter>') end -- prepare for the next subfolder path = path .. "\\" end end if filterfound then _p(1,'</ItemGroup>') end end -- -- The second portion of the filters file assigns filters to each source -- code file, as needed. Section is one of "ClCompile", "ClInclude", -- "ResourceCompile", or "None". -- function vc2010.filefiltergroup(prj, section) local files = vc2010.getfilegroup(prj, section) if #files > 0 then _p(1,'<ItemGroup>') for _, file in ipairs(files) do local filter if file.name ~= file.vpath then filter = path.getdirectory(file.vpath) else filter = path.getdirectory(file.name) end if filter ~= "." then _p(2,'<%s Include=\"%s\">', section, path.translate(file.name, "\\")) _p(3,'<Filter>%s</Filter>', path.translate(filter, "\\")) _p(2,'</%s>', section) else _p(2,'<%s Include=\"%s\" />', section, path.translate(file.name, "\\")) end end _p(1,'</ItemGroup>') end end -- -- Output the VC2010 filters file -- function vc2010.generate_filters(prj) io.indent = " " vc2010.header() vc2010.filteridgroup(prj) vc2010.filefiltergroup(prj, "None") vc2010.filefiltergroup(prj, "ClInclude") vc2010.filefiltergroup(prj, "ClCompile") vc2010.filefiltergroup(prj, "ResourceCompile") _p('</Project>') end
bsd-3-clause
AlexandreCA/darkstar
scripts/zones/Port_Bastok/npcs/Jabbar.lua
13
1802
----------------------------------- -- Area: Port Bastok -- NPC: Jabbar -- Type: Tenshodo Merchant -- Involved in Quests: Tenshodo Menbership -- @pos -99.718 -2.299 26.027 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then if (player:sendGuild(60419, 1, 23, 4)) then player:showText(npc,TENSHODO_SHOP_OPEN_DIALOG); end elseif (player:getQuestStatus(JEUNO,TENSHODO_MEMBERSHIP) == QUEST_ACCEPTED) then if (player:hasKeyItem(TENSHODO_APPLICATION_FORM)) then player:startEvent(0x0098); else player:startEvent(0x0097); end else player:startEvent(0x0096); 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 == 0x0097) then player:addKeyItem(TENSHODO_APPLICATION_FORM); player:messageSpecial(KEYITEM_OBTAINED,TENSHODO_APPLICATION_FORM); end end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/vulcan_claymore.lua
42
1451
----------------------------------------- -- ID: 18379 -- Item: Vulcan Claymore -- Additional Effect: Fire Damage -- Enchantment: Enfire ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0); dmg = adjustForTarget(target,dmg,ELE_FIRE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_FIRE_DAMAGE,message,dmg; end end; ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) local effect = EFFECT_ENFIRE; doEnspell(target,target,nil,effect); end;
gpl-3.0
AlexandreCA/update
scripts/globals/items/slice_of_roast_mutton.lua
35
1397
----------------------------------------- -- ID: 4437 -- Item: slice_of_roast_mutton -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 3 -- Intelligence -1 -- Attack % 27 -- Attack Cap 30 ----------------------------------------- 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,4437); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 27); target:addMod(MOD_FOOD_ATT_CAP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 27); target:delMod(MOD_FOOD_ATT_CAP, 30); end;
gpl-3.0
ztesbot/ztesrobot
plugins/Lyrics.lua
695
2113
do local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs' local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5' local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect' local function getInfo(query) print('Getting info of ' .. query) local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY ..'&q='..URL.escape(query) local b, c = http.request(url) if c ~= 200 then return nil end local result = json:decode(b) local artist = result[1].artist.name local track = result[1].title return artist, track end local function getLyrics(query) local artist, track = getInfo(query) if artist and track then local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist) ..'&song='..URL.escape(track) local b, c = http.request(url) if c ~= 200 then return nil end local xml = require("xml") local result = xml.load(b) if not result then return nil end if xml.find(result, 'LyricSong') then track = xml.find(result, 'LyricSong')[1] end if xml.find(result, 'LyricArtist') then artist = xml.find(result, 'LyricArtist')[1] end local lyric if xml.find(result, 'Lyric') then lyric = xml.find(result, 'Lyric')[1] else lyric = nil end local cover if xml.find(result, 'LyricCovertArtUrl') then cover = xml.find(result, 'LyricCovertArtUrl')[1] else cover = nil end return artist, track, lyric, cover else return nil end end local function run(msg, matches) local artist, track, lyric, cover = getLyrics(matches[1]) if track and artist and lyric then if cover then local receiver = get_receiver(msg) send_photo_from_url(receiver, cover) end return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric else return 'Oops! Lyrics not found or something like that! :/' end end return { description = 'Getting lyrics of a song', usage = '!lyrics [track or artist - track]: Search and get lyrics of the song', patterns = { '^!lyrics? (.*)$' }, run = run } end
gpl-2.0
samboy/Oblige
scripts/oblige.lua
1
26715
------------------------------------------------------------------------ -- OBLIGE : INTERFACE WITH GUI CODE ------------------------------------------------------------------------ -- -- Oblige Level Maker -- -- Copyright (C) 2006-2017 Andrew Apted -- -- 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 2 -- 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. -- ------------------------------------------------------------------------ gui.import("defs") gui.import("util") gui.import("brush") gui.import("prefab") gui.import("seed") gui.import("grower") gui.import("area") gui.import("connect") gui.import("quest") gui.import("automata") gui.import("cave") gui.import("layout") gui.import("render") gui.import("boss_map") gui.import("room") gui.import("fight") gui.import("monster") gui.import("item") gui.import("naming") gui.import("title_gen") gui.import("level") function ob_traceback(msg) -- guard against very early errors if not gui or not gui.printf then return msg end gui.printf("\n") gui.printf("@1****** ERROR OCCURRED ******\n\n") gui.printf("Stack Trace:\n") local stack_limit = 40 local function format_source(info) if not info.short_src or info.currentline <= 0 then return "" end local base_fn = string.match(info.short_src, "[^/]*$") return string.format("@ %s:%d", base_fn, info.currentline) end for i = 1,stack_limit do local info = debug.getinfo(i+1) if not info then break end if i == stack_limit then gui.printf("(remaining stack trace omitted)\n") break; end if info.what == "Lua" then local func_name = "???" if info.namewhat and info.namewhat != "" then func_name = info.name or "???" else -- perform our own search of the global namespace, -- since the standard LUA code (5.1.2) will not check it -- for the topmost function (the one called by C code) each k,v in _G do if v == info.func then func_name = k break; end end end gui.printf(" %d: %s() %s\n", i, func_name, format_source(info)) elseif info.what == "main" then gui.printf(" %d: main body %s\n", i, format_source(info)) elseif info.what == "tail" then gui.printf(" %d: tail call\n", i) elseif info.what == "C" then if info.namewhat and info.namewhat != "" then gui.printf(" %d: c-function %s()\n", i, info.name or "???") end end end return msg end function ob_ref_table(op, t) if not gui.___REFS then gui.___REFS = {} end if op == "clear" then gui.___REFS = {} collectgarbage("collect") return end if op == "store" then if t == _G then return 0 end local id = 1 + #gui.___REFS gui.___REFS[id] = t -- t == table return id end if op == "lookup" then if t == 0 then return _G end return gui.___REFS[t] -- t == id number end error("ob_ref_table: unknown op: " .. tostring(op)) end ------------------------------------------------------------------------ function ob_check_ui_module(def) return string.match(def.name, "^ui") != nil end function ob_match_word_or_table(tab, conf) if type(tab) == "table" then return tab[conf] and tab[conf] > 0 else return tab == conf end end function ob_match_game(T) if not T.game then return true end if T.game == "any" then return true end -- special check: if required game is "doomish" then allow any -- of the DOOM games to match. if T.game == "doomish" then T.game = { doom1=1, doom2=1 } end local game = T.game local result = true -- negated check? if type(game) == "string" and string.sub(game, 1, 1) == '!' then game = string.sub(game, 2) result = not result end -- normal check if ob_match_word_or_table(game, OB_CONFIG.game) then return result end -- handle extended games local game_def = OB_GAMES[OB_CONFIG.game] while game_def do if not game_def.extends then break; end if ob_match_word_or_table(game, game_def.extends) then return result end game_def = OB_GAMES[game_def.extends] end return not result end function ob_match_engine(T) if not T.engine then return true end if T.engine == "any" then return true end local engine = T.engine local result = true -- negated check? if type(engine) == "string" and string.sub(engine, 1, 1) == '!' then engine = string.sub(engine, 2) result = not result end -- normal check if ob_match_word_or_table(engine, OB_CONFIG.engine) then return result end -- handle extended engines local engine_def = OB_ENGINES[OB_CONFIG.engine] while engine_def do if not engine_def.extends then break; end if ob_match_word_or_table(engine, engine_def.extends) then return result end engine_def = OB_ENGINES[engine_def.extends] end return not result end function ob_match_playmode(T) -- TODO : remove this function return true end function ob_match_level_theme(T) if not T.theme then return true end if T.theme == "any" then return true end local theme = T.theme local result = true -- negated check? if type(theme) == "string" and string.sub(theme, 1, 1) == '!' then theme = string.sub(theme, 2) result = not result end -- normal check if ob_match_word_or_table(theme, LEVEL.theme_name) then return result end return not result end function ob_match_module(T) if not T.module then return true end local mod_tab = T.module if type(mod_tab) != "table" then mod_tab = { [T.module]=1 } T.module = mod_tab end -- require ALL specified modules to be present and enabled each name,_ in mod_tab do local def = OB_MODULES[name] if not (def and def.shown and def.enabled) then return false end end return true end function ob_match_feature(T) if not T.feature then return true end local feat_tab = T.feature if type(feat_tab) != "table" then feat_tab = { [T.feature]=1 } T.feature = feat_tab end -- require ALL specified features to be available each name,_ in feat_tab do local param = PARAM[name] if param == nil or param == false then return false end end return true end function ob_match_conf(T) assert(OB_CONFIG.game) assert(OB_CONFIG.engine) if not ob_match_game(T) then return false end if not ob_match_engine(T) then return false end if not ob_match_module(T) then return false end return true --OK-- end function ob_update_engines() local need_new = false each name,def in OB_ENGINES do local shown = ob_match_conf(def) if not shown and (OB_CONFIG.engine == name) then need_new = true end gui.enable_choice("engine", name, shown) end if need_new then OB_CONFIG.engine = "nolimit" gui.set_button("engine", OB_CONFIG.engine) end end function ob_update_themes() local new_label each name,def in OB_THEMES do local shown = ob_match_conf(def) if not shown and (OB_CONFIG.theme == name) then new_label = def.label end def.shown = shown gui.enable_choice("theme", name, def.shown) end -- try to keep the same GUI label if new_label then each name,def in OB_THEMES do local shown = ob_match_conf(def) if shown and def.label == new_label then OB_CONFIG.theme = name gui.set_button("theme", OB_CONFIG.theme) return end end -- otherwise revert to As Original OB_CONFIG.theme = "original" gui.set_button("theme", OB_CONFIG.theme) end end function ob_update_modules() -- modules may depend on other modules, hence we may need -- to repeat this multiple times until all the dependencies -- have flowed through. for loop = 1,100 do local changed = false each name,def in OB_MODULES do local shown = ob_match_conf(def) if shown != def.shown then changed = true end def.shown = shown gui.show_module(name, def.shown) end if not changed then break; end end end function ob_update_all() ob_update_engines() ob_update_modules() ob_update_themes() end function ob_find_mod_option(mod, opt_name) if not mod.options then return nil end -- if 'options' is a list, search it one-by-one if mod.options[1] then each opt in mod.options do if opt.name == opt_name then return opt end end end return mod.options[opt_name] end function ob_defs_conflict(def1, def2) if not def1.conflicts then return false end if not def2.conflicts then return false end each name,_ in def1.conflicts do if def2.conflicts[name] then return true end end return false end function ob_set_mod_option(name, option, value) local mod = OB_MODULES[name] if not mod then gui.printf("Ignoring unknown module: %s\n", name) return end if option == "self" then -- convert 'value' from string to a boolean value = not (value == "false" or value == "0") if mod.enabled == value then return -- no change end mod.enabled = value -- handle conflicting modules (like Radio buttons) if value then each other,odef in OB_MODULES do if odef != mod and ob_defs_conflict(mod, odef) then odef.enabled = false gui.set_module(other, odef.enabled) end end end -- this is required for parsing the CONFIG.TXT file -- [but redundant when the user merely changed the widget] gui.set_module(name, mod.enabled) ob_update_all() return end local opt = ob_find_mod_option(mod, option) if not opt then gui.printf("Ignoring unknown option: %s.%s\n", name, option) return end -- this can only happen while parsing the CONFIG.TXT file -- (containing some no-longer-used value). if not opt.avail_choices[value] then warning("invalid choice: %s (for option %s.%s)\n", value, name, option) return end opt.value = value gui.set_module_option(name, option, value) -- no need to call ob_update_all -- (nothing ever depends on custom options) end function ob_set_config(name, value) -- See the document 'doc/Config_Flow.txt' for a good -- description of the flow of configuration values -- between the C++ GUI and the Lua scripts. assert(name and value and type(value) == "string") if name == "seed" then OB_CONFIG[name] = tonumber(value) or 0 return end -- check all the UI modules for a matching option -- [ this is only needed when parsing the CONFIG.txt file ] each _,mod in OB_MODULES do if ob_check_ui_module(mod) then each opt in mod.options do if opt.name == name then ob_set_mod_option(mod.name, name, value) return end end end end if OB_CONFIG[name] and OB_CONFIG[name] == value then return -- no change end -- validate some important variables if name == "game" then assert(OB_CONFIG.game) if not OB_GAMES[value] then gui.printf("Ignoring unknown game: %s\n", value) return end elseif name == "engine" then assert(OB_CONFIG.engine) if not OB_ENGINES[value] then gui.printf("Ignoring unknown engine: %s\n", value) return end elseif name == "theme" then assert(OB_CONFIG.theme) if not OB_THEMES[value] then gui.printf("Ignoring unknown theme: %s\n", value) return end end OB_CONFIG[name] = value if name == "game" or name == "engine" then ob_update_all() end -- this is required for parsing the CONFIG.TXT file -- [ but redundant when the user merely changed the widget ] if name == "game" or name == "engine" or name == "theme" or name == "length" then gui.set_button(name, OB_CONFIG[name]) end end function ob_read_all_config(need_full, log_only) local function do_line(fmt, ...) if log_only then gui.printf(fmt .. "\n", ...) else gui.config_line(string.format(fmt, ...)) end end local function do_value(name, value) do_line("%s = %s", name, value or "XXX") end local function do_mod_value(name, value) do_line(" %s = %s", name, value or "XXX") end ---| ob_read_all_config |--- -- workaround for a limitation in C++ code if need_full == "" then need_full = false end if OB_CONFIG.seed and OB_CONFIG.seed != 0 then do_line("seed = %d", OB_CONFIG.seed) do_line("") end do_line("---- Game Settings ----") do_line("") do_value("game", OB_CONFIG.game) do_value("engine", OB_CONFIG.engine) do_value("length", OB_CONFIG.length) do_value("theme", OB_CONFIG.theme) do_line("") -- the UI modules/panels use bare option names each name in table.keys_sorted(OB_MODULES) do local def = OB_MODULES[name] if ob_check_ui_module(def) then do_line("---- %s ----", def.label) do_line("") each opt in def.options do do_value(opt.name, opt.value) end do_line("") end end do_line("---- Other Modules ----") do_line("") each name in table.keys_sorted(OB_MODULES) do local def = OB_MODULES[name] if ob_check_ui_module(def) then continue end if not need_full and not def.shown then continue end do_line("@%s = %s", name, sel(def.enabled, "1", "0")) -- module options if need_full or def.enabled then if def.options and not table.empty(def.options) then if def.options[1] then each opt in def.options do do_mod_value(opt.name, opt.value) end else each o_name,opt in def.options do do_mod_value(o_name, opt.value) end end end end do_line("") end do_line("-- END --") end function ob_load_game(game) -- 'game' parameter must be a sub-directory of the games/ folder -- ignore the template game -- it is only instructional if game == "template" then return end gui.debugf(" %s\n", game) gui.set_import_dir("games/" .. game) -- the base script will import even more script files gui.import("base") gui.set_import_dir("") end function ob_load_all_games() gui.printf("Loading all games...\n") local list = gui.scan_directory("games", "DIRS") if not list then error("Failed to scan 'games' directory") end if OB_CONFIG.only_game then gui.printf("Only loading one game: '%s'\n", OB_CONFIG.only_game) ob_load_game(OB_CONFIG.only_game) else each game in list do ob_load_game(game) end end if table.empty(OB_GAMES) then error("Failed to load any games at all") end end function ob_load_all_engines() gui.printf("Loading all engines...\n") local list = gui.scan_directory("engines", "*.lua") if not list then gui.printf("FAILED: scan 'engines' directory\n") return end gui.set_import_dir("engines") each filename in list do gui.debugf(" %s\n", filename) gui.import(filename) end gui.set_import_dir("") end function ob_load_all_modules() gui.printf("Loading all modules...\n") local list = gui.scan_directory("modules", "*.lua") if not list then gui.printf("FAILED: scan 'modules' directory\n") return end gui.set_import_dir("modules") each filename in list do gui.debugf(" %s\n", filename) gui.import(filename) end gui.set_import_dir("") end function ob_init() -- the missing print functions gui.printf = function (fmt, ...) if fmt then gui.raw_log_print(string.format(fmt, ...)) end end gui.debugf = function (fmt, ...) if fmt then gui.raw_debug_print(string.format(fmt, ...)) end end gui.printf("~~ Oblige Lua initialization begun ~~\n\n") -- load definitions for all games ob_load_all_games() ob_load_all_engines() ob_load_all_modules() table.name_up(OB_GAMES) table.name_up(OB_THEMES) table.name_up(OB_ENGINES) table.name_up(OB_MODULES) local function preinit_all(DEFS) local removed = {} each name,def in DEFS do if def.preinit_func then if def.preinit_func(def) == REMOVE_ME then table.insert(removed, name) end end end each name in removed do DEFS[name] = nil end end preinit_all(OB_GAMES) preinit_all(OB_THEMES) preinit_all(OB_ENGINES) preinit_all(OB_MODULES) local function button_sorter(A, B) if A.priority or B.priority then return (A.priority or 50) > (B.priority or 50) end return A.label < B.label end local function create_buttons(what, DEFS) assert(DEFS) gui.debugf("creating buttons for %s\n", what) local list = {} local min_priority = 999 each name,def in DEFS do assert(def.name and def.label) table.insert(list, def) min_priority = math.min(min_priority, def.priority or 50) end -- add separators for the Game, Engine and Theme menus if what == "game" and min_priority < 49 then table.insert(list, { priority=49, name="_", label="_" }) end if what == "engine" and min_priority < 92 then table.insert(list, { priority=92, name="_", label="_" }) end if what == "theme" and min_priority < 79 then table.insert(list, { priority=79, name="_", label="_" }) end table.sort(list, button_sorter) each def in list do if what == "module" then local where = def.side or "right" gui.add_module(where, def.name, def.label, def.tooltip) else gui.add_choice(what, def.name, def.label) end -- TODO : review this, does it belong HERE ? if what == "game" then gui.enable_choice("game", def.name, true) end end -- set the current value if what != "module" then local default = list[1] and list[1].name OB_CONFIG[what] = default end end local function simple_buttons(what, choices, default) for i = 1,#choices,2 do local id = choices[i] local label = choices[i+1] gui. add_choice(what, id, label) gui.enable_choice(what, id, true) end OB_CONFIG[what] = default end local function create_mod_options() gui.debugf("creating module options\n", what) each _,mod in OB_MODULES do if not mod.options then mod.options = {} else local list = mod.options -- handle lists (for UI modules) different from key/value tables if list[1] == nil then list = {} each name,opt in mod.options do opt.name = name table.insert(list, opt) end table.sort(list, button_sorter) end each opt in list do assert(opt.label) assert(opt.choices) gui.add_module_option(mod.name, opt.name, opt.label, opt.tooltip, opt.gap) opt.avail_choices = {} for i = 1,#opt.choices,2 do local id = opt.choices[i] local label = opt.choices[i+1] gui.add_option_choice(mod.name, opt.name, id, label) opt.avail_choices[id] = 1 end -- select a default value if not opt.default then if opt.avail_choices["default"] then opt.default = "default" elseif opt.avail_choices["normal"] then opt.default = "normal" elseif opt.avail_choices["medium"] then opt.default = "medium" elseif opt.avail_choices["mixed"] then opt.default = "mixed" else opt.default = opt.choices[1] end end opt.value = opt.default gui.set_module_option(mod.name, opt.name, opt.value) end -- for opt end end -- for mod end OB_CONFIG.seed = 0 create_buttons("game", OB_GAMES) create_buttons("engine", OB_ENGINES) create_buttons("theme", OB_THEMES) simple_buttons("length", LENGTH_CHOICES, "game") create_buttons("module", OB_MODULES) create_mod_options() ob_update_all() gui.set_button("game", OB_CONFIG.game) gui.set_button("engine", OB_CONFIG.engine) gui.set_button("length", OB_CONFIG.length) gui.set_button("theme", OB_CONFIG.theme) gui.printf("\n~~ Completed Lua initialization ~~\n\n") end function ob_game_format() assert(OB_CONFIG) assert(OB_CONFIG.game) local game = OB_GAMES[OB_CONFIG.game] assert(game) if game.extends then game = assert(OB_GAMES[game.extends]) end return assert(game.format) end function ob_default_filename() -- create a default filename [ WITHOUT any extension ] assert(OB_CONFIG) assert(OB_CONFIG.game) gui.rand_seed(OB_CONFIG.seed + 0) Naming_init() OB_CONFIG.title = Naming_grab_one("TITLE") -- massage into a usable filename local str = string.lower(OB_CONFIG.title) str = string.gsub(str, "%p", "") str = string.gsub(str, " ", "_") return str end ------------------------------------------------------------------------ function ob_merge_tab(name, tab) assert(name and tab) if not GAME[name] then GAME[name] = table.deep_copy(tab) return end -- support replacing _everything_ -- [ needed mainly for Doom 1 themes ] if tab.replace_all then GAME[name] = {} end table.merge_w_copy(GAME[name], tab) GAME[name].replace_all = nil end function ob_merge_table_list(tab_list) each GT in tab_list do assert(GT) each name,tab in GT do -- upper-case names should always be tables to copy if string.match(name, "^[A-Z]") then if type(tab) != "table" then error("Game field not a table: " .. tostring(name)) end ob_merge_tab(name, tab) end end end end function ob_add_current_game() local function recurse(name, child) local def = OB_GAMES[name] if not def then error("UNKNOWN GAME: " .. name) end -- here is the tricky bit : by recursing now, we can process all the -- definitions in the correct order (children after parents). if def.extends then recurse(def.extends, def) end if def.tables then ob_merge_table_list(def.tables) end if child and def.hooks then child.hooks = table.merge_missing(child.hooks or {}, def.hooks) end each keyword in { "format", "sub_format", "game_dir" } do if def[keyword] != nil then GAME[keyword] = def[keyword] end end return def end table.insert(GAME.modules, 1, recurse(OB_CONFIG.game)) end function ob_add_current_engine() local function recurse(name, child) local def = OB_ENGINES[name] if not def then error("UNKNOWN ENGINE: " .. name) end if def.extends then recurse(def.extends, def) end if def.tables then ob_merge_table_list(def.tables) end if child and def.hooks then child.hooks = table.merge_missing(child.hooks or {}, def.hooks) end return def end table.insert(GAME.modules, 2, recurse(OB_CONFIG.engine)) end function ob_sort_modules() GAME.modules = {} -- find all the visible & enabled modules -- [ ignore the special UI modules/panels ] each _,mod in OB_MODULES do if mod.enabled and mod.shown and not ob_check_ui_module(mod) then table.insert(GAME.modules, mod) end end -- sort them : lowest -> highest priority, because later -- entries can override things done by earlier ones. local function module_sorter(A, B) if A.priority or B.priority then return (A.priority or 50) < (B.priority or 50) end return A.label < B.label end if #GAME.modules > 1 then table.sort(GAME.modules, module_sorter) end end function ob_invoke_hook(name, ...) -- two passes, for example: setup and setup2 for pass = 1,2 do each mod in GAME.modules do local func = mod.hooks and mod.hooks[name] if func then func(mod, ...) end end name = name .. "2" end end function ob_transfer_ui_options() each _,mod in OB_MODULES do if ob_check_ui_module(mod) then each opt in mod.options do OB_CONFIG[opt.name] = opt.value or "UNSET" end end end -- fixes for backwards compatibility if OB_CONFIG.length == "full" then OB_CONFIG.length = "game" end if OB_CONFIG.theme == "mixed" then OB_CONFIG.theme = "epi" end if OB_CONFIG.size == "tiny" then OB_CONFIG.size = "small" end end function ob_build_setup() ob_clean_up() Naming_init() if OB_CONFIG.title then GAME.title = OB_CONFIG.title end ob_transfer_ui_options() ob_sort_modules() -- first entry in module list *must* be the game def, and second entry -- must be the engine definition. NOTE: neither are real modules! ob_add_current_game() ob_add_current_engine() -- merge tables from each module -- [ but skip GAME and ENGINE, which are already merged ] each mod in GAME.modules do if _index > 2 and mod.tables then ob_merge_table_list(mod.tables) end end PARAM = assert(GAME.PARAMETERS) table.merge_missing(PARAM, GLOBAL_PARAMETERS) -- load all the prefab definitions Fab_load_all_definitions() Grower_preprocess_grammar() gui.rand_seed(OB_CONFIG.seed + 0) ob_invoke_hook("setup") table.name_up(GAME.THEMES) table.name_up(GAME.ROOM_THEMES) table.name_up(GAME.ROOMS) if GAME.sub_format then gui.property("sub_format", GAME.sub_format) end gui.property("spot_low_h", PARAM.spot_low_h) gui.property("spot_high_h", PARAM.spot_high_h) end function ob_clean_up() GAME = {} THEME = {} PARAM = {} STYLE = {} LEVEL = nil EPISODE = nil PREFABS = nil SEEDS = nil collectgarbage("collect") end function ob_build_cool_shit() assert(OB_CONFIG) assert(OB_CONFIG.game) gui.printf("\n\n") gui.printf("~~~~~~~ Making Levels ~~~~~~~\n\n") ob_read_all_config(false, "log_only") gui.ticker() ob_build_setup() local status = Level_make_all() ob_clean_up() gui.printf("\n") if status == "abort" then gui.printf("\n") gui.printf("~~~~~~~ Build Aborted! ~~~~~~~\n\n") return "abort" end gui.printf("\n") gui.printf("~~~~~~ Finished Making Levels ~~~~~~\n\n") return "ok" end
gpl-2.0
AlexandreCA/update
scripts/globals/abilities/choral_roll.lua
9
2852
----------------------------------- -- Ability: Choral Roll -- Decreases spell interruption rate for party members within area of effect -- Optimal Job: Bard -- Lucky Number: 2 -- Unlucky Number: 6 -- Level: 26 -- -- Die Roll |No BRD |With BRD -- -------- -------- ------- -- 1 |-13 |-38 -- 2 |-55 |-80 -- 3 |-17 |-42 -- 4 |-20 |-45 -- 5 |-25 |-50 -- 6 |-8 |-33 -- 7 |-30 |-55 -- 8 |-35 |-60 -- 9 |-40 |-65 -- 10 |-45 |-70 -- 11 |-65 |-90 -- Bust |+25 |+25 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else player:setLocalVar("BRD_roll_bonus", 0); return 0,0; end end; ----------------------------------- -- onUseAbilityRoll ----------------------------------- function onUseAbilityRoll(caster,target,ability,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {13, 55, 17, 20, 25, 8, 30, 35, 40, 45, 65, 25} local effectpower = effectpowers[total] local jobBonus = caster:getLocalVar("BRD_roll_bonus"); if (total < 12) then -- see chaos_roll.lua for comments if (jobBonus == 0) then if (caster:hasPartyJob(JOB_BRD) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then jobBonus = 1; else jobBonus = 2; end end if (jobBonus == 1) then effectpower = effectpower + 25; end if (target:getID() == caster:getID()) then caster:setLocalVar("BRD_roll_bonus", jobBonus); end end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CHORAL_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_SPELLINTERRUPT) == false) then ability:setMsg(423); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Northern_San_dOria/npcs/Belgidiveau.lua
25
2335
----------------------------------- -- Area: Northern San d'Oria -- NPC: Belgidiveau -- Starts and Finishes Quest: Trouble at the Sluice -- @zone 231 -- @pos -98 0 69 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) troubleAtTheSluice = player:getQuestStatus(SANDORIA,TROUBLE_AT_THE_SLUICE); NeutralizerKI = player:hasKeyItem(NEUTRALIZER); if (troubleAtTheSluice == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3) then player:startEvent(0x0039); elseif (troubleAtTheSluice == QUEST_ACCEPTED and NeutralizerKI == false) then player:startEvent(0x0037); elseif (NeutralizerKI) then player:startEvent(0x0038); else player:startEvent(0x0249); 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 == 0x0039 and option == 0) then player:addQuest(SANDORIA,TROUBLE_AT_THE_SLUICE); player:setVar("troubleAtTheSluiceVar",1); elseif (csid == 0x0038) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16706); -- Heavy Axe else player:tradeComplete(); player:delKeyItem(NEUTRALIZER); player:addItem(16706); player:messageSpecial(ITEM_OBTAINED,16706); -- Heavy Axe player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,TROUBLE_AT_THE_SLUICE); end end end;
gpl-3.0
nwf/openwrt-luci
libs/luci-lib-nixio/axTLS/samples/lua/axssl.lua
176
19286
#!/usr/local/bin/lua -- -- Copyright (c) 2007, Cameron Rich -- -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright notice, -- this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the axTLS project nor the names of its -- contributors may be used to endorse or promote products derived -- from this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -- "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -- LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -- A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR -- CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -- SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED -- TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -- DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -- OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -- NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF -- THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -- -- -- Demonstrate the use of the axTLS library in Lua with a set of -- command-line parameters similar to openssl. In fact, openssl clients -- should be able to communicate with axTLS servers and visa-versa. -- -- This code has various bits enabled depending on the configuration. To enable -- the most interesting version, compile with the 'full mode' enabled. -- -- To see what options you have, run the following: -- > [lua] axssl s_server -? -- > [lua] axssl s_client -? -- -- The axtls/axtlsl shared libraries must be in the same directory or be found -- by the OS. -- -- require "bit" require("axtlsl") local socket = require("socket") -- print version? if #arg == 1 and arg[1] == "version" then print("axssl.lua "..axtlsl.ssl_version()) os.exit(1) end -- -- We've had some sort of command-line error. Print out the basic options. -- function print_options(option) print("axssl: Error: '"..option.."' is an invalid command.") print("usage: axssl [s_server|s_client|version] [args ...]") os.exit(1) end -- -- We've had some sort of command-line error. Print out the server options. -- function print_server_options(build_mode, option) local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl.ssl_get_config( axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) print("unknown option "..option) print("usage: s_server [args ...]") print(" -accept\t- port to accept on (default is 4433)") print(" -quiet\t\t- No server output") if build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then print(" -cert arg\t- certificate file to add (in addition to ".. "default) to chain -") print("\t\t Can repeat up to "..cert_size.." times") print(" -key arg\t- Private key file to use - default DER format") print(" -pass\t\t- private key file pass phrase source") end if build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then print(" -verify\t- turn on peer certificate verification") print(" -CAfile arg\t- Certificate authority - default DER format") print("\t\t Can repeat up to "..ca_cert_size.." times") end if build_mode == axtlsl.SSL_BUILD_FULL_MODE then print(" -debug\t\t- Print more output") print(" -state\t\t- Show state messages") print(" -show-rsa\t- Show RSA state") end os.exit(1) end -- -- We've had some sort of command-line error. Print out the client options. -- function print_client_options(build_mode, option) local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl.ssl_get_config( axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) print("unknown option "..option) if build_mode >= axtlsl.SSL_BUILD_ENABLE_CLIENT then print("usage: s_client [args ...]") print(" -connect host:port - who to connect to (default ".. "is localhost:4433)") print(" -verify\t- turn on peer certificate verification") print(" -cert arg\t- certificate file to use - default DER format") print(" -key arg\t- Private key file to use - default DER format") print("\t\t Can repeat up to "..cert_size.." times") print(" -CAfile arg\t- Certificate authority - default DER format") print("\t\t Can repeat up to "..ca_cert_size.."times") print(" -quiet\t\t- No client output") print(" -pass\t\t- private key file pass phrase source") print(" -reconnect\t- Drop and re-make the connection ".. "with the same Session-ID") if build_mode == axtlsl.SSL_BUILD_FULL_MODE then print(" -debug\t\t- Print more output") print(" -state\t\t- Show state messages") print(" -show-rsa\t- Show RSA state") end else print("Change configuration to allow this feature") end os.exit(1) end -- Implement the SSL server logic. function do_server(build_mode) local i = 2 local v local port = 4433 local options = axtlsl.SSL_DISPLAY_CERTS local quiet = false local password = "" local private_key_file = nil local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl. ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) local cert = {} local ca_cert = {} while i <= #arg do if arg[i] == "-accept" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 port = arg[i] elseif arg[i] == "-quiet" then quiet = true options = bit.band(options, bit.bnot(axtlsl.SSL_DISPLAY_CERTS)) elseif build_mode >= axtlsl.SSL_BUILD_SERVER_ONLY then if arg[i] == "-cert" then if i >= #arg or #cert >= cert_size then print_server_options(build_mode, arg[i]) end i = i + 1 table.insert(cert, arg[i]) elseif arg[i] == "-key" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 private_key_file = arg[i] options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY) elseif arg[i] == "-pass" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 password = arg[i] elseif build_mode >= axtlsl.SSL_BUILD_ENABLE_VERIFICATION then if arg[i] == "-verify" then options = bit.bor(options, axtlsl.SSL_CLIENT_AUTHENTICATION) elseif arg[i] == "-CAfile" then if i >= #arg or #ca_cert >= ca_cert_size then print_server_options(build_mode, arg[i]) end i = i + 1 table.insert(ca_cert, arg[i]) elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then if arg[i] == "-debug" then options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES) elseif arg[i] == "-state" then options = bit.bor(options, axtlsl.SSL_DISPLAY_STATES) elseif arg[i] == "-show-rsa" then options = bit.bor(options, axtlsl.SSL_DISPLAY_RSA) else print_server_options(build_mode, arg[i]) end else print_server_options(build_mode, arg[i]) end else print_server_options(build_mode, arg[i]) end else print_server_options(build_mode, arg[i]) end i = i + 1 end -- Create socket for incoming connections local server_sock = socket.try(socket.bind("*", port)) --------------------------------------------------------------------------- -- This is where the interesting stuff happens. Up until now we've -- just been setting up sockets etc. Now we do the SSL handshake. --------------------------------------------------------------------------- local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_SVR_SESS) if ssl_ctx == nil then error("Error: Server context is invalid") end if private_key_file ~= nil then local obj_type = axtlsl.SSL_OBJ_RSA_KEY if string.find(private_key_file, ".p8") then obj_type = axtlsl.SSL_OBJ_PKCS8 end if string.find(private_key_file, ".p12") then obj_type = axtlsl.SSL_OBJ_PKCS12 end if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file, password) ~= axtlsl.SSL_OK then error("Private key '" .. private_key_file .. "' is undefined.") end end for _, v in ipairs(cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .. "' is undefined.") end end for _, v in ipairs(ca_cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .."' is undefined.") end end while true do if not quiet then print("ACCEPT") end local client_sock = server_sock:accept(); local ssl = axtlsl.ssl_server_new(ssl_ctx, client_sock:getfd()) -- do the actual SSL handshake local connected = false local res local buf while true do socket.select({client_sock}, nil) res, buf = axtlsl.ssl_read(ssl) if res == axtlsl.SSL_OK then -- connection established and ok if axtlsl.ssl_handshake_status(ssl) == axtlsl.SSL_OK then if not quiet and not connected then display_session_id(ssl) display_cipher(ssl) end connected = true end end if res > axtlsl.SSL_OK then for _, v in ipairs(buf) do io.write(string.format("%c", v)) end elseif res < axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end break end end -- client was disconnected or the handshake failed. print("CONNECTION CLOSED") axtlsl.ssl_free(ssl) client_sock:close() end axtlsl.ssl_ctx_free(ssl_ctx) end -- -- Implement the SSL client logic. -- function do_client(build_mode) local i = 2 local v local port = 4433 local options = bit.bor(axtlsl.SSL_SERVER_VERIFY_LATER, axtlsl.SSL_DISPLAY_CERTS) local private_key_file = nil local reconnect = 0 local quiet = false local password = "" local session_id = {} local host = "127.0.0.1" local cert_size = axtlsl.ssl_get_config(axtlsl.SSL_MAX_CERT_CFG_OFFSET) local ca_cert_size = axtlsl. ssl_get_config(axtlsl.SSL_MAX_CA_CERT_CFG_OFFSET) local cert = {} local ca_cert = {} while i <= #arg do if arg[i] == "-connect" then if i >= #arg then print_client_options(build_mode, arg[i]) end i = i + 1 local t = string.find(arg[i], ":") host = string.sub(arg[i], 1, t-1) port = string.sub(arg[i], t+1) elseif arg[i] == "-cert" then if i >= #arg or #cert >= cert_size then print_client_options(build_mode, arg[i]) end i = i + 1 table.insert(cert, arg[i]) elseif arg[i] == "-key" then if i >= #arg then print_client_options(build_mode, arg[i]) end i = i + 1 private_key_file = arg[i] options = bit.bor(options, axtlsl.SSL_NO_DEFAULT_KEY) elseif arg[i] == "-CAfile" then if i >= #arg or #ca_cert >= ca_cert_size then print_client_options(build_mode, arg[i]) end i = i + 1 table.insert(ca_cert, arg[i]) elseif arg[i] == "-verify" then options = bit.band(options, bit.bnot(axtlsl.SSL_SERVER_VERIFY_LATER)) elseif arg[i] == "-reconnect" then reconnect = 4 elseif arg[i] == "-quiet" then quiet = true options = bit.band(options, bnot(axtlsl.SSL_DISPLAY_CERTS)) elseif arg[i] == "-pass" then if i >= #arg then print_server_options(build_mode, arg[i]) end i = i + 1 password = arg[i] elseif build_mode == axtlsl.SSL_BUILD_FULL_MODE then if arg[i] == "-debug" then options = bit.bor(options, axtlsl.SSL_DISPLAY_BYTES) elseif arg[i] == "-state" then options = bit.bor(axtlsl.SSL_DISPLAY_STATES) elseif arg[i] == "-show-rsa" then options = bit.bor(axtlsl.SSL_DISPLAY_RSA) else -- don't know what this is print_client_options(build_mode, arg[i]) end else -- don't know what this is print_client_options(build_mode, arg[i]) end i = i + 1 end local client_sock = socket.try(socket.connect(host, port)) local ssl local res if not quiet then print("CONNECTED") end --------------------------------------------------------------------------- -- This is where the interesting stuff happens. Up until now we've -- just been setting up sockets etc. Now we do the SSL handshake. --------------------------------------------------------------------------- local ssl_ctx = axtlsl.ssl_ctx_new(options, axtlsl.SSL_DEFAULT_CLNT_SESS) if ssl_ctx == nil then error("Error: Client context is invalid") end if private_key_file ~= nil then local obj_type = axtlsl.SSL_OBJ_RSA_KEY if string.find(private_key_file, ".p8") then obj_type = axtlsl.SSL_OBJ_PKCS8 end if string.find(private_key_file, ".p12") then obj_type = axtlsl.SSL_OBJ_PKCS12 end if axtlsl.ssl_obj_load(ssl_ctx, obj_type, private_key_file, password) ~= axtlsl.SSL_OK then error("Private key '"..private_key_file.."' is undefined.") end end for _, v in ipairs(cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .. "' is undefined.") end end for _, v in ipairs(ca_cert) do if axtlsl.ssl_obj_load(ssl_ctx, axtlsl.SSL_OBJ_X509_CACERT, v, "") ~= axtlsl.SSL_OK then error("Certificate '"..v .."' is undefined.") end end -- Try session resumption? if reconnect ~= 0 then local session_id = nil local sess_id_size = 0 while reconnect > 0 do reconnect = reconnect - 1 ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), session_id, sess_id_size) res = axtlsl.ssl_handshake_status(ssl) if res ~= axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end axtlsl.ssl_free(ssl) os.exit(1) end display_session_id(ssl) session_id = axtlsl.ssl_get_session_id(ssl) sess_id_size = axtlsl.ssl_get_session_id_size(ssl) if reconnect > 0 then axtlsl.ssl_free(ssl) client_sock:close() client_sock = socket.try(socket.connect(host, port)) end end else ssl = axtlsl.ssl_client_new(ssl_ctx, client_sock:getfd(), nil, 0) end -- check the return status res = axtlsl.ssl_handshake_status(ssl) if res ~= axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end os.exit(1) end if not quiet then local common_name = axtlsl.ssl_get_cert_dn(ssl, axtlsl.SSL_X509_CERT_COMMON_NAME) if common_name ~= nil then print("Common Name:\t\t\t"..common_name) end display_session_id(ssl) display_cipher(ssl) end while true do local line = io.read() if line == nil then break end local bytes = {} for i = 1, #line do bytes[i] = line.byte(line, i) end bytes[#line+1] = 10 -- add carriage return, null bytes[#line+2] = 0 res = axtlsl.ssl_write(ssl, bytes, #bytes) if res < axtlsl.SSL_OK then if not quiet then axtlsl.ssl_display_error(res) end break end end axtlsl.ssl_ctx_free(ssl_ctx) client_sock:close() end -- -- Display what cipher we are using -- function display_cipher(ssl) io.write("CIPHER is ") local cipher_id = axtlsl.ssl_get_cipher_id(ssl) if cipher_id == axtlsl.SSL_AES128_SHA then print("AES128-SHA") elseif cipher_id == axtlsl.SSL_AES256_SHA then print("AES256-SHA") elseif axtlsl.SSL_RC4_128_SHA then print("RC4-SHA") elseif axtlsl.SSL_RC4_128_MD5 then print("RC4-MD5") else print("Unknown - "..cipher_id) end end -- -- Display what session id we have. -- function display_session_id(ssl) local session_id = axtlsl.ssl_get_session_id(ssl) local v if #session_id > 0 then print("-----BEGIN SSL SESSION PARAMETERS-----") for _, v in ipairs(session_id) do io.write(string.format("%02x", v)) end print("\n-----END SSL SESSION PARAMETERS-----") end end -- -- Main entry point. Doesn't do much except works out whether we are a client -- or a server. -- if #arg == 0 or (arg[1] ~= "s_server" and arg[1] ~= "s_client") then print_options(#arg > 0 and arg[1] or "") end local build_mode = axtlsl.ssl_get_config(axtlsl.SSL_BUILD_MODE) _ = arg[1] == "s_server" and do_server(build_mode) or do_client(build_mode) os.exit(0)
apache-2.0
AlexandreCA/update
scripts/zones/Pashhow_Marshlands/npcs/Sharp_Tooth_IM.lua
30
3065
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Sharp Tooth, I.M. -- Type: Border Conquest Guards -- @pos 536.291 23.517 694.063 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Pashhow_Marshlands/TextIDs"); local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = DERFLAND; local csid = 0x7ff8; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
AlexandreCA/darkstar
scripts/zones/Port_Jeuno/npcs/Karl.lua
26
2503
----------------------------------- -- Area: Port Jeuno -- NPC: Karl -- Starts and Finishes Quest: Child's Play -- @pos -60 0.1 -8 246 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,CHILD_S_PLAY) == QUEST_ACCEPTED and trade:hasItemQty(776,1) == true and trade:getItemCount() == 1) then player:startEvent(0x0001); -- Finish quest end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ChildsPlay = player:getQuestStatus(JEUNO,CHILD_S_PLAY); local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,16) == false) then player:startEvent(316); elseif (player:getQuestStatus(JEUNO,THE_WONDER_MAGIC_SET) == QUEST_ACCEPTED and ChildsPlay == QUEST_AVAILABLE) then player:startEvent(0x0000); -- Start quest elseif (ChildsPlay == QUEST_ACCEPTED) then player:startEvent(0x003d); -- mid quest CS else player:startEvent(0x003a); -- Standard dialog 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 == 0x0000) then player:addQuest(JEUNO,CHILD_S_PLAY); elseif (csid == 0x0001) then player:addTitle(TRADER_OF_MYSTERIES); player:addKeyItem(WONDER_MAGIC_SET); player:messageSpecial(KEYITEM_OBTAINED,WONDER_MAGIC_SET); player:addFame(JEUNO, 30); player:tradeComplete(trade); player:completeQuest(JEUNO,CHILD_S_PLAY); elseif (csid == 316) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",16,true); end end;
gpl-3.0
AlexandreCA/update
scripts/zones/Bastok_Mines/npcs/Pavvke.lua
36
2173
----------------------------------- -- Area: Bastok Mines -- NPC: Pavvke -- Starts Quests: Fallen Comrades (100%) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); SilverTag = trade:hasItemQty(13116,1); Fallen = player:getQuestStatus(BASTOK,FALLEN_COMRADES); if (Fallen == 1 and SilverTag == true and count == 1) then player:tradeComplete(); player:startEvent(0x005b); elseif (Fallen == 2 and SilverTag == true and count == 1) then player:tradeComplete(); player:startEvent(0x005c); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Fallen = player:getQuestStatus(BASTOK,FALLEN_COMRADES); pLevel = player:getMainLvl(player); pFame = player:getFameLevel(BASTOK); if (Fallen == 0 and pLevel >= 12 and pFame >= 2) then player:startEvent(0x005a); else player:startEvent(0x004b); 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 == 0x005a) then player:addQuest(BASTOK,FALLEN_COMRADES); elseif (csid == 0x005b) then player:completeQuest(BASTOK,FALLEN_COMRADES); player:addFame(BASTOK,BAS_FAME*120); player:addGil(GIL_RATE*550); player:messageSpecial(GIL_OBTAINED,GIL_RATE*550); elseif (csid == 0x005c) then player:addFame(BASTOK,BAS_FAME*8); player:addGil(GIL_RATE*550); player:messageSpecial(GIL_OBTAINED,GIL_RATE*550); end end;
gpl-3.0
AlexandreCA/darkstar
scripts/globals/items/divine_sword.lua
42
1076
----------------------------------------- -- ID: 16549 -- Item: Divine Sword -- Additional Effect: Light Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(7,21); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0); dmg = adjustForTarget(target,dmg,ELE_LIGHT); dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_LIGHT_DAMAGE,message,dmg; end end;
gpl-3.0
FPtje/FProfiler
lua/fprofiler/ui/clientcontrol.lua
2
4281
local get, update, onUpdate = FProfiler.UI.getModelValue, FProfiler.UI.updateModel, FProfiler.UI.onModelUpdate --[[------------------------------------------------------------------------- (Re)start clientside profiling ---------------------------------------------------------------------------]] local function restartProfiling() if get({"client", "shouldReset"}) then FProfiler.Internal.reset() update({"client", "recordTime"}, 0) end local focus = get({"client", "focusObj"}) update({"client", "sessionStart"}, CurTime()) update({"client", "sessionStartSysTime"}, SysTime()) FProfiler.Internal.start(focus) end --[[------------------------------------------------------------------------- Stop profiling ---------------------------------------------------------------------------]] local function stopProfiling() FProfiler.Internal.stop() local newTime = get({"client", "recordTime"}) + SysTime() - (get({"client", "sessionStartSysTime"}) or 0) -- Get the aggregated data local mostTime = FProfiler.Internal.getAggregatedResults(100) update({"client", "bottlenecks"}, mostTime) update({"client", "topLagSpikes"}, FProfiler.Internal.getMostExpensiveSingleCalls()) update({"client", "recordTime"}, newTime) update({"client", "sessionStart"}, nil) update({"client", "sessionStartSysTime"}, nil) end --[[------------------------------------------------------------------------- Start/stop recording when the recording status is changed ---------------------------------------------------------------------------]] onUpdate({"client", "status"}, function(new, old) if new == old then return end (new == "Started" and restartProfiling or stopProfiling)() end) --[[------------------------------------------------------------------------- Update the current selected focus object when data is entered ---------------------------------------------------------------------------]] onUpdate({"client", "focusStr"}, function(new) update({"client", "focusObj"}, FProfiler.funcNameToObj(new)) end) --[[------------------------------------------------------------------------- Update info when a different line is selected ---------------------------------------------------------------------------]] onUpdate({"client", "currentSelected"}, function(new) if not new or not new.info or not new.info.linedefined or not new.info.lastlinedefined or not new.info.short_src then return end update({"client", "sourceText"}, FProfiler.readSource(new.info.short_src, new.info.linedefined, new.info.lastlinedefined)) end) --[[------------------------------------------------------------------------- When a function is to be printed to console ---------------------------------------------------------------------------]] onUpdate({"client", "toConsole"}, function(data) if not data then return end update({"client", "toConsole"}, nil) show(data) file.CreateDir("fprofiler") file.Write("fprofiler/profiledata.txt", showStr(data)) MsgC(Color(200, 200, 200), "-----", Color(120, 120, 255), "NOTE", Color(200, 200, 200), "---------------\n") MsgC(Color(200, 200, 200), "If the above function does not fit in console, you can find it in data/fprofiler/profiledata.txt\n\n") end) --[[------------------------------------------------------------------------- API function: start profiling ---------------------------------------------------------------------------]] function FProfiler.start(focus) update({"client", "focusStr"}, tostring(focus)) update({"client", "focusObj"}, focus) update({"client", "shouldReset"}, true) update({"client", "status"}, "Started") end --[[------------------------------------------------------------------------- API function: stop profiling ---------------------------------------------------------------------------]] function FProfiler.stop() update({"client", "status"}, "Stopped") end --[[------------------------------------------------------------------------- API function: continue profiling ---------------------------------------------------------------------------]] function FProfiler.continueProfiling() update({"client", "shouldReset"}, false) update({"client", "status"}, "Started") end
lgpl-2.1
RebootRevival/FFXI_Test
scripts/zones/Port_Windurst/npcs/Sigismund.lua
3
2357
----------------------------------- -- Area: Windurst Waters -- NPC: Sigismund -- Starts and Finishes Quest: To Catch a Falling Star -- !pos -110 -10 82 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Windurst/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) starstatus = player:getQuestStatus(WINDURST,TO_CATCH_A_FALLIHG_STAR); if (starstatus == 1 and trade:hasItemQty(546,1) == true and trade:getItemCount() == 1 and trade:getGil() == 0) then player:startEvent(0x00c7); -- Quest Finish end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) starstatus = player:getQuestStatus(WINDURST,TO_CATCH_A_FALLIHG_STAR); if (starstatus == QUEST_AVAILABLE) then player:startEvent(0x00c4,0,546); -- Quest Start elseif (starstatus == QUEST_ACCEPTED) then player:startEvent(0x00c5,0,546); -- Quest Reminder elseif (starstatus == QUEST_COMPLETED and player:getVar("QuestCatchAFallingStar_prog") > 0) then player:startEvent(0x00c8); -- After Quest player:setVar("QuestCatchAFallingStar_prog",0) else player:startEvent(0x0165); 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 == 0x00c4) then player:addQuest(WINDURST,TO_CATCH_A_FALLIHG_STAR); elseif (csid == 0x00c7) then player:tradeComplete(trade); player:completeQuest(WINDURST,TO_CATCH_A_FALLIHG_STAR); player:addFame(WINDURST,75); player:addItem(12316); player:messageSpecial(ITEM_OBTAINED,12316); player:setVar("QuestCatchAFallingStar_prog",2); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Southern_San_dOria/npcs/Aravoge_TK.lua
3
2889
----------------------------------- -- Area: Southern San d'Oria -- NPC: Aravoge, T.K. -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Southern_San_dOria/TextIDs"); local guardnation = NATION_SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border local size = #SandInv; local inventory = SandInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ffa,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); updateConquestGuard(player,csid,option,size,inventory); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); finishConquestGuard(player,csid,option,size,inventory,guardnation); end;
gpl-3.0
rudolfmleziva/AdministratorTeritorial
cocos2d/cocos/scripting/lua-bindings/auto/api/Skin.lua
10
2198
-------------------------------- -- @module Skin -- @extend Sprite -- @parent_module ccs -------------------------------- -- -- @function [parent=#Skin] getBone -- @param self -- @return Bone#Bone ret (return value: ccs.Bone) -------------------------------- -- -- @function [parent=#Skin] getNodeToWorldTransformAR -- @param self -- @return mat4_table#mat4_table ret (return value: mat4_table) -------------------------------- -- -- @function [parent=#Skin] initWithFile -- @param self -- @param #string filename -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Skin] getDisplayName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- -- @function [parent=#Skin] updateArmatureTransform -- @param self -------------------------------- -- -- @function [parent=#Skin] initWithSpriteFrameName -- @param self -- @param #string spriteFrameName -- @return bool#bool ret (return value: bool) -------------------------------- -- -- @function [parent=#Skin] setBone -- @param self -- @param #ccs.Bone bone -------------------------------- -- @overload self, string -- @overload self -- @function [parent=#Skin] create -- @param self -- @param #string pszFileName -- @return Skin#Skin ret (return value: ccs.Skin) -------------------------------- -- -- @function [parent=#Skin] createWithSpriteFrameName -- @param self -- @param #string pszSpriteFrameName -- @return Skin#Skin ret (return value: ccs.Skin) -------------------------------- -- -- @function [parent=#Skin] updateTransform -- @param self -------------------------------- -- -- @function [parent=#Skin] getNodeToWorldTransform -- @param self -- @return mat4_table#mat4_table ret (return value: mat4_table) -------------------------------- -- -- @function [parent=#Skin] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -------------------------------- -- js ctor -- @function [parent=#Skin] Skin -- @param self return nil
gpl-3.0
tommo/mock
mock/sqscript/SQNodeMsg.lua
1
2611
module 'mock' -------------------------------------------------------------------- CLASS: SQNodeMsg ( SQNode ) :MODEL{ Field 'msg' :string(); Field 'data' :string(); } function SQNodeMsg:__init() self.msg = '' self.data = nil end function SQNodeMsg:load( data ) local args = data.args self.msg = args[1] or false self.data = args[2] or nil end function SQNodeMsg:enter( state, env ) if not self.msg or self.msg == '' then return false end local targets = self:getContextEntities( state ) for i, target in ipairs( targets ) do target:tell( self.msg, self.data ) end end function SQNodeMsg:getRichText() return string.format( '<cmd>MSG</cmd> <data>%s ( <string>%s</string> )</data>', self.msg, self.data ) end -------------------------------------------------------------------- CLASS: SQNodeChildMsg ( SQNode ) :MODEL{ Field 'target' :string(); Field 'msg' :string(); Field 'data' :string(); } function SQNodeChildMsg:__init() self.target = '' self.msg = '' self.data = nil end function SQNodeChildMsg:load( data ) local args = data.args self.target = args[1] self.msg = args[2] or false self.data = args[3] or nil end function SQNodeChildMsg:enter( state, env ) if not self.msg or self.msg == '' then return false end local target = self:getContextEntity( state ):findChildCom( self.target ) target:tell( self.msg, self.data ) end function SQNodeChildMsg:getRichText() return string.format( '<cmd>MSG</cmd> <data>%s ( <string>%s</string> )</data>', self.msg, self.data ) end -------------------------------------------------------------------- CLASS: SQNodeWaitMsg ( SQNode ) :MODEL{ Field 'msg' :string() } function SQNodeWaitMsg:__init() self.msg = '' end function SQNodeWaitMsg:enter( state, env ) local entity = state:getEnv( 'entity' ) if not entity then return false end local msgListener = function( msg, data ) return self:onMsg( state, env, msg, data ) end env.msgListener = msgListener entity:addMsgListener( msgListener ) end function SQNodeWaitMsg:step( state, env ) if env.received then local entity = state:getEnv( 'entity' ) entity:removeMsgListener( env.msgListener ) return true end end function SQNodeWaitMsg:onMsg( state, env, msg, data ) if msg == self.msg then env.received = true end end function SQNodeWaitMsg:getRichText() return string.format( '<cmd>WAIT_MSG</cmd> <data>%s</data>', self.msg ) end -------------------------------------------------------------------- registerSQNode( 'tell', SQNodeMsg ) registerSQNode( 'tellto', SQNodeChildMsg ) registerSQNode( 'wait_msg', SQNodeWaitMsg )
mit
RebootRevival/FFXI_Test
scripts/zones/Port_San_dOria/npcs/Portaure.lua
17
1666
----------------------------------- -- Area: Port San d'Oria -- NPC: Portaure -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradePortaure") == 0) then player:messageSpecial(PORTAURE_DIALOG); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradePortaure",1); player:messageSpecial(FLYER_ACCEPTED); player:messageSpecial(FLYERS_HANDED,17 - player:getVar("FFR")); player:tradeComplete(); elseif (player:getVar("tradePortaure") ==1) then player:messageSpecial(FLYER_ALREADY); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x28b); 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
RebootRevival/FFXI_Test
scripts/globals/weaponskills/red_lotus_blade.lua
23
1318
----------------------------------- -- Red Lotus Blade -- Sword weapon skill -- Skill Level: 50 -- Deals fire elemental damage to enemy. Damage varies with TP. -- Aligned with the Flame Gorget & Breeze Gorget. -- Aligned with the Flame Belt & Breeze Belt. -- Element: Fire -- Modifiers: STR:40% ; INT:40% -- 100%TP 200%TP 300%TP -- 1.00 2.38 3.75 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.ftp100 = 1; params.ftp200 = 2.38; params.ftp300 = 3; params.str_wsc = 0.3; 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_FIRE; params.skill = SKILL_SWD; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp300 = 3.75; params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Goodzilam/Goodzila-bot_v1.5
plugins/web_shot.lua
110
1424
local helpers = require "OAuth.helpers" local base = 'https://screenshotmachine.com/' local url = base .. 'processor.php' local function get_webshot_url(param) local response_body = {} local request_constructor = { url = url, method = "GET", sink = ltn12.sink.table(response_body), headers = { referer = base, dnt = "1", origin = base, ["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36" }, redirect = false } local arguments = { urlparam = param, size = "FULL" } request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments) local ok, response_code, response_headers, response_status_line = https.request(request_constructor) if not ok or response_code ~= 200 then return nil end local response = table.concat(response_body) return string.match(response, "href='(.-)'") end local function run(msg, matches) local find = get_webshot_url(matches[1]) if find then local imgurl = base .. find local receiver = get_receiver(msg) send_photo_from_url(receiver, imgurl) end end return { description = "Website Screen Shot", usage = { "/web (url) : screen shot of website" }, patterns = { "^[!/]web (https?://[%w-_%.%?%.:/%+=&]+)$", }, run = run }
gpl-2.0
RebootRevival/FFXI_Test
scripts/zones/The_Ashu_Talif/Zone.lua
10
1253
----------------------------------- -- -- Zone: The_Ashu_Talif -- ----------------------------------- require("scripts/globals/settings"); local TheAshuTalif = require("scripts/zones/The_Ashu_Talif/IDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option,target) -- printf("Zone Update CSID: %u",csid); -- printf("Zone Update RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("Zone Finish CSID: %u",csid); -- printf("Zone Finish RESULT: %u",option); if(csid == 102) then player:setPos(0,0,0,0,54); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/items/loaf_of_iron_bread.lua
12
1184
----------------------------------------- -- ID: 4499 -- Item: loaf_of_iron_bread -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 4 -- Vitality 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,1800,4499); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 4); target:addMod(MOD_VIT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 4); target:delMod(MOD_VIT, 1); end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/globals/spells/graviga.lua
1
1114
----------------------------------------- -- Spell: Gravity ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Pull base stats. local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); local power = 50; -- 50% reduction -- Duration, including resistance. Unconfirmed. local duration = 120; local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = 35; params.bonus = 0; params.effect = EFFECT_WEIGHT; duration = duration * applyResistanceEffect(caster, target, spell, params); if (duration >= 30) then --Do it! if (target:addStatusEffect(EFFECT_WEIGHT,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(284); end return EFFECT_WEIGHT; end;
gpl-3.0
rafradek/wire
lua/entities/gmod_wire_egp/lib/egplib/objectcontrol.lua
9
7301
-------------------------------------------------------- -- Objects -------------------------------------------------------- local EGP = EGP EGP.Objects = {} EGP.Objects.Names = {} EGP.Objects.Names_Inverted = {} -- This object is not used. It's only a base EGP.Objects.Base = {} EGP.Objects.Base.ID = 0 EGP.Objects.Base.x = 0 EGP.Objects.Base.y = 0 EGP.Objects.Base.w = 0 EGP.Objects.Base.h = 0 EGP.Objects.Base.r = 255 EGP.Objects.Base.g = 255 EGP.Objects.Base.b = 255 EGP.Objects.Base.a = 255 EGP.Objects.Base.material = "" if CLIENT then EGP.Objects.Base.material = false end EGP.Objects.Base.parent = 0 EGP.Objects.Base.Transmit = function( self ) EGP:SendPosSize( self ) EGP:SendColor( self ) EGP:SendMaterial( self ) net.WriteInt( self.parent, 16 ) end EGP.Objects.Base.Receive = function( self ) local tbl = {} EGP:ReceivePosSize( tbl ) EGP:ReceiveColor( tbl, self ) EGP:ReceiveMaterial( tbl ) tbl.parent = net.ReadInt(16) return tbl end EGP.Objects.Base.DataStreamInfo = function( self ) return { x = self.x, y = self.y, w = self.w, h = self.h, r = self.r, g = self.g, b = self.b, a = self.a, material = self.material, parent = self.parent } end ---------------------------- -- Get Object ---------------------------- function EGP:GetObjectByID( ID ) for k,v in pairs( EGP.Objects ) do if (v.ID == ID) then return table.Copy( v ) end end ErrorNoHalt( "[EGP] Error! Object with ID '" .. ID .. "' does not exist. Please post this bug message in the EGP thread on the wiremod forums.\n" ) end ---------------------------- -- Load all objects ---------------------------- function EGP:NewObject( Name ) if self.Objects[Name] then return self.Objects[Name] end -- Create table self.Objects[Name] = {} -- Set info self.Objects[Name].Name = Name table.Inherit( self.Objects[Name], self.Objects.Base ) -- Create lookup table local ID = table.Count(self.Objects) self.Objects[Name].ID = ID self.Objects.Names[Name] = ID -- Inverted lookup table self.Objects.Names_Inverted[ID] = Name return self.Objects[Name] end local folder = "entities/gmod_wire_egp/lib/objects/" local files = file.Find(folder.."*.lua", "LUA") table.sort( files ) for _,v in pairs( files ) do include(folder..v) if (SERVER) then AddCSLuaFile(folder..v) end end ---------------------------- -- Object existance check ---------------------------- function EGP:HasObject( Ent, index ) if (!EGP:ValidEGP( Ent )) then return false end if SERVER then index = math.Round(math.Clamp(index or 1, 1, self.ConVars.MaxObjects:GetInt())) end if (!Ent.RenderTable or #Ent.RenderTable == 0) then return false end for k,v in pairs( Ent.RenderTable ) do if (v.index == index) then return true, k, v end end return false end ---------------------------- -- Object order changing ---------------------------- function EGP:SetOrder( Ent, from, to ) if (!Ent.RenderTable or #Ent.RenderTable == 0) then return false end if (Ent.RenderTable[from]) then to = math.Clamp(math.Round(to or 1),1,#Ent.RenderTable) table.insert( Ent.RenderTable, to, table.remove( Ent.RenderTable, from ) ) if (SERVER) then Ent.RenderTable[to].ChangeOrder = {from,to} end return true end return false end ---------------------------- -- Create / edit objects ---------------------------- function EGP:CreateObject( Ent, ObjID, Settings ) if (!self:ValidEGP( Ent )) then return false end if (!self.Objects.Names_Inverted[ObjID]) then ErrorNoHalt("Trying to create nonexistant object! Please report this error to Divran at wiremod.com. ObjID: " .. ObjID .. "\n") return false end if SERVER then Settings.index = math.Round(math.Clamp(Settings.index or 1, 1, self.ConVars.MaxObjects:GetInt())) end local bool, k, v = self:HasObject( Ent, Settings.index ) if (bool) then -- Already exists. Change settings: if (v.ID != ObjID) then -- Not the same kind of object, create new local Obj = {} Obj = self:GetObjectByID( ObjID ) self:EditObject( Obj, Settings ) Obj.index = Settings.index Ent.RenderTable[k] = Obj return true, Obj else return self:EditObject( v, Settings ), v end else -- Did not exist. Create: local Obj = self:GetObjectByID( ObjID ) self:EditObject( Obj, Settings ) Obj.index = Settings.index table.insert( Ent.RenderTable, Obj ) return true, Obj end end function EGP:EditObject( Obj, Settings ) local ret = false for k,v in pairs( Settings ) do if (Obj[k] ~= nil and Obj[k] ~= v) then Obj[k] = v ret = true end end return ret end -------------------------------------------------------- -- Homescreen -------------------------------------------------------- EGP.HomeScreen = {} local mat if CLIENT then mat = Material else mat = function( str ) return str end end -- Create table local tbl = { { ID = EGP.Objects.Names["Box"], Settings = { x = 256, y = 256, h = 356, w = 356, material = mat("expression 2/cog"), r = 150, g = 34, b = 34, a = 255 } }, { ID = EGP.Objects.Names["Text"], Settings = {x = 256, y = 256, text = "EGP 3", fontid = 1, valign = 1, halign = 1, size = 50, r = 135, g = 135, b = 135, a = 255 } } } --[[ Old homescreen (EGP v2 home screen design contest winner) local tbl = { { ID = EGP.Objects.Names["Box"], Settings = { x = 256, y = 256, w = 362, h = 362, material = true, angle = 135, r = 75, g = 75, b = 200, a = 255 } }, { ID = EGP.Objects.Names["Box"], Settings = { x = 256, y = 256, w = 340, h = 340, material = true, angle = 135, r = 10, g = 10, b = 10, a = 255 } }, { ID = EGP.Objects.Names["Text"], Settings = { x = 229, y = 28, text = "E", size = 100, fontid = 4, r = 200, g = 50, b = 50, a = 255 } }, { ID = EGP.Objects.Names["Text"], Settings = { x = 50, y = 200, text = "G", size = 100, fontid = 4, r = 200, g = 50, b = 50, a = 255 } }, { ID = EGP.Objects.Names["Text"], Settings = { x = 400, y = 200, text = "P", size = 100, fontid = 4, r = 200, g = 50, b = 50, a = 255 } }, { ID = EGP.Objects.Names["Text"], Settings = { x = 228, y = 375, text = "2", size = 100, fontid = 4, r = 200, g = 50, b = 50, a = 255 } }, { ID = EGP.Objects.Names["Box"], Settings = { x = 256, y = 256, w = 256, h = 256, material = mat("expression 2/cog"), angle = 45, r = 255, g = 50, b = 50, a = 255 } }, { ID = EGP.Objects.Names["Box"], Settings = { x = 128, y = 241, w = 256, h = 30, material = true, r = 10, g = 10, b = 10, a = 255 } }, { ID = EGP.Objects.Names["Box"], Settings = { x = 241, y = 128, w = 30, h = 256, material = true, r = 10, g = 10, b = 10, a = 255 } }, { ID = EGP.Objects.Names["Circle"], Settings = { x = 256, y = 256, w = 70, h = 70, material = true, r = 255, g = 50, b = 50, a = 255 } }, { ID = EGP.Objects.Names["Box"], Settings = { x = 256, y = 256, w = 362, h = 362, material = mat("gui/center_gradient"), angle = 135, r = 75, g = 75, b = 200, a = 75 } }, { ID = EGP.Objects.Names["Box"], Settings = { x = 256, y = 256, w = 362, h = 362, material = mat("gui/center_gradient"), angle = 135, r = 75, g = 75, b = 200, a = 75 } } } ]] -- Convert table for k,v in pairs( tbl ) do local obj = EGP:GetObjectByID( v.ID ) obj.index = k for k2,v2 in pairs( v.Settings ) do if obj[k2] ~= nil then obj[k2] = v2 end end table.insert( EGP.HomeScreen, obj ) end
apache-2.0
ciufciuf57/nodemcu-firmware
lua_modules/bh1750/bh1750.lua
89
1372
-- *************************************************************************** -- BH1750 module for ESP8266 with nodeMCU -- BH1750 compatible tested 2015-1-22 -- -- Written by xiaohu -- -- MIT license, http://opensource.org/licenses/MIT -- *************************************************************************** local moduleName = ... local M = {} _G[moduleName] = M --I2C slave address of GY-30 local GY_30_address = 0x23 -- i2c interface ID local id = 0 --LUX local l --CMD local CMD = 0x10 local init = false --Make it more faster local i2c = i2c function M.init(sda, scl) i2c.setup(id, sda, scl, i2c.SLOW) --print("i2c ok..") init = true end local function read_data(ADDR, commands, length) i2c.start(id) i2c.address(id, ADDR, i2c.TRANSMITTER) i2c.write(id, commands) i2c.stop(id) i2c.start(id) i2c.address(id, ADDR,i2c.RECEIVER) tmr.delay(200000) c = i2c.read(id, length) i2c.stop(id) return c end local function read_lux() dataT = read_data(GY_30_address, CMD, 2) --Make it more faster UT = dataT:byte(1) * 256 + dataT:byte(2) l = (UT*1000/12) return(l) end function M.read() if (not init) then print("init() must be called before read.") else read_lux() end end function M.getlux() return l end return M
mit
RebootRevival/FFXI_Test
scripts/globals/spells/raiton_san.lua
7
1452
----------------------------------------- -- Spell: Raiton: San -- Deals lightning damage to an enemy and lowers its resistance against earth. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_RAITON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_RAITON_EFFECT); -- T1 mag atk if(caster:getMerit(MERIT_RAITON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_RAITON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_RAITON_SAN) - 5; end local params = {}; params.dmg = 134; params.multiplier = 1.5; params.hasMultipleTargetReduction = false; params.resistBonus = bonusAcc; params.mabBonus = bonusMab; dmg = doNinjutsuNuke(caster, target, spell, params); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_EARTHRES); return dmg; end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Kazham/npcs/Vah_Keshura.lua
17
1073
----------------------------------- -- Area: Kazham -- NPC: Vah Keshura -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00BB); -- scent from Blue Rafflesias else player:startEvent(0x007C); 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
RebootRevival/FFXI_Test
scripts/zones/Windurst_Waters/Zone.lua
24
3310
----------------------------------- -- -- Zone: Windurst_Waters (238) -- ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/events/harvest_festivals"); require("scripts/globals/missions"); require("scripts/globals/settings"); require("scripts/globals/zone"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Check if we are on Windurst Mission 1-3 zone:registerRegion(1, 23,-12,-208, 31,-8,-197); applyHalloweenNpcCostumes(zone:getID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; -- FIRST LOGIN (START CS) if (player:getPlaytime(false) == 0) then if (OPENING_CUTSCENE_ENABLE == 1) then cs = 531; end player:setPos(-40,-5,80,64); player:setHomePoint(); end -- MOG HOUSE EXIT if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then position = math.random(1,5) + 157; player:setPos(position,-5,-62,192); if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then cs = 30004; end player:setVar("PlayerMainJob",0); end if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status") == 1) then -- COP MEMORIES_OF_A_MAIDEN--3-3B: Windurst Route player:setVar("MEMORIES_OF_A_MAIDEN_Status",2); cs = 871; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Windurst Mission 1-3, final cutscene with Leepe-Hoppe -- If we're on Windurst Mission 1-3 if (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE and player:getVar("MissionStatus") == 2) then player:startEvent(0x0092); end end, } end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 531) then player:messageSpecial(ITEM_OBTAINED, 536); elseif (csid == 30004 and option == 0) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); elseif (csid == 146) then -- Returned from Giddeus, Windurst 1-3 player:setVar("MissionStatus", 3); player:setVar("ghoo_talk", 0); player:setVar("laa_talk", 0); end end;
gpl-3.0
RebootRevival/FFXI_Test
scripts/zones/Quicksand_Caves/npcs/qm2.lua
3
1323
----------------------------------- -- Area: Quicksand Caves -- NPC: qm2 -- Notes: Used to spawn Tribunus VII-I -- !pos -49.944 -0.891 -139.485 208 ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Quicksand_Caves/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade Antican Tag if (GetMobAction(17629643) == 0 and trade:hasItemQty(1190,1) and trade:getItemCount() == 1) then player:tradeComplete(); SpawnMob(17629643):updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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