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
abosalah22/zak
plugins/aboshoshoo1.lua
1
4292
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ BY SAJAD NOORI (@SAJJADNOORI) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY SAJJAD NOORI ▀▄ ▄▀ ▀▄ ▄▀ help1 : مساعدة ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local function run(msg, matches) if is_momod(msg) and matches[1]== "help1" then return [[ ❣ setadmin : لرفع اداري للمجموعه ❣ demoteadmin : لتنزيل اداري من المجموعه ❣ promote : لرفع او تصعيد ادمن ❣ demote : لتنزيل او حذف الادمن ❣ owner : لعرض المدير ❣ modlist : لاظهار ادمنية المجموعة ❣ admins : اضهار اداريين المجموعه 🔸➖🔹➖🔸➖🔹➖🔸 ✔️ Commands for control membee ❣ kick : لطرد العضو ❣ ban : لحظر العظر ❣ unban : فتح الخظر عن العضو ❣ kickme : للخروج من المجموعة ❣ silent : لتفعيل الصمت على احد الاعضاء ❣ clean mutelist: الغاء الصمت على العضو ❣ block : لحضر الكلمة ❣ words : لعرض الكلمات المحظورة ❣ unblock : لفتح حضر الكلمة ❣ me : لمعرفه موقعك في المجموعة 🔸➖🔹➖🔸➖🔹➖🔸 ✔️ Commands for control ❣ rules : لاضهار القوانين ❣ setrules : لاظافة القوانين ❣ setphoto : لوضع صورة ❣ setname : لوضع اسم ❣ setusername : لوضع معرف للكروب ❣ setabout : لاظافة الوصف ❣ id : لاظهار الايدي ❣ settings : اضهار اعدادات المجموعة ❣ info : اضهار المعلومات الخاصه بك ❣ info group : اضهار معلومات المجموعة ❣ settings modes : اضهار اعادادات الوسائط ❣ newlink : لصنع الرابط او تغيرة ❣ link : لضهور رابط المجموعه ❣ setlink : لوضع رابط للمجموعه ❣ linksl : للحصول على الرابط في الخاص 🔸➖🔹➖🔸➖🔹➖🔸 ✔️ Commands for Security ❣ lock all : لقفل المجموعه باكملها ❣ unlock all : لفتح المجموعه باكملها ❣ lock member : لقفل اضافة المجموعة ❣ unlock member : للفتح اضافة المجموعة ❣ lock text : لقفل دردشة المجموعة ❣ unlock text : فتح الدردشه ❣ lock photo : لمنع إرسال الصور ❣ unlock photo : للسماح بإرسال الصور ❣ lock audio : لمنع البصمات ❣ unlock audio : للسماح بإرسال البصمات ❣ lock video : لمنع ارسال فديو ❣ unlock video : للسماح بإرسال فديو ❣ lock links : لمنع الروابط ❣ unlock links : للسماح بإرسال روابط ❣ lock flood : لمنع التكرار ❣ unlock flood : للسماح بلتكرار ❣ lock sticker : لمنع الملصقات ❣ unlock sticker : للسماح بلملصقات ❣ lock gifs : لمنع الصور المتحركة ❣ unlock gifs : للسماح بالصور المتحركة ❣ lock documents : لمنع ارسال الملفات ❣ unlock documents : للسماح بإرسال الملفات ❣ lock spam : لمنع الكلايش الطويلة ❣ unlock spam : للسماح بلكلايش الطويلة ❣ lock rtl : لمنع اطافة جماعة ❣ unlock rtl : للسماح بإضافة جماعة ❣ lock arabic : لمنع اللغة ألعربيه ❣ unlock arabic : للسماح بلغه ألعربيه ❣ lock fwd : لمنع اعاديت توجيه ❣ unlock fwd : للسماح باعادت توجيه 🔸➖🔹➖🔸➖🔹➖🔸 ]] end if not is_momod(msg) then return "Only admins 😎🖕🏿" end end return { description = "Help list", usage = "Help list", patterns = { "(help1)" }, run = run } end
gpl-2.0
scan-bot/scan-bot
plugins/sudo.lua
359
1878
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
Ninjistix/darkstar
scripts/globals/effects/prowess_killer.lua
34
2257
----------------------------------- -- -- EFFECT_PROWESS : "Killer" effects bonus -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VERMIN_KILLER, effect:getPower()); target:addMod(MOD_BIRD_KILLER, effect:getPower()); target:addMod(MOD_AMORPH_KILLER, effect:getPower()); target:addMod(MOD_LIZARD_KILLER, effect:getPower()); target:addMod(MOD_AQUAN_KILLER, effect:getPower()); target:addMod(MOD_PLANTOID_KILLER, effect:getPower()); target:addMod(MOD_BEAST_KILLER, effect:getPower()); target:addMod(MOD_UNDEAD_KILLER, effect:getPower()); target:addMod(MOD_ARCANA_KILLER, effect:getPower()); target:addMod(MOD_DRAGON_KILLER, effect:getPower()); target:addMod(MOD_DEMON_KILLER, effect:getPower()); target:addMod(MOD_EMPTY_KILLER, effect:getPower()); -- target:addMod(MOD_HUMANOID_KILLER, effect:getPower()); target:addMod(MOD_LUMORIAN_KILLER, effect:getPower()); target:addMod(MOD_LUMINION_KILLER, effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VERMIN_KILLER, effect:getPower()); target:delMod(MOD_BIRD_KILLER, effect:getPower()); target:delMod(MOD_AMORPH_KILLER, effect:getPower()); target:delMod(MOD_LIZARD_KILLER, effect:getPower()); target:delMod(MOD_AQUAN_KILLER, effect:getPower()); target:delMod(MOD_PLANTOID_KILLER, effect:getPower()); target:delMod(MOD_BEAST_KILLER, effect:getPower()); target:delMod(MOD_UNDEAD_KILLER, effect:getPower()); target:delMod(MOD_ARCANA_KILLER, effect:getPower()); target:delMod(MOD_DRAGON_KILLER, effect:getPower()); target:delMod(MOD_DEMON_KILLER, effect:getPower()); target:delMod(MOD_EMPTY_KILLER, effect:getPower()); -- target:delMod(MOD_HUMANOID_KILLER, effect:getPower()); target:delMod(MOD_LUMORIAN_KILLER, effect:getPower()); target:delMod(MOD_LUMINION_KILLER, effect:getPower()); end;
gpl-3.0
ccyphers/kong
spec/03-plugins/10-acl/01-api_spec.lua
4
8079
local cjson = require "cjson" local helpers = require "spec.helpers" describe("Plugin: acl (API)", function() local consumer, admin_client setup(function() assert(helpers.start_kong()) admin_client = helpers.admin_client() end) teardown(function() if admin_client then admin_client:close() end helpers.stop_kong() end) describe("/consumers/:consumer/acls/", function() setup(function() helpers.dao:truncate_tables() consumer = assert(helpers.dao.consumers:insert { username = "bob" }) end) after_each(function() helpers.dao:truncate_table("acls") end) describe("POST", function() it("creates an ACL association", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/acls", body = { group = "admin" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(201, res) local json = cjson.decode(body) assert.equal(consumer.id, json.consumer_id) assert.equal("admin", json.group) end) describe("errors", function() it("returns bad request", function() local res = assert(admin_client:send { method = "POST", path = "/consumers/bob/acls", body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) assert.equal([[{"group":"group is required"}]], body) end) end) end) describe("PUT", function() it("creates a basic-auth credential", function() local res = assert(admin_client:send { method = "PUT", path = "/consumers/bob/acls", body = { group = "pro" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(201, res) local json = cjson.decode(body) assert.equal(consumer.id, json.consumer_id) assert.equal("pro", json.group) end) describe("errors", function() it("returns bad request", function() local res = assert(admin_client:send { method = "PUT", path = "/consumers/bob/acls", body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) assert.equal([[{"group":"group is required"}]], body) end) end) end) describe("GET", function() setup(function() for i = 1, 3 do assert(helpers.dao.acls:insert { group = "group"..i, consumer_id = consumer.id }) end end) teardown(function() helpers.dao:truncate_table("acls") end) it("retrieves the first page", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/acls" }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.is_table(json.data) assert.equal(3, #json.data) assert.equal(3, json.total) end) end) end) describe("/consumers/:consumer/acls/:id", function() local acl, acl2 before_each(function() helpers.dao:truncate_table("acls") acl = assert(helpers.dao.acls:insert { group = "hello", consumer_id = consumer.id }) acl2 = assert(helpers.dao.acls:insert { group = "hello2", consumer_id = consumer.id }) end) describe("GET", function() it("retrieves by id", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/acls/"..acl.id }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(acl.id, json.id) end) it("retrieves by group", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/acls/"..acl.group }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.equal(acl.id, json.id) end) it("retrieves ACL by id only if the ACL belongs to the specified consumer", function() assert(helpers.dao.consumers:insert { username = "alice" }) local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/acls/"..acl.id }) assert.res_status(200, res) res = assert(admin_client:send { method = "GET", path = "/consumers/alice/acls/"..acl.id }) assert.res_status(404, res) end) it("retrieves ACL by group only if the ACL belongs to the specified consumer", function() local res = assert(admin_client:send { method = "GET", path = "/consumers/bob/acls/"..acl.group }) assert.res_status(200, res) res = assert(admin_client:send { method = "GET", path = "/consumers/alice/acls/"..acl.group }) assert.res_status(404, res) end) end) describe("PATCH", function() it("updates an ACL group by id", function() local previous_group = acl.group local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/acls/"..acl.id, body = { group = "updatedGroup" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.not_equal(previous_group, json.group) end) it("updates an ACL group by group", function() local previous_group = acl.group local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/acls/"..acl.group, body = { group = "updatedGroup2" }, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(200, res) local json = cjson.decode(body) assert.not_equal(previous_group, json.group) end) describe("errors", function() it("handles invalid input", function() local res = assert(admin_client:send { method = "PATCH", path = "/consumers/bob/acls/"..acl.id, body = {}, headers = { ["Content-Type"] = "application/json" } }) local body = assert.res_status(400, res) assert.equal([[{"group":"ACL group already exist for this consumer"}]], body) end) end) end) describe("DELETE", function() it("deletes an ACL group by id", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/acls/"..acl.id, }) assert.res_status(204, res) end) it("deletes an ACL group by group", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/acls/"..acl2.group, }) assert.res_status(204, res) end) describe("errors", function() it("returns 404 on missing group", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/acls/blah" }) assert.res_status(404, res) end) it("returns 404 if not found", function() local res = assert(admin_client:send { method = "DELETE", path = "/consumers/bob/acls/00000000-0000-0000-0000-000000000000" }) assert.res_status(404, res) end) end) end) end) end)
apache-2.0
Ninjistix/darkstar
scripts/globals/spells/drain_ii.lua
5
2074
----------------------------------------- -- Spell: Drain II -- Drain functions only on skill level!! ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --calculate raw damage (unknown function -> only dark skill though) - using http://www.bluegartr.com/threads/44518-Drain-Calculations -- also have small constant to account for 0 dark skill local dmg = 20 + (1.236 * caster:getSkillLevel(DARK_MAGIC_SKILL)); if (dmg > (caster:getSkillLevel(DARK_MAGIC_SKILL) + 85)) then dmg = (caster:getSkillLevel(DARK_MAGIC_SKILL) + 85); end --get resist multiplier (1x if no resist) local params = {}; params.diff = caster:getStat(MOD_INT)-target:getStat(MOD_INT); params.attribute = MOD_INT; params.skillType = DARK_MAGIC_SKILL; params.bonus = 1.0; local resist = applyResistance(caster, target, spell, params); --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()); --add in final adjustments if (dmg < 0) then dmg = 0 end if (target:getHP() < dmg) then dmg = target:getHP(); end if (target:isUndead()) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- No effect return dmg; end dmg = finalMagicAdjustments(caster,target,spell,dmg); local leftOver = (caster:getHP() + dmg) - caster:getMaxHP(); if (leftOver > 0) then caster:addStatusEffect(EFFECT_MAX_HP_BOOST, (leftOver/caster:getMaxHP())*100, 0, 60); end caster:addHP(dmg); spell:setMsg(msgBasic.MAGIC_DRAIN_HP); --change msg to 'xxx hp drained from the yyyy.' return dmg; end;
gpl-3.0
arca1n/cocos2d-x_nextpeer_integration
samples/Lua/TestLua/Resources/luaScript/ActionsEaseTest/ActionsEaseTest.lua
4
15911
local kTagAction1 = 1 local kTagAction2 = 2 local kTagSlider = 1 local s = cc.Director:getInstance():getWinSize() local scheduler = cc.Director:getInstance():getScheduler() local function createSimpleMoveBy() return cc.MoveBy:create(3, cc.p(s.width - 130, 0)) end local function createSimpleDelayTime() return cc.DelayTime:create(0.25) end local function positionForTwo() grossini:setPosition(cc.p(60, s.height * 1 / 5)) tamara:setPosition(cc.p(60, s.height * 4 / 5)) kathia:setVisible(false) end local function getBaseLayer() local layer = cc.Layer:create() grossini = cc.Sprite:create(s_pPathGrossini) tamara = cc.Sprite:create(s_pPathSister1) kathia = cc.Sprite:create(s_pPathSister2) layer:addChild(grossini, 3) layer:addChild(kathia, 2) layer:addChild(tamara, 1) grossini:setPosition(cc.p(60, s.height * 1 / 5)) kathia:setPosition(cc.p(60, s.height * 2.5 / 5)) tamara:setPosition(cc.p(60, s.height * 4 / 5)) Helper.initWithLayer(layer) return layer end ----------------------------------- -- SpriteEase ----------------------------------- local SpriteEase_entry = nil local function testStopAction(dt) scheduler:unscheduleScriptEntry(SpriteEase_entry) tamara:stopActionByTag(1) kathia:stopActionByTag(1) grossini:stopActionByTag(1) end local function SpriteEase_onEnterOrExit(tag) if tag == "enter" then SpriteEase_entry = scheduler:scheduleScriptFunc(testStopAction, 6.25, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(SpriteEase_entry) end end local function SpriteEase() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease_in = cc.EaseIn:create(createSimpleMoveBy(), 2.5) local move_ease_in_back = move_ease_in:reverse() local move_ease_out = cc.EaseOut:create(createSimpleMoveBy(), 2.5) local move_ease_out_back = move_ease_out:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease_in,createSimpleDelayTime(),move_ease_in_back,createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_out,createSimpleDelayTime(),move_ease_out_back,createSimpleDelayTime()) local a2 = grossini:runAction(cc.RepeatForever:create(seq1)) a2:setTag(1) local a1 = tamara:runAction(cc.RepeatForever:create(seq2)) a1:setTag(1) local a = kathia:runAction(cc.RepeatForever:create(seq3)) a:setTag(1) layer:registerScriptHandler(SpriteEase_onEnterOrExit) Helper.titleLabel:setString("EaseIn - EaseOut - Stop") return layer end ----------------------------------- -- SpriteEaseInOut ----------------------------------- local function SpriteEaseInOut() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_ease_inout1 = cc.EaseInOut:create(createSimpleMoveBy(), 0.65) local move_ease_inout_back1 = move_ease_inout1:reverse() local move_ease_inout2 = cc.EaseInOut:create(createSimpleMoveBy(), 1.35) local move_ease_inout_back2 = move_ease_inout2:reverse() local move_ease_inout3 = cc.EaseInOut:create(createSimpleMoveBy(), 1.0) local move_ease_inout_back3 = move_ease_inout3:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move_ease_inout1,delay,move_ease_inout_back1,createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease_inout2,createSimpleDelayTime(),move_ease_inout_back2,createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_inout3, createSimpleDelayTime(), move_ease_inout_back3, createSimpleDelayTime() ) tamara:runAction(cc.RepeatForever:create(seq1)) kathia:runAction(cc.RepeatForever:create(seq2)) grossini:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("EaseInOut and rates") return layer end ----------------------------------- -- SpriteEaseExponential ----------------------------------- local function SpriteEaseExponential() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease_in = cc.EaseExponentialIn:create(createSimpleMoveBy()) local move_ease_in_back = move_ease_in:reverse() local move_ease_out = cc.EaseExponentialOut:create(createSimpleMoveBy()) local move_ease_out_back = move_ease_out:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease_in, createSimpleDelayTime(), move_ease_in_back, createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_out, createSimpleDelayTime(), move_ease_out_back, createSimpleDelayTime()) grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) kathia:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("ExpIn - ExpOut actions") return layer end ----------------------------------- -- SpriteEaseExponentialInOut ----------------------------------- local function SpriteEaseExponentialInOut() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease = cc.EaseExponentialInOut:create(createSimpleMoveBy()) local move_ease_back = move_ease:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease, createSimpleDelayTime(), move_ease_back, createSimpleDelayTime() ) positionForTwo() grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) Helper.titleLabel:setString("EaseExponentialInOut action") return layer end ----------------------------------- -- SpriteEaseSine ----------------------------------- local function SpriteEaseSine() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease_in = cc.EaseSineIn:create(createSimpleMoveBy()) local move_ease_in_back = move_ease_in:reverse() local move_ease_out = cc.EaseSineOut:create(createSimpleMoveBy()) local move_ease_out_back = move_ease_out:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime() ) local seq2 = cc.Sequence:create(move_ease_in, createSimpleDelayTime(), move_ease_in_back, createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_out, createSimpleDelayTime(), move_ease_out_back,createSimpleDelayTime()) grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) kathia:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("EaseSineIn - EaseSineOut") return layer end ----------------------------------- -- SpriteEaseSineInOut ----------------------------------- local function SpriteEaseSineInOut() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease = cc.EaseSineInOut:create(createSimpleMoveBy()) local move_ease_back = move_ease:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease, createSimpleDelayTime(), move_ease_back, createSimpleDelayTime()) positionForTwo() grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) Helper.titleLabel:setString("EaseSineInOut action") return layer end ----------------------------------- -- SpriteEaseElastic ----------------------------------- local function SpriteEaseElastic() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease_in = cc.EaseElasticIn:create(createSimpleMoveBy()) local move_ease_in_back = move_ease_in:reverse() local move_ease_out = cc.EaseElasticOut:create(createSimpleMoveBy()) local move_ease_out_back = move_ease_out:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime() ) local seq2 = cc.Sequence:create(move_ease_in, createSimpleDelayTime(), move_ease_in_back, createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_out, createSimpleDelayTime(), move_ease_out_back, createSimpleDelayTime()) grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) kathia:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("Elastic In - Out actions") return layer end ----------------------------------- -- SpriteEaseElasticInOut ----------------------------------- local function SpriteEaseElasticInOut() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_ease_inout1 = cc.EaseElasticInOut:create(createSimpleMoveBy(), 0.3) local move_ease_inout_back1 = move_ease_inout1:reverse() local move_ease_inout2 = cc.EaseElasticInOut:create(createSimpleMoveBy(), 0.45) local move_ease_inout_back2 = move_ease_inout2:reverse() local move_ease_inout3 = cc.EaseElasticInOut:create(createSimpleMoveBy(), 0.6) local move_ease_inout_back3 = move_ease_inout3:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move_ease_inout1, delay, move_ease_inout_back1, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease_inout2, createSimpleDelayTime(), move_ease_inout_back2, createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_inout3, createSimpleDelayTime(), move_ease_inout_back3, createSimpleDelayTime()) tamara:runAction(cc.RepeatForever:create(seq1)) kathia:runAction(cc.RepeatForever:create(seq2)) grossini:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("EaseElasticInOut action") return layer end ----------------------------------- -- SpriteEaseBounce ----------------------------------- local function SpriteEaseBounce() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease_in = cc.EaseBounceIn:create(createSimpleMoveBy()) local move_ease_in_back = move_ease_in:reverse() local move_ease_out = cc.EaseBounceOut:create(createSimpleMoveBy()) local move_ease_out_back = move_ease_out:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime() ) local seq2 = cc.Sequence:create(move_ease_in, createSimpleDelayTime(), move_ease_in_back, createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_out, createSimpleDelayTime(), move_ease_out_back, createSimpleDelayTime()) grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) kathia:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("Bounce In - Out actions") return layer end ----------------------------------- -- SpriteEaseBounceInOut ----------------------------------- local function SpriteEaseBounceInOut() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease = cc.EaseBounceInOut:create(createSimpleMoveBy()) local move_ease_back = move_ease:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease, createSimpleDelayTime(), move_ease_back, createSimpleDelayTime()) positionForTwo() grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) Helper.titleLabel:setString("EaseBounceInOut action") return layer end ----------------------------------- -- SpriteEaseBack ----------------------------------- local function SpriteEaseBack() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease_in = cc.EaseBackIn:create(createSimpleMoveBy()) local move_ease_in_back = move_ease_in:reverse() local move_ease_out = cc.EaseBackOut:create(createSimpleMoveBy()) local move_ease_out_back = move_ease_out:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease_in, createSimpleDelayTime(), move_ease_in_back, createSimpleDelayTime()) local seq3 = cc.Sequence:create(move_ease_out, createSimpleDelayTime(), move_ease_out_back, createSimpleDelayTime()) grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) kathia:runAction(cc.RepeatForever:create(seq3)) Helper.titleLabel:setString("Back In - Out actions") return layer end ----------------------------------- -- SpriteEaseBackInOut ----------------------------------- local function SpriteEaseBackInOut() local layer = getBaseLayer() local move = createSimpleMoveBy() local move_back = move:reverse() local move_ease = cc.EaseBackInOut:create(createSimpleMoveBy()) local move_ease_back = move_ease:reverse() local delay = createSimpleDelayTime() local seq1 = cc.Sequence:create(move, delay, move_back, createSimpleDelayTime()) local seq2 = cc.Sequence:create(move_ease,createSimpleDelayTime(), move_ease_back, createSimpleDelayTime()) positionForTwo() grossini:runAction(cc.RepeatForever:create(seq1)) tamara:runAction(cc.RepeatForever:create(seq2)) Helper.titleLabel:setString("EaseBackInOut action") return layer end ----------------------------------- -- SpeedTest ----------------------------------- local SpeedTest_entry = nil local SpeedTest_action1 = nil local SpeedTest_action2 = nil local SpeedTest_action3 = nil local function altertime(dt) SpeedTest_action1:setSpeed(math.random() * 2) SpeedTest_action2:setSpeed(math.random() * 2) SpeedTest_action3:setSpeed(math.random() * 2) end local function SpeedTest_onEnterOrExit(tag) if tag == "enter" then SpeedTest_entry = scheduler:scheduleScriptFunc(altertime, 1.0, false) elseif tag == "exit" then scheduler:unscheduleScriptEntry(SpeedTest_entry) end end local function SpeedTest() local layer = getBaseLayer() local jump1 = cc.JumpBy:create(4, cc.p(- s.width + 80, 0), 100, 4) local jump2 = jump1:reverse() local rot1 = cc.RotateBy:create(4, 360 * 2) local rot2 = rot1:reverse() local seq3_1 = cc.Sequence:create(jump2, jump1) local seq3_2 = cc.Sequence:create(rot1, rot2) local spawn = cc.Spawn:create(seq3_1, seq3_2) SpeedTest_action1 = cc.Speed:create(cc.RepeatForever:create(spawn), 1.0) local spawn2 = tolua.cast(spawn:clone(), "Spawn") SpeedTest_action2 = cc.Speed:create(cc.RepeatForever:create(spawn2), 1.0) local spawn3 = tolua.cast(spawn:clone(), "Spawn") SpeedTest_action3 = cc.Speed:create(cc.RepeatForever:create(spawn3), 1.0) grossini:runAction(SpeedTest_action2) tamara:runAction(SpeedTest_action3) kathia:runAction(SpeedTest_action1) layer:registerScriptHandler(SpeedTest_onEnterOrExit) Helper.titleLabel:setString("Speed action") return layer end function EaseActionsTest() local scene = cc.Scene:create() cclog("EaseActionsTest") Helper.createFunctionTable = { SpriteEase, SpriteEaseInOut, SpriteEaseExponential, SpriteEaseExponentialInOut, SpriteEaseSine, SpriteEaseSineInOut, SpriteEaseElastic, SpriteEaseElasticInOut, SpriteEaseBounce, SpriteEaseBounceInOut, SpriteEaseBack, SpriteEaseBackInOut, SpeedTest } scene:addChild(SpriteEase()) scene:addChild(CreateBackMenuItem()) return scene end
mit
jokersso3/joker
plugins/security.lua
1
19775
--Begin security.lua --Prerequisite: local function isABotBadWay (user) local username = user.username or '' return username:match("[Bb]ot$") end local function get_variables_hash(msg) return 'chat:'..msg.to.id..':badword' end local function list_variablesbad(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = 'List of words :\n\n' for i=1, #names do text = text..'> '..names[i]..'\n' end return text else return end end local function list_variables2(msg, value) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do if string.match(value, names[i]) and not is_momod(msg) then if msg.to.type == 'channel' then delete_msg(msg.id,ok_cb,false) else kick_user(msg.from.id, msg.to.id) end return end --text = text..names[i]..'\n' end end end --Prerequisite. --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle and Edited by @janlou -- Powered by @AdvanTeam -- CopyRight all right reserved if is_chat_msg(msg) or is_super_group(msg) then local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' local to_super = msg.to.type == 'channel' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = 'no' end if settings.lock_tgservice then lock_tgservice = settings.lock_tgservice else lock_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_member then lock_member = settings.lock_member else lock_member = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = 'no' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = 'no' end if settings.strict then strict = settings.strict else strict = 'no' end if not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") or msg.text:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.text:match("[Hh][Tt][Tt][Pp][Ss]://(.*)") or msg.text:match("[Hh][Tt][Tt][Pp]://(.*)") or msg.text:match("(.*)(.[([Cc][Oo][Mm])([Ii][Rr])([Nn][Ee][Tt])([Oo][Rr][Gg])([Ii][Oo])([Cc][Ff])([Cc][Oo])])") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "yes" and not is_bot then delete_msg(msg.id, ok_cb, false) delete_msg(msg.id, ok_cb, false) delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if msg.service then if lock_tgservice == "yes" then delete_msg(msg.id, ok_cb, false) if to_chat then return end end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) delete_msg(msg.id, ok_cb, false) delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") or msg.media.caption:match("@[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") if is_link_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then kick_user(user_id, msg.to.id) end if lock_member == 'yes' then kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == 'yes' then kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end --[[if msg.text:match("@[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") then if lock_link == 'yes' then if msg.to.type == 'channel' then if strict == 'no' then delete_msg(msg.id, ok_cb, false) elseif strict == 'yes' then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end if msg.to.type == 'chat' then kick_user(msg.from.id, msg.to.id) end end end]] if msg.text:match("/[Ss][Tt][Aa][Rr][Tt]") then if msg.to.type == "user" then return "Hello dear ["..msg.from.print_name.."], welcome to "..msg.to.print_name.."\nThanks for /start me :)\n" end end if msg.text:match("^[!/#][Rr][Aa][Tt][Ee]$") then Group_rate = _config.Group_rate Supergroup_rate = _config.Supergroup_rate if Group_rate ~= "" or Supergroup_rate ~= "" then rate = "Rate of:\n\nChat: "..Group_rate.."\nSuperGroup: "..Supergroup_rate send_msg(get_receiver(msg), rate, ok_cb, false) else rate = "Erore: Rate is not set!" send_msg(get_receiver(msg), rate, ok_cb, false) end end if is_chat_msg(msg) or is_super_group(msg) then receiver = get_receiver(msg) user = "user" chat = "chat" channel = "channel" local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_media'] then lock_media = data[tostring(msg.to.id)]['settings']['lock_media'] end if data[tostring(msg.to.id)]['settings']['lock_number'] then lock_number = data[tostring(msg.to.id)]['settings']['lock_number'] end if data[tostring(msg.to.id)]['settings']['lock_poker'] then lock_poker = data[tostring(msg.to.id)]['settings']['lock_poker'] end if data[tostring(msg.to.id)]['settings']['lock_tag'] then lock_tag = data[tostring(msg.to.id)]['settings']['lock_tag'] end if data[tostring(msg.to.id)]['settings']['lock_fwd'] then lock_fwd = data[tostring(msg.to.id)]['settings']['lock_fwd'] end if data[tostring(msg.to.id)]['settings']['lock_reply'] then lock_reply = data[tostring(msg.to.id)]['settings']['lock_reply'] end if data[tostring(msg.to.id)]['settings']['lock_share'] then lock_share = data[tostring(msg.to.id)]['settings']['lock_share'] end if data[tostring(msg.to.id)]['settings']['lock_bots'] then lock_bots = data[tostring(msg.to.id)]['settings']['lock_bots'] end if data[tostring(msg.to.id)]['settings']['lock_inline'] then lock_inline = data[tostring(msg.to.id)]['settings']['lock_inline'] end if data[tostring(msg.to.id)]['settings']['strict'] then lock_strict = data[tostring(msg.to.id)]['settings']['strict'] end if data[tostring(msg.to.id)]['settings']['lock_cmd'] then lock_cmd = data[tostring(msg.to.id)]['settings']['lock_cmd'] end end end --Media lock: if msg.text:match("%[(photo)%]") or msg.text:match("%[(video)%]") or msg.text:match("%[(document)%]") or msg.text:match("%[(gif)%]") or msg.text:match("%[(unsupported)%]") or msg.text:match("%[(audio)%]") then if lock_media == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Media lock. --Share lock: if msg.text:match("%[(contact)%]") then if lock_share == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Share lock. --Number lock: if msg.text:match("%d+") then if lock_number == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Number lock. --Poker lock: if msg.text:match("😐") then if lock_poker == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Poker lock. --Tag lock: if msg.text:match("#") then if lock_tag == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Tag lock. --Bots lock: if msg.text:match("^!!tgservice (chat_add_user)$") or msg.text:match("^!!tgservice (chat_add_user_link)$") then if lock_bots == "yes" then local user = msg.action.user or msg.from if isABotBadWay(user) then userId = user.id chatId = msg.to.id if msg.to.type == channel then kickUser("user#id"..userId, "channel#id"..chatId) channel_kick_user("channel#id"..msg.to.id, 'user#id'..userId, ok_cb, false) end end end end --Bots lock. --Inline lock: if msg.text == "[unsupported]" then if msg.to.type == channel then if lock_inline == "yes" then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Inline lock. end --Fwd lock: if msg.fwd_from then if redis:get('fwd:'..msg.to.id) then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end --Fwd lock. --Reply lock: if msg.reply_id then if redis:get('reply:'..msg.to.id) then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end --Reply lock. --Cmd Lock: if msg.text:match("^[/#!](.*)$") and lock_cmd == "yes" then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end return false end --Cmd Lock. -- End 'RondoMsgChecks' text checks by @Rondoozle end end if msg.text:match("^[!/#][Aa][Dd][Vv][Aa][Nn]$") then txt = _config.about_text send_msg(get_receiver(msg), txt, ok_cb, false) end return msg end --End pre_process function return { patterns = {}, pre_process = pre_process, } --End security.lua --By @Rondoozle
gpl-2.0
SharpWoW/Chocobo
ChocoboOptions.lua
1
9333
--[[ Copyright (c) 2010-2020 by Adam Hellberg This file is part of Chocobo. Chocobo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Chocobo 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 Chocobo. If not, see <http://www.gnu.org/licenses/>. --]] local L = _G["ChocoboLocale"] local C = Chocobo C.Options = {} local CO = C.Options local function createList(parent, header, listGetter, addFunc, removeFunc, resetFunc) local list = CreateFrame("Frame", nil, parent, "ChocoboSongsAndMountsListTemplate") list.items = {} list.Header:SetText(header) list.AddButton:SetText(L["Options_Add"]) list.AddButton:SetScript("OnClick", function() local item = list.EditBox:GetText() addFunc(item) list:RefreshLayout() list.EditBox:SetText("") end) list.ResetButton:SetText(L["Options_Reset"]) list.ResetButton:SetScript("OnClick", function() resetFunc() list:RefreshLayout() end) list.ListScrollFrame.update = function() list:RefreshLayout() end list:SetScript("OnShow", function(self) self.items = listGetter() HybridScrollFrame_CreateButtons(self.ListScrollFrame, "ChocoboSongsAndMountsItemTemplate") self:RefreshLayout() end) function list:RemoveItem(index) local item = listGetter()[index] removeFunc(item) self:RefreshLayout() end function list:RefreshLayout() local items = self.items local buttons = HybridScrollFrame_GetButtons(self.ListScrollFrame) local offset = HybridScrollFrame_GetOffset(self.ListScrollFrame) for buttonIndex = 1, #buttons do local button = buttons[buttonIndex] local itemIndex = buttonIndex + offset if itemIndex <= #items then local item = items[itemIndex] button:SetID(itemIndex) button.Text:SetText(item) button:SetWidth(self.ListScrollFrame.scrollChild:GetWidth()) button:Show() else button:Hide() end end local buttonHeight = self.ListScrollFrame.buttonHeight local totalHeight = #items * buttonHeight local shownHeight = #buttons * buttonHeight HybridScrollFrame_Update(self.ListScrollFrame, totalHeight, shownHeight) end HybridScrollFrame_SetDoNotHideScrollBar(list.ListScrollFrame, true) return list end local frame = CreateFrame("Frame") CO.Frame = frame frame:Hide() frame.name = "Chocobo" frame.refresh = function() CO:Update() end frame.logo = frame:CreateTexture(nil, "ARTWORK") frame.logo:SetBlendMode("BLEND") frame.logo:SetTexture([[Interface\AddOns\Chocobo\images\chocobo.tga]]) frame.logo:SetSize(256, 512) frame.logo:SetPoint("BOTTOMRIGHT", 0, -75) frame.description = CreateFrame("Frame", nil, frame) frame.description:SetSize(370, 30) frame.description:SetPoint("TOP", 0, -10) frame.description.label = frame.description:CreateFontString(nil, "OVERLAY") frame.description.label:SetFont([[Fonts\FRIZQT__.TTF]], 12, "OUTLINE") frame.description.label:SetPoint("TOPLEFT") frame.description.label:SetPoint("BOTTOMRIGHT") frame.description.label:SetTextColor(1, 0.8196079, 0) frame.songs = createList( frame, L["SongsAndMounts_Songs"], function() return C.Global.MUSIC end, function(item) C:AddMusic(item) end, function(item) C:RemoveMusic(item) end, function() C:ResetMusic() end) frame.songs:SetHeight(200) frame.songs:SetPoint("TOP", 0, -40) frame.songs:SetPoint("LEFT", 5, 0) frame.songs:SetPoint("RIGHT", frame, "BOTTOM", -20, 0) frame.mounts = createList( frame, L["SongsAndMounts_Mounts"], function() return C.Global.MOUNTS end, function(item) C:AddMount(item) end, function(item) C:RemoveMount(item) end, function() C:ResetMounts() end) frame.mounts:SetPoint("TOP", frame.songs) frame.mounts:SetPoint("LEFT", frame, "BOTTOM") frame.mounts:SetPoint("RIGHT", -28, 0) frame.mounts:SetPoint("BOTTOM", frame.songs) frame.toggleMount = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate") frame.toggleMount:SetSize(240, 38) frame.toggleMount:SetPoint("TOP", 0, -250) frame.toggleMount:SetScript("OnClick", function() Chocobo:FilterMount(nil, true) CO:Update() end) frame.toggleDebug = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate") frame.toggleDebug:SetSize(240, 38) frame.toggleDebug:SetPoint("TOP", 0, -293) frame.toggleDebug:SetScript("OnClick", function() Chocobo:ToggleDebug(true) CO:Update() end) frame.toggleButton = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate") frame.toggleButton:SetSize(240, 38) frame.toggleButton:SetPoint("TOP", 0, -336) frame.toggleButton:SetScript("OnClick", function() Chocobo:Toggle(true) CO:Update() end) frame.preventDupeToggle = CreateFrame( "CheckButton", "ChocoboOptionsPreventDupeToggle", frame, "OptionsCheckButtonTemplate") frame.preventDupeToggle:SetSize(40, 40) frame.preventDupeToggle:SetPoint("BOTTOMLEFT", 20, 160) frame.preventDupeToggle:SetScript("OnClick", function() Chocobo:PreventDupeToggle(true) CO:Update() end) frame.preventDupeToggle.label = _G[frame.preventDupeToggle:GetName() .. "Text"] frame.preventDupeToggle.label:SetText(L["Options_PreventDupeToggle"]) frame.plainstriderToggle = CreateFrame( "CheckButton", "ChocoboOptionsPlainstriderToggle", frame, "OptionsCheckButtonTemplate") frame.plainstriderToggle:SetSize(40, 40) frame.plainstriderToggle:SetPoint("BOTTOMLEFT", frame.preventDupeToggle, 0, -40) frame.plainstriderToggle:SetScript("OnClick", function() Chocobo:PlainstriderToggle(true) CO:Update() end) frame.plainstriderToggle.label = _G[frame.plainstriderToggle:GetName() .. "Text"] frame.plainstriderToggle.label:SetText(L["Options_PlainstriderToggle"]) frame.ravenLordToggle = CreateFrame("CheckButton", "ChocoboOptionsRavenLordToggle", frame, "OptionsCheckButtonTemplate") frame.ravenLordToggle:SetSize(40, 40) frame.ravenLordToggle:SetPoint("BOTTOMLEFT", frame.plainstriderToggle, 0, -40) frame.ravenLordToggle:SetScript("OnClick", function() Chocobo:RavenLordToggle(true) CO:Update() end) frame.ravenLordToggle.label = _G[frame.ravenLordToggle:GetName() .. "Text"] frame.ravenLordToggle.label:SetText(L["Options_RavenLordToggle"]) frame.flametalonToggle = CreateFrame( "CheckButton", "ChocoboOptionsFlametalonToggle", frame, "OptionsCheckButtonTemplate") frame.flametalonToggle:SetSize(40, 40) frame.flametalonToggle:SetPoint("BOTTOMLEFT", frame.ravenLordToggle, 0, -40) frame.flametalonToggle:SetScript("OnClick", function() Chocobo:FlametalonToggle(true) CO:Update() end) frame.flametalonToggle.label = _G[frame.flametalonToggle:GetName() .. "Text"] frame.flametalonToggle.label:SetText(L["Options_FlametalonToggle"]) frame.ridingCraneToggle = CreateFrame( "CheckButton", "ChocoboOptionsRidingCraneToggle", frame, "OptionsCheckButtonTemplate") frame.ridingCraneToggle:SetSize(40, 40) frame.ridingCraneToggle:SetPoint("BOTTOMLEFT", frame.flametalonToggle, 0, -40) frame.ridingCraneToggle:SetScript("OnClick", function() Chocobo:RidingCraneToggle(true) CO:Update() end) frame.ridingCraneToggle.label = _G[frame.ridingCraneToggle:GetName() .. "Text"] frame.ridingCraneToggle.label:SetText(L["Options_RidingCraneToggle"]) function CO:Open() InterfaceOptionsFrame_OpenToCategory(frame) InterfaceOptionsFrame_OpenToCategory(frame) end function CO:Update() local AddOnState, MountState, DebugState local asColor local dColor if Chocobo.Global["ENABLED"] then AddOnState = L["Options_Enabled"] asColor = "00FF00" else AddOnState = L["Options_Disabled"] asColor = "FF0000" end if Chocobo.Global["ALLMOUNTS"] then MountState = L["Options_AllMounts"] else MountState = L["Options_Hawkstrider"] end if Chocobo.Global["DEBUG"] then DebugState = L["Options_Enabled"] dColor = "00FF00" else DebugState = L["Options_Disabled"] dColor = "FF0000" end frame.toggleButton:SetText((L["Options_AddOnState"]):format(asColor, AddOnState)) frame.toggleMount:SetText(MountState) frame.toggleDebug:SetText((L["Options_DebugState"]):format(dColor, DebugState)) frame.description.label:SetText((L["Options_Description"]):format(Chocobo:GetVersion())) frame.preventDupeToggle:SetChecked(Chocobo.Global["PREVENTDUPE"]) frame.plainstriderToggle:SetChecked(Chocobo.Global["PLAINSTRIDER"]) frame.ridingCraneToggle:SetChecked(Chocobo.Global["RIDINGCRANE"]) frame.ravenLordToggle:SetChecked(Chocobo.Global["RAVENLORD"]) frame.flametalonToggle:SetChecked(Chocobo.Global["FLAMETALON"]) end frame:SetScript("OnShow", function() CO:Update() end) InterfaceOptions_AddCategory(frame)
gpl-3.0
Ninjistix/darkstar
scripts/globals/abilities/curing_waltz_ii.lua
2
2553
----------------------------------- -- Ability: Curing Waltz II -- Heals HP to target player. -- Obtained: Dancer Level 30 -- TP Required: 35% -- Recast Time: 00:08 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- function onAbilityCheck(player,target,ability) if (target:getHP() == 0) then return msgBasic.CANNOT_ON_THAT_TARG,0; elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then return msgBasic.UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 350) then return msgBasic.NOT_ENOUGH_TP,0; else --[[ Apply "Waltz Ability Delay" reduction 1 modifier = 1 second]] local recastMod = player:getMod(MOD_WALTZ_DELAY); if (recastMod ~= 0) then local newRecast = ability:getRecast() +recastMod; ability:setRecast(utils.clamp(newRecast,0,newRecast)); end -- Apply "Fan Dance" Waltz recast reduction if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then local fanDanceMerits = target:getMerit(MERIT_FAN_DANCE); -- Every tier beyond the 1st is -5% recast time if (fanDanceMerits > 5) then ability:setRecast(ability:getRecast() * ((fanDanceMerits -5)/100)); end end return 0,0; end end; function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(350); end; --Grabbing variables. local vit = target:getStat(MOD_VIT); local chr = player:getStat(MOD_CHR); local mjob = player:getMainJob(); --19 for DNC main. local sjob = player:getSubJob(); local cure = 0; --Performing sj mj check. if (mjob == 19) then cure = (vit+chr)*0.5+130; end if (sjob == 19) then cure = (vit+chr)*0.25+130; end -- apply waltz modifiers cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100))); --Reducing TP. --Applying server mods.... cure = cure * CURE_POWER; --Cap the final amount to max HP. if ((target:getMaxHP() - target:getHP()) < cure) then cure = (target:getMaxHP() - target:getHP()); end --Do it target:restoreHP(cure); target:wakeUp(); player:updateEnmityFromCure(target,cure); return cure; end;
gpl-3.0
dinodeck/ninety_nine_days_of_dev
006_magic_menu/code/Party.lua
8
1448
Party = {} Party.__index = Party function Party:Create() local this = { mMembers = {} } setmetatable(this, self) return this end function Party:Add(member) self.mMembers[member.mId] = member end function Party:RemoveById(id) self.mMembers[id] = nil end function Party:Remove(member) self:RemoveById(member.mId) end function Party:ToArray() local array = {} for k, v in pairs(self.mMembers) do table.insert(array, v) end return array end -- Count the number of this item equipped function Party:EquipCount(itemId) local count = 0 for _,v in pairs(self.mMembers) do count = count + v:EquipCount(itemId) end return count end function Party:Rest() for _, v in pairs(self.mMembers) do local stats = v.mStats if stats:Get("hp_now") > 0 then stats:Set("hp_now", stats:Get("hp_max")) stats:Set("mp_now", stats:Get("mp_max")) end end end function Party:DebugPrintParty() for _, v in pairs(self.mMembers) do local stats = v.mStats local name = v.mName local hpNow = stats:Get("hp_now") local hpMax = stats:Get("hp_max") print(string.format("%s\t\t%d/%d", name, hpNow, hpMax)) end end function Party:DebugHurtParty() for _, v in pairs(self.mMembers) do local stats = v.mStats stats:Set("hp_now", 10) print("ow") end end
mit
dinodeck/ninety_nine_days_of_dev
001_cancel_textboxes/code/Party.lua
8
1448
Party = {} Party.__index = Party function Party:Create() local this = { mMembers = {} } setmetatable(this, self) return this end function Party:Add(member) self.mMembers[member.mId] = member end function Party:RemoveById(id) self.mMembers[id] = nil end function Party:Remove(member) self:RemoveById(member.mId) end function Party:ToArray() local array = {} for k, v in pairs(self.mMembers) do table.insert(array, v) end return array end -- Count the number of this item equipped function Party:EquipCount(itemId) local count = 0 for _,v in pairs(self.mMembers) do count = count + v:EquipCount(itemId) end return count end function Party:Rest() for _, v in pairs(self.mMembers) do local stats = v.mStats if stats:Get("hp_now") > 0 then stats:Set("hp_now", stats:Get("hp_max")) stats:Set("mp_now", stats:Get("mp_max")) end end end function Party:DebugPrintParty() for _, v in pairs(self.mMembers) do local stats = v.mStats local name = v.mName local hpNow = stats:Get("hp_now") local hpMax = stats:Get("hp_max") print(string.format("%s\t\t%d/%d", name, hpNow, hpMax)) end end function Party:DebugHurtParty() for _, v in pairs(self.mMembers) do local stats = v.mStats stats:Set("hp_now", 10) print("ow") end end
mit
Ninjistix/darkstar
scripts/zones/The_Sanctuary_of_ZiTah/TextIDs.lua
5
1933
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item>. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6384; -- You cannot obtain the <item>. Try trading again after sorting your inventory. ITEM_OBTAINED = 6386; -- Obtained: <item>. GIL_OBTAINED = 6387; -- Obtained <number> gil. KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6395; -- You obtain <param2 number> <param1 item>! BEASTMEN_BANNER = 7128; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7548; -- You can't fish here. -- Conquest CONQUEST = 7215; -- You've earned conquest points! -- Quest Dialogs SENSE_OF_FOREBODING = 6401; -- You are suddenly overcome with a sense of foreboding... STURDY_BRANCH = 7761; -- It is a beautiful, sturdy branch. NOTHING_OUT_OF_ORDINARY = 7786; -- There is nothing out of the ordinary here. -- ZM4 Dialog SOMETHING_BETTER = 7731; -- Don't you have something better to do right now? CANNOT_REMOVE_FRAG = 7734; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed... ALREADY_OBTAINED_FRAG = 7735; -- You have already obtained this monument's FOUND_ALL_FRAGS = 7737; -- You now have all 8 fragments of light! ZILART_MONUMENT = 7738; -- It is an ancient Zilart monument. -- conquest Base CONQUEST_BASE = 7047; -- Tallying conquest results... -- chocobo digging DIG_THROW_AWAY = 7561; -- 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 = 7563; -- You dig and you dig, but find nothing.
gpl-3.0
Ninjistix/darkstar
scripts/globals/abilities/manifestation.lua
2
1089
----------------------------------- -- Ability: Manifestation -- Extends the effect of your next enfeebling1 black magic spell to targets within range. MP cost and casting time2 are doubled. -- Obtained: Scholar Level 40 -- Recast Time: Stratagem Charge -- Duration: 1 compatible black magic spell or 60 seconds, whichever occurs first -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_MANIFESTATION) then return msgBasic.EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; function onUseAbility(player,target,ability) player:addStatusEffect(EFFECT_MANIFESTATION,1,0,60); return EFFECT_MANIFESTATION; end;
gpl-3.0
eugenesan/openwrt-luci
protocols/ipv6/luasrc/model/cbi/admin_network/proto_hnet.lua
40
1492
--[[ LuCI - Lua Configuration Interface Copyright 2013 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local mode = section:taboption("general", ListValue, "mode", translate("Category")) mode:value("auto", translate("Automatic")) mode:value("external", translate("External")) mode:value("guest", translate("Guest")) mode:value("adhoc", translate("Ad-Hoc")) mode.default = "auto" local plen = section:taboption("advanced", Value, "ip6assign", translate("IPv6 assignment length"), translate("Assign a part of given length of every public IPv6-prefix to this interface")) plen.datatype = "max(128)" plen.default = "64" section:taboption("advanced", Value, "link_id", translate("IPv6 assignment hint"), translate("Assign prefix parts using this hexadecimal subprefix ID for this interface.")) plen = section:taboption("advanced", Value, "ip4assign", translate("IPv4 assignment length")) plen.datatype = "max(32)" plen.default = "24" local o = section:taboption("advanced", Value, "dnsname", translate("DNS-Label / FQDN")) o.default = map.name luci.tools.proto.opt_macaddr(section, ifc, translate("Override MAC address")) o = section:taboption("advanced", Value, "mtu", translate("Override MTU")) o.placeholder = "1500" o.datatype = "max(9200)"
apache-2.0
Ninjistix/darkstar
scripts/zones/Windurst_Woods/npcs/Anillah.lua
3
1496
----------------------------------- -- Area: Windurst Woods -- NPC: Anillah -- Type: Clothcraft Image Support -- !pos -34.800 -2.25 -119.950 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,3); local SkillCap = getCraftSkillCap(player,SKILL_CLOTHCRAFT); local SkillLevel = player:getSkillLevel(SKILL_CLOTHCRAFT); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == false) then player:startEvent(10015,SkillCap,SkillLevel,2,511,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(10015,SkillCap,SkillLevel,2,511,player:getGil(),7108,0,0); end else player:startEvent(10015); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 10015 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,4,2); player:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,1,0,120); end end;
gpl-3.0
kahrl/minetest-mod-away
init.lua
1
5895
------------------------------------- -- Away mod by kahrl -- -- Idea by jordan4ibanez & kahrl -- -- Version 1.0 -- ------------------------------------- -- -- Set yourself as away using the server command -- /away -- You can also give a reason, as follows: -- /away Saving the princess -- -- Each time somebody mentions your nick, the server will print a message -- that you are currently away (however, not more than once per minute). -- -- You can set yourself as no longer away with another /away, -- or by talking. If somebody tried to talk to you while you were away, -- the server will inform everyone that you're back. Doing something else -- in-game (e.g. moving around, digging, building, etc.) does not reset -- the away status. -- -- You can check your current away status: -- /away? -- You can also check any other player's status: -- /away? name -- -- Note: an away reason is hidden in case the user in question is -- missing the 'shout' privilege. -- -- The mod version AWAY_VERSION = '1.0' -- The name of the /away command AWAY_COMMAND = '/away' -- The name of the /away? command AWAYP_COMMAND = '/away?' -- The minimum time between away notifications, in seconds. Defaults to 60. AWAY_INFORM_INTERVAL = 60 -- The interval at which the mod looks for disconnected players, and resets -- their AFK status. -- This could be removed if a register_on_disconnectplayer callback was added. AWAY_CHECK_DISCONNECT_INTERVAL = 60 -- Set of away players local away_players = {} -- Maps player name to reason or nil if not applicable local away_reasons = {} -- Maps player to the time others were last informed about their afk-ness, -- or nil if not applicable local away_last_inform = {} -- List of inform messages to send on globalstep -- The purpose of this is that inform messages show up *after* the -- chat message that caused them local away_inform_outbox = {} function is_away(name) return away_players[name] ~= nil end function get_away_reason(name) -- If a player's shout privilege has been revoked, -- others shouldn't see the away reason if is_away(name) and minetest.get_player_privs(name)['shout'] then return away_reasons[name] else return '' end end function set_away(name, reason) if is_away(name) then minetest.chat_send_player(name, "You are still marked as away (away reason updated)") away_reasons[name] = reason else minetest.chat_send_player(name, "You are now marked as away") away_players[name] = true away_reasons[name] = reason away_last_inform[name] = nil end end function unset_away(name) if is_away(name) then if away_last_inform[name] ~= nil then table.insert(away_inform_outbox, name .. " is no longer away") else minetest.chat_send_player(name, "You are no longer marked as away") end away_players[name] = nil away_reasons[name] = nil away_last_inform[name] = nil end end function toggle_away(name, reason) if is_away(name) and reason == '' then unset_away(name) else set_away(name, reason) end end -- Returns 'present' or 'away' or 'away (<reason>)' or 'disconnected' function get_away_status(name) if minetest.env:get_player_by_name(name) == nil then return 'disconnected' elseif is_away(name) then reason = get_away_reason(name) if reason == '' then return 'away' else return 'away (' .. reason .. ')' end else return 'present' end end minetest.register_on_chat_message(function(name, message) local cmd cmd = AWAYP_COMMAND if message:sub(1, #cmd) == cmd then -- /away? local name2 = string.match(message, cmd:gsub("?", "[?]").." (.*)") if name2 == nil or name2 == '' or name2 == name then name2 = name minetest.chat_send_player(name, "Your status: " .. get_away_status(name2)) else minetest.chat_send_player(name, name2 .. "'s status: " .. get_away_status(name2)) end return true -- Handled chat message end cmd = AWAY_COMMAND if message:sub(1, #cmd) == cmd then -- /away local reason = string.match(message, AWAY_COMMAND.." (.*)") if reason == nil then reason = '' end toggle_away(name, reason) return true -- Handled chat message end if message:sub(1, 1) ~= '/' then -- Normal chat message (not a command) if not minetest.get_player_privs(name)['shout'] then -- Ignore if player has no shout privilege return false -- Continue normal processing end if is_away(name) then unset_away(name) end for awayname, _ in pairs(away_players) do -- Does the message contain the name of the away player? if message:find(awayname, 1, true) then local time = os.time() if away_last_inform[awayname] == nil or away_last_inform[awayname] <= time - AWAY_INFORM_INTERVAL then local info = '' local reason = get_away_reason(awayname) if reason == '' then info = awayname .. ' is away' else info = awayname .. ' is away: ' .. reason end table.insert(away_inform_outbox, info) away_last_inform[awayname] = time end end end return false -- Continue normal processing end end) local away_check_disconnect_timer = 0 minetest.register_globalstep(function(dtime) away_check_disconnect_timer = away_check_disconnect_timer + dtime if away_check_disconnect_timer >= AWAY_CHECK_DISCONNECT_INTERVAL then away_check_disconnect_timer = 0 local disconnected = {} for name, _ in pairs(away_players) do if minetest.env:get_player_by_name(name) == nil then table.insert(disconnected, name) end end for _, name in ipairs(disconnected) do away_players[name] = nil away_reasons[name] = nil away_last_inform[name] = nil end end if #away_inform_outbox ~= 0 then for _, message in ipairs(away_inform_outbox) do minetest.chat_send_all("Server: " .. message) end away_inform_outbox = {} end end) print("away mod version " .. AWAY_VERSION .. " loaded")
gpl-2.0
timstclair/kube-contrib
ingress/controllers/nginx/lua/error_page.lua
45
1661
http = require "resty.http" def_backend = "upstream-default-backend" local concat = table.concat local upstream = require "ngx.upstream" local get_servers = upstream.get_servers local get_upstreams = upstream.get_upstreams local random = math.random local us = get_upstreams() function openURL(status) local httpc = http.new() local random_backend = get_destination() local res, err = httpc:request_uri(random_backend, { path = "/", method = "GET", headers = { ["X-Code"] = status or "404", ["X-Format"] = ngx.var.httpAccept or "html", } }) if not res then ngx.log(ngx.ERR, err) ngx.exit(500) end if ngx.var.http_cookie then ngx.header["Cookie"] = ngx.var.http_cookie end ngx.status = tonumber(status) ngx.say(res.body) end function get_destination() for _, u in ipairs(us) do if u == def_backend then local srvs, err = get_servers(u) local us_table = {} if not srvs then return "http://127.0.0.1:8181" else for _, srv in ipairs(srvs) do us_table[srv["name"]] = srv["weight"] end end local destination = random_weight(us_table) return "http://"..destination end end end function random_weight(tbl) local total = 0 for k, v in pairs(tbl) do total = total + v end local offset = random(0, total - 1) for k1, v1 in pairs(tbl) do if offset < v1 then return k1 end offset = offset - v1 end end
apache-2.0
blackman1380/antispam
plugins/inrealm.lua
183
36473
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then if msg.to.type == 'chat' and not is_realm(msg) then data[tostring(msg.to.id)]['group_type'] = 'Group' save_data(_config.moderation.data, data) elseif msg.to.type == 'channel' then data[tostring(msg.to.id)]['group_type'] = 'SuperGroup' save_data(_config.moderation.data, data) end end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid send_large_msg(chat, user..'\n'..name) send_large_msg(channel, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin1(msg) then return "For admins 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 set_rules(msg, data, target) if not is_admin1(msg) then return "For admins 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 -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins 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_name(msg, data, target) if not is_admin1(msg) then return "For admins 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins 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_member(msg, data, target) if not is_admin1(msg) then return "For admins 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins 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 lock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" 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_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" 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_arabic(msg, data, target) if not is_admin1(msg) then return "For admins 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_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public end -- show SuperGroup settings local function show_super_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(msg.to.id)]['settings'] then if not data[tostring(msg.to.id)]['settings']['public'] then data[tostring(msg.to.id)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function returnids(cb_extra, success, result) local i = 1 local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n" i = i + 1 end end local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function cb_user_info(cb_extra, success, result) local receiver = cb_extra.receiver if result.first_name then first_name = result.first_name:gsub("_", " ") else first_name = "None" end if result.last_name then last_name = result.last_name:gsub("_", " ") else last_name = "None" end if result.username then username = "@"..result.username else username = "@[none]" end text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username send_large_msg(receiver, text) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_id..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List of global admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do if data[tostring(v)] then if data[tostring(v)]['settings'] then local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end end end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already an admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then send_large_msg(receiver, "@"..member_username..' is not an admin.') return end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.peer_id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function res_user_support(cb_extra, success, result) local receiver = cb_extra.receiver local get_cmd = cb_extra.get_cmd local support_id = result.peer_id if get_cmd == 'addsupport' then support_add(support_id) send_large_msg(receiver, "User ["..support_id.."] has been added to the support team") elseif get_cmd == 'removesupport' then support_remove(support_id) send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team") end end local function set_log_group(target, data) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(target)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'no' then return 'Log group is not set' else data[tostring(target)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then local receiver = get_receiver(msg) savelog(msg.to.id, "log file created by owner/support/admin") send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r") text = file:read("*a") send_large_msg(receiver,text) file:close() end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false) end if matches[1] == 'whois' and is_momod(msg) then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] user_info(user_id, cb_user_info, {receiver = receiver}) end if not is_sudo(msg) then if is_realm(msg) and is_admin1(msg) then print("Admin detected") else return end end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end --[[ Experimental if matches[1] == 'createsuper' and matches[2] then if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'super_group' return create_group(msg) end]] if matches[1] == 'createrealm' and matches[2] then if not is_sudo(msg) then return "Sudo users only !" end group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then local target = matches[3] local about = matches[4] return set_description(msg, data, target, about) end if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then local channel = 'channel#id'..matches[3] local about_text = matches[4] local data_cat = 'description' local target = matches[3] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) return "Description has been set for ["..matches[2]..']' end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then return lock_group_links(msg, data, target) end if matches[3] == 'spam' then return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return lock_group_sticker(msg, data, target) end end if matches[1] == 'unlock' then local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end if matches[3] == 'arabic' then return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' then return unlock_group_links(msg, data, target) end if matches[3] == 'spam' then return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return unlock_group_sticker(msg, data, target) end end if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_group_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_supergroup_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'setname' and is_realm(msg) then local settings = data[tostring(matches[2])]['settings'] 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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin1(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) rename_channel(channel_to_rename, group_name_set, ok_cb, false) savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end --[[if matches[1] == 'set' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.peer_id savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(target, data) end end if matches[1] == 'rem' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return unset_log_group(target, data) end end]] if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'rem' and matches[2] then -- Group configuration removal data[tostring(matches[2])] = 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(matches[2])] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Chat '..matches[2]..' removed') end if matches[1] == 'chat_add_user' then if not msg.service then return end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin1(msg) and is_realm(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'support' and matches[2] then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been added to the support team") support_add(support_id) return "User ["..support_id.."] has been added to the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "addsupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == '-support' then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been removed from the support team") support_remove(support_id) return "User ["..support_id.."] has been removed from the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "removesupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' then if matches[2] == 'admins' then return admin_list(msg) end -- if matches[2] == 'support' and not matches[2] then -- return support_list() -- end end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' or msg.to.type == 'channel' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' or msg.to.type == 'channel' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end 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 resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^[#!/](creategroup) (.*)$", "^[#!/](createsuper) (.*)$", "^[#!/](createrealm) (.*)$", "^[#!/](setabout) (%d+) (.*)$", "^[#!/](setrules) (%d+) (.*)$", "^[#!/](setname) (.*)$", "^[#!/](setgpname) (%d+) (.*)$", "^[#!/](setname) (%d+) (.*)$", "^[#!/](lock) (%d+) (.*)$", "^[#!/](unlock) (%d+) (.*)$", "^[#!/](mute) (%d+)$", "^[#!/](unmute) (%d+)$", "^[#!/](settings) (.*) (%d+)$", "^[#!/](wholist)$", "^[#!/](who)$", "^[#!/]([Ww]hois) (.*)", "^[#!/](type)$", "^[#!/](kill) (chat) (%d+)$", "^[#!/](kill) (realm) (%d+)$", "^[#!/](rem) (%d+)$", "^[#!/](addadmin) (.*)$", -- sudoers only "^[#!/](removeadmin) (.*)$", -- sudoers only "[#!/ ](support)$", "^[#!/](support) (.*)$", "^[#!/](-support) (.*)$", "^[#!/](list) (.*)$", "^[#!/](log)$", "^[#!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
wounds1/zaza2
plugins/inrealm.lua
183
36473
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin1(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.peer_id, result.peer_id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then if msg.to.type == 'chat' and not is_realm(msg) then data[tostring(msg.to.id)]['group_type'] = 'Group' save_data(_config.moderation.data, data) elseif msg.to.type == 'channel' then data[tostring(msg.to.id)]['group_type'] = 'SuperGroup' save_data(_config.moderation.data, data) end end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid send_large_msg(chat, user..'\n'..name) send_large_msg(channel, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin1(msg) then return "For admins 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 set_rules(msg, data, target) if not is_admin1(msg) then return "For admins 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 -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin1(msg) then return "For admins 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_name(msg, data, target) if not is_admin1(msg) then return "For admins 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 --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin1(msg) then return "For admins 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_member(msg, data, target) if not is_admin1(msg) then return "For admins 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 --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin1(msg) then return "For admins 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 lock_group_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" 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_flood(msg, data, target) if not is_admin1(msg) then return "For admins only!" 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_arabic(msg, data, target) if not is_admin1(msg) then return "For admins 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_admin1(msg) then return "For admins only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'SuperGroup spam is already locked' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'SuperGroup spam has been locked' end end local function unlock_group_spam(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'SuperGroup spam is not locked' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup spam has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL char. in names is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL char. in names has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL char. in names is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL char. in names has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'SuperGroup is now: public' end local function unset_public_membermod(msg, data, target) if not is_admin1(msg) then return "For admins only!" end local group_public_lock = data[tostring(target)]['settings']['public'] if group_public_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'SuperGroup is now: not public' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings for "..target..":\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nPublic: "..settings.public end -- show SuperGroup settings local function show_super_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin1(msg) then return "For admins only!" end if data[tostring(msg.to.id)]['settings'] then if not data[tostring(msg.to.id)]['settings']['public'] then data[tostring(msg.to.id)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "SuperGroup settings for "..target..":\nLock links : "..settings.lock_link.."\nLock flood: "..settings.flood.."\nLock spam: "..settings.lock_spam.."\nLock Arabic: "..settings.lock_arabic.."\nLock Member: "..settings.lock_member.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public.."\nStrict settings: "..settings.strict return text end local function returnids(cb_extra, success, result) local i = 1 local receiver = cb_extra.receiver local chat_id = "chat#id"..result.peer_id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' (ID: '..result.peer_id..'):\n\n' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text ..i..' - '.. string.gsub(v.print_name,"_"," ") .. " [" .. v.peer_id .. "] \n\n" i = i + 1 end end local file = io.open("./groups/lists/"..result.peer_id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function cb_user_info(cb_extra, success, result) local receiver = cb_extra.receiver if result.first_name then first_name = result.first_name:gsub("_", " ") else first_name = "None" end if result.last_name then last_name = result.last_name:gsub("_", " ") else last_name = "None" end if result.username then username = "@"..result.username else username = "@[none]" end text = "User Info:\n\nID: "..result.peer_id.."\nFirst: "..first_name.."\nLast: "..last_name.."\nUsername: "..username send_large_msg(receiver, text) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_id..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List of global admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do if data[tostring(v)] then if data[tostring(v)]['settings'] then local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end end end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, '@'..member_username..' is already an admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then send_large_msg(receiver, "@"..member_username..' is not an admin.') return end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Admin @'..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.peer_id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function res_user_support(cb_extra, success, result) local receiver = cb_extra.receiver local get_cmd = cb_extra.get_cmd local support_id = result.peer_id if get_cmd == 'addsupport' then support_add(support_id) send_large_msg(receiver, "User ["..support_id.."] has been added to the support team") elseif get_cmd == 'removesupport' then support_remove(support_id) send_large_msg(receiver, "User ["..support_id.."] has been removed from the support team") end end local function set_log_group(target, data) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(target)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin1(msg) then return end local log_group = data[tostring(target)]['log_group'] if log_group == 'no' then return 'Log group is not set' else data[tostring(target)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then local receiver = get_receiver(msg) savelog(msg.to.id, "log file created by owner/support/admin") send_document(receiver,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and msg.to.type == 'chat' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) local file = io.open("./groups/lists/"..msg.to.id.."memberlist.txt", "r") text = file:read("*a") send_large_msg(receiver,text) file:close() end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) send_document("chat#id"..msg.to.id,"./groups/lists/"..msg.to.id.."memberlist.txt", ok_cb, false) end if matches[1] == 'whois' and is_momod(msg) then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] user_info(user_id, cb_user_info, {receiver = receiver}) end if not is_sudo(msg) then if is_realm(msg) and is_admin1(msg) then print("Admin detected") else return end end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end --[[ Experimental if matches[1] == 'createsuper' and matches[2] then if not is_sudo(msg) or is_admin1(msg) and is_realm(msg) then return "You cant create groups!" end group_name = matches[2] group_type = 'super_group' return create_group(msg) end]] if matches[1] == 'createrealm' and matches[2] then if not is_sudo(msg) then return "Sudo users only !" end group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[1] == 'setabout' and matches[2] == 'group' and is_realm(msg) then local target = matches[3] local about = matches[4] return set_description(msg, data, target, about) end if matches[1] == 'setabout' and matches[2] == 'sgroup'and is_realm(msg) then local channel = 'channel#id'..matches[3] local about_text = matches[4] local data_cat = 'description' local target = matches[3] channel_set_about(channel, about_text, ok_cb, false) data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) return "Description has been set for ["..matches[2]..']' end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end if matches[2] == 'arabic' then return lock_group_arabic(msg, data, target) end if matches[3] == 'links' then return lock_group_links(msg, data, target) end if matches[3] == 'spam' then return lock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return lock_group_sticker(msg, data, target) end end if matches[1] == 'unlock' then local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end if matches[3] == 'arabic' then return unlock_group_arabic(msg, data, target) end if matches[3] == 'links' then return unlock_group_links(msg, data, target) end if matches[3] == 'spam' then return unlock_group_spam(msg, data, target) end if matches[3] == 'rtl' then return unlock_group_rtl(msg, data, target) end if matches[3] == 'sticker' then return unlock_group_sticker(msg, data, target) end end if matches[1] == 'settings' and matches[2] == 'group' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_group_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'settings' and matches[2] == 'sgroup' and data[tostring(matches[3])]['settings'] then local target = matches[3] text = show_supergroup_settingsmod(msg, target) return text.."\nID: "..target.."\n" end if matches[1] == 'setname' and is_realm(msg) then local settings = data[tostring(matches[2])]['settings'] 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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin1(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local chat_to_rename = 'chat#id'..matches[2] local channel_to_rename = 'channel#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) rename_channel(channel_to_rename, group_name_set, ok_cb, false) savelog(matches[3], "Group { "..group_name_set.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end --[[if matches[1] == 'set' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.peer_id savelog(msg.to.peer_id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(target, data) end end if matches[1] == 'rem' then if matches[2] == 'loggroup' and is_sudo(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return unset_log_group(target, data) end end]] if matches[1] == 'kill' and matches[2] == 'chat' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' and matches[3] then if not is_admin1(msg) then return end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'rem' and matches[2] then -- Group configuration removal data[tostring(matches[2])] = 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(matches[2])] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, 'Chat '..matches[2]..' removed') end if matches[1] == 'chat_add_user' then if not msg.service then return end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin1(msg) and is_realm(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if not is_sudo(msg) then-- Sudo only return end if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'support' and matches[2] then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been added to the support team") support_add(support_id) return "User ["..support_id.."] has been added to the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "addsupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == '-support' then if string.match(matches[2], '^%d+$') then local support_id = matches[2] print("User "..support_id.." has been removed from the support team") support_remove(support_id) return "User ["..support_id.."] has been removed from the support team" else local member = string.gsub(matches[2], "@", "") local receiver = get_receiver(msg) local get_cmd = "removesupport" resolve_username(member, res_user_support, {get_cmd = get_cmd, receiver = receiver}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' then if matches[2] == 'admins' then return admin_list(msg) end -- if matches[2] == 'support' and not matches[2] then -- return support_list() -- end end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' or msg.to.type == 'channel' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' or msg.to.type == 'channel' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) send_document("channel#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end 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 resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^[#!/](creategroup) (.*)$", "^[#!/](createsuper) (.*)$", "^[#!/](createrealm) (.*)$", "^[#!/](setabout) (%d+) (.*)$", "^[#!/](setrules) (%d+) (.*)$", "^[#!/](setname) (.*)$", "^[#!/](setgpname) (%d+) (.*)$", "^[#!/](setname) (%d+) (.*)$", "^[#!/](lock) (%d+) (.*)$", "^[#!/](unlock) (%d+) (.*)$", "^[#!/](mute) (%d+)$", "^[#!/](unmute) (%d+)$", "^[#!/](settings) (.*) (%d+)$", "^[#!/](wholist)$", "^[#!/](who)$", "^[#!/]([Ww]hois) (.*)", "^[#!/](type)$", "^[#!/](kill) (chat) (%d+)$", "^[#!/](kill) (realm) (%d+)$", "^[#!/](rem) (%d+)$", "^[#!/](addadmin) (.*)$", -- sudoers only "^[#!/](removeadmin) (.*)$", -- sudoers only "[#!/ ](support)$", "^[#!/](support) (.*)$", "^[#!/](-support) (.*)$", "^[#!/](list) (.*)$", "^[#!/](log)$", "^[#!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Ninjistix/darkstar
scripts/zones/Cloister_of_Tides/npcs/Water_Protocrystal.lua
5
1895
----------------------------------- -- 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(2); 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==2) 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
mohammadtofani/fox
plugins/p.lua
134
6165
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
ArchiveTeam/googlemoderator-grab
googlemoderator.lua
1
1325
local url_count = 0 local tries = 0 wget.callbacks.httploop_result = function(url, err, http_stat) -- NEW for 2014: Slightly more verbose messages because people keep -- complaining that it's not moving or not working status_code = http_stat["statcode"] url_count = url_count + 1 io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n") io.stdout:flush() if status_code ~= 200 and status_code ~= 403 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 1") tries = tries + 1 if tries >= 15 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end elseif status_code == 0 then io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n") io.stdout:flush() os.execute("sleep 10") tries = tries + 1 if tries >= 10 then io.stdout:write("\nI give up...\n") io.stdout:flush() tries = 0 return wget.actions.ABORT else return wget.actions.CONTINUE end end tries = 0 local sleep_time = 0 if sleep_time > 0.001 then os.execute("sleep " .. sleep_time) end return wget.actions.NOTHING end
unlicense
neofob/sile
languages/as.lua
3
1139
SILE.hyphenator.languages["as"] = {} SILE.hyphenator.languages["as"].patterns = { -- GENERAL RULE -- Do not break either side of ZERO-WIDTH JOINER (U+200D) "2‍2", -- Break on both sides of ZERO-WIDTH NON JOINER (U+200C) "1‌1", -- Break before or after any independent vowel. "অ1", "আ1", "ই1", "ঈ1", "উ1", "ঊ1", "ঋ1", "ৠ1", "ঌ1", "ৡ1", "এ1", "ঐ1", "ও1", "ঔ1", -- Break after any dependent vowel, but not before. "া1", "ি1", "ী1", "ু1", "ূ1", "ৃ1", "ৄ1", "ৢ1", "ৣ1", "ে1", "ৈ1", "ো1", "ৌ1", "2়2", "ৗ1", -- Break before or after any consonant. "1ক", "1খ", "1গ", "1ঘ", "1ঙ", "1চ", "1ছ", "1জ", "1ঝ", "1ঞ", "1ট", "1ঠ", "1ড", "1ড়", "1ঢ", "1ঢ়", "1ণ", "1ত", "1থ", "1দ", "1ধ", "1ন", "1প", "1ফ", "1ব", "1ভ", "1ম", "1য", "1য়", "1র", "1ল", "1শ", "1ষ", "1স", "1হ", -- Do not break after khanda ta. "ৎ1", -- Do not break before chandrabindu, anusvara, visarga, avagraha, -- nukta and au length mark. "2ঃ1", "2ং1", "2ঁ1", "2ঽ1", -- Do not break either side of virama (may be within conjunct). "2্2", }
mit
ztuowen/chill-dev
Manual/test-cases/examples/cuda-chill/nbody.lua
3
1653
--CUBLAS 2 MM Multiply --This function form intializes "CUDAIZE v2" versus "CUDAIZE v1" if you --call init() and use global variables to specify procedure and loop --Second parameter is procedure # and third is loop # init("nbody.c", "nbody_cpu" , 0) dofile("cudaize.lua") --defines custom tile_by_index, copy_to_registers, --copy_to_shared methods NBODIES=16384 --Tj=128 CHANGE FOR BEST..... BEST IS 64BLOCKS 128THREADS --Ti=256 Tj=64 Ti=32 Tjjj=1 Tiii=1 Tn=0.1 --normalize_index("j") -- --print_code() --normalize_index("n") -- TILE COMMANDS ZEROOOOOOOOOOO:3 --tile_by_index({"i","j"},{Ti,Tj},{l1_control="ii",l2_control="jj"},{"ii","jj","i","j"})--CU=-1 tile_by_index({"i"},{Ti},{l1_control="ii"},{"ii","i","j"})--CU=-1 --normalize_index("i") --tile_by_index({"n"},{Tn},{l1_control="nn"},{"jj","ii","nn","j","i","n"})--CU=-1 --tile_by_index({"j","i"},{Tjjj,Tiii},{l1_control="jjj",l2_control="iii"},{"jj","ii","nn","jjj","j","iii","i","n"})--CU=3 --tile_by_index({"j"}, {Tn}, {l1_control="j",l1_tile="jjj"}, {"ii", "jj", "nn","jjj","j","i","n"}) --tile_by_index({"i"}, {Ti/2}, {l1_control="iii"}, {"ii","iii", "jj","i","j"}) --print_code() cudaize("kernel_GPU",{oldpos=4*NBODIES,oldpos1=4*NBODIES,oldvel=4*NBODIES,force=4*NBODIES,newpos=4*NBODIES,newvel=4*NBODIES},{block={"ii"}, thread={"i"}})--CU=3 print_code() --tile(0,6,6) --copy_to_shared("tx","oldpos",-16) --copy_to_registers("j","oldpos") --copy_to_registers("j","oldpos1") --copy_to_registers("j","force") --copy_to_texture("oldpos") --tile(1,3,3) --tile(2,3,3) print_code() --unroll_to_depth(1) -- --tile(2,3,3) --unroll(2,3,0) --unroll(0,5,0) --print_code()
gpl-3.0
codedash64/Urho3D
bin/Data/LuaScripts/35_SignedDistanceFieldText.lua
26
7747
-- Signed distance field text example. -- This sample demonstrates: -- - Creating a 3D scene with static content -- - Creating a 3D text use SDF Font -- - Displaying the scene using the Renderer subsystem -- - Handling keyboard and mouse input to move a freelook camera require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") -- Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple -- plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger -- (100 x 100 world units) local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a directional light to the world so that we can see something. The light scene node's orientation controls the -- light direction we will use the SetDirection() function which calculates the orientation from a forward direction vector. -- The light will use default settings (white light, no shadows) local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) -- The direction vector does not need to be normalized local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL -- Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a -- quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains -- LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll -- see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the -- same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the -- scene. local NUM_OBJECTS = 200 for i = 1, NUM_OBJECTS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0) mushroomNode:SetScale(0.5 + Random(2.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") local mushroomTitleNode = mushroomNode:CreateChild("MushroomTitle") mushroomTitleNode.position = Vector3(0.0, 1.2, 0.0) local mushroomTitleText = mushroomTitleNode:CreateComponent("Text3D") mushroomTitleText.text = "Mushroom " .. i mushroomTitleText:SetFont(cache:GetResource("Font", "Fonts/BlueHighway.sdf"), 24) mushroomTitleText.color = Color(1.0, 0.0, 0.0) if (i % 3) == 1 then mushroomTitleText.color = Color(0.0, 1.0, 0.0) mushroomTitleText.textEffect = TE_SHADOW mushroomTitleText.effectColor = Color(0.5, 0.5, 0.5) end if (i % 3) == 2 then mushroomTitleText.color = Color(1.0, 1.0, 0.0) mushroomTitleText.textEffect = TE_STROKE mushroomTitleText.effectColor = Color(0.5, 0.5, 0.5) end mushroomTitleText:SetAlignment(HA_CENTER, VA_CENTER) end -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") cameraNode:CreateComponent("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw +MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed -- Use the Translate() function (default local space) to move relative to the node's orientation. if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end
mit
carnalis/Urho3D
bin/Data/LuaScripts/35_SignedDistanceFieldText.lua
26
7747
-- Signed distance field text example. -- This sample demonstrates: -- - Creating a 3D scene with static content -- - Creating a 3D text use SDF Font -- - Displaying the scene using the Renderer subsystem -- - Handling keyboard and mouse input to move a freelook camera require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") -- Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple -- plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger -- (100 x 100 world units) local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a directional light to the world so that we can see something. The light scene node's orientation controls the -- light direction we will use the SetDirection() function which calculates the orientation from a forward direction vector. -- The light will use default settings (white light, no shadows) local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) -- The direction vector does not need to be normalized local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL -- Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a -- quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains -- LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll -- see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the -- same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the -- scene. local NUM_OBJECTS = 200 for i = 1, NUM_OBJECTS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0) mushroomNode:SetScale(0.5 + Random(2.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") local mushroomTitleNode = mushroomNode:CreateChild("MushroomTitle") mushroomTitleNode.position = Vector3(0.0, 1.2, 0.0) local mushroomTitleText = mushroomTitleNode:CreateComponent("Text3D") mushroomTitleText.text = "Mushroom " .. i mushroomTitleText:SetFont(cache:GetResource("Font", "Fonts/BlueHighway.sdf"), 24) mushroomTitleText.color = Color(1.0, 0.0, 0.0) if (i % 3) == 1 then mushroomTitleText.color = Color(0.0, 1.0, 0.0) mushroomTitleText.textEffect = TE_SHADOW mushroomTitleText.effectColor = Color(0.5, 0.5, 0.5) end if (i % 3) == 2 then mushroomTitleText.color = Color(1.0, 1.0, 0.0) mushroomTitleText.textEffect = TE_STROKE mushroomTitleText.effectColor = Color(0.5, 0.5, 0.5) end mushroomTitleText:SetAlignment(HA_CENTER, VA_CENTER) end -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") cameraNode:CreateComponent("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw +MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed -- Use the Translate() function (default local space) to move relative to the node's orientation. if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end
mit
Ninjistix/darkstar
scripts/zones/Spire_of_Vahzl/npcs/_0n0.lua
22
1534
----------------------------------- -- Area: Spire of Vahzl -- NPC: Web of Recollection ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; else player:messageSpecial(FAINT_SCRAPING); return 1; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; else return 1; 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 Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
jamiepg1/MCServer
MCServer/Plugins/TestLuaRocks/TestLuaRocks.lua
22
1232
-- TestLuaRocks.lua -- This is a mockup plugin that does a quick test of LuaRocks capability in MCServer -- "Success" is when the plugin loads, downloads the forum webpage and displays the headers and length and then displays both libs as loaded. -- "Failure" usually manifests as one of the "require" lines failing, although you have the luarock installed. -- Note that the plugin deliberately never fully loads, so that it can be reloaded fast by pressing its Enable button in the webadmin's plugin list. local log30 = require("30log"); local socket = require("socket"); local http = require("socket.http"); LOGINFO("Trying to download a webpage..."); local body, code, headers = http.request('http://forum.mc-server.org/index.php'); LOG("code: " .. tostring(code)); LOG("headers: "); for k, v in pairs(headers or {}) do LOG(" " .. k .. ": " .. v); end LOG("body length: " .. string.len(body)); function Initialize(a_Plugin) if (socket == nil) then LOG("LuaSocket not found"); else LOG("LuaSocket loaded"); end if (log30 == nil) then LOG("30log not found"); else LOG("30log loaded"); end LOGINFO("Preventing plugin load so that it may be requested again from the webadmin."); return false; end
apache-2.0
bmddota/ContainersPlayground
game/dota_addons/containersplayground/scripts/vscripts/internal/util.lua
1
2497
function DebugPrint(...) local spew = Convars:GetInt('barebones_spew') or -1 if spew == -1 and BAREBONES_DEBUG_SPEW then spew = 1 end if spew == 1 then print(...) end end function DebugPrintTable(...) local spew = Convars:GetInt('barebones_spew') or -1 if spew == -1 and BAREBONES_DEBUG_SPEW then spew = 1 end if spew == 1 then PrintTable(...) end end function PrintTable(t, indent, done) --print ( string.format ('PrintTable type %s', type(keys)) ) if type(t) ~= "table" then return end done = done or {} done[t] = true indent = indent or 0 local l = {} for k, v in pairs(t) do table.insert(l, k) end table.sort(l) for k, v in ipairs(l) do -- Ignore FDesc if v ~= 'FDesc' then local value = t[v] if type(value) == "table" and not done[value] then done [value] = true print(string.rep ("\t", indent)..tostring(v)..":") PrintTable (value, indent + 2, done) elseif type(value) == "userdata" and not done[value] then done [value] = true print(string.rep ("\t", indent)..tostring(v)..": "..tostring(value)) PrintTable ((getmetatable(value) and getmetatable(value).__index) or getmetatable(value), indent + 2, done) else if t.FDesc and t.FDesc[v] then print(string.rep ("\t", indent)..tostring(t.FDesc[v])) else print(string.rep ("\t", indent)..tostring(v)..": "..tostring(value)) end end end end end -- Colors COLOR_NONE = '\x06' COLOR_GRAY = '\x06' COLOR_GREY = '\x06' COLOR_GREEN = '\x0C' COLOR_DPURPLE = '\x0D' COLOR_SPINK = '\x0E' COLOR_DYELLOW = '\x10' COLOR_PINK = '\x11' COLOR_RED = '\x12' COLOR_LGREEN = '\x15' COLOR_BLUE = '\x16' COLOR_DGREEN = '\x18' COLOR_SBLUE = '\x19' COLOR_PURPLE = '\x1A' COLOR_ORANGE = '\x1B' COLOR_LRED = '\x1C' COLOR_GOLD = '\x1D' --[[Author: Noya Date: 09.08.2015. Hides all dem hats ]] function HideWearables( unit ) local unit = event.caster unit.hiddenWearables = {} -- Keep every wearable handle in a table to show them later local model = unit:FirstMoveChild() while model ~= nil do if model:GetClassname() == "dota_item_wearable" then model:AddEffects(EF_NODRAW) -- Set model hidden table.insert(unit.hiddenWearables, model) end model = model:NextMovePeer() end end function ShowWearables( unit ) for i,v in pairs(unit.hiddenWearables) do v:RemoveEffects(EF_NODRAW) end end
apache-2.0
Ninjistix/darkstar
scripts/globals/spells/cura_ii.lua
3
4199
----------------------------------------- -- Spell: Cura -- Restores hp in area of effect. Self target only -- From what I understand, Cura's base potency is the same as Cure II's. -- With Afflatus Misery Bonus, it can be as potent as a Curaga III -- Modeled after our cure_ii.lua, which was modeled after the below reference -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) if (caster:getID() ~= target:getID()) then return msgBasic.CANNOT_PERFORM_TARG; else return 0; end; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 60; if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster); divisor = 1; constant = 20; if (power > 170) then divisor = 35.6666; constant = 87.62; elseif (power > 110) then divisor = 2; constant = 47.5; end else power = getCurePower(caster); if (power < 70) then divisor = 1; constant = 60; basepower = 40; elseif (power < 125) then divisor = 5.5; constant = 90; basepower = 70; elseif (power < 200) then divisor = 7.5; constant = 100; basepower = 125; elseif (power < 400) then divisor = 10; constant = 110; basepower = 200; elseif (power < 700) then divisor = 20; constant = 130; basepower = 400; else divisor = 999999; constant = 145; basepower = 0; end end if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCure(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end --Apply Afflatus Misery Bonus to Final Result if (caster:hasStatusEffect(EFFECT_AFFLATUS_MISERY)) then if (caster:getID() == target:getID()) then -- Let's use a local var to hold the power of Misery so the boost is applied to all targets, caster:setLocalVar("Misery_Power", caster:getMod(MOD_AFFLATUS_MISERY)); end; local misery = caster:getLocalVar("Misery_Power"); --THIS IS LARELY SEMI-EDUCATED GUESSWORK. THERE IS NOT A --LOT OF CONCRETE INFO OUT THERE ON CURA THAT I COULD FIND --Not very much documentation for Cura II known at all. --As with Cura, the Afflatus Misery bonus can boost this spell up --to roughly the level of a Curaga 3. For Cura I vs Curaga II, --this is document at ~175HP, 15HP less than the cap of 190HP. So --for Cura II, i'll go with 15 less than the cap of Curaga III (390): 375 --So with lack of available formula documentation, I'll go with that. --printf("BEFORE AFFLATUS MISERY BONUS: %d", basecure); basecure = basecure + misery; if (basecure > 375) then basecure = 375; end --printf("AFTER AFFLATUS MISERY BONUS: %d", basecure); --Afflatus Misery Mod Gets Used Up caster:setMod(MOD_AFFLATUS_MISERY, 0); end final = getCureFinal(caster,spell,basecure,minCure,false); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; target:addHP(final); target:wakeUp(); --Enmity for Cura is fixed, so its CE/VE is set in the SQL and not calculated with updateEnmityFromCure spell:setMsg(msgBasic.AOE_HP_RECOVERY); local mpBonusPercent = (final*caster:getMod(MOD_CURE2MP_PERCENT))/100; if (mpBonusPercent > 0) then caster:addMP(mpBonusPercent); end return final; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/garland_of_bliss.lua
3
1795
----------------------------------- -- Garland Of Bliss -- Staff weapon skill -- Skill level: N/A -- Lowers target's defense. Duration of effect varies with TP. Nirvana: Aftermath effect varies with TP. -- Reduces enemy's defense by 12.5%. -- Available only after completing the Unlocking a Myth (Summoner) quest. -- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget. -- Aligned with the Flame Belt, Light Belt & Aqua Belt. -- Element: Light -- Modifiers: MND:40% -- 100%TP 200%TP 300%TP -- 2.00 2.00 2.00 ----------------------------------- 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 = 2; params.ftp200 = 2; params.ftp300 = 2; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_STF; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25; params.str_wsc = 0.3; params.mnd_wsc = 0.7; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); if (damage > 0 and target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then local duration = (30 + (tp/1000 * 30)) * applyResistanceAddEffect(player,target,ELE_WIND,0); target:addStatusEffect(EFFECT_DEFENSE_DOWN, 12.5, 0, duration); end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Ninjistix/darkstar
scripts/zones/Upper_Jeuno/npcs/Hinda.lua
5
1042
----------------------------------- -- Area: Upper Jeuno -- NPC: Hinda -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Upper_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,9) == false) then player:startEvent(10087); else player:startEvent(161); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 10087) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",9,true); end end;
gpl-3.0
davidbuzz/ardupilot
libraries/AP_Scripting/examples/rover-set-steering-and-throttle.lua
24
2101
-- cause a rover to drive in a figure of eight pattern by directly controlling steering and throttle -- -- CAUTION: This script only works for Rover -- this script waits for the vehicle to be armed and RC6 input > 1800 and then: -- a) switches to Guided mode -- b) increases throttle to 30% and turns right at 20% for 10 seconds -- c) keep throttle at 30% and turns left at 20% for 10 seconds -- d) switches to Hold mode local stage = 0 local stage_counter = 0 local rover_guided_mode_num = 15 local rover_hold_mode_num = 4 -- the main update function that directly sets throttle and steering out to drive a figure of eight pattern function update() if not arming:is_armed() then -- reset state when disarmed stage = 0 stage_counter = 0 else pwm6 = rc:get_pwm(6) if pwm6 and pwm6 > 1800 then -- check if RC6 input has moved high if (stage == 0) then -- change to guided mode if (vehicle:set_mode(rover_guided_mode_num)) then -- change to Guided mode stage = stage + 1 stage_counter = 0 end elseif (stage == 1) then -- Stage1: increase throttle to 30% and turn right 20% if (vehicle:set_steering_and_throttle(0.2, 0.3)) then stage_counter = stage_counter + 1 if (stage_counter >= 10) then stage = stage + 1 stage_counter = 0 end end elseif (stage == 2) then -- Stage2: keep throttle at 30% and turn left 20% if (vehicle:set_steering_and_throttle(-0.2, 0.3)) then stage_counter = stage_counter + 1 if (stage_counter >= 10) then stage = stage + 1 stage_counter = 0 end end elseif (stage == 3) then -- Stage3: change to Hold mode vehicle:set_mode(rover_hold_mode_num) stage = stage + 1 gcs:send_text(0, "finished, switching to Hold") end else -- RC6 has been moved low if stage > 3 then stage = 0 stage_counter = 0 end end end return update, 1000 end return update()
gpl-3.0
AlexisBRENON/awesome
spec/wibox/test_utils.lua
6
3100
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2014 Uli Schlachter --------------------------------------------------------------------------- local object = require("gears.object") local wbase = require("wibox.widget.base") local lbase = require("wibox.layout.base") local say = require("say") local assert = require("luassert") local spy = require("luassert.spy") local stub = require("luassert.stub") local real_draw_widget = lbase.draw_widget local widgets_drawn = nil -- This function would reject stubbed widgets local real_check_widget = wbase.check_widget wbase.check_widget = function() end local function stub_draw_widget(wibox, cr, widget, x, y, width, height) assert.is.equal("wibox", wibox) assert.is.equal("cr", cr) table.insert(widgets_drawn, { widget, x, y, width, height }) end -- {{{ Own widget-based assertions local function widget_fit(state, arguments) if #arguments ~= 3 then return false end local widget = arguments[1] local given = arguments[2] local expected = arguments[3] local w, h = widget:fit(given[1], given[2]) local fits = expected[1] == w and expected[2] == h if state.mod == fits then return true end -- For proper error message, mess with the arguments arguments[1] = given[1] arguments[2] = given[2] arguments[3] = expected[1] arguments[4] = expected[2] arguments[5] = w arguments[6] = h return false end say:set("assertion.widget_fit.positive", "Offering (%s, %s) to widget and expected (%s, %s), but got (%s, %s)") assert:register("assertion", "widget_fit", widget_fit, "assertion.widget_fit.positive", "assertion.widget_fit.positive") -- }}} return { real_check_widget = real_check_widget, widget_stub = function(width, height) local w = object() w:add_signal("widget::updated") w.fit = function() return width or 10, height or 10 end w.draw = function() end w._fit_geometry_cache = {} spy.on(w, "fit") stub(w, "draw") return w end, stub_draw_widget = function() lbase.draw_widget = stub_draw_widget widgets_drawn = {} end, revert_draw_widget = function() lbase.draw_widget = real_draw_widget widgets_drawn = nil end, check_widgets_drawn = function(expected) assert.is.equals(#expected, #widgets_drawn) for k, v in pairs(expected) do -- widget, x, y, width, height -- Compared like this so we get slightly less bad error messages assert.is.equals(expected[k][1], widgets_drawn[k][1]) assert.is.equals(expected[k][2], widgets_drawn[k][2]) assert.is.equals(expected[k][3], widgets_drawn[k][3]) assert.is.equals(expected[k][4], widgets_drawn[k][4]) assert.is.equals(expected[k][5], widgets_drawn[k][5]) end widgets_drawn = {} end } -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
eugenesan/openwrt-luci
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_config.lua
80
1274
--[[ LuCI - Lua Configuration Interface (c) 2009 Daniel Dickinson Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.controller.luci_diag.devinfo_common") m = Map("luci_devinfo", translate("SIP Device Scanning Configuration"), translate("Configure scanning for supported SIP devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices.")) s = m:section(SimpleSection, "", translate("Use Configuration")) b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)")) b.value = "" b.titleref = luci.dispatcher.build_url("admin", "status", "smap_devinfo") scannet = m:section(TypedSection, "smap_scannet", translate("Scanning Configuration"), translate("Networks to scan for supported devices")) scannet.addremove = true scannet.anonymous = false local ports ports = scannet:option(Value, "ports", translate("Ports")) ports.optional = true ports.rmempty = true luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet) return m
apache-2.0
neofob/sile
packages/tate.lua
1
4995
local pdf = require("justenoughlibtexpdf") SILE.tateFramePrototype = SILE.framePrototype { direction = "TTB-RTL", enterHooks = { function (self) self.oldtypesetter = SILE.typesetter SILE.typesetter.leadingFor = function(self, v) v.height = SILE.toPoints("1zw") return SILE.settings.get("document.parskip") end SILE.typesetter.breakIntoLines = SILE.require("packages/break-firstfit") end }, leaveHooks = { function (self) SILE.typesetter = self.oldtypesetter end } } SILE.newTateFrame = function ( spec ) return SILE.newFrame(spec, SILE.tateFramePrototype) end SILE.registerCommand("tate-frame", function (options, content) SILE.documentState.thisPageTemplate.frames[options.id] = SILE.newTateFrame(options) end, "Declares (or re-declares) a frame on this page.") local swap = function (x) local w = x.width x.width = SILE.length.new({}) + x.height x.height = type(w) == "table" and w.length or w end local outputLatinInTate = function (self, typesetter, line) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.toPoints("-0.5zw")) typesetter.frame:advancePageDirection(SILE.toPoints("0.25zw")) local horigin = typesetter.frame.state.cursorX local vorigin = -typesetter.frame.state.cursorY self:oldOutputYourself(typesetter,line) typesetter.frame.state.cursorY = -vorigin typesetter.frame:advanceWritingDirection(self:lineContribution()) -- My baseline moved typesetter.frame:advanceWritingDirection(SILE.toPoints("0.5zw") ) typesetter.frame:advancePageDirection(- SILE.toPoints("0.25zw")) end local outputTateChuYoko = function (self, typesetter, line) -- My baseline moved local em = SILE.toPoints("1zw") typesetter.frame:advanceWritingDirection(-(em) + em/4 - self:lineContribution()/2) typesetter.frame:advancePageDirection(2*self.height - self.width.length/2) self:oldOutputYourself(typesetter,line) typesetter.frame:advanceWritingDirection(-self:lineContribution()*1.5+self.height*3/4) end -- Eventually will be automatically called by script detection, but for now -- called manually SILE.registerCommand("latin-in-tate", function (options, content) local nodes local oldT = SILE.typesetter local prevDirection = oldT.frame.direction if oldT.frame:writingDirection() ~= "TTB" then return SILE.process(content) end SILE.require("packages/rotate") SILE.settings.temporarily(function() local latinT = SILE.defaultTypesetter {} latinT.frame = oldT.frame latinT:initState() SILE.typesetter = latinT SILE.settings.set("document.language", "und") SILE.settings.set("font.direction", "LTR") SILE.process(content) nodes = SILE.typesetter.state.nodes SILE.typesetter:shapeAllNodes(nodes) SILE.typesetter.frame.direction = prevDirection end) SILE.typesetter = oldT SILE.typesetter:pushGlue({ width = SILE.length.new({length = SILE.toPoints("0.5zw"), stretch = SILE.toPoints("0.25zw"), shrink = SILE.toPoints("0.25zw") }) }) for i = 1,#nodes do if SILE.typesetter.frame:writingDirection() ~= "TTB" then SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif nodes[i]:isGlue() then nodes[i].width = nodes[i].width SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] elseif SILE.length.make(nodes[i]:lineContribution()).length > 0 then SILE.call("hbox", {}, function () SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes+1] = nodes[i] end) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.oldOutputYourself = n.outputYourself n.outputYourself = outputLatinInTate n.misfit = true end end end, "Typeset rotated Western text in vertical Japanese") SILE.registerCommand("tate-chu-yoko", function (options, content) if SILE.typesetter.frame:writingDirection() ~= "TTB" then return SILE.process(content) end -- SILE.typesetter:pushGlue({ -- width = SILE.length.new({length = SILE.toPoints("0.5zw"), -- stretch = SILE.toPoints("0.25zw"), -- shrink = SILE.toPoints("0.25zw") -- }) -- }) SILE.settings.temporarily(function() SILE.settings.set("document.language", "und") SILE.settings.set("font.direction", "LTR") SILE.call("rotate",{angle =-90}, function () SILE.call("hbox", {}, content) local n = SILE.typesetter.state.nodes[#SILE.typesetter.state.nodes] n.misfit = true n.oldOutputYourself = n.outputYourself n.outputYourself = outputTateChuYoko end) end) -- SILE.typesetter:pushGlue({ -- width = SILE.length.new({length = SILE.toPoints("0.5zw"), -- stretch = SILE.toPoints("0.25zw"), -- shrink = SILE.toPoints("0.25zw") -- }) -- }) end)
mit
Ninjistix/darkstar
scripts/globals/mobskills/pw_calcifying_deluge.lua
34
1153
--------------------------------------------- -- Calcifying Deluge -- -- Description: Delivers a threefold ranged attack to targets in an area of effect. Additional effect: Petrification -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown -- Notes: Used only by Medusa. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 1865) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,MOBPARAM_3_SHADOW); local typeEffect = EFFECT_PETRIFICATION; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 30); target:delHP(dmg); return dmg; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/curaga_v.lua
5
1427
----------------------------------------- -- Spell: Curaga V -- Restores HP of all party members within area of effect. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local minCure = 600; local divisor = 1; local constant = 570; local power = getCurePowerOld(caster); if (power > 780) then divisor = 2.667; constant = 814;--this is too powerful and needs to be fixed when the rest of the curaga 5 numbers are determined end local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,false); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:restoreHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); spell:setMsg(msgBasic.AOE_HP_RECOVERY); local mpBonusPercent = (final*caster:getMod(MOD_CURE2MP_PERCENT))/100; if (mpBonusPercent > 0) then caster:addMP(mpBonusPercent); end return final; end;
gpl-3.0
BooM-amour/bomb
plugins/lock_badword.lua
59
1102
local function run(msg, matches) if msg.to.type == 'chat' then if is_owner(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_adds = data[tostring(msg.to.id)]['settings']['lock_badw'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if lock_adds == "yes" then send_large_msg(chat, 'Badwords is not allowed here!!') chat_del_user(chat, user, ok_cb, true) end end end return { patterns = { "(ک*س)$", "کیر", "کص", "کــــــــــیر", "کــــــــــــــــــــــــــــــیر", "کـیـــــــــــــــــــــــــــــــــــــــــــــــــــر", "ک×یر", "ک÷یر", "ک*ص", "کــــــــــیرر", "kir", "kos", "گوساله", "gosale", "gusale" }, run = run }
gpl-2.0
tele911/xy-test
plugins/lock_badword.lua
59
1102
local function run(msg, matches) if msg.to.type == 'chat' then if is_owner(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_adds = data[tostring(msg.to.id)]['settings']['lock_badw'] end end end local chat = get_receiver(msg) local user = "user#id"..msg.from.id if lock_adds == "yes" then send_large_msg(chat, 'Badwords is not allowed here!!') chat_del_user(chat, user, ok_cb, true) end end end return { patterns = { "(ک*س)$", "کیر", "کص", "کــــــــــیر", "کــــــــــــــــــــــــــــــیر", "کـیـــــــــــــــــــــــــــــــــــــــــــــــــــر", "ک×یر", "ک÷یر", "ک*ص", "کــــــــــیرر", "kir", "kos", "گوساله", "gosale", "gusale" }, run = run }
gpl-2.0
dafei2015/hugular_cstolua
Client/Assets/uLua/Source/LuaJIT/src/host/genminilua.lua
127
11962
---------------------------------------------------------------------------- -- Lua script to generate a customized, minified version of Lua. -- The resulting 'minilua' is used for the build process of LuaJIT. ---------------------------------------------------------------------------- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- local sub, match, gsub = string.sub, string.match, string.gsub local LUA_VERSION = "5.1.5" local LUA_SOURCE local function usage() io.stderr:write("Usage: ", arg and arg[0] or "genminilua", " lua-", LUA_VERSION, "-source-dir\n") os.exit(1) end local function find_sources() LUA_SOURCE = arg and arg[1] if not LUA_SOURCE then usage() end if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end local fp = io.open(LUA_SOURCE .. "lua.h") if not fp then LUA_SOURCE = LUA_SOURCE.."src/" fp = io.open(LUA_SOURCE .. "lua.h") if not fp then usage() end end local all = fp:read("*a") fp:close() if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then io.stderr:write("Error: version mismatch\n") usage() end end local LUA_FILES = { "lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c", "lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c", "llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c", "lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c", } local REMOVE_LIB = {} gsub([[ collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset select tostring xpcall foreach foreachi getn maxn setn popen tmpfile seek setvbuf __tostring clock date difftime execute getenv rename setlocale time tmpname dump gfind len reverse LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME ]], "%S+", function(name) REMOVE_LIB[name] = true end) local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, } local CUSTOM_MAIN = [[ typedef unsigned int UB; static UB barg(lua_State *L,int idx){ union{lua_Number n;U64 b;}bn; bn.n=lua_tonumber(L,idx)+6755399441055744.0; if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number"); return(UB)bn.b; } #define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1; static int tobit(lua_State *L){ BRET(barg(L,1))} static int bnot(lua_State *L){ BRET(~barg(L,1))} static int band(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)} static int bor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)} static int bxor(lua_State *L){ int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)} static int lshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)} static int rshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)} static int arshift(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)} static int rol(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))} static int ror(lua_State *L){ UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))} static int bswap(lua_State *L){ UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)} static int tohex(lua_State *L){ UB b=barg(L,1); int n=lua_isnone(L,2)?8:(int)barg(L,2); const char *hexdigits="0123456789abcdef"; char buf[8]; int i; if(n<0){n=-n;hexdigits="0123456789ABCDEF";} if(n>8)n=8; for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;} lua_pushlstring(L,buf,(size_t)n); return 1; } static const struct luaL_Reg bitlib[] = { {"tobit",tobit}, {"bnot",bnot}, {"band",band}, {"bor",bor}, {"bxor",bxor}, {"lshift",lshift}, {"rshift",rshift}, {"arshift",arshift}, {"rol",rol}, {"ror",ror}, {"bswap",bswap}, {"tohex",tohex}, {NULL,NULL} }; int main(int argc, char **argv){ lua_State *L = luaL_newstate(); int i; luaL_openlibs(L); luaL_register(L, "bit", bitlib); if (argc < 2) return sizeof(void *); lua_createtable(L, 0, 1); lua_pushstring(L, argv[1]); lua_rawseti(L, -2, 0); lua_setglobal(L, "arg"); if (luaL_loadfile(L, argv[1])) goto err; for (i = 2; i < argc; i++) lua_pushstring(L, argv[i]); if (lua_pcall(L, argc - 2, 0, 0)) { err: fprintf(stderr, "Error: %s\n", lua_tostring(L, -1)); return 1; } lua_close(L); return 0; } ]] local function read_sources() local t = {} for i, name in ipairs(LUA_FILES) do local fp = assert(io.open(LUA_SOURCE..name, "r")) t[i] = fp:read("*a") assert(fp:close()) end t[#t+1] = CUSTOM_MAIN return table.concat(t) end local includes = {} local function merge_includes(src) return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name) if includes[name] then return "" end includes[name] = true local fp = assert(io.open(LUA_SOURCE..name, "r")) local src = fp:read("*a") assert(fp:close()) src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "") src = gsub(src, "#endif%s*$", "") return merge_includes(src) end) end local function get_license(src) return match(src, "/%*+\n%* Copyright %(.-%*/\n") end local function fold_lines(src) return gsub(src, "\\\n", " ") end local strings = {} local function save_str(str) local n = #strings+1 strings[n] = str return "\1"..n.."\2" end local function save_strings(src) src = gsub(src, '"[^"\n]*"', save_str) return gsub(src, "'[^'\n]*'", save_str) end local function restore_strings(src) return gsub(src, "\1(%d+)\2", function(numstr) return strings[tonumber(numstr)] end) end local function def_istrue(def) return def == "INT_MAX > 2147483640L" or def == "LUAI_BITSINT >= 32" or def == "SIZE_Bx < LUAI_BITSINT-1" or def == "cast" or def == "defined(LUA_CORE)" or def == "MINSTRTABSIZE" or def == "LUA_MINBUFFER" or def == "HARDSTACKTESTS" or def == "UNUSED" end local head, defs = {[[ #ifdef _MSC_VER typedef unsigned __int64 U64; #else typedef unsigned long long U64; #endif int _CRT_glob = 0; ]]}, {} local function preprocess(src) local t = { match(src, "^(.-)#") } local lvl, on, oldon = 0, true, {} for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do if pp == "if" or pp == "ifdef" or pp == "ifndef" then lvl = lvl + 1 oldon[lvl] = on on = def_istrue(def) elseif pp == "else" then if oldon[lvl] then if on == false then on = true else on = false end end elseif pp == "elif" then if oldon[lvl] then on = def_istrue(def) end elseif pp == "endif" then on = oldon[lvl] lvl = lvl - 1 elseif on then if pp == "include" then if not head[def] and not REMOVE_EXTINC[def] then head[def] = true head[#head+1] = "#include "..def.."\n" end elseif pp == "define" then local k, sp, v = match(def, "([%w_]+)(%s*)(.*)") if k and not (sp == "" and sub(v, 1, 1) == "(") then defs[k] = gsub(v, "%a[%w_]*", function(tok) return defs[tok] or tok end) else t[#t+1] = "#define "..def.."\n" end elseif pp ~= "undef" then error("unexpected directive: "..pp.." "..def) end end if on then t[#t+1] = txt end end return gsub(table.concat(t), "%a[%w_]*", function(tok) return defs[tok] or tok end) end local function merge_header(src, license) local hdr = string.format([[ /* This is a heavily customized and minimized copy of Lua %s. */ /* It's only used to build LuaJIT. It does NOT have all standard functions! */ ]], LUA_VERSION) return hdr..license..table.concat(head)..src end local function strip_unused1(src) return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func) return REMOVE_LIB[func] and "" or line end) end local function strip_unused2(src) return gsub(src, "Symbolic Execution.-}=", "") end local function strip_unused3(src) src = gsub(src, "extern", "static") src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(") src = gsub(src, "#define lua_assert[^\n]*\n", "") src = gsub(src, "lua_assert%b();?", "") src = gsub(src, "default:\n}", "default:;\n}") src = gsub(src, "lua_lock%b();", "") src = gsub(src, "lua_unlock%b();", "") src = gsub(src, "luai_threadyield%b();", "") src = gsub(src, "luai_userstateopen%b();", "{}") src = gsub(src, "luai_userstate%w+%b();", "") src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser") src = gsub(src, "trydecpoint%(ls,seminfo%)", "luaX_lexerror(ls,\"malformed number\",TK_NUMBER)") src = gsub(src, "int c=luaZ_lookahead%b();", "") src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;", "return 1;") src = gsub(src, "getfuncname%b():", "NULL:") src = gsub(src, "getobjname%b():", "NULL:") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "") src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "") src = gsub(src, "(twoto%b()%()", "%1(size_t)") src = gsub(src, "i<sizenode", "i<(int)sizenode") return gsub(src, "\n\n+", "\n") end local function strip_comments(src) return gsub(src, "/%*.-%*/", " ") end local function strip_whitespace(src) src = gsub(src, "^%s+", "") src = gsub(src, "%s*\n%s*", "\n") src = gsub(src, "[ \t]+", " ") src = gsub(src, "(%W) ", "%1") return gsub(src, " (%W)", "%1") end local function rename_tokens1(src) src = gsub(src, "getline", "getline_") src = gsub(src, "struct ([%w_]+)", "ZX%1") return gsub(src, "union ([%w_]+)", "ZY%1") end local function rename_tokens2(src) src = gsub(src, "ZX([%w_]+)", "struct %1") return gsub(src, "ZY([%w_]+)", "union %1") end local function func_gather(src) local nodes, list = {}, {} local pos, len = 1, #src while pos < len do local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos) if d then local n = #list+1 list[n] = d nodes[w] = n else local s d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos) if not d then d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos) if not d then d = match(src, "^[^\n]*\n", pos) end end if s == "{" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) if sub(d, -2) == "{\n" then d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3) end end local k, v = nil, d if w == "typedef" then if match(d, "^typedef enum") then head[#head+1] = d else k = match(d, "([%w_]+);\n$") if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end end elseif w == "enum" then head[#head+1] = v elseif w ~= nil then k = match(d, "^[^\n]-([%w_]+)[(%[=]") if k then if w ~= "static" and k ~= "main" then v = "static "..d end else k = w end end if w and k then local o = nodes[k] if o then nodes["*"..k] = o end local n = #list+1 list[n] = v nodes[k] = n end end pos = pos + #d end return nodes, list end local function func_visit(nodes, list, used, n) local i = nodes[n] for m in string.gmatch(list[i], "[%w_]+") do if nodes[m] then local j = used[m] if not j then used[m] = i func_visit(nodes, list, used, m) elseif i < j then used[m] = i end end end end local function func_collect(src) local nodes, list = func_gather(src) local used = {} func_visit(nodes, list, used, "main") for n,i in pairs(nodes) do local j = used[n] if j and j < i then used["*"..n] = j end end for n,i in pairs(nodes) do if not used[n] then list[i] = "" end end return table.concat(list) end find_sources() local src = read_sources() src = merge_includes(src) local license = get_license(src) src = fold_lines(src) src = strip_unused1(src) src = save_strings(src) src = strip_unused2(src) src = strip_comments(src) src = preprocess(src) src = strip_whitespace(src) src = strip_unused3(src) src = rename_tokens1(src) src = func_collect(src) src = rename_tokens2(src) src = restore_strings(src) src = merge_header(src, license) io.write(src)
mit
malyutinegor/starsim
app/scripts/libs/hump-timer.lua
1
6532
--[[ Copyright (c) 2010-2013 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. 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 Timer = {} Timer.__index = Timer local function _nothing_() end function Timer:update(dt) local to_remove = {} for handle in pairs(self.functions) do -- handle: { -- time = <number>, -- after = <function>, -- during = <function>, -- limit = <number>, -- count = <number>, -- } handle.time = handle.time + dt handle.during(dt, math.max(handle.limit - handle.time, 0)) while handle.time >= handle.limit and handle.count > 0 do if handle.after(handle.after) == false then handle.count = 0 break end handle.time = handle.time - handle.limit handle.count = handle.count - 1 end if handle.count == 0 then table.insert(to_remove, handle) end end for i = 1, #to_remove do self.functions[to_remove[i]] = nil end end function Timer:during(delay, during, after) local handle = { time = 0, during = during, after = after or _nothing_, limit = delay, count = 1 } self.functions[handle] = true return handle end function Timer:after(delay, func) return self:during(delay, _nothing_, func) end function Timer:every(delay, after, count) local count = count or math.huge -- exploit below: math.huge - 1 = math.huge local handle = { time = 0, during = _nothing_, after = after, limit = delay, count = count } self.functions[handle] = true return handle end function Timer:cancel(handle) self.functions[handle] = nil end function Timer:clear() self.functions = {} end function Timer:script(f) local co = coroutine.wrap(f) co(function(t) self:after(t, co) coroutine.yield() end) end Timer.tween = setmetatable({ -- helper functions out = function(f) -- 'rotates' a function return function(s, ...) return 1 - f(1-s, ...) end end, chain = function(f1, f2) -- concatenates two functions return function(s, ...) return (s < .5 and f1(2*s, ...) or 1 + f2(2*s-1, ...)) * .5 end end, -- useful tweening functions linear = function(s) return s end, quad = function(s) return s*s end, cubic = function(s) return s*s*s end, quart = function(s) return s*s*s*s end, quint = function(s) return s*s*s*s*s end, sine = function(s) return 1-math.cos(s*math.pi/2) end, expo = function(s) return 2^(10*(s-1)) end, circ = function(s) return 1 - math.sqrt(1-s*s) end, back = function(s,bounciness) bounciness = bounciness or 1.70158 return s*s*((bounciness+1)*s - bounciness) end, bounce = function(s) -- magic numbers ahead local a,b = 7.5625, 1/2.75 return math.min(a*s^2, a*(s-1.5*b)^2 + .75, a*(s-2.25*b)^2 + .9375, a*(s-2.625*b)^2 + .984375) end, elastic = function(s, amp, period) amp, period = amp and math.max(1, amp) or 1, period or .3 return (-amp * math.sin(2*math.pi/period * (s-1) - math.asin(1/amp))) * 2^(10*(s-1)) end, }, { -- register new tween __call = function(tween, self, len, subject, target, method, after, ...) -- recursively collects fields that are defined in both subject and target into a flat list local function tween_collect_payload(subject, target, out) for k,v in pairs(target) do local ref = subject[k] assert(type(v) == type(ref), 'Type mismatch in field "'..k..'".') if type(v) == 'table' then tween_collect_payload(ref, v, out) else local ok, delta = pcall(function() return (v-ref)*1 end) assert(ok, 'Field "'..k..'" does not support arithmetic operations') out[#out+1] = {subject, k, delta} end end return out end method = tween[method or 'linear'] -- see __index local payload, t, args = tween_collect_payload(subject, target, {}), 0, {...} local last_s = 0 return self:during(len, function(dt) t = t + dt local s = method(math.min(1, t/len), unpack(args)) local ds = s - last_s last_s = s for _, info in ipairs(payload) do local ref, key, delta = unpack(info) ref[key] = ref[key] + delta * ds end end, after) end, -- fetches function and generated compositions for method `key` __index = function(tweens, key) if type(key) == 'function' then return key end assert(type(key) == 'string', 'Method must be function or string.') if rawget(tweens, key) then return rawget(tweens, key) end local function construct(pattern, f) local method = rawget(tweens, key:match(pattern)) if method then return f(method) end return nil end local out, chain = rawget(tweens,'out'), rawget(tweens,'chain') return construct('^in%-([^-]+)$', function(...) return ... end) or construct('^out%-([^-]+)$', out) or construct('^in%-out%-([^-]+)$', function(f) return chain(f, out(f)) end) or construct('^out%-in%-([^-]+)$', function(f) return chain(out(f), f) end) or error('Unknown interpolation method: ' .. key) end}) -- Timer instancing function Timer.new() return setmetatable({functions = {}, tween = Timer.tween}, Timer) end -- default instance local default = Timer.new() -- module forwards calls to default instance local module = {} for k in pairs(Timer) do if k ~= "__index" then module[k] = function(...) return default[k](default, ...) end end end module.tween = setmetatable({}, { __index = Timer.tween, __newindex = function(k,v) Timer.tween[k] = v end, __call = function(t, ...) return default:tween(...) end, }) return setmetatable(module, {__call = Timer.new})
gpl-3.0
heritage902/railroad
pugixml/scripts/premake4.lua
128
2376
-- Reset RNG seed to get consistent results across runs (i.e. XCode) math.randomseed(12345) local static = _ARGS[1] == 'static' local action = premake.action.current() if string.startswith(_ACTION, "vs") then if action then -- Disable solution generation function action.onsolution(sln) sln.vstudio_configs = premake.vstudio_buildconfigs(sln) end -- Rename output file function action.onproject(prj) local name = "%%_" .. _ACTION .. (static and "_static" or "") if static then for k, v in pairs(prj.project.__configs) do v.objectsdir = v.objectsdir .. "Static" end end if _ACTION == "vs2010" then premake.generate(prj, name .. ".vcxproj", premake.vs2010_vcxproj) else premake.generate(prj, name .. ".vcproj", premake.vs200x_vcproj) end end end elseif _ACTION == "codeblocks" then action.onsolution = nil function action.onproject(prj) premake.generate(prj, "%%_" .. _ACTION .. ".cbp", premake.codeblocks_cbp) end elseif _ACTION == "codelite" then action.onsolution = nil function action.onproject(prj) premake.generate(prj, "%%_" .. _ACTION .. ".project", premake.codelite_project) end end solution "pugixml" objdir(_ACTION) targetdir(_ACTION) if string.startswith(_ACTION, "vs") then if _ACTION ~= "vs2002" and _ACTION ~= "vs2003" then platforms { "x32", "x64" } configuration "x32" targetdir(_ACTION .. "/x32") configuration "x64" targetdir(_ACTION .. "/x64") end configurations { "Debug", "Release" } if static then configuration "Debug" targetsuffix "sd" configuration "Release" targetsuffix "s" else configuration "Debug" targetsuffix "d" end else if _ACTION == "xcode3" then platforms "universal" end configurations { "Debug", "Release" } configuration "Debug" targetsuffix "d" end project "pugixml" kind "StaticLib" language "C++" files { "../src/pugixml.hpp", "../src/pugiconfig.hpp", "../src/pugixml.cpp" } flags { "NoPCH", "NoMinimalRebuild", "NoEditAndContinue", "Symbols" } uuid "89A1E353-E2DC-495C-B403-742BE206ACED" configuration "Debug" defines { "_DEBUG" } configuration "Release" defines { "NDEBUG" } flags { "Optimize" } if static then configuration "*" flags { "StaticRuntime" } end
gpl-3.0
dinodeck/ninety_nine_days_of_dev
006_magic_menu/code/Dice.lua
10
2092
Dice = {} Dice.__index = Dice function Dice:Create(diceStr) local this = { mDice = {} } setmetatable(this, self) this:Parse(diceStr) return this end function Dice:Parse(diceStr) local len = string.len(diceStr) local index = 1 local allDice = {} while index <= len do local die die, index = self:ParseDie(diceStr, index) table.insert(self.mDice, die) index = index + 1 -- eat ' ' end end function Dice:ParseDie(diceStr, i) local rolls rolls, i = self:ParseNumber(diceStr, i) i = i + 1 -- Move past the \'D\' local sides sides, i = self:ParseNumber(diceStr, i) if i == string.len(diceStr) or string.sub(diceStr, i, i) == ' ' then return { rolls, sides, 0 }, i end if string.sub(diceStr, i, i) == '+' then i = i + 1 -- move past the '+' local plus plus, i = self:ParseNumber(diceStr, i) return { rolls, sides, plus }, i end end function Dice:ParseNumber(str, index) local isNum = { ['0'] = true, ['1'] = true, ['2'] = true, ['3'] = true, ['4'] = true, ['5'] = true, ['6'] = true, ['7'] = true, ['8'] = true, ['9'] = true } local len = string.len(str) local subStr = {} for i = index, len do local char = string.sub(str, i, i) if not isNum[char] then return tonumber(table.concat(subStr)), i end table.insert(subStr, char) end return tonumber(table.concat(subStr)), len end -- Notice this uses a . not a : meaning the function can be called -- without having a class instance. e.g Dice.RollDie(1, 6) is ok function Dice.RollDie(rolls, faces, modifier) local total = 0 for i = 1, rolls do total = total + math.random(1, faces) end return total + (modifier or 0) end function Dice:Roll() local total = 0 for _, die in ipairs(self.mDice) do total = total + Dice.RollDie(unpack(die)) end return total end
mit
rigeirani/seed
bot/seedbot.lua
44
10244
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin" }, sudo_users = {110626080,103649648,143723991,111020322,0,tonumber(our_id)},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[Teleseed v2 - Open Source An advance Administration bot based on yagop/telegram-bot https://github.com/SEEDTEAM/TeleSeed Admins @iwals [Founder] @imandaneshi [Developer] @Rondoozle [Developer] @seyedan25 [Manager] Special thanks to awkward_potato Siyanew topkecleon Vamptacus Our channels @teleseedch [English] @iranseed [persian] ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ Commands list : !kick [username|id] You can also do it by reply !ban [ username|id] You can also do it by reply !unban [id] You can also do it by reply !who Members list !modlist Moderators list !promote [username] Promote someone !demote [username] Demote someone !kickme Will kick user !about Group description !setphoto Set and locks group photo !setname [name] Set group name !rules Group rules !id return group id or user id !help !lock [member|name|bots|leave] Locks [member|name|bots|leaveing] !unlock [member|name|bots|leave] Unlocks [member|name|bots|leaving] !set rules <text> Set <text> as rules !set about <text> Set <text> as about !settings Returns group settings !newlink create/revoke your group link !link returns group link !owner returns group owner id !setowner [id] Will set id as owner !setflood [value] Set [value] as flood sensitivity !stats Simple message statistics !save [value] <text> Save <text> as [value] !get [value] Returns text of [value] !clean [modlist|rules|about] Will clear [modlist|rules|about] and set it to nil !res [username] returns user id "!res @username" !log will return group logs !banlist will return group ban list **U can use both "/" and "!" *Only owner and mods can add bots in group *Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only owner can use res,setowner,promote,demote and log commands ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
eugenesan/openwrt-luci
modules/base/luasrc/http/protocol/conditionals.lua
88
4757
--[[ HTTP protocol implementation for LuCI - RFC2616 / 14.19, 14.24 - 14.28 (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- --- LuCI http protocol implementation - HTTP/1.1 bits. -- This class provides basic ETag handling and implements most of the -- conditional HTTP/1.1 headers specified in RFC2616 Sct. 14.24 - 14.28 . module("luci.http.protocol.conditionals", package.seeall) local date = require("luci.http.protocol.date") --- Implement 14.19 / ETag. -- @param stat A file.stat structure -- @return String containing the generated tag suitable for ETag headers function mk_etag( stat ) if stat ~= nil then return string.format( '"%x-%x-%x"', stat.ino, stat.size, stat.mtime ) end end --- 14.24 / If-Match -- Test whether the given message object contains an "If-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating whether the precondition is ok -- @return Alternative status code if the precondition failed function if_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) -- Check for matching resource if type(h['If-Match']) == "string" then for ent in h['If-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then return true end end return false, 412 end return true end --- 14.25 / If-Modified-Since -- Test whether the given message object contains an "If-Modified-Since" header -- and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating whether the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_modified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Modified-Since']) == "string" then local since = date.to_unix( h['If-Modified-Since'] ) if stat == nil or since < stat.mtime then return true end return false, 304, { ["ETag"] = mk_etag( stat ); ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } end return true end --- 14.26 / If-None-Match -- Test whether the given message object contains an "If-None-Match" header and -- compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating whether the precondition is ok -- @return Alternative status code if the precondition failed -- @return Table containing extra HTTP headers if the precondition failed function if_none_match( req, stat ) local h = req.headers local etag = mk_etag( stat ) local method = req.env and req.env.REQUEST_METHOD or "GET" -- Check for matching resource if type(h['If-None-Match']) == "string" then for ent in h['If-None-Match']:gmatch("([^, ]+)") do if ( ent == '*' or ent == etag ) and stat ~= nil then if method == "GET" or method == "HEAD" then return false, 304, { ["ETag"] = etag; ["Date"] = date.to_http( os.time() ); ["Last-Modified"] = date.to_http( stat.mtime ) } else return false, 412 end end end end return true end --- 14.27 / If-Range -- The If-Range header is currently not implemented due to the lack of general -- byte range stuff in luci.http.protocol . This function will always return -- false, 412 to indicate a failed precondition. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating whether the precondition is ok -- @return Alternative status code if the precondition failed function if_range( req, stat ) -- Sorry, no subranges (yet) return false, 412 end --- 14.28 / If-Unmodified-Since -- Test whether the given message object contains an "If-Unmodified-Since" -- header and compare it against the given stat object. -- @param req HTTP request message object -- @param stat A file.stat object -- @return Boolean indicating whether the precondition is ok -- @return Alternative status code if the precondition failed function if_unmodified_since( req, stat ) local h = req.headers -- Compare mtimes if type(h['If-Unmodified-Since']) == "string" then local since = date.to_unix( h['If-Unmodified-Since'] ) if stat ~= nil and since <= stat.mtime then return false, 412 end end return true end
apache-2.0
johnsoch/cuberite
Server/Plugins/APIDump/Classes/Network.lua
11
38094
-- Network.lua -- Defines the documentation for the cNetwork-related classes and cUrlClient return { cNetwork = { Desc = [[ This is the namespace for high-level network-related operations. Allows plugins to make TCP connections to the outside world using a callback-based API.</p> <p> All functions in this namespace are static, they should be called on the cNetwork class itself: <pre class="prettyprint lang-lua"> local Server = cNetwork:Listen(1024, ListenCallbacks); </pre></p> ]], Functions = { Connect = { IsStatic = true, Params = { { Name = "Host", Type = "string", }, { Name = "Port", Type = "number", }, { Name = "LinkCallbacks", Type = "table", }, }, Returns = { { Type = "boolean", }, }, Notes = "Begins establishing a (client) TCP connection to the specified host. Uses the LinkCallbacks table to report progress, success, errors and incoming data. Returns false if it fails immediately (bad port value, bad hostname format), true otherwise. Host can be either an IP address or a hostname.", }, CreateUDPEndpoint = { IsStatic = true, Params = { { Name = "Port", Type = "number", }, { Name = "UDPCallbacks", Type = "table", }, }, Returns = { { Type = "cUDPEndpoint", }, }, Notes = "Creates a UDP endpoint that listens for incoming datagrams on the specified port, and can be used to send or broadcast datagrams. Uses the UDPCallbacks to report incoming datagrams or errors. If the endpoint cannot be created, the OnError callback is called with the error details and the returned endpoint will report IsOpen() == false. The plugin needs to store the returned endpoint object for as long as it needs the UDP port open; if the endpoint is garbage-collected by Lua, the socket will be closed and no more incoming data will be reported.<br>If the Port is zero, the OS chooses an available UDP port for the endpoint; use {{cUDPEndpoint}}:GetPort() to query the port number in such case.", }, EnumLocalIPAddresses = { IsStatic = true, Returns = { { Type = "table", }, }, Notes = "Returns all local IP addresses for network interfaces currently available on the machine, as an array-table of strings.", }, HostnameToIP = { IsStatic = true, Params = { { Name = "Host", Type = "string", }, { Name = "LookupCallbacks", Type = "table", }, }, Returns = { { Type = "boolean", }, }, Notes = "Begins a DNS lookup to find the IP address(es) for the specified host. Uses the LookupCallbacks table to report progress, success or errors. Returns false if it fails immediately (bad hostname format), true if the lookup started successfully. Host can be either a hostname or an IP address.", }, IPToHostname = { IsStatic = true, Params = { { Name = "Address", Type = "string", }, { Name = "LookupCallbacks", Type = "table", }, }, Returns = { { Type = "boolean", }, }, Notes = "Begins a reverse-DNS lookup to find out the hostname for the specified IP address. Uses the LookupCallbacks table to report progress, success or errors. Returns false if it fails immediately (bad address format), true if the lookup started successfully.", }, Listen = { IsStatic = true, Params = { { Name = "Port", Type = "number", }, { Name = "ListenCallbacks", Type = "table", }, }, Returns = { { Type = "cServerHandle", }, }, Notes = "Starts listening on the specified port. Uses the ListenCallbacks to report incoming connections or errors. Returns a {{cServerHandle}} object representing the server. If the listen operation failed, the OnError callback is called with the error details and the returned server handle will report IsListening() == false. The plugin needs to store the server handle object for as long as it needs the server running, if the server handle is garbage-collected by Lua, the listening socket will be closed and all current connections dropped.", }, }, AdditionalInfo = { { Header = "Using callbacks", Contents = [[ The entire Networking API is callback-based. Whenever an event happens on the network object, a specific plugin-provided function is called. The callbacks are stored in tables which are passed to the API functions, each table contains multiple callbacks for the various situations.</p> <p> There are four different callback variants used: LinkCallbacks, LookupCallbacks, ListenCallbacks and UDPCallbacks. Each is used in the situation appropriate by its name - LinkCallbacks are used for handling the traffic on a single network link (plus additionally creation of such link when connecting as a client), LookupCallbacks are used when doing DNS and reverse-DNS lookups, ListenCallbacks are used for handling incoming connections as a server and UDPCallbacks are used for incoming UDP datagrams.</p> <p> LinkCallbacks have the following structure:<br/> <pre class="prettyprint lang-lua"> local LinkCallbacks = { OnConnected = function ({{cTCPLink|a_TCPLink}}) -- The specified {{cTCPLink|link}} has succeeded in connecting to the remote server. -- Only called if the link is being connected as a client (using cNetwork:Connect() ) -- Not used for incoming server links -- All returned values are ignored end, OnError = function ({{cTCPLink|a_TCPLink}}, a_ErrorCode, a_ErrorMsg) -- The specified error has occured on the {{cTCPLink|link}} -- No other callback will be called for this link from now on -- For a client link being connected, this reports a connection error (destination unreachable etc.) -- It is an Undefined Behavior to send data to a_TCPLink in or after this callback -- All returned values are ignored end, OnReceivedData = function ({{cTCPLink|a_TCPLink}}, a_Data) -- Data has been received on the {{cTCPLink|link}} -- Will get called whenever there's new data on the {{cTCPLink|link}} -- a_Data contains the raw received data, as a string -- All returned values are ignored end, OnRemoteClosed = function ({{cTCPLink|a_TCPLink}}) -- The remote peer has closed the {{cTCPLink|link}} -- The link is already closed, any data sent to it now will be lost -- No other callback will be called for this link from now on -- All returned values are ignored end, } </pre></p> <p> LookupCallbacks have the following structure:<br/> <pre class="prettyprint lang-lua"> local LookupCallbacks = { OnError = function (a_Query, a_ErrorCode, a_ErrorMsg) -- The specified error has occured while doing the lookup -- a_Query is the hostname or IP being looked up -- No other callback will be called for this lookup from now on -- All returned values are ignored end, OnFinished = function (a_Query) -- There are no more DNS records for this query -- a_Query is the hostname or IP being looked up -- No other callback will be called for this lookup from now on -- All returned values are ignored end, OnNameResolved = function (a_Hostname, a_IP) -- A DNS record has been found, the specified hostname resolves to the IP -- Called for both Hostname -&gt; IP and IP -&gt; Hostname lookups -- May be called multiple times if a hostname resolves to multiple IPs -- All returned values are ignored end, } </pre></p> <p> ListenCallbacks have the following structure:<br/> <pre class="prettyprint lang-lua"> local ListenCallbacks = { OnAccepted = function ({{cTCPLink|a_TCPLink}}) -- A new connection has been accepted and a {{cTCPLink|Link}} for it created -- It is safe to send data to the link now -- All returned values are ignored end, OnError = function (a_ErrorCode, a_ErrorMsg) -- The specified error has occured while trying to listen -- No other callback will be called for this server handle from now on -- This callback is called before the cNetwork:Listen() call returns -- All returned values are ignored end, OnIncomingConnection = function (a_RemoteIP, a_RemotePort, a_LocalPort) -- A new connection is being accepted, from the specified remote peer -- This function needs to return either nil to drop the connection, -- or valid LinkCallbacks to use for the new connection's {{cTCPLink|TCPLink}} object return SomeLinkCallbacks end, } </pre></p> <p> UDPCallbacks have the following structure:<br/> <pre class="prettyprint lang-lua"> local UDPCallbacks = { OnError = function (a_ErrorCode, a_ErrorMsg) -- The specified error has occured when trying to listen for incoming UDP datagrams -- No other callback will be called for this endpoint from now on -- This callback is called before the cNetwork:CreateUDPEndpoint() call returns -- All returned values are ignored end, OnReceivedData = function ({{cUDPEndpoint|a_UDPEndpoint}}, a_Data, a_RemotePeer, a_RemotePort) -- A datagram has been received on the {{cUDPEndpoint|endpoint}} from the specified remote peer -- a_Data contains the raw received data, as a string -- All returned values are ignored end, } </pre> ]], }, { Header = "Example client connection", Contents = [[ The following example, adapted from the NetworkTest plugin, shows a simple example of a client connection using the cNetwork API. It connects to www.google.com on port 80 (http) and sends a http request for the front page. It dumps the received data to the console.</p> <p> First, the callbacks are defined in a table. The OnConnected() callback takes care of sending the http request once the socket is connected. The OnReceivedData() callback sends all data to the console. The OnError() callback logs any errors. Then, the connection is initiated using the cNetwork::Connect() API function.</p> <p> <pre class="prettyprint lang-lua"> -- Define the callbacks to use for the client connection: local ConnectCallbacks = { OnConnected = function (a_Link) -- Connection succeeded, send the http request: a_Link:Send("GET / HTTP/1.0\r\nHost: www.google.com\r\n\r\n") end, OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) -- Log the error to console: LOG("An error has occurred while talking to google.com: " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) -- Log the received data to console: LOG("Incoming http data:\r\n" .. a_Data) end, OnRemoteClosed = function (a_Link) -- Log the event into the console: LOG("Connection to www.google.com closed") end, } -- Connect: if not(cNetwork:Connect("www.google.com", 80, ConnectCallbacks)) then -- Highly unlikely, but better check for errors LOG("Cannot queue connection to www.google.com") end -- Note that the connection is being made on the background, -- there's no guarantee that it's already connected at this point in code </pre> ]], }, { Header = "Example server implementation", Contents = [[ The following example, adapted from the NetworkTest plugin, shows a simple example of creating a server listening on a TCP port using the cNetwork API. The server listens on port 9876 and for each incoming connection it sends a welcome message and then echoes back whatever the client has sent ("echo server").</p> <p> First, the callbacks for the listening server are defined. The most important of those is the OnIncomingConnection() callback that must return the LinkCallbacks that will be used for the new connection. In our simple scenario each connection uses the same callbacks, so a predefined callbacks table is returned; it is, however, possible to define different callbacks for each connection. This allows the callbacks to be "personalised", for example by the remote IP or the time of connection. The OnAccepted() and OnError() callbacks only log that they occurred, there's no processing needed for them.</p> <p> Finally, the cNetwork:Listen() API function is used to create the listening server. The status of the server is checked and if it is successfully listening, it is stored in a global variable, so that Lua doesn't garbage-collect it until we actually want the server closed.</p> <p> <pre class="prettyprint lang-lua"> -- Define the callbacks used for the incoming connections: local EchoLinkCallbacks = { OnConnected = function (a_Link) -- This will not be called for a server connection, ever assert(false, "Unexpected Connect callback call") end, OnError = function (a_Link, a_ErrorCode, a_ErrorMsg) -- Log the error to console: local RemoteName = "'" .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. "'" LOG("An error has occurred while talking to " .. RemoteName .. ": " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")") end, OnReceivedData = function (a_Link, a_Data) -- Send the received data back to the remote peer a_Link:Send(Data) end, OnRemoteClosed = function (a_Link) -- Log the event into the console: local RemoteName = "'" .. a_Link:GetRemoteIP() .. ":" .. a_Link:GetRemotePort() .. "'" LOG("Connection to '" .. RemoteName .. "' closed") end, } -- Define the callbacks used by the server: local ListenCallbacks = { OnAccepted = function (a_Link) -- No processing needed, just log that this happened: LOG("OnAccepted callback called") end, OnError = function (a_ErrorCode, a_ErrorMsg) -- An error has occured while listening for incoming connections, log it: LOG("Cannot listen, error " .. a_ErrorCode .. " (" .. a_ErrorMsg .. ")" end, OnIncomingConnection = function (a_RemoteIP, a_RemotePort, a_LocalPort) -- A new connection is being accepted, give it the EchoCallbacks return EchoLinkCallbacks end, } -- Start the server: local Server = cNetwork:Listen(9876, ListenCallbacks) if not(Server:IsListening()) then -- The error has been already printed in the OnError() callbacks -- Just bail out return; end -- Store the server globally, so that it stays open: g_Server = Server ... -- Elsewhere in the code, when terminating: -- Close the server and let it be garbage-collected: g_Server:Close() g_Server = nil </pre> ]], }, }, }, cServerHandle = { Desc = [[ This class provides an interface for TCP sockets listening for a connection. In order to listen, the plugin needs to use the {{cNetwork}}:Listen() function to create the listening socket.</p> <p> Note that when Lua garbage-collects this class, the listening socket is closed. Therefore the plugin should keep it referenced in a global variable for as long as it wants the server running. ]], Functions = { Close = { Notes = "Closes the listening socket. No more connections will be accepted, and all current connections will be closed.", }, IsListening = { Returns = { { Type = "boolean", }, }, Notes = "Returns true if the socket is listening.", }, }, }, cTCPLink = { Desc = [[ This class wraps a single TCP connection, that has been established. Plugins can create these by calling {{cNetwork}}:Connect() to connect to a remote server, or by listening using {{cNetwork}}:Listen() and accepting incoming connections. The links are callback-based - when an event such as incoming data or remote disconnect happens on the link, a specific callback is called. See the additional information in {{cNetwork}} documentation for details.</p> <p> The link can also optionally perform TLS encryption. Plugins can use the StartTLSClient() function to start the TLS handshake as the client side. Since that call, the OnReceivedData() callback is overridden internally so that the data is first routed through the TLS decryptor, and the plugin's callback is only called for the decrypted data, once it starts arriving. The Send function changes its behavior so that the data written by the plugin is first encrypted and only then sent over the network. Note that calling Send() before the TLS handshake finishes is supported, but the data is queued internally and only sent once the TLS handshake is completed. ]], Functions = { Close = { Notes = "Closes the link forcefully (TCP RST). There's no guarantee that the last sent data is even being delivered. See also the Shutdown() method.", }, GetLocalIP = { Returns = { { Type = "string", }, }, Notes = "Returns the IP address of the local endpoint of the TCP connection.", }, GetLocalPort = { Returns = { { Type = "number", }, }, Notes = "Returns the port of the local endpoint of the TCP connection.", }, GetRemoteIP = { Returns = { { Type = "string", }, }, Notes = "Returns the IP address of the remote endpoint of the TCP connection.", }, GetRemotePort = { Returns = { { Type = "number", }, }, Notes = "Returns the port of the remote endpoint of the TCP connection.", }, Send = { Params = { { Name = "Data", Type = "string", }, }, Notes = "Sends the data (raw string) to the remote peer. The data is sent asynchronously and there is no report on the success of the send operation, other than the connection being closed or reset by the underlying OS.", }, Shutdown = { Notes = "Shuts the socket down for sending data. Notifies the remote peer that there will be no more data coming from us (TCP FIN). The data that is in flight will still be delivered. The underlying socket will be closed when the remote end shuts down as well, or after a timeout.", }, StartTLSClient = { Params = { { Name = "OwnCert", Type = "string", }, { Name = "OwnPrivateKey", Type = "string", }, { Name = "OwnPrivateKeyPassword", Type = "string", }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrorMessage", Type = "string", IsOptional = true, }, }, Notes = "Starts a TLS handshake on the link, as a client side of the TLS. The Own___ parameters specify the client certificate and its corresponding private key and password; all three parameters are optional and no client certificate is presented to the remote peer if they are not used or all empty. Once the TLS handshake is started by this call, all incoming data is first decrypted before being sent to the OnReceivedData callback, and all outgoing data is queued until the TLS handshake completes, and then sent encrypted over the link. Returns true on success, nil and optional error message on immediate failure.<br/><b>NOTE:</b> The TLS support in the API is currently experimental and shouldn't be considered safe - there's no peer certificate verification and the error reporting is only basic.", }, StartTLSServer = { Params = { { Name = "Certificate", Type = "string", }, { Name = "PrivateKey", Type = "string", }, { Name = "PrivateKeyPassword", Type = "string", }, { Name = "StartTLSData", Type = "string", }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrorMessage", Type = "string", IsOptional = true, }, }, Notes = "Starts a TLS handshake on the link, as a server side of the TLS. The plugin needs to specify the server certificate and its corresponding private key and password. The StartTLSData can contain data that the link has already reported as received but it should be used as part of the TLS handshake. Once the TLS handshake is started by this call, all incoming data is first decrypted before being sent to the OnReceivedData callback, and all outgoing data is queued until the TLS handshake completes, and then sent encrypted over the link. Returns true on success, nil and optional error message on immediate failure.<br/><b>NOTE:</b> The TLS support in the API is currently experimental and shouldn't be considered safe - there's no peer certificate verification and the error reporting is only basic.", }, }, }, cUDPEndpoint = { Desc = [[ Represents a UDP socket that is listening for incoming datagrams on a UDP port and can send or broadcast datagrams to other peers on the network. Plugins can create an instance of the endpoint by calling {{cNetwork}}:CreateUDPEndpoint(). The endpoints are callback-based - when a datagram is read from the network, the OnRececeivedData() callback is called with details about the datagram. See the additional information in {{cNetwork}} documentation for details.</p> <p> Note that when Lua garbage-collects this class, the listening socket is closed. Therefore the plugin should keep this object referenced in a global variable for as long as it wants the endpoint open. ]], Functions = { Close = { Notes = "Closes the UDP endpoint. No more datagrams will be reported through the callbacks, the UDP port will be closed.", }, EnableBroadcasts = { Notes = "Some OSes need this call before they allow UDP broadcasts on an endpoint.", }, GetPort = { Returns = { { Type = "number", }, }, Notes = "Returns the local port number of the UDP endpoint listening for incoming datagrams. Especially useful if the UDP endpoint was created with auto-assign port (0).", }, IsOpen = { Returns = { { Type = "boolean", }, }, Notes = "Returns true if the UDP endpoint is listening for incoming datagrams.", }, Send = { Params = { { Name = "RawData", Type = "string", }, { Name = "RemoteHost", Type = "string", }, { Name = "RemotePort", Type = "number", }, }, Returns = { { Type = "boolean", }, }, Notes = "Sends the specified raw data (string) to the specified remote host. The RemoteHost can be either a hostname or an IP address; if it is a hostname, the endpoint will queue a DNS lookup first, if it is an IP address, the send operation is executed immediately. Returns true if there was no immediate error, false on any failure. Note that the return value needn't represent whether the packet was actually sent, only if it was successfully queued.", }, }, }, cUrlClient = { Desc = [[ Implements high-level asynchronous access to URLs, such as downloading webpages over HTTP(S).</p> <p> Note that unlike other languages' URL access libraries, this class implements asynchronous requests. This means that the functions only start a request and return immediately. The request is then fulfilled in the background, while the server continues to run. The response is delivered back to the plugin using callbacks. This allows the plugin to start requests and not block the server until the response is received.</p> <p> The functions that make network requests are all static and have a dual interface. Either you can use a single callback function, which gets called once the entire response is received or an error is encountered. Or you can use a table of callback functions, each function being called whenever the specific event happens during the request and response lifetime. See the Simple Callback and Callback Table chapters later on this page for details and examples.</p> <p> All the request function also support optional parameters for further customization of the request - the Headers parameter specifies additional HTTP headers that are to be sent (as a dictionary-table of key -> value), the RequestBody parameter specifying the optional body of the request (used mainly for POST and PUT requests), and an Options parameter specifying additional options specific to the protocol used. ]], Functions = { Delete = { { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "table", }, { Name = "Headers", Type = "table", IsOptional = true, }, { Name = "RequestBody", Type = "string", IsOptional = true, }, { Name = "Options", Type = "table", IsOptional = true, }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrorMessagge", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP DELETE request. Alias for Request(\"DELETE\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "function", }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrorMessagge", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP DELETE request. Alias for Request(\"DELETE\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, }, Get = { { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "table", }, { Name = "Headers", Type = "table", IsOptional = true, }, { Name = "RequestBody", Type = "string", IsOptional = true, }, { Name = "Options", Type = "table", IsOptional = true, }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP GET request. Alias for Request(\"GET\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "function", }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP GET request. Alias for Request(\"GET\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", } }, Post = { { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "table", }, { Name = "Headers", Type = "table", IsOptional = true, }, { Name = "RequestBody", Type = "string", IsOptional = true, }, { Name = "Options", Type = "table", IsOptional = true, }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP POST request. Alias for Request(\"POST\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "function", }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP POST request. Alias for Request(\"POST\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, }, Put = { { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "table", }, { Name = "Headers", Type = "table", IsOptional = true, }, { Name = "RequestBody", Type = "string", IsOptional = true, }, { Name = "Options", Type = "table", IsOptional = true, }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP PUT request. Alias for Request(\"PUT\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, { IsStatic = true, Params = { { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "function", }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a HTTP PUT request. Alias for Request(\"PUT\", ...). Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, }, Request = { IsStatic = true, Params = { { Name = "Method", Type = "string", }, { Name = "URL", Type = "string", }, { Name = "Callbacks", Type = "table", }, { Name = "Headers", Type = "table", IsOptional = true, }, { Name = "RequestBody", Type = "string", IsOptional = true, }, { Name = "Options", Type = "table", IsOptional = true, }, }, Returns = { { Name = "IsSuccess", Type = "boolean", }, { Name = "ErrMsg", Type = "string", IsOptional = true, }, }, Notes = "Starts a request with the specified Method. Returns true on succes, false and error message on immediate failure (unparsable URL etc.).", }, }, AdditionalInfo = { { Header = "Simple Callback", Contents = [[ When you don't need fine control for receiving the requests and are interested only in the result, you can use the simple callback approach. Pass a single function as the Callback parameter, the function will get called when the response is fully processed, either with the body of the response, or with an error message: <pre class="prettyprint lang-lua"> cUrlClient:Get(url, function (a_Body, a_Data) if (a_Body) then -- Response received correctly, a_Body contains the entire response body, -- a_Data is a dictionary-table of the response's HTTP headers else -- There was an error, a_Data is the error message string end end ) </pre> ]], }, { Header = "Callback Table", Contents = [[ To provide complete control over the request and response handling, Cuberite allows plugins to pass a table of callbacks as the Callback parameter. Then the respective functions are called for their respective events during the lifetime of the request and response. This way it is possible to process huge downloads that wouldn't fit into memory otherwise, or display detailed progress.</p> Each callback function receives a "self" as its first parameter, this allows the functions to access the Callback table and any of its other members, allowing the use of Lua object idiom for the table. See <a href="https://forum.cuberite.org/thread-2062.html">this forum post</a> for an example. <p> The following callback functions are used by Cuberite. Any callback that is not assigned is silently ignored. The table may also contain other functions and other values, those are silently ignored.</p> <table> <tr><th>Callback</th><th>Params</th><th>Notes</th></tr> <tr><td>OnConnected</td><td>self, {{cTCPLink}}, RemoteIP, RemotePort</td><td>Called when the connection to the remote host is established. <i>Note that current implementation doesn't provide the {{cTCPLink}} parameter and passes nil instead.</i></td></tr> <tr><td>OnCertificateReceived</td><td>self</td><td>Called for HTTPS URLs when the server's certificate is received. If the callback returns anything else than true, the connection is aborted. <i>Note that the current implementation doesn't provide the certificate because there is no representation for the cert in Lua.</i></td></tr> <tr><td>OnTlsHandshakeCompleted</td><td>self</td><td>Called for HTTPS URLs when the TLS is established on the connection.</td></tr> <tr><td>OnRequestSent</td><td>self</td><td>Called after the entire request is sent to the server.</td></tr> <tr><td>OnStatusLine</td><td>self, HttpVersion, StatusCode, Rest</td><td>The initial line of the response has been parsed. HttpVersion is typically "HTTP/1.1", StatusCode is the numerical HTTP status code reported by the server (200 being OK), Rest is the rest of the line, usually a short message in case of an error.</td></tr> <tr><td>OnHeader</td><td>self, Name, Value</td><td>A new HTTP response header line has been received.</td></tr> <tr><td>OnHeadersFinished</td><td>self, AllHeaders</td><td>All HTTP response headers have been parsed. AllHeaders is a dictionary-table containing all the headers received.</td></tr> <tr><td>OnBodyData</td><td>self, Data</td><td>A piece of the response body has been received. This callback is called repeatedly until the entire body is reported through its Data parameter.</td></tr> <tr><td>OnBodyFinished</td><td>self</td><td>The entire response body has been reported by OnBodyData(), the response has finished.</td></tr> <tr><td>OnError</td><td>self, ErrorMsg</td><td>Called whenever an error is detected. After this call, no other callback will get called.</td></tr> <tr><td>OnRedirecting</td><td>self, NewUrl</td><td>Called if the server returned a valid redirection HTTP status code and a Location header, and redirection is allowed by the Options.</td></tr> </table> <p> The following example is adapted from the Debuggers plugin's "download" command, it downloads the contents of an URL into a file. <pre class="prettyprint lang-lua"> function HandleConsoleDownload(a_Split) -- Console command handler -- Read the params from the command: local url = a_Split[2] local fnam = a_Split[3] if (not(url) or not(fnam)) then return true, "Missing parameters. Usage: download <url> <filename>" end -- Define the cUrlClient callbacks local callbacks = { OnStatusLine = function (self, a_HttpVersion, a_Status, a_Rest) -- Only open the output file if the server reports a success: if (a_Status ~= 200) then LOG("Cannot download " .. url .. ", HTTP error code " .. a_Status) return end local f, err = io.open(fnam, "wb") if not(f) then LOG("Cannot download " .. url .. ", error opening the file " .. fnam .. ": " .. (err or "<no message>")) return end self.m_File = f end, OnBodyData = function (self, a_Data) -- If the file has been opened, write the data: if (self.m_File) then self.m_File:write(a_Data) end end, OnBodyFinished = function (self) -- If the file has been opened, close it and report success if (self.m_File) then self.m_File:close() LOG("File " .. fnam .. " has been downloaded.") end end, } -- Start the URL download: local isSuccess, msg = cUrlClient:Get(url, callbacks) if not(isSuccess) then LOG("Cannot start an URL download: " .. (msg or "<no message>")) return true end return true end </pre> ]], }, { Header = "Options", Contents = [[ The requests support the following options, specified in the optional Options table parameter: <table> <tr><th>Option name</th><th>Description</th></tr> <tr><td>MaxRedirects</td><td>Maximum number of HTTP redirects that the cUrlClient will follow. If the server still reports a redirect after reaching this many redirects, the cUrlClient reports an error. May be specified as either a number or a string parsable into a number. Default: 30.</td></tr> <tr><td>OwnCert</td><td>The client certificate to use, if requested by the server. A string containing a PEM- or DER-encoded cert is expected.</td></tr> <tr><td>OwnPrivKey</td><td>The private key appropriate for OwnCert. A string containing a PEM- or DER-encoded private key is expected.</td></tr> <tr><td>OwnPrivKeyPassword</td><td>The password for OwnPrivKey. If not present or empty, no password is assumed.</td></tr> </table> <p> Redirection: <ul> <li>If a redirect is received, and redirection is allowed by MaxRedirects, the redirection is reported via OnRedirecting() callback and the request is restarted at the redirect URL, without reporting any of the redirect's headers nor body.</li> <li>If a redirect is received and redirection is not allowed (maximum redirection attempts have been reached), the OnRedirecting() callback is called with the redirect URL and then the request terminates with an OnError() callback, without reporting the redirect's headers nor body.</li> </ul> ]], }, }, }, }
apache-2.0
TRex22/hawkthorne-journey
src/hawk/i18n.lua
1
1149
local json = require 'hawk/json' local middle = require 'hawk/middleclass' local i18n = middle.class("i18n") function i18n:initialize(path, locale) self.path = path self:setLocale("en-US") end function i18n:getLocale(locale) local path = self.path .. "/" .. locale .. '.json' assert(love.filesystem.exists(path), string.format("The locale %q is unknown", locale)) local contents, _ = love.filesystem.read(path) return json.decode(contents) end function i18n:translate(id) local result = self.strings[id] assert(result, string.format("The id %q was not found in the current locale (%q)", id, self.currentLocale)) return result end function i18n:__call(id) return self:translate(id) end function i18n:getLocales() local langs = {} -- will return a list of available language files for i,p in pairs(love.filesystem.enumerate(self.path)) do local name = p:gsub('.json', '') table.insert(langs, name) end return langs end function i18n:getCurrentLocale() return self.currentLocale end function i18n:setLocale(locale) self.currentLocale = locale self.strings = self:getLocale(locale) end return i18n
mit
wangyi0226/skynet
lualib/skynet/dns.lua
12
12001
--[[ lua dns resolver library See https://github.com/xjdrew/levent/blob/master/levent/dns.lua for more detail -- resource record type: -- TYPE value and meaning -- A 1 a host address -- NS 2 an authoritative name server -- MD 3 a mail destination (Obsolete - use MX) -- MF 4 a mail forwarder (Obsolete - use MX) -- CNAME 5 the canonical name for an alias -- SOA 6 marks the start of a zone of authority -- MB 7 a mailbox domain name (EXPERIMENTAL) -- MG 8 a mail group member (EXPERIMENTAL) -- MR 9 a mail rename domain name (EXPERIMENTAL) -- NULL 10 a null RR (EXPERIMENTAL) -- WKS 11 a well known service description -- PTR 12 a domain name pointer -- HINFO 13 host information -- MINFO 14 mailbox or mail list information -- MX 15 mail exchange -- TXT 16 text strings -- AAAA 28 a ipv6 host address -- only appear in the question section: -- AXFR 252 A request for a transfer of an entire zone -- MAILB 253 A request for mailbox-related records (MB, MG or MR) -- MAILA 254 A request for mail agent RRs (Obsolete - see MX) -- * 255 A request for all records -- -- resource recode class: -- IN 1 the Internet -- CS 2 the CSNET class (Obsolete - used only for examples in some obsolete RFCs) -- CH 3 the CHAOS class -- HS 4 Hesiod [Dyer 87] -- only appear in the question section: -- * 255 any class -- ]] --[[ -- struct header { -- uint16_t tid # identifier assigned by the program that generates any kind of query. -- uint16_t flags # flags -- uint16_t qdcount # the number of entries in the question section. -- uint16_t ancount # the number of resource records in the answer section. -- uint16_t nscount # the number of name server resource records in the authority records section. -- uint16_t arcount # the number of resource records in the additional records section. -- } -- -- request body: -- struct request { -- string name -- uint16_t atype -- uint16_t class -- } -- -- response body: -- struct response { -- string name -- uint16_t atype -- uint16_t class -- uint16_t ttl -- uint16_t rdlength -- string rdata -- } --]] local skynet = require "skynet" local socket = require "skynet.socket" local MAX_DOMAIN_LEN = 1024 local MAX_LABEL_LEN = 63 local MAX_PACKET_LEN = 2048 local DNS_HEADER_LEN = 12 local TIMEOUT = 30 * 100 -- 30 seconds local QTYPE = { A = 1, CNAME = 5, AAAA = 28, } local QCLASS = { IN = 1, } local weak = {__mode = "kv"} local CACHE = {} local dns = {} local request_pool = {} local local_hosts -- local static table lookup for hostnames dns.DEFAULT_HOSTS = "/etc/hosts" dns.DEFAULT_RESOLV_CONF = "/etc/resolv.conf" -- return name type: 'ipv4', 'ipv6', or 'hostname' local function guess_name_type(name) if name:match("^[%d%.]+$") then return "ipv4" end if name:find(":") then return "ipv6" end return "hostname" end -- http://man7.org/linux/man-pages/man5/hosts.5.html local function parse_hosts() if not dns.DEFAULT_HOSTS then return end local f = io.open(dns.DEFAULT_HOSTS) if not f then return end local rts = {} for line in f:lines() do local ip, hosts = string.match(line, "^%s*([%[%]%x%.%:]+)%s+([^#;]+)") if not ip or not hosts then goto continue end local family = guess_name_type(ip) if family == "hostname" then goto continue end for host in hosts:gmatch("%S+") do host = host:lower() local rt = rts[host] if not rt then rt = {} rts[host] = rt end if not rt[family] then rt[family] = {} end table.insert(rt[family], ip) end ::continue:: end return rts end -- http://man7.org/linux/man-pages/man5/resolv.conf.5.html local function parse_resolv_conf() if not dns.DEFAULT_RESOLV_CONF then return end local f = io.open(dns.DEFAULT_RESOLV_CONF) if not f then return end local server for line in f:lines() do server = line:match("^%s*nameserver%s+([^#;%s]+)") if server then break end end f:close() return server end function dns.flush() CACHE[QTYPE.A] = setmetatable({},weak) CACHE[QTYPE.AAAA] = setmetatable({},weak) end dns.flush() local function verify_domain_name(name) if #name > MAX_DOMAIN_LEN then return false end if not name:match("^[_%l%d%-%.]+$") then return false end for w in name:gmatch("([_%w%-]+)%.?") do if #w > MAX_LABEL_LEN then return false end end return true end local next_tid = 1 local function gen_tid() local tid = next_tid if request_pool[tid] then tid = nil for i = 1, 65535 do -- find available tid if not request_pool[i] then tid = i break end end assert(tid) end next_tid = tid + 1 if next_tid > 65535 then next_tid = 1 end return tid end local function pack_header(t) return string.pack(">HHHHHH", t.tid, t.flags, t.qdcount, t.ancount or 0, t.nscount or 0, t.arcount or 0) end local function pack_question(name, qtype, qclass) local labels = {} for w in name:gmatch("([_%w%-]+)%.?") do table.insert(labels, string.pack("s1",w)) end table.insert(labels, '\0') table.insert(labels, string.pack(">HH", qtype, qclass)) return table.concat(labels) end local function unpack_header(chunk) local tid, flags, qdcount, ancount, nscount, arcount, left = string.unpack(">HHHHHH", chunk) return { tid = tid, flags = flags, qdcount = qdcount, ancount = ancount, nscount = nscount, arcount = arcount }, left end -- unpack a resource name local function unpack_name(chunk, left) local t = {} local jump_pointer local tag, offset, label while true do tag, left = string.unpack("B", chunk, left) if tag & 0xc0 == 0xc0 then -- pointer offset,left = string.unpack(">H", chunk, left - 1) offset = offset & 0x3fff if not jump_pointer then jump_pointer = left end -- offset is base 0, need to plus 1 left = offset + 1 elseif tag == 0 then break else label, left = string.unpack("s1", chunk, left - 1) t[#t+1] = label end end return table.concat(t, "."), jump_pointer or left end local function unpack_question(chunk, left) local name, left = unpack_name(chunk, left) local atype, class, left = string.unpack(">HH", chunk, left) return { name = name, atype = atype, class = class }, left end local function unpack_answer(chunk, left) local name, left = unpack_name(chunk, left) local atype, class, ttl, rdata, left = string.unpack(">HHI4s2", chunk, left) return { name = name, atype = atype, class = class, ttl = ttl, rdata = rdata },left end local function unpack_rdata(qtype, chunk) if qtype == QTYPE.A then local a,b,c,d = string.unpack("BBBB", chunk) return string.format("%d.%d.%d.%d", a,b,c,d) elseif qtype == QTYPE.AAAA then local a,b,c,d,e,f,g,h = string.unpack(">HHHHHHHH", chunk) return string.format("%x:%x:%x:%x:%x:%x:%x:%x", a, b, c, d, e, f, g, h) else error("Error qtype " .. qtype) end end local dns_server = { fd = nil, address = nil, port = nil, retire = nil, } local function resolve(content) if #content < DNS_HEADER_LEN then -- drop skynet.error("Recv an invalid package when dns query") return end local answer_header,left = unpack_header(content) -- verify answer assert(answer_header.qdcount == 1, "malformed packet") local question,left = unpack_question(content, left) local ttl local answer local answers_ipv4 local answers_ipv6 for i=1, answer_header.ancount do answer, left = unpack_answer(content, left) local answers if answer.atype == QTYPE.A then answers_ipv4 = answers_ipv4 or {} answers = answers_ipv4 elseif answer.atype == QTYPE.AAAA then answers_ipv6 = answers_ipv6 or {} answers = answers_ipv6 end if answers then local ip = unpack_rdata(answer.atype, answer.rdata) ttl = ttl and math.min(ttl, answer.ttl) or answer.ttl answers[#answers+1] = ip end end if answers_ipv4 then CACHE[QTYPE.A][question.name] = { answers = answers_ipv4, ttl = skynet.now() + ttl * 100 } end if answers_ipv6 then CACHE[QTYPE.AAAA][question.name] = { answers = answers_ipv6, ttl = skynet.now() + ttl * 100 } end local resp = request_pool[answer_header.tid] if not resp then -- the resp may be timeout return end if question.name ~= resp.name then skynet.error("Recv an invalid name when dns query") end local r = CACHE[resp.qtype][resp.name] if r then resp.answers = r.answers end skynet.wakeup(resp.co) end local function connect_server() local fd = socket.udp(function(str, from) resolve(str) end) if not dns_server.address then dns_server.address = parse_resolv_conf() dns_server.port = 53 end assert(dns_server.address, "Call dns.server first") local ok, err = pcall(socket.udp_connect,fd, dns_server.address, dns_server.port) if not ok then socket.close(fd) error(err) end dns_server.fd = fd skynet.error(string.format("Udp server open %s:%s (%d)", dns_server.address, dns_server.port, fd)) end local DNS_SERVER_RETIRE = 60 * 100 local function touch_server() dns_server.retire = skynet.now() if dns_server.fd then return end connect_server() local function check_alive() if skynet.now() > dns_server.retire + DNS_SERVER_RETIRE then local fd = dns_server.fd if fd then dns_server.fd = nil socket.close(fd) skynet.error(string.format("Udp server close %s:%s (%d)", dns_server.address, dns_server.port, fd)) end else skynet.timeout( 2 * DNS_SERVER_RETIRE, check_alive) end end skynet.timeout( 2 * DNS_SERVER_RETIRE, check_alive) end function dns.server(server, port) dns_server.address = server dns_server.port = port or 53 end local function lookup_cache(name, qtype, ignorettl) local result = CACHE[qtype][name] if result then if ignorettl or (result.ttl > skynet.now()) then return result.answers end end end local function suspend(tid, name, qtype) local req = { name = name, tid = tid, qtype = qtype, co = coroutine.running(), } request_pool[tid] = req skynet.fork(function() skynet.sleep(TIMEOUT) local req = request_pool[tid] if req then -- cancel tid skynet.error(string.format("DNS query %s timeout", name)) request_pool[tid] = nil skynet.wakeup(req.co) end end) skynet.wait(req.co) request_pool[tid] = nil if not req.answers then local answers = lookup_cache(name, qtype, true) if answers then return answers[1], answers end error "timeout or no answer" end return req.answers[1], req.answers end -- lookup local static table local function local_resolve(name, ipv6) if not local_hosts then local_hosts = parse_hosts() end if not local_hosts then return end local family = ipv6 and "ipv6" or "ipv4" local t = local_hosts[name] if t then local answers = t[family] if answers then return answers[1], answers end end return nil end -- lookup dns server local function remote_resolve(name, ipv6) local qtype = ipv6 and QTYPE.AAAA or QTYPE.A local answers = lookup_cache(name, qtype) if answers then return answers[1], answers end local question_header = { tid = gen_tid(), flags = 0x100, -- flags: 00000001 00000000, set RD qdcount = 1, } local req = pack_header(question_header) .. pack_question(name, qtype, QCLASS.IN) touch_server() socket.write(dns_server.fd, req) return suspend(question_header.tid, name, qtype) end function dns.resolve(name, ipv6) local name = name:lower() local ntype = guess_name_type(name) if ntype ~= "hostname" then if (ipv6 and name == "ipv4") or (not ipv6 and name == "ipv6") then return nil, "illegal ip address" end return name end if not verify_domain_name(name) then return nil, "illegal name" end local answer, answers = local_resolve(name, ipv6) if answer then return answer, answers end return remote_resolve(name, ipv6) end return dns
mit
neilbu/osrm-backend
profiles/lib/tags.lua
8
3030
-- Helpers for searching and parsing tags local Tags = {} -- return [forward,backward] values for a specific tag. -- e.g. for maxspeed search forward: -- maxspeed:forward -- maxspeed -- and backward: -- maxspeed:backward -- maxspeed function Tags.get_forward_backward_by_key(way,data,key) local forward = way:get_value_by_key(key .. ':forward') local backward = way:get_value_by_key(key .. ':backward') if forward and backward then return forward, backward end local common = way:get_value_by_key(key) return forward or common, backward or common end -- return [forward,backward] values, searching a -- prioritized sequence of tags -- e.g. for the sequence [maxspeed,advisory] search forward: -- maxspeed:forward -- maxspeed -- advisory:forward -- advisory -- and for backward: -- maxspeed:backward -- maxspeed -- advisory:backward -- advisory function Tags.get_forward_backward_by_set(way,data,keys) local forward, backward for i,key in ipairs(keys) do if not forward then forward = way:get_value_by_key(key .. ':forward') end if not backward then backward = way:get_value_by_key(key .. ':backward') end if not forward or not backward then local common = way:get_value_by_key(key) forward = forward or common backward = backward or common end if forward and backward then break end end return forward, backward end -- look through a sequence of keys combined with a prefix -- e.g. for the sequence [motorcar,motor_vehicle,vehicle] and the prefix 'oneway' search for: -- oneway:motorcar -- oneway:motor_vehicle -- oneway:vehicle function Tags.get_value_by_prefixed_sequence(way,seq,prefix) local v for i,key in ipairs(seq) do v = way:get_value_by_key(prefix .. ':' .. key) if v then return v end end end -- look through a sequence of keys combined with a postfix -- e.g. for the sequence [motorcar,motor_vehicle,vehicle] and the postfix 'oneway' search for: -- motorcar:oneway -- motor_vehicle:oneway -- vehicle:oneway function Tags.get_value_by_postfixed_sequence(way,seq,postfix) local v for i,key in ipairs(seq) do v = way:get_value_by_key(key .. ':' .. postfix) if v then return v end end end -- check if key-value pairs are set in a way and return a -- corresponding constant if it is. e.g. for this input: -- -- local speeds = { -- highway = { -- residential = 20, -- primary = 40 -- }, -- amenity = { -- parking = 10 -- } -- } -- -- we would check whether the following key-value combinations -- are set, and return the corresponding constant: -- -- highway = residential => 20 -- highway = primary => 40 -- amenity = parking => 10 function Tags.get_constant_by_key_value(way,lookup) for key,set in pairs(lookup) do local way_value = way:get_value_by_key(key) for value,t in pairs(set) do if way_value == value then return key,value,t end end end end return Tags
bsd-2-clause
arca1n/cocos2d-x_nextpeer_integration
cocos/scripting/lua/script/Cocos2d.lua
4
6861
cc = cc or {} cc.DIRECTOR_PROJECTION_2D = 0 cc.DIRECTOR_PROJECTION_3D = 1 function cc.clampf(value, min_inclusive, max_inclusive) -- body local temp = 0 if min_inclusive > max_inclusive then temp = min_inclusive min_inclusive = max_inclusive max_inclusive = temp end if value < min_inclusive then return min_inclusive elseif value < max_inclusive then return value else return max_inclusive end end --Point function cc.p(_x,_y) if nil == _y then return { x = _x.x, y = _x.y } else return { x = _x, y = _y } end end function cc.pAdd(pt1,pt2) return {x = pt1.x + pt2.x , y = pt1.y + pt2.y } end function cc.pSub(pt1,pt2) return {x = pt1.x - pt2.x , y = pt1.y - pt2.y } end function cc.pMul(pt1,factor) return { x = pt1.x * factor , y = pt1.y * factor } end function cc.pMidpoint(pt1,pt2) return { x = (pt1.x + pt2.x) / 2.0 , y = ( pt1.y + pt2.y) / 2.0 } end function cc.pForAngle(a) return { x = math.cos(a), y = math.sin(a) } end function cc.pGetLength(pt) return math.sqrt( pt.x * pt.x + pt.y * pt.y ) end function cc.pNormalize(pt) local length = cc.pGetLength(pt) if 0 == length then return { x = 1.0,y = 0.0 } end return { x = pt.x / length, y = pt.y / length } end function cc.pCross(self,other) return self.x * other.y - self.y * other.x end function cc.pDot(self,other) return self.x * other.x - self.y * other.y end function cc.pToAngleSelf(self) return math.atan2(self.y, self.x) end function cc.pGetAngle(self,other) local a2 = cc.pNormalize(self) local b2 = cc.pNormalize(other) local angle = math.atan2(cc.pCross(a2, b2), cc.pDot(a2, b2) ) if angle < 1.192092896e-7 then return 0.0 end return angle end function cc.pGetDistance(startP,endP) return cc.pGetLength(cc.pSub(startP,endP)) end function cc.pIsLineIntersect(A, B, C, D, s, t) if ((A.x == B.x) and (A.y == B.y)) or ((C.x == D.x) and (C.y == D.y))then return false, s, t end local BAx = B.x - A.x local BAy = B.y - A.y local DCx = D.x - C.x local DCy = D.y - C.y local ACx = A.x - C.x local ACy = A.y - C.y local denom = DCy * BAx - DCx * BAy s = DCx * ACy - DCy * ACx t = BAx * ACy - BAy * ACx if (denom == 0) then if (s == 0 or t == 0) then return true, s , t end return false, s, t end s = s / denom t = t / denom return true,s,t end function cc.pPerp(pt) return { x = -pt.y, y = pt.x } end function cc.RPerp(pt) return { x = pt.y, y = -pt.x } end function cc.pProject(pt1, pt2) return { x = pt2.x * (cc.pDot(pt1,pt2) / cc.pDot(pt2,pt2)) , y = pt2.y * (cc.pDot(pt1,pt2) / cc.pDot(pt2,pt2)) } end function cc.pRotate(pt1, pt2) return { x = pt1.x * pt2.x - pt1.y * pt2.y, y = pt1.x * pt2.y + pt1.y * pt2.x } end function cc.pUnrotate(pt1, pt2) return { x = pt1.x * pt2.x + pt1.y * pt2.y, pt1.y * pt2.x - pt1.x * pt2.y } end function cc.pLengthSQ(pt) return cc.pDot(pt) end function cc.pDistanceSQ(pt1,pt2) return cc.pLengthSQ(cc.pSub(pt1,pt2)) end function cc.pGetClampPoint(pt1,pt2,pt3) return { x = cc.clampf(pt1.x, pt2.x, pt3.x), y = cc.clampf(pt1.y, pt2.y, pt3.y) } end function cc.pFromSize(sz) return { x = sz.width, y = sz.height } end function cc.pLerp(pt1,pt2,alpha) return cc.pAdd(cc.pMul(pt1, 1.0 - alpha), cc.pMul(pt2,alpha) ) end function cc.pFuzzyEqual(pt1,pt2,variance) if (pt1.x - variance <= pt2.x) and (pt2.x <= pt1.x + variance) and (pt1.y - variance <= pt2.y) and (pt2.y <= pt1.y + variance) then return true else return false end end function cc.pRotateByAngle(pt1, pt2, angle) return cc.pAdd(pt2, cc.pRotate( cc.pSub(pt1, pt2),cc.pForAngle(angle))) end function cc.pIsSegmentIntersect(pt1,pt2,pt3,pt4) local s,t,ret = 0,0,false ret,s,t =cc.pIsLineIntersect(pt1, pt2, pt3, pt4,s,t) if ret and s >= 0.0 and s <= 1.0 and t >= 0.0 and t <= 0.0 then return true; end return false end function cc.pGetIntersectPoint(pt1,pt2,pt3,pt4) local s,t, ret = 0,0,false ret,s,t = cc.pIsLineIntersect(pt1,pt2,pt3,pt4,s,t) if ret then return cc.p(pt1.x + s * (pt2.x - pt1.x), pt1.y + s * (pt2.y - pt1.y)) else return cc.p(0,0) end end --Size function cc.size( _width,_height ) return { width = _width, height = _height } end --Rect function cc.rect(_x,_y,_width,_height) return { x = _x, y = _y, width = _width, height = _height } end function cc.rectEqualToRect(rect1,rect2) if ((rect1.x >= rect2.x) or (rect1.y >= rect2.y) or ( rect1.x + rect1.width <= rect2.x + rect2.width) or ( rect1.y + rect1.height <= rect2.y + rect2.height)) then return false end return true end function cc.rectGetMaxX(rect) return rect.x + rect.width end function cc.rectGetMidX(rect) return rect.x + rect.width / 2.0 end function cc.rectGetMinX(rect) return rect.x end function cc.rectGetMaxY(rect) return rect.y + rect.height end function cc.rectGetMidY(rect) return rect.y + rect.height / 2.0 end function cc.rectGetMinY(rect) return rect.y end function cc.rectContainsPoint( rect, point ) local ret = false if (point.x >= rect.x) and (point.x <= rect.x + rect.width) and (point.y >= rect.y) and (point.y <= rect.y + rect.height) then ret = true end return ret end function cc.rectIntersectsRect( rect1, rect2 ) local intersect = not ( rect1.x > rect2.x + rect2.width or rect1.x + rect1.width < rect2.x or rect1.y > rect2.y + rect2.height or rect1.y + rect1.height < rect2.y ) return intersect end function cc.rectUnion( rect1, rect2 ) local rect = cc.rect(0, 0, 0, 0) rect.x = math.min(rect1.x, rect2.x) rect.y = math.min(rect1.y, rect2.y) rect.width = math.max(rect1.x + rect1.width, rect2.x + rect2.width) - rect.x rect.height = math.max(rect1.y + rect1.height, rect2.y + rect2.height) - rect.y return rect end function cc.rectIntersection( rect1, rect2 ) local intersection = cc.rect( math.max(rect1.x, rect2.x), math.max(rect1.y, rect2.y), 0, 0) intersection.width = math.min(rect1.x + rect1.width, rect2.x + rect2.width) - intersection.x intersection.height = math.min(rect1.y + rect1.height, rect2.y + rect2.height) - intersection.y return intersection end --Color3B function cc.c3b( _r,_g,_b ) return { r = _r, g = _g, b = _b } end --Color4B function cc.c4b( _r,_g,_b,_a ) return { r = _r, g = _g, b = _b, a = _a } end --Color4F function cc.c4f( _r,_g,_b,_a ) return { r = _r, g = _g, b = _b, a = _a } end
mit
Ninjistix/darkstar
scripts/globals/spells/bio_ii.lua
2
2409
----------------------------------------- -- Spell: Bio II -- Deals dark damage that weakens an enemy's attacks and gradually reduces its HP. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --calculate raw damage local basedmg = caster:getSkillLevel(DARK_MAGIC_SKILL) / 4; local params = {}; params.dmg = basedmg; params.multiplier = 2; params.skillType = DARK_MAGIC_SKILL; params.attribute = MOD_INT; params.hasMultipleTargetReduction = false; local dmg = calculateMagicDamage(caster, target, spell, params); -- Softcaps at 8, should always do at least 1 if (dmg > 30) then dmg = 30; end if (dmg < 1) then dmg = 1; end --get resist multiplier (1x if no resist) local params = {}; params.diff = caster:getStat(MOD_INT)-target:getStat(MOD_INT); params.attribute = MOD_INT; params.skillType = DARK_MAGIC_SKILL; params.bonus = 1.0; local resist = applyResistance(caster, target, spell, params); --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()); --add in final adjustments including the actual damage dealt local final = finalMagicAdjustments(caster,target,spell,dmg); -- Calculate duration. local duration = 120; -- Check for Dia. local dia = target:getStatusEffect(EFFECT_DIA); -- Calculate DoT (rough, though fairly accurate) local dotdmg = 3 + math.floor(caster:getSkillLevel(DARK_MAGIC_SKILL) / 60); -- Do it! if (target:addStatusEffect(EFFECT_BIO,dotdmg,3,duration,FLAG_ERASABLE, 10,2)) then spell:setMsg(msgBasic.MAGIC_DMG); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end --Try to kill same tier Dia (default behavior) if (DIA_OVERWRITE == 1 and dia ~= nil) then if (dia:getPower() <= 2) then target:delStatusEffect(EFFECT_DIA); end end return final; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/settings.lua
2
11554
----------------------------------------------- ------------- GLOBAL SETTINGS ------------- ----------------------------------------------- -- This is to allow server operators to further customize their servers. As more features are added to pXI, the list will surely expand. -- Anything scripted can be customized with proper script editing. -- PLEASE REQUIRE THIS SCRIPT IN ANY SCRIPTS YOU DO: ADD THIS LINE TO THE TOP!!!! -- require("scripts/globals/settings"); -- With this script added to yours, you can pull variables from it!! -- Always include status.lua, which defines mods -- require("scripts/globals/status"); -- Common functions require("scripts/globals/common"); -- Enable Expansion (1= yes 0= no) ENABLE_COP = 0; ENABLE_TOAU = 0; ENABLE_WOTG = 0; ENABLE_ACP = 0; ENABLE_AMK = 0; ENABLE_ASA = 0; ENABLE_ABYSSEA = 0; ENABLE_SOA = 0; ENABLE_ROV = 0; ENABLE_VOIDWATCH = 0; -- Not an expansion, but has its own storyline. -- FIELDS OF VALOR/Grounds of Valor settings ENABLE_FIELD_MANUALS = 1; -- Enables Fields of Valor ENABLE_GROUNDS_TOMES = 1; -- Enables Grounds of Valor REGIME_WAIT = 1; -- Make people wait till 00:00 game time as in retail. If it's 0, there is no wait time. LOW_LEVEL_REGIME = 0; -- Allow people to kill regime targets even if they give no exp, allowing people to farm regime targets at 75 in low level areas. -- Setting to lock content more accurately to the content you have defined above -- This generally results in a more accurate presentation of your selected expansions -- as well as a less confusing player experience for things that are disabled (things that are disabled are not loaded) -- This feature correlates to the content_tag column in the SQL files RESTRICT_CONTENT = 0; -- CHARACTER CONFIG INITIAL_LEVEL_CAP = 50; -- The initial level cap for new players. There seems to be a hardcap of 255. MAX_LEVEL = 75; -- Level max of the server, lowers the attainable cap by disabling Limit Break quests. NORMAL_MOB_MAX_LEVEL_RANGE_MIN = 81; -- Lower Bound of Max Level Range for Normal Mobs (0 = Uncapped) NORMAL_MOB_MAX_LEVEL_RANGE_MAX = 84; -- Upper Bound of Max Level Range for Normal Mobs (0 = Uncapped) START_GIL = 10; -- Amount of gil given to newly created characters. START_INVENTORY = 30; -- Starting inventory and satchel size. Ignores values < 30. Do not set above 80! OPENING_CUTSCENE_ENABLE = 0; -- Set to 1 to enable opening cutscenes, 0 to disable. SUBJOB_QUEST_LEVEL = 18; -- Minimum level to accept either subjob quest. Set to 0 to start the game with subjobs unlocked. ADVANCED_JOB_LEVEL = 30; -- Minimum level to accept advanced job quests. Set to 0 to start the game with advanced jobs. ALL_MAPS = 0; -- Set to 1 to give starting characters all the maps. UNLOCK_OUTPOST_WARPS = 0; -- Set to 1 to give starting characters all outpost warps. 2 to add Tu'Lia and Tavnazia. SHOP_PRICE = 1.000; -- Multiplies prices in NPC shops. GIL_RATE = 1.000; -- Multiplies gil earned from quests. Won't always display in game. BAYLD_RATE = 1.000; -- Multiples bayld earned from quests. EXP_RATE = 1.000; -- Multiplies exp earned from fov and quests. TABS_RATE = 1.000; -- Multiplies tabs earned from fov. CURE_POWER = 1.000; -- Multiplies amount healed from Healing Magic, including the relevant Blue Magic. ELEMENTAL_POWER = 1.000; -- Multiplies damage dealt by Elemental and non-drain Dark Magic. DIVINE_POWER = 1.000; -- Multiplies damage dealt by Divine Magic. NINJUTSU_POWER = 1.000; -- Multiplies damage dealt by Ninjutsu Magic. BLUE_POWER = 1.000; -- Multiplies damage dealt by Blue Magic. DARK_POWER = 1.000; -- Multiplies amount drained by Dark Magic. ITEM_POWER = 1.000; -- Multiplies the effect of items such as Potions and Ethers. WEAPON_SKILL_POWER = 1.000; -- Multiplies damage dealt by Weapon Skills. WEAPON_SKILL_POINTS = 1.000; -- Multiplies points earned during weapon unlocking. USE_ADOULIN_WEAPON_SKILL_CHANGES = false; -- true/false. Change to toggle new Adoulin weapon skill damage calculations HARVESTING_BREAK_CHANCE = 0.33; -- % chance for the sickle to break during harvesting. Set between 0 and 1. EXCAVATION_BREAK_CHANCE = 0.33; -- % chance for the pickaxe to break during excavation. Set between 0 and 1. LOGGING_BREAK_CHANCE = 0.33; -- % chance for the hatchet to break during logging. Set between 0 and 1. MINING_BREAK_CHANCE = 0.33; -- % chance for the pickaxe to break during mining. Set between 0 and 1. HARVESTING_RATE = 0.50; -- % chance to recieve an item from haresting. Set between 0 and 1. EXCAVATION_RATE = 0.50; -- % chance to recieve an item from excavation. Set between 0 and 1. LOGGING_RATE = 0.50; -- % chance to recieve an item from logging. Set between 0 and 1. MINING_RATE = 50; -- % chance to recieve an item from mining. Set between 0 and 100. HEALING_TP_CHANGE = -100; -- Change in TP for each healing tick. Default is -100 -- SE implemented coffer/chest illusion time in order to prevent coffer farming. No-one in the same area can open a chest or coffer for loot (gil, gems & items) -- till a random time between MIN_ILLSION_TIME and MAX_ILLUSION_TIME. During this time players can loot keyitem and item related to quests (AF, maps... etc.) COFFER_MAX_ILLUSION_TIME = 3600; -- 1 hour COFFER_MIN_ILLUSION_TIME = 1800; -- 30 minutes CHEST_MAX_ILLUSION_TIME = 3600; -- 1 hour CHEST_MIN_ILLUSION_TIME = 1800; -- 30 minutes -- Sets spawn type for: Behemoth, Fafnir, Adamantoise, King Behemoth, Nidhog, Aspidochelone. -- Use 0 for timed spawns, 1 for force pop only, 2 for both LandKingSystem_NQ = 0; LandKingSystem_HQ = 0; -- DYNAMIS SETTINGS BETWEEN_2DYNA_WAIT_TIME = 1; -- wait time between 2 Dynamis (in real day) min: 1 day DYNA_MIDNIGHT_RESET = true; -- if true, makes the wait time count by number of server midnights instead of full 24 hour intervals DYNA_LEVEL_MIN = 65; -- level min for entering in Dynamis TIMELESS_HOURGLASS_COST = 500000; -- refund for the timeless hourglass for Dynamis. PRISMATIC_HOURGLASS_COST = 50000; -- cost of the prismatic hourglass for Dynamis. CURRENCY_EXCHANGE_RATE = 100; -- X Tier 1 ancient currency -> 1 Tier 2, and so on. Certain values may conflict with shop items. Not designed to exceed 198. RELIC_2ND_UPGRADE_WAIT_TIME = 604800; -- wait time for 2nd relic upgrade (stage 2 -> stage 3) in seconds. 604800s = 1 RL week. RELIC_3RD_UPGRADE_WAIT_TIME = 295200; -- wait time for 3rd relic upgrade (stage 3 -> stage 4) in seconds. 295200s = 82 hours. FREE_COP_DYNAMIS = 1 ; -- Authorize player to entering inside COP Dynamis without completing COP mission ( 1 = enable 0= disable) -- QUEST/MISSION SPECIFIC SETTINGS WSNM_LEVEL = 70; -- Min Level to get WSNM Quests WSNM_SKILL_LEVEL = 240; AF1_QUEST_LEVEL = 40; -- Minimum level to start AF1 quest AF2_QUEST_LEVEL = 50; -- Minimum level to start AF2 quest AF3_QUEST_LEVEL = 50; -- Minimum level to start AF3 quest AF1_FAME = 20; -- base fame for completing an AF1 quest AF2_FAME = 40; -- base fame for completing an AF2 quest AF3_FAME = 60; -- base fame for completing an AF3 quest DEBUG_MODE = 0; -- Set to 1 to activate auto-warping to the next location (only supported by certain missions / quests). QM_RESET_TIME = 300; -- Default time (in seconds) you have from killing ???-pop mission NMs to click again and get key item, until ??? resets. OldSchoolG1 = false; -- Set to true to require farming Exoray Mold, Bombd Coal, and Ancient Papyrus drops instead of allowing key item method. OldSchoolG2 = false; -- Set true to require the NMs for "Atop the Highest Mountains" be dead to get KI like before SE changed it. FrigiciteDuration = 30; -- When OldSChoolG2 is enabled, this is the time (in seconds) you have from killing Boreal NMs to click the "???" target. -- JOB ABILITY/TRAIT SPECIFIC SETTINGS CIRCLE_KILLER_EFFECT = 20; -- Intimidation percentage granted by circle effects. (made up number) KILLER_EFFECT = 10; -- Intimidation percentage from killer job traits. -- SPELL SPECIFIC SETTINGS DIA_OVERWRITE = 1; --Set to 1 to allow Bio to overwrite same tier Dia. Default is 1. BIO_OVERWRITE = 0; --Set to 1 to allow Dia to overwrite same tier Bio. Default is 0. BARELEMENT_OVERWRITE = 1; --Set to 1 to allow Barelement spells to overwrite each other (prevent stacking). Default is 1. BARSTATUS_OVERWRITE = 1; --Set to 1 to allow Barstatus spells to overwrite each other (prevent stacking). Default is 1. STONESKIN_CAP = 350; -- soft cap for hp absorbed by stoneskin BLINK_SHADOWS = 2; -- number of shadows supplied by Blink spell ENSPELL_DURATION = 180; -- duration of RDM en-spells SPIKE_EFFECT_DURATION = 180; -- the duration of RDM, BLM spikes effects (not Reprisal) ELEMENTAL_DEBUFF_DURATION = 120; -- base duration of elemental debuffs AQUAVEIL_COUNTER = 1; -- Base amount of hits Aquaveil absorbs to prevent spell interrupts. Retail is 1. ABSORB_SPELL_AMOUNT = 8; -- how much of a stat gets absorbed by DRK absorb spells - expected to be a multiple of 8. ABSORB_SPELL_TICK = 9; -- duration of 1 absorb spell tick SNEAK_INVIS_DURATION_MULTIPLIER = 1; -- multiplies duration of sneak,invis,deodorize to reduce player torture. 1 = retail behavior. USE_OLD_CURE_FORMULA = false; -- true/false. if true, uses older cure formula (3*MND + VIT + 3*(healing skill/5)) // cure 6 will use the newer formula -- CELEBRATIONS EXPLORER_MOOGLE = 1; -- Enables Explorer Moogle teleports EXPLORER_MOOGLE_LEVELCAP = 10; HALLOWEEN_2005 = 0; -- Set to 1 to Enable the 2005 version of Harvest Festival, will start on Oct. 20 and end Nov. 1. HALLOWEEN_YEAR_ROUND = 0; -- Set to 1 to have Harvest Festival initialize outside of normal times. -- MISC HOMEPOINT_HEAL = 0; --Set to 1 if you want Home Points to heal you like in single-player Final Fantasy games. RIVERNE_PORTERS = 120; -- Time in seconds that Unstable Displacements in Cape Riverne stay open after trading a scale. LANTERNS_STAY_LIT = 1200; -- time in seconds that lanterns in the Den of Rancor stay lit. ENABLE_COP_ZONE_CAP=1; -- enable or disable lvl cap TIMEZONE_OFFSET = 9.0; -- Offset from UTC used to determine when "JP Midnight" is for the server. Default is JST (+9.0). ALLOW_MULTIPLE_EXP_RINGS = 0; -- Set to 1 to remove ownership restrictions on the Chariot/Empress/Emperor Band trio. BYPASS_EXP_RING_ONE_PER_WEEK = 0; -- -- Set to 1 to bypass the limit of one ring per Conquest Tally Week. NUMBER_OF_DM_EARRINGS = 1; -- Number of earrings players can simultaneously own from Divine Might before scripts start blocking them (Default: 1) HOMEPOINT_TELEPORT = 0; -- Enables the homepoint teleport system DIG_ABUNDANCE_BONUS = 0; -- Increase chance of digging up an item (450 = item digup chance +45) DIG_FATIGUE = 1; -- Set to 0 to disable Dig Fatigue DIG_GRANT_BURROW = 0; -- Set to 1 to grant burrow ability DIG_GRANT_BORE = 0; -- Set to 1 to grant bore ability ENM_COOLDOWN = 120; -- Number of hours before a player can obtain same KI for ENMs (default: 5 days) FORCE_SPAWN_QM_RESET_TIME = 300; -- Number of seconds the ??? remains hidden for after the despawning of the mob it force spawns. -- LIMBUS BETWEEN_2COSMOCLEANSE_WAIT_TIME = 3; -- day between 2 limbus keyitem (default 3 days) DIMENSIONAL_PORTAL_UNLOCK = false; -- Set true to bypass requirements for using dimensional portals to reach sea for Limbus -- ABYSSEA VISITANT_BONUS = 1.00; -- Default: 1.00 - (retail) - Multiplies the base time value of each Traverser Stone.
gpl-3.0
Ninjistix/darkstar
scripts/zones/Palborough_Mines/npcs/_3za.lua
5
1172
----------------------------------- -- Area: Palborough Mines -- NPC: Refiner Lid -- Involved In Mission: Journey Abroad -- @zone 143 -- !pos 180 -32 167 ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) gravelQty = trade:getItemQty(597); -- Mine Gravel already_in = player:getVar("refiner_input"); if (already_in + gravelQty > 10) then player:startEvent(20); elseif (trade:getItemCount() == gravelQty) then player:tradeComplete(); player:setVar("refiner_input",already_in + gravelQty); player:startEvent(19,597,gravelQty); else player:startEvent(21); end end; function onTrigger(player,npc) player:startEvent(18); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
TRex22/hawkthorne-journey
src/instructions.lua
3
3287
local Gamestate = require 'vendor/gamestate' local window = require 'window' local camera = require 'camera' local sound = require 'vendor/TEsound' local fonts = require 'fonts' local controls = require 'controls' local VerticalParticles = require "verticalparticles" local Menu = require 'menu' local state = Gamestate.new() local menu = Menu.new({ 'UP', 'DOWN', 'LEFT', 'RIGHT', 'SELECT', 'START', 'JUMP', 'ATTACK', 'INTERACT', }) local descriptions = { UP = 'Move Up / Look', DOWN = 'Move Down / Duck', LEFT = 'Move Left', RIGHT = 'Move Right', SELECT = 'Inventory', START = 'Pause', JUMP = 'Jump / OK', ATTACK = 'Attack', INTERACT = 'Interact', } menu:onSelect(function() controls.enableRemap = true state.statusText = "PRESS NEW KEY" end) function state:init() VerticalParticles.init() self.arrow = love.graphics.newImage("images/menu/arrow.png") self.background = love.graphics.newImage("images/menu/pause.png") self.instructions = {} -- The X coordinates of the columns self.left_column = 160 self.right_column = 300 -- The Y coordinate of the top key self.top = 95 -- Vertical spacing between keys self.spacing = 17 end function state:enter(previous) fonts.set( 'big' ) sound.playMusic( "daybreak" ) camera:setPosition(0, 0) self.instructions = controls.getButtonmap() self.previous = previous self.option = 0 self.statusText = '' end function state:leave() fonts.reset() end function state:keypressed( button ) if controls.enableRemap then self:remapKey(button) end if controls.getButton then menu:keypressed(button) end if button == 'START' then Gamestate.switch(self.previous) end end function state:update(dt) VerticalParticles.update(dt) end function state:draw() VerticalParticles.draw() love.graphics.draw(self.background, camera:getWidth() / 2 - self.background:getWidth() / 2, camera:getHeight() / 2 - self.background:getHeight() / 2) local n = 1 love.graphics.setColor(255, 255, 255) local back = controls.getKey("START") .. ": BACK TO MENU" local howto = controls.getKey("ATTACK") .. " OR " .. controls.getKey("JUMP") .. ": REASSIGN CONTROL" love.graphics.print(back, 25, 25) love.graphics.print(howto, 25, 55) love.graphics.print(self.statusText, self.left_column, 280) love.graphics.setColor( 0, 0, 0, 255 ) for i, button in ipairs(menu.options) do local y = self.top + self.spacing * (i - 1) local key = controls.getKey(button) love.graphics.print(descriptions[button], self.left_column, y, 0, 0.5) love.graphics.print(key, self.right_column, y, 0, 0.5) end love.graphics.setColor( 255, 255, 255, 255 ) love.graphics.draw(self.arrow, 135, 87 + self.spacing * menu:selected()) end function state:remapKey(key) local button = menu.options[menu:selected() + 1] if not controls.newButton(key, button) then self.statusText = "KEY IS ALREADY IN USE" else if key == ' ' then key = 'space' end assert(controls.getKey(button) == key) self.statusText = button .. ": " .. key end controls.enableRemap = false end return state
mit
otservme/global1051
data/actions/scripts/tools/rope.lua
7
1024
local holeId = { 294, 369, 370, 383, 392, 408, 409, 410, 427, 428, 430, 462, 469, 470, 482, 484, 485, 489, 924, 3135, 3136, 7933, 7938, 8170, 8286, 8285, 8284, 8281, 8280, 8279, 8277, 8276, 8323, 8567, 8585, 8596, 8595, 8249, 8250, 8251, 8252, 8253, 8254, 8255, 8256, 8972, 9606, 9625, 13190, 14461, 19519, 21536 } function onUse(cid, item, fromPosition, itemEx, toPosition) local tile = toPosition:getTile() if isInArray(ropeSpots, tile:getGround():getId()) or tile:getItemById(14435) then Player(cid):teleportTo({x = toPosition.x, y = toPosition.y + 1, z = toPosition.z - 1}, false) return true elseif isInArray(holeId, itemEx.itemid) then toPosition.z = toPosition.z + 1 tile = toPosition:getTile() if tile then local thing = tile:getTopVisibleThing() if thing:isItem() and thing:getType():isMovable() then return thing:moveTo({x = toPosition.x, y = toPosition.y + 1, z = toPosition.z - 1}) end end return Player(cid):sendCancelMessage(RETURNVALUE_NOTPOSSIBLE) end return false end
gpl-2.0
Xamla/torch-ros
demo/orbit.lua
1
2203
ros = require 'ros' tf = ros.tf --[[ Compute points along an arc on a plane around a center point and normal. You can use rviz to display the moving 'eye' transform with the TF display. Please make sure 'Fixed Frame' is set to 'world'. ]] function normalize(v) return v / torch.norm(v) end function totensor(t) return not t or torch.isTensor(t) and t or torch.Tensor(t) end function pos_vector(v) if v:size(1) ~= 4 then v = torch.Tensor({ v[1], v[2], v[3], 1 }) end return v end function project_onto_plane(plane_point, plane_normal, pt) return pt - plane_normal * torch.dot(pt - plane_point, plane_normal) end function look_at_pose(eye, at, up) -- eye becomes origin, 'at' lies on z-axis local xaxis = normalize(at - eye) local yaxis = -normalize(torch.cross(xaxis, up)) local zaxis = torch.cross(xaxis, yaxis) local basis = torch.Tensor(3,3) basis[{{},{1}}] = xaxis basis[{{},{2}}] = yaxis basis[{{},{3}}] = zaxis local t = tf.Transform() t:setBasis(basis) t:setOrigin(eye) return t end function generate_arc(center, normal, start_pt, total_rotation_angle, angle_step, look_at, up) up = up or torch.Tensor({0,0,1}) look_at = look_at or center center = totensor(center) normal = totensor(normal) start_pt = totensor(start_pt) start_pt = project_onto_plane(center, normal, start_pt) look_at = totensor(look_at) up = totensor(up) local poses = {} local steps = math.max(math.floor(total_rotation_angle / angle_step + 0.5), 1) for i=0,steps do local theta = total_rotation_angle * i / steps local t = tf.Transform() t:setRotation(tf.Quaternion(normal, theta)) t:setOrigin(center) local eye = t:toTensor() * pos_vector(start_pt-center) local pose = look_at_pose(eye[{{1,3}}], look_at, up) table.insert(poses, pose) end return poses end x = generate_arc({1,1,0.25}, {0,0,1}, {0.5,1.5,1.25}, 2 * math.pi, 0.1, {1,1,0}) ros.init('lookat') ros.Time.init() local b = tf.TransformBroadcaster() local i = 1 while ros.ok() do print(x[i]) local st = tf.StampedTransform(x[i], ros.Time.now(), 'world', 'eye') b:sendTransform(st) ros.Duration(0.1):sleep() i = (i % #x) + 1 ros.spinOnce() end
bsd-3-clause
Ninjistix/darkstar
scripts/zones/Windurst_Waters/npcs/Orn.lua
5
1330
----------------------------------- -- Area: Windurst Waters -- NPC: Orn -- !pos -68 -9 30 238 ----------------------------------- require("scripts/globals/settings"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) bookwormStatus = player:getQuestStatus(WINDURST,EARLY_BIRD_CATCHES_THE_BOOKWORM); if (bookwormStatus == QUEST_ACCEPTED and player:getVar("EARLY_BIRD_TRACK_BOOK") == 3) then player:startEvent(399); elseif (bookwormStatus == QUEST_ACCEPTED and player:getVar("EARLY_BIRD_TRACK_BOOK") == 2) then player:startEvent(398); elseif (bookwormStatus == QUEST_ACCEPTED and player:getVar("EARLY_BIRD_TRACK_BOOK") == 1) then player:startEvent(396); elseif (bookwormStatus == QUEST_ACCEPTED and player:hasKeyItem(10) == true) then player:startEvent(395); else player:startEvent(652); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 395) then player:setVar("EARLY_BIRD_TRACK_BOOK",1); elseif (csid == 398) then player:setVar("EARLY_BIRD_TRACK_BOOK",3); end end;
gpl-3.0
amir1213/tamir
plugins/torrent_search.lua
411
1622
--[[ NOT USED DUE TO SSL ERROR -- See https://getstrike.net/api/ local function strike_search(query) local strike_base = 'http://getstrike.net/api/v2/torrents/' local url = strike_base..'search/?phrase='..URL.escape(query) print(url) local b,c = http.request(url) print(b,c) local search = json:decode(b) vardump(search) if c ~= 200 then return search.message end vardump(search) local results = search.results local text = 'Results: '..results local results = math.min(results, 3) for i=1,results do local torrent = search.torrents[i] text = text..torrent.torrent_title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.seeds ..'\n'..torrent.magnet_uri..'\n\n' end return text end]]-- local function search_kickass(query) local url = 'http://kat.cr/json.php?q='..URL.escape(query) local b,c = http.request(url) local data = json:decode(b) local text = 'Results: '..data.total_results..'\n\n' local results = math.min(#data.list, 5) for i=1,results do local torrent = data.list[i] local link = torrent.torrentLink link = link:gsub('%?title=.+','') text = text..torrent.title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.leechs ..'\n'..link --..'\n magnet:?xt=urn:btih:'..torrent.hash ..'\n\n' end return text end local function run(msg, matches) local query = matches[1] return search_kickass(query) end return { description = "Search Torrents", usage = "!torrent <search term>: Search for torrent", patterns = { "^!torrent (.+)$" }, run = run }
gpl-2.0
dinodeck/ninety_nine_days_of_dev
004_stat_numbers/code/FrontMenuState.lua
2
6216
FrontMenuState = {} FrontMenuState.__index = FrontMenuState function FrontMenuState:Create(parent) local layout = Layout:Create() layout:Contract('screen', 118, 40) layout:SplitHorz('screen', "top", "bottom", 0.12, 2) layout:SplitVert('bottom', "left", "party", 0.726, 2) layout:SplitHorz('left', "menu", "gold", 0.7, 2) local this this = { mParent = parent, mStack = parent.mStack, mStateMachine = parent.mStateMachine, mLayout = layout, mSelections = Selection:Create { spacingY = 32, data = { { id = "items", text = "Items" }, { id = "status", text = "Status" }, { id = "equipment", text = "Equipment" }, { id = "save", text = "Save" }, { id = "load", text = "Load" } }, RenderItem = function(...) this:RenderMenuItem(...) end, OnSelection = function(...) this:OnMenuClick(...) end }, mPanels = { layout:CreatePanel("gold"), layout:CreatePanel("top"), layout:CreatePanel("party"), layout:CreatePanel("menu") }, mTopBarText = parent.mMapDef.name, mInPartyMenu = false, } setmetatable(this, self) this.mSelections.mX = this.mLayout:MidX("menu") - 60 this.mSelections.mY = this.mLayout:Top("menu") - 24 this.mPartyMenu = Selection:Create { spacingY = 90, data = this:CreatePartySummaries(), columns = 1, rows = 3, OnSelection = function(...) this:OnPartyMemberChosen(...) end, RenderItem = function(menu, renderer, x, y, item) if item then item:SetPosition(x, y + 35) item:Render(renderer) end end } this.mPartyMenu:HideCursor() return this end function FrontMenuState:RenderMenuItem(menu, renderer, x, y, item) local color = Vector.Create(1, 1, 1, 1) local canSave = self.mParent.mMapDef.can_save local text = item.text if item.id == "save" and not canSave then color = Vector.Create(0.6, 0.6, 0.6, 1) end if item.id == "load" and not Save:DoesExist() then color = Vector.Create(0.6, 0.6, 0.6, 1) end if item then renderer:DrawText2d(x, y, text, color) end end function FrontMenuState:Enter() end function FrontMenuState:Exit() end function FrontMenuState:OnMenuClick(index, item) if item.id == "items" then return self.mStateMachine:Change("items") end if item.id == "save" then if self.mParent.mMapDef.can_save then self.mStack:Pop() Save:Save() self.mStack:PushFit(gRenderer, 0, 0, "Saved!") end return end if item.id == "load" then if Save:DoesExist() then Save:Load() gGame.Stack:PushFit(gRenderer, 0, 0, "Loaded!") end return end self.mInPartyMenu = true self.mSelections:HideCursor() self.mPartyMenu:ShowCursor() self.mPrevTopBarText = self.mTopBarText self.mTopBarText = "Choose a party member" end function FrontMenuState:OnPartyMemberChosen(actorIndex, actorSummary) -- Need to move state according to menu selection local indexToStateId = { [2] = "status", [3] = "equip", -- more states can go here. } local actor = actorSummary.mActor local index = self.mSelections:GetIndex() local stateId = indexToStateId[index] self.mStateMachine:Change(stateId, actor) end function FrontMenuState:Update(dt) if self.mInPartyMenu then self.mPartyMenu:HandleInput() if Keyboard.JustPressed(KEY_BACKSPACE) or Keyboard.JustPressed(KEY_ESCAPE) then self.mInPartyMenu = false self.mTopBarText = self.mPrevTopBarText self.mSelections:ShowCursor() self.mPartyMenu:HideCursor() end else self.mSelections:HandleInput() if Keyboard.JustPressed(KEY_BACKSPACE) or Keyboard.JustPressed(KEY_ESCAPE) then self.mStack:Pop() end end end function FrontMenuState:CreatePartySummaries() local partyMembers = gGame.World.mParty.mMembers local out = {} for _, v in pairs(partyMembers) do print(_, v, v.mName) local summary = ActorSummary:Create(v, { showXP = true}) table.insert(out, summary) end print("Out size", #out) return out end function FrontMenuState:Render(renderer) local font = gGame.Font.default for k, v in ipairs(self.mPanels) do v:Render(renderer) end renderer:ScaleText(self.mParent.mTitleSize, self. mParent.mTitleSize) renderer:AlignText("left", "center") local menuX = self.mLayout:Left("menu") - 16 local menuY = self.mLayout:Top("menu") - 24 self.mSelections:SetPosition(menuX, menuY) self.mSelections:Render(renderer) local nameX = self.mLayout:MidX("top") local nameY = self.mLayout:MidY("top") renderer:AlignText("center", "center") renderer:DrawText2d(nameX, nameY, self.mTopBarText) local goldX = self.mLayout:MidX("gold") - 22 local goldY = self.mLayout:MidY("gold") + 22 renderer:ScaleText(self.mParent.mLabelSize, self.mParent.mLabelSize) renderer:AlignText("right", "top") renderer:DrawText2d(goldX, goldY, "GP:") renderer:DrawText2d(goldX, goldY - 25, "TIME:") renderer:AlignText("left", "top") font:AlignText("left", "top") font:DrawText2d(renderer, math.floor(goldX + 10), math.floor(goldY), gGame.World:GoldAsString()) font:DrawText2d(renderer, goldX + 10, goldY - 25, gGame.World:TimeAsString()) local partyX = self.mLayout:Left("party") - 16 local partyY = self.mLayout:Top("party") - 45 self.mPartyMenu:SetPosition(partyX, partyY) self.mPartyMenu:Render(renderer) end
mit
Ninjistix/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5fs.lua
5
2283
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: South Plate -- !pos 185 -32 -10 195 ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local state0 = 8; local state1 = 9; local DoorOffset = npc:getID() - 27; -- _5f1 if (npc:getAnimation() == 8) then state0 = 9; state1 = 8; end -- Gates -- Shiva's Gate GetNPCByID(DoorOffset):setAnimation(state0); GetNPCByID(DoorOffset+1):setAnimation(state0); GetNPCByID(DoorOffset+2):setAnimation(state0); GetNPCByID(DoorOffset+3):setAnimation(state0); GetNPCByID(DoorOffset+4):setAnimation(state0); -- Odin's Gate GetNPCByID(DoorOffset+5):setAnimation(state1); GetNPCByID(DoorOffset+6):setAnimation(state1); GetNPCByID(DoorOffset+7):setAnimation(state1); GetNPCByID(DoorOffset+8):setAnimation(state1); GetNPCByID(DoorOffset+9):setAnimation(state1); -- Leviathan's Gate GetNPCByID(DoorOffset+10):setAnimation(state0); GetNPCByID(DoorOffset+11):setAnimation(state0); GetNPCByID(DoorOffset+12):setAnimation(state0); GetNPCByID(DoorOffset+13):setAnimation(state0); GetNPCByID(DoorOffset+14):setAnimation(state0); -- Titan's Gate GetNPCByID(DoorOffset+15):setAnimation(state1); GetNPCByID(DoorOffset+16):setAnimation(state1); GetNPCByID(DoorOffset+17):setAnimation(state1); GetNPCByID(DoorOffset+18):setAnimation(state1); GetNPCByID(DoorOffset+19):setAnimation(state1); -- Plates -- East Plate GetNPCByID(DoorOffset+20):setAnimation(state0); GetNPCByID(DoorOffset+21):setAnimation(state0); -- North Plate GetNPCByID(DoorOffset+22):setAnimation(state0); GetNPCByID(DoorOffset+23):setAnimation(state0); -- West Plate GetNPCByID(DoorOffset+24):setAnimation(state0); GetNPCByID(DoorOffset+25):setAnimation(state0); -- South Plate GetNPCByID(DoorOffset+26):setAnimation(state0); GetNPCByID(DoorOffset+27):setAnimation(state0); return 0; end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/commands/setplayernation.lua
22
1385
--------------------------------------------------------------------------------------------------- -- func: setplayernation -- desc: Sets the target players nation. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "ss" }; function error(player, msg) player:PrintToPlayer(msg); player:PrintToPlayer("!setplayernation {player} <nation>"); player:PrintToPlayer("Nations: 0=San d'Oria 1=Bastok 2=Windurst"); end; function onTrigger(player, arg1, arg2) local targ; local nation; -- validate target if (arg2 ~= nil) then targ = GetPlayerByName(arg1); if (targ == nil) then error(player, string.format( "Player named '%s' not found!", arg1 )); return; end nation = tonumber(arg2); elseif (arg1 ~= nil) then targ = player; nation = tonumber(arg1); end -- validate nation if (nation == nil or nation < 0 or nation > 2) then error(player, "Invalid nation ID."); return; end local nationByNum = { [0] = "San d'Oria", [1] = "Bastok", [2] = "Windurst" } -- set nation targ:setNation( nation ); player:PrintToPlayer( string.format("Set %s's home nation to %s.", targ:getName(), nationByNum[nation]) ); end;
gpl-3.0
charles-l/LD29
Worm.lua
1
2137
Worm = class('Worm') Worm:include(DynCol) Worm:include(Stateful) Worm.static.sprite = love.graphics.newImage('res/worm.png') function Worm:initialize(x, leapDist) self:createCol(x, love.graphics.getHeight() + math.random(100, 200), 20, 100) self.jumpV = 13 self.speed = 4 self.leapDist = leapDist self.g = anim8.newGrid(10, 40, Worm.static.sprite:getWidth(), Worm.static.sprite:getHeight()) self.move = anim8.newAnimation(self.g('1-2', 1), 0.5) self.c.data = self self.dead = false self.timeLeft = timer.add(10, function() self.dead = true end) end function Worm:update(dt) self.p.x, self.p.y = self.c:center() self.c:move(0, -self.speed) if not self.c:collidesWith(t.floor.c) then PS:dirt(self.p.x, self.p.y + 50) self:gotoState('Leap') end end local Leap = Worm:addState('Leap') function Leap:update(dt) self.move:update(dt) self:applyGravity(dt) self.jumpV = self.jumpV - 1*dt if self.c:rotation() < math.pi then self.c:rotate(self.leapDist/300) end self.c:move(self.leapDist, -self.jumpV) if self.c:collidesWith(t.floor.c) then self:gotoState('Burrow') end end local Burrow = Worm:addState('Burrow') function Burrow:update(dt) self.p.x, self.p.y = self.c:center() self.c:move(0, self.speed) end function Worm:draw() local x, y = self.c:center() self.move:draw(Worm.static.sprite, x, y, self.c:rotation(), 2, 2, 5, Worm.static.sprite:getHeight()/2) if debug then self:debugDrawCol() end end WormSpawner = class('WormSpawner') function WormSpawner:initialize(density) self.worms = {} self.density = density self.timer = timer.addPeriodic(1, function() for i=0, self.density do table.insert(self.worms, Worm(math.random(10, love.graphics.getWidth() - 50), math.random(-3, 3))) end end) self.densityTimer = timer.addPeriodic(10, function() self.density = self.density + 1 end) end function WormSpawner:update(dt) for i,v in ipairs(self.worms) do if v.dead then table.remove(self.worms, i) end v:update(dt) end end function WormSpawner:drawWorms() for i,v in ipairs(self.worms) do v:draw() end end
mit
wangyi0226/skynet
service/sharedatad.lua
7
3384
local skynet = require "skynet" local sharedata = require "skynet.sharedata.corelib" local table = table local cache = require "skynet.codecache" cache.mode "OFF" -- turn off codecache, because CMD.new may load data file local NORET = {} local pool = {} local pool_count = {} local objmap = {} local collect_tick = 10 local function newobj(name, tbl) assert(pool[name] == nil) local cobj = sharedata.host.new(tbl) sharedata.host.incref(cobj) local v = {obj = cobj, watch = {} } objmap[cobj] = v pool[name] = v pool_count[name] = { n = 0, threshold = 16 } end local function collect1min() if collect_tick > 1 then collect_tick = 1 end end local function collectobj() while true do skynet.sleep(60*100) -- sleep 1min if collect_tick <= 0 then collect_tick = 10 -- reset tick count to 10 min collectgarbage() for obj, v in pairs(objmap) do if v == true then if sharedata.host.getref(obj) <= 0 then objmap[obj] = nil sharedata.host.delete(obj) end end end else collect_tick = collect_tick - 1 end end end local CMD = {} local env_mt = { __index = _ENV } function CMD.new(name, t, ...) local dt = type(t) local value if dt == "table" then value = t elseif dt == "string" then value = setmetatable({}, env_mt) local f if t:sub(1,1) == "@" then f = assert(loadfile(t:sub(2),"bt",value)) else f = assert(load(t, "=" .. name, "bt", value)) end local _, ret = assert(skynet.pcall(f, ...)) setmetatable(value, nil) if type(ret) == "table" then value = ret end elseif dt == "nil" then value = {} else error ("Unknown data type " .. dt) end newobj(name, value) end function CMD.delete(name) local v = assert(pool[name]) pool[name] = nil pool_count[name] = nil assert(objmap[v.obj]) objmap[v.obj] = true sharedata.host.decref(v.obj) for _,response in pairs(v.watch) do response(true) end end function CMD.query(name) local v = assert(pool[name], name) local obj = v.obj sharedata.host.incref(obj) return v.obj end function CMD.confirm(cobj) if objmap[cobj] then sharedata.host.decref(cobj) end return NORET end function CMD.update(name, t, ...) local v = pool[name] local watch, oldcobj if v then watch = v.watch oldcobj = v.obj objmap[oldcobj] = true sharedata.host.decref(oldcobj) pool[name] = nil pool_count[name] = nil end CMD.new(name, t, ...) local newobj = pool[name].obj if watch then sharedata.host.markdirty(oldcobj) for _,response in pairs(watch) do sharedata.host.incref(newobj) response(true, newobj) end end collect1min() -- collect in 1 min end local function check_watch(queue) local n = 0 for k,response in pairs(queue) do if not response "TEST" then queue[k] = nil n = n + 1 end end return n end function CMD.monitor(name, obj) local v = assert(pool[name]) if obj ~= v.obj then sharedata.host.incref(v.obj) return v.obj end local n = pool_count[name].n + 1 if n > pool_count[name].threshold then n = n - check_watch(v.watch) pool_count[name].threshold = n * 2 end pool_count[name].n = n table.insert(v.watch, skynet.response()) return NORET end skynet.start(function() skynet.fork(collectobj) skynet.dispatch("lua", function (session, source ,cmd, ...) local f = assert(CMD[cmd]) local r = f(...) if r ~= NORET then skynet.ret(skynet.pack(r)) end end) end)
mit
Ninjistix/darkstar
scripts/zones/Batallia_Downs/npcs/qm3.lua
5
1467
----------------------------------- -- Area: Batallia Downs -- NPC: qm3 (???) -- Involved in Mission 9-1 (San dOria) -- !pos 210 17 -615 105 ----------------------------------- package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Batallia_Downs/TextIDs"); require("scripts/zones/Batallia_Downs/MobIDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == BREAKING_BARRIERS and player:getVar("MissionStatus") == 3 and not GetMobByID(SUPARNA):isSpawned() and not GetMobByID(SUPARNA_FLEDGLING):isSpawned()) then if (player:getVar("Mission9-1Kills") > 0) then player:startEvent(904); else SpawnMob(SUPARNA); SpawnMob(SUPARNA_FLEDGLING); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; function onTrade(player,npc,trade) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 904) then player:addKeyItem(FIGURE_OF_LEVIATHAN); player:messageSpecial(KEYITEM_OBTAINED,FIGURE_OF_LEVIATHAN); player:setVar("MissionStatus",4); player:setVar("Mission9-1Kills",0); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/VeLugannon_Palace/mobs/Detector.lua
7
2061
----------------------------------- -- Area: VeLugannon Palace -- MOB: Detector ----------------------------------- require("scripts/globals/groundsofvalor"); ----------------------------------- function onMobInitialize(mob) end; function onMobSpawn(mob) local Detector = mob:getID(); GetMobByID(Detector):setLocalVar("1",1); end; function onMobFight(mob,target) local Detector = mob:getID(); local Caretaker = Detector + 1; local ExtraVar = GetMobByID(Detector):getLocalVar("1"); -- Summons a Detector every 15 seconds. -- TODO: Casting animation for before summons. When he spawns them isn't exactly retail accurate. -- Should be ~10s to start cast, and another ~5 to finish. -- Detectors can also still spawn the Caretakers while sleeping, moving, etc. if (GetMobAction(Caretaker) == 16) then GetMobByID(Caretaker):updateEnmity(target); end if (ExtraVar <= 6) then -- Maximum number of pets Detector can spawn is 5 if (mob:getBattleTime() % 15 < 3 and mob:getBattleTime() > 3) then if (GetMobAction(Caretaker) == 0) then SpawnMob(Caretaker):updateEnmity(target); GetMobByID(Caretaker):setPos(GetMobByID(Detector):getXPos()+1, GetMobByID(Detector):getYPos(), GetMobByID(Detector):getZPos()+1); -- Set Caretaker x and z position +1 from Detector GetMobByID(Detector):setLocalVar("1",ExtraVar+1); return; end end end end; function onMobDisengage(mob) local Detector = mob:getID(); local Caretaker = mob:getID() + 1; GetMobByID(Detector):resetLocalVars(); if (GetMobAction(Caretaker) ~= 0) then DespawnMob(Caretaker); end end; function onMobDeath(mob, player, isKiller) checkGoVregime(player,mob,743,1); end; function onMobDespawn( mob ) local Detector = mob:getID(); local Caretaker = mob:getID() + 1; GetMobByID(Detector):resetLocalVars(); if (GetMobAction(Caretaker) ~= 0) then DespawnMob(Caretaker); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Nashmau/TextIDs.lua
5
1902
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_CANNOT_BE_OBTAINEDX = 6381; -- You cannot obtain the ITEM_OBTAINED = 6386; -- Obtained: <item> ITEM_OBTAINEDX = 6395; -- You obtain ?Numeric Parameter 1? ?Possible Special Code: 01??Speaker Name?)??BAD CHAR: 80??BAD CHAR: 80??BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?!?Prompt? GIL_OBTAINED = 6387; -- Obtained <number> gil KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7047; -- You can't fish here HOMEPOINT_SET = 7308; -- Home point set! -- Other Texts NENE_DELIVERY_DIALOG = 10831; -- Yooo want to send gooods? Yooo want to send link clink NANA_DELIVERY_DIALOG = 10832; -- Yooo send gooods. Yooo send link clink. -- Quest Dialog NOMAD_MOOGLE_DIALOG = 7328; -- I'm a traveling moogle, kupo. I help adventurers in the Outlands access items they have stored in a Mog House elsewhere, kupo. -- Shop Texts JAJAROON_SHOP_DIALOG = 10477; -- Hellooo. Yooo have caaard? Can do gaaame? Jajaroon have diiice. TSUTSUROON_SHOP_DIALOG = 10487; -- What yooo want? Have katana, katana, and nin-nin...yooo want? MAMAROON_SHOP_DIALOG = 10490; -- Welcome to maaagic shop. Lots of magics for yooo. POPOROON_SHOP_DIALOG = 10492; -- Come, come. Buy aaarmor, looots of armor! WATAKHAMAZOM_SHOP_DIALOG = 10493; -- Looking for some bows and bolts to strrrike fear into the hearts of your enemies? You can find 'em here! CHICHIROON_SHOP_DIALOG = 10495; -- Howdy-hooo! I gots soooper rare dice for yooo. PIPIROON_SHOP_DIALOG = 0; -- [UNKNOWN] YOYOROON_SHOP_DIALOG = 0; -- [UNKNOWN] -- Porter Moogle RETRIEVE_DIALOG_ID = 11884; -- You retrieve$ from the porter moogle's care.
gpl-3.0
Ninjistix/darkstar
scripts/zones/Spire_of_Vahzl/Zone.lua
5
1122
----------------------------------- -- -- Zone: Spire_of_Vahzl (23) -- ----------------------------------- package.loaded["scripts/zones/Spire_of_Vahzl/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Spire_of_Vahzl/TextIDs"); require("scripts/globals/missions"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-0.039,-2.049,293.640,64); -- Floor 1 {R} end if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==7) then cs = 20; end return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 20) then player:setVar("PromathiaStatus",8); end end;
gpl-3.0
wounds1/zaza2
plugins/arabic_lock.lua
234
1405
antiarabic = {}-- An empty table for solving multiple kicking problem do local function run(msg, matches) if is_momod(msg) then -- Ignore mods,owner,admins return end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_arabic'] then if data[tostring(msg.to.id)]['settings']['lock_arabic'] == 'yes' then if is_whitelisted(msg.from.id) then return end if antiarabic[msg.from.id] == true then return end if msg.to.type == 'chat' then local receiver = get_receiver(msg) local username = msg.from.username local name = msg.from.first_name if username and is_super_group(msg) then send_large_msg(receiver , "Arabic/Persian is not allowed here\n@"..username.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") else send_large_msg(receiver , "Arabic/Persian is not allowed here\nName: "..name.."["..msg.from.id.."]\nStatus: User kicked/msg deleted") end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked (arabic was locked) ") local chat_id = msg.to.id local user_id = msg.from.id kick_user(user_id, chat_id) end antiarabic[msg.from.id] = true end end return end local function cron() antiarabic = {} -- Clear antiarabic table end return { patterns = { "([\216-\219][\128-\191])" }, run = run, cron = cron } end
gpl-2.0
dafei2015/hugular_cstolua
Client/tools/luaTools/win/lua/jit/bc.lua
74
5606
---------------------------------------------------------------------------- -- LuaJIT bytecode listing module. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module lists the bytecode of a Lua function. If it's loaded by -jbc -- it hooks into the parser and lists all functions of a chunk as they -- are parsed. -- -- Example usage: -- -- luajit -jbc -e 'local x=0; for i=1,1e6 do x=x+i end; print(x)' -- luajit -jbc=- foo.lua -- luajit -jbc=foo.list foo.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_LISTFILE. The file is overwritten every time the module -- is started. -- -- This module can also be used programmatically: -- -- local bc = require("jit.bc") -- -- local function foo() print("hello") end -- -- bc.dump(foo) --> -- BYTECODE -- [...] -- print(bc.line(foo, 2)) --> 0002 KSTR 1 1 ; "hello" -- -- local out = { -- -- Do something with each line: -- write = function(t, ...) io.write(...) end, -- close = function(t) end, -- flush = function(t) end, -- } -- bc.dump(foo, out) -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20003, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local bit = require("bit") local sub, gsub, format = string.sub, string.gsub, string.format local byte, band, shr = string.byte, bit.band, bit.rshift local funcinfo, funcbc, funck = jutil.funcinfo, jutil.funcbc, jutil.funck local funcuvname = jutil.funcuvname local bcnames = vmdef.bcnames local stdout, stderr = io.stdout, io.stderr ------------------------------------------------------------------------------ local function ctlsub(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" else return format("\\%03d", byte(c)) end end -- Return one bytecode line. local function bcline(func, pc, prefix) local ins, m = funcbc(func, pc) if not ins then return end local ma, mb, mc = band(m, 7), band(m, 15*8), band(m, 15*128) local a = band(shr(ins, 8), 0xff) local oidx = 6*band(ins, 0xff) local op = sub(bcnames, oidx+1, oidx+6) local s = format("%04d %s %-6s %3s ", pc, prefix or " ", op, ma == 0 and "" or a) local d = shr(ins, 16) if mc == 13*128 then -- BCMjump return format("%s=> %04d\n", s, pc+d-0x7fff) end if mb ~= 0 then d = band(d, 0xff) elseif mc == 0 then return s.."\n" end local kc if mc == 10*128 then -- BCMstr kc = funck(func, -d-1) kc = format(#kc > 40 and '"%.40s"~' or '"%s"', gsub(kc, "%c", ctlsub)) elseif mc == 9*128 then -- BCMnum kc = funck(func, d) if op == "TSETM " then kc = kc - 2^52 end elseif mc == 12*128 then -- BCMfunc local fi = funcinfo(funck(func, -d-1)) if fi.ffid then kc = vmdef.ffnames[fi.ffid] else kc = fi.loc end elseif mc == 5*128 then -- BCMuv kc = funcuvname(func, d) end if ma == 5 then -- BCMuv local ka = funcuvname(func, a) if kc then kc = ka.." ; "..kc else kc = ka end end if mb ~= 0 then local b = shr(ins, 24) if kc then return format("%s%3d %3d ; %s\n", s, b, d, kc) end return format("%s%3d %3d\n", s, b, d) end if kc then return format("%s%3d ; %s\n", s, d, kc) end if mc == 7*128 and d > 32767 then d = d - 65536 end -- BCMlits return format("%s%3d\n", s, d) end -- Collect branch targets of a function. local function bctargets(func) local target = {} for pc=1,1000000000 do local ins, m = funcbc(func, pc) if not ins then break end if band(m, 15*128) == 13*128 then target[pc+shr(ins, 16)-0x7fff] = true end end return target end -- Dump bytecode instructions of a function. local function bcdump(func, out, all) if not out then out = stdout end local fi = funcinfo(func) if all and fi.children then for n=-1,-1000000000,-1 do local k = funck(func, n) if not k then break end if type(k) == "proto" then bcdump(k, out, true) end end end out:write(format("-- BYTECODE -- %s-%d\n", fi.loc, fi.lastlinedefined)) local target = bctargets(func) for pc=1,1000000000 do local s = bcline(func, pc, target[pc] and "=>") if not s then break end out:write(s) end out:write("\n") out:flush() end ------------------------------------------------------------------------------ -- Active flag and output file handle. local active, out -- List handler. local function h_list(func) return bcdump(func, out) end -- Detach list handler. local function bclistoff() if active then active = false jit.attach(h_list) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach list handler. local function bcliston(outfile) if active then bclistoff() end if not outfile then outfile = os.getenv("LUAJIT_LISTFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(h_list, "bc") active = true end -- Public module functions. module(...) line = bcline dump = bcdump targets = bctargets on = bcliston off = bclistoff start = bcliston -- For -j command line option.
mit
dmekersa/create2Dmobilegames
ChickenSprite/chicken_packer.lua
1
1407
-- -- created with TexturePacker (http://www.codeandweb.com/texturepacker) -- -- $TexturePacker:SmartUpdate:f7d1d7007b7802f7006ab5b725c167b8:80ac306c7910ffcff4e0135f3b07762a:508315e819c8c5d7d547404630422e16$ -- -- local sheetInfo = require("mysheet") -- local myImageSheet = graphics.newImageSheet( "mysheet.png", sheetInfo:getSheet() ) -- local sprite = display.newSprite( myImageSheet , {frames={sheetInfo:getFrameIndex("sprite")}} ) -- local SheetInfo = {} SheetInfo.sheet = { frames = { { -- blitzsubspeed1 x=530, y=2, width=174, height=160, }, { -- blitzsubspeed2 x=354, y=2, width=174, height=160, }, { -- blitzsubspeed3 x=178, y=2, width=174, height=160, }, { -- blitzsubspeed4 x=2, y=2, width=174, height=160, }, }, sheetContentWidth = 706, sheetContentHeight = 164 } SheetInfo.frameIndex = { ["blitzsubspeed1"] = 1, ["blitzsubspeed2"] = 2, ["blitzsubspeed3"] = 3, ["blitzsubspeed4"] = 4, } function SheetInfo:getSheet() return self.sheet; end function SheetInfo:getFrameIndex(name) return self.frameIndex[name]; end return SheetInfo
unlicense
Ninjistix/darkstar
scripts/globals/effects/accuracy_boost.lua
32
1029
----------------------------------- -- -- EFFECT_ACCURACY_BOOST -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_ACC,effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) -- the effect loses accuracy of 1 every 3 ticks depending on the source of the acc boost local boostACC_effect_size = effect:getPower(); if (boostACC_effect_size > 0) then effect:setPower(boostACC_effect_size - 1) target:delMod(MOD_ACC,1); end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local boostACC_effect_size = effect:getPower(); if (boostACC_effect_size > 0) then target:delMod(MOD_ACC,effect:getPower()); end end;
gpl-3.0
SharpWoW/Chocobo
ChocoboCommand.lua
1
10477
--[[ Copyright (c) 2010-2020 by Adam Hellberg This file is part of Chocobo. Chocobo is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. Chocobo 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 Chocobo. If not, see <http://www.gnu.org/licenses/>. --]] Chocobo.Command = { Slash = { "chocobo" }, Commands = {} } local C = Chocobo local CC = C.Command local CLib = ChocoboLib local L = _G["ChocoboLocale"] local AddCustomPattern = "\"([%w%p%s]+)\" \"([%w%p%s]+)\"" -- Argument #1 (command) can be either string or a table. function CC:Register(command, func) if type(command) == "string" then command = {command} end for _,v in pairs(command) do if not self:HasCommand(v) then if v ~= "__DEFAULT__" then v = v:lower() end self.Commands[v] = func end end end function CC:HasCommand(command) return self.Commands[command] end function CC:HandleCommand(command, args) if self:HasCommand(command) then self.Commands[command](args) elseif self:HasCommand("__DEFAULT__") then self.Commands["__DEFAULT__"](args) else C:ErrorMsg((L["InvalidCommand"]):format(command)) end end CC:Register("__DEFAULT__", function() C:Msg(L["HelpMessage1"]) C:Msg(L["HelpMessage2"]) C:Msg(L["HelpMessage3"]) C:Msg(L["HelpMessage4"]) C:Msg(L["HelpMessage17"]) C:Msg(L["HelpMessage18"]) C:Msg(L["HelpMessage19"]) C:Msg(L["HelpMessage5"]) C:Msg(L["HelpMessage6"]) C:Msg(L["HelpMessage7"]) C:Msg(L["HelpMessage8"]) C:Msg(L["HelpMessage9"]) C:Msg(L["HelpMessage10"]) C:Msg(L["HelpMessage12"]) C:Msg(L["HelpMessage13"]) C:Msg(L["HelpMessage14"]) C:Msg(L["HelpMessage15"]) C:Msg(L["HelpMessage16"]) C:Msg(L["HelpMessage11"]) end) CC:Register({"options", "o", "config", "gui"}, function() Chocobo.SoundControl.Options:Open() Chocobo.Options:Open() end) CC:Register({"allmounts", "am", "all"}, function() C:FilterMount(false) end) CC:Register({"hawkstrider", "hs", "hawk"}, function() C:FilterMount(true) end) CC:Register({"modetoggle", "mounttoggle", "mt"}, function() C:FilterMount() end) CC:Register({"toggle", "t"}, function() C:Toggle() end) CC:Register({"plainstridertoggle", "plainstrider", "plainstriders", "ps"}, function() C:PlainstriderToggle() end) CC:Register({"ridingcranetoggle", "ridingcrane", "ridingcranes", "rc"}, function() C:RidingCraneToggle() end) CC:Register({"ravenlordtoggle", "ravenlord", "rl"}, function() C:RavenLordToggle() end) CC:Register({"flametalontoggle", "flametalon", "flame", "alysrazor", "alys"}, function() C:FlametalonToggle() end) CC:Register({"preventdupetoggle", "pdtoggle", "pdt"}, function() C:PreventDupeToggle() end) CC:Register({"soundcontrol", "sc", "sndctrl", "sound"}, function(args) local handled = false if #args > 0 then local vol = tonumber(args[3]) if args[1] == "gui" or args[1] == "options" then Chocobo.SoundControl.Options:Open() handled = true elseif args[1] == "toggle" or args[1] == "t" then C.SoundControl:Toggle() handled = true elseif args[1] == "default" or args[1] == "d" then C.SoundControl:ToggleDefault() handled = true elseif args[1] == "music" or args[1] == "m" then if #args > 1 then if args[2] == "toggle" or args[2] == "t" then C.SoundControl:ToggleMusic() handled = true elseif args[2]:match("^mount") or args[2] == "m" then C.SoundControl:ToggleMusicMount() handled = true elseif args[2]:match("^not?mount") or args[2] == "nm" then C.SoundControl:ToggleMusicNoMount() handled = true elseif args[2] == "volume" or args[2] == "vol" or args[2] == "v" then if type(vol) == "number" then C.SoundControl:SetMusicVolume(vol) handled = true elseif args[3] == "toggle" or args[3] == "t" then C.SoundControl:ToggleMusicVolume() handled = true else C.SoundControl:PrintMusicVolume() handled = true end end end elseif args[1] == "sfx" or args[1] == "sound" or args[1] == "s" then if #args > 1 then if args[2] == "toggle" or args[2] == "t" then C.SoundControl:ToggleSFX() handled = true elseif args[2]:match("^mount") or args[2] == "m" then C.SoundControl:ToggleSFXMount() handled = true elseif args[2]:match("^not?mount") or args[2] == "nm" then C.SoundControl:ToggleSFXNoMount() handled = true elseif args[2] == "volume" or args[2] == "vol" or args[2] == "v" then if type(vol) == "number" then C.SoundControl:SetSFXVolume(vol) handled = true elseif args[3] == "toggle" or args[3] == "t" then C.SoundControl:ToggleSFXVolume() handled = true else C.SoundControl:PrintSFXVolume() handled = true end end end elseif args[1] == "ambience" or args[1] == "amb" or args[1] == "a" then if #args > 1 then if args[2] == "toggle" or args[2] == "t" then C.SoundControl:ToggleAmbience() handled = true elseif args[2]:match("^mount") or args[2] == "m" then C.SoundControl:ToggleAmbienceMount() handled = true elseif args[2]:match("^not?mount") or args[2] == "nm" then C.SoundControl:ToggleAmbienceNoMount() handled = true elseif args[2] == "volume" or args[2] == "vol" or args[2] == "v" then if type(vol) == "number" then C.SoundControl:SetAmbienceVolume(vol) handled = true elseif args[3] == "toggle" or args[3] == "t" then C.SoundControl:ToggleAmbienceVolume() handled = true else C.SoundControl:PrintAmbienceVolume() handled = true end end end end end if not handled then C:Msg(L["SCSyntax1"]) C:Msg(L["SCSyntax2"]) end end) CC:Register({"list", "l", "ls"}, function() C:PrintMusic() end) CC:Register({"reset", "r"}, function() C:ResetMusic() end) CC:Register({"listmounts", "lm"}, function() C:PrintMounts() end) CC:Register({"resetmounts", "rm"}, function() C:ResetMounts() end) CC:Register({"debug", "d"}, function(args) if not args[1] then C:Debug() else C:Debug(args[1]:lower()) end end) CC:Register({"add", "a"}, function(args) if #args > 0 then local song = args[1] if #args > 1 then for i=2,#args do song = song .. " " .. args[i] end end C:AddMusic(song) else C:Msg(L["AddSyntax"]) end end) CC:Register({"remove", "rem", "delete", "del"}, function(args) if #args > 0 then local song = args[1] if #args > 1 then for i=2,#args do song = song .. " " .. args[i] end end C:RemoveMusic(song) else C:Msg(L["RemoveSyntax"]) end end) CC:Register({"addcustom", "addc", "ac"}, function(args) if #args < 2 then C:ErrorMsg(L["AddCustomSyntax"]) return end local arg = args[1] for i=2,#args do arg = arg .. " " .. args[i] end local mount, song = arg:match(AddCustomPattern) if not mount or not song then C:ErrorMsg(L["AddCustomSyntax"]) return end C:AddCustomMusic(song, mount) end) CC:Register({"removecustom", "removec", "remc", "rc"}, function(args) if #args < 1 then C:ErrorMsg(L["RemoveCustomSyntax"]) return end local arg = args[1] if #args > 1 then for i=2,#args do arg = arg .. " " .. args[i] end end C:RemoveCustomMusic(arg) end) CC:Register({"addmount", "addm"}, function(args) if #args > 0 then local mount = args[1] if #args > 1 then for i=2,#args do mount = mount .. " " .. args[i] end end C:AddMount(mount) else C:Msg(L["AddMountSyntax"]) end end) CC:Register({"removemount", "remm", "deletemount", "delmount", "delm"}, function(args) if #args > 0 then local mount = args[1] if #args > 1 then for i=2,#args do mount = mount .. " " .. args[i] end end C:RemoveMount(mount) else C:Msg(L["RemoveMountSyntax"]) end end) for i,v in ipairs(CC.Slash) do _G["SLASH_" .. C.Name:upper() .. i] = "/" .. v end SlashCmdList[C.Name:upper()] = function(msg) msg = CLib:Trim(msg) local args = CLib:Split(msg) local cmd = args[1] local t = {} if #args > 1 then for i=2,#args do table.insert(t, args[i]) end end CC:HandleCommand(cmd, t) end
gpl-3.0
Ninjistix/darkstar
scripts/zones/Apollyon/mobs/Fir_Bholg.lua
5
1066
----------------------------------- -- Area: Apollyon SW -- NPC: Fir Bholg ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- function onMobSpawn(mob) end; function onMobEngaged(mob,target) end; function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (mobID ==16932869) then -- time GetNPCByID(16932864+14):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+14):setStatus(STATUS_NORMAL); elseif (mobID ==16932871) then -- recover GetNPCByID(16932864+16):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+16):setStatus(STATUS_NORMAL); elseif (mobID ==16932874) then -- item GetNPCByID(16932864+15):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+15):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Kazham/npcs/Vanono.lua
5
1130
----------------------------------- -- Area: Kazham -- NPC: Vanono -- Type: Standard NPC -- @zone 250 -- !pos -23.140 -5 -23.101 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 3) then player:startEvent(264); elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") > 3) then player:startEvent(268); else player:startEvent(262); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 264) then player:setVar("MissionStatus",4); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Korroloka_Tunnel/npcs/qm2.lua
5
2281
----------------------------------- -- Area: Korroloka Tunnel -- NPC: ??? (qm2) -- Involved In Quest: Ayame and Kaede -- !pos -208 -9 176 173 ----------------------------------- package.loaded["scripts/zones/Korroloka_Tunnel/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Korroloka_Tunnel/TextIDs"); require("scripts/zones/Korroloka_Tunnel/MobIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,AYAME_AND_KAEDE) == QUEST_ACCEPTED) then if (player:getVar("AyameAndKaede_Event") == 2 and player:hasKeyItem(STRANGELY_SHAPED_CORAL) == false) then if (not GetMobByID(KORROLOKA_LEECH_I):isSpawned() and not GetMobByID(KORROLOKA_LEECH_II):isSpawned() and not GetMobByID(KORROLOKA_LEECH_III):isSpawned()) then if (player:getVar("KorrolokaLeeches_Killed") > 0) then player:addKeyItem(STRANGELY_SHAPED_CORAL); player:messageSpecial(KEYITEM_OBTAINED,STRANGELY_SHAPED_CORAL); player:setVar("KorrolokaLeeches_Killed",0); if (player:getVar("KorrolokaLeeches_SpawningPC") > 0) then player:setVar("KorrolokaLeeches_SpawningPC",0); npc:hideNPC(FORCE_SPAWN_QM_RESET_TIME); end else player:messageSpecial(SENSE_OF_BOREBODING); SpawnMob(KORROLOKA_LEECH_I); SpawnMob(KORROLOKA_LEECH_II); SpawnMob(KORROLOKA_LEECH_III); player:setVar("KorrolokaLeeches_SpawningPC", 1); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/spells/victory_march.lua
5
1420
----------------------------------------- -- Spell: Victory March -- Gives party members Haste ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); ----------------------------------------- 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 = 43; if (sLvl+iLvl > 300) then power = power + math.floor((sLvl+iLvl-300) / 7); end if (power >= 96) then power = 96; end local iBoost = caster:getMod(MOD_MARCH_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost*16; 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_MARCH,power,0,duration,caster:getID(), 0, 2)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); end return EFFECT_MARCH; end;
gpl-3.0
neofob/sile
languages/it.lua
3
2859
SILE.hyphenator.languages["it"] = {} SILE.hyphenator.languages["it"].patterns = { ".a3p2n", -- After the Garzanti dictionary: a-pnea, a-pnoi-co ".anti1", ".anti3m2n", ".bio1", ".ca4p3s", ".circu2m1", ".contro1", ".di2s3cine", ".e2x1eu", ".fran2k3", ".free3", ".li3p2sa", ".narco1", ".opto1", ".orto3p2", ".para1", ".ph2l", ".ph2r", ".poli3p2", ".pre1", ".p2s", ".re1i2scr", ".sha2re3", ".tran2s3c", ".tran2s3d", ".tran2s3l", ".tran2s3n", ".tran2s3p", ".tran2s3r", ".tran2s3t", ".su2b3lu", ".su2b3r", ".wa2g3n", ".wel2t1", "2'2", "a1ia", "a1ie", "a1io", "a1iu", "a1uo", "a1ya", "2at.", "e1iu", "e2w", "o1ia", "o1ie", "o1io", "o1iu", "1b", "2bb", "2bc", "2bd", "2bf", "2bm", "2bn", "2bp", "2bs", "2bt", "2bv", "b2l", "b2r", "2b.", "2b'", "1c", "2cb", "2cc", "2cd", "2cf", "2ck", "2cm", "2cn", "2cq", "2cs", "2ct", "2cz", "2chh", "c2h", "2ch.", "2ch'.", "2ch''.", "2chb", "ch2r", "2chn", "c2l", "c2r", "2c.", "2c'", ".c2", "1d", "2db", "2dd", "2dg", "2dl", "2dm", "2dn", "2dp", "d2r", "2ds", "2dt", "2dv", "2dw", "2d.", "2d'", ".d2", "1f", "2fb", "2fg", "2ff", "2fn", "f2l", "f2r", "2fs", "2ft", "2f.", "2f'", "1g", "2gb", "2gd", "2gf", "2gg", "g2h", "g2l", "2gm", "g2n", "2gp", "g2r", "2gs", "2gt", "2gv", "2gw", "2gz", "2gh2t", "2g.", "2g'", ".h2", "1h", "2hb", "2hd", "2hh", "hi3p2n", "h2l", "2hm", "2hn", "2hr", "2hv", "2h.", "2h'", ".j2", "1j", "2j.", "2j'", ".k2", "1k", "2kg", "2kf", "k2h", "2kk", "k2l", "2km", "k2r", "2ks", "2kt", "2k.", "2k'", "1l", "2lb", "2lc", "2ld", "2l3f2", "2lg", "l2h", "l2j", "2lk", "2ll", "2lm", "2ln", "2lp", "2lq", "2lr", "2ls", "2lt", "2lv", "2lw", "2lz", "2l.", "2l'.", "2l''", "1m", "2mb", "2mc", "2mf", "2ml", "2mm", "2mn", "2mp", "2mq", "2mr", "2ms", "2mt", "2mv", "2mw", "2m.", "2m'", "1n", "2nb", "2nc", "2nd", "2nf", "2ng", "2nk", "2nl", "2nm", "2nn", "2np", "2nq", "2nr", "2ns", "n2s3fer", "2nt", "2nv", "2nz", "n2g3n", "2nheit", "2n.", "2n'", "1p", "2pd", "p2h", "p2l", "2pn", "3p2ne", "2pp", "p2r", "2ps", "3p2sic", "2pt", "2pz", "2p.", "2p'", "1q", "2qq", "2q.", "2q'", "1r", "2rb", "2rc", "2rd", "2rf", "r2h", "2rg", "2rk", "2rl", "2rm", "2rn", "2rp", "2rq", "2rr", "2rs", "2rt", "r2t2s3", "2rv", "2rx", "2rw", "2rz", "2r.", "2r'", "1s2", "2shm", "2sh.", "2sh'", "2s3s", "s4s3m", "2s3p2n", "2stb", "2stc", "2std", "2stf", "2stg", "2stm", "2stn", "2stp", "2sts", "2stt", "2stv", "2sz", "4s.", "4s'.", "4s''", ".t2", "1t", "2tb", "2tc", "2td", "2tf", "2tg", "t2h", "2th.", "t2l", "2tm", "2tn", "2tp", "t2r", "t2s", "3t2sch", "2tt", "t2t3s", "2tv", "2tw", "t2z", "2tzk", "tz2s", "2t.", "2t'.", "2t''", "1v", "2vc", "v2l", "v2r", "2vv", "2v.", "2v'.", "2v''", "1w", "w2h", "wa2r", "2w1y", "2w.", "2w'", "1x", "2xb", "2xc", "2xf", "2xh", "2xm", "2xp", "2xt", "2xw", "2x.", "2x'", "y1ou", "y1i", "1z", "2zb", "2zd", "2zl", "2zn", "2zp", "2zt", "2zs", "2zv", "2zz", "2z.", "2z'.", "2z''", ".z2", }
mit
Ninjistix/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/npcs/_20m.lua
5
7859
----------------------------------- -- Area: Alzadaal Undersea Ruins -- Door: Runic Seal -- !pos 125 -2 20 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/besieged"); require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) -- See notes below player:setVar("NyzulLoopGuard",0); -- Reset Latch 1 player:setVar("NyzulReady",0); -- Reset Latch 2 if (player:getCurrentMission(TOAU) == PATH_OF_DARKNESS and player:hasKeyItem(NYZUL_ISLE_ROUTE) and player:getVar("AhtUrganStatus") == 1) then player:setVar("PathOfDarkness",1); player:startEvent(405, 58, -6, 0, 99, 5, 0); elseif (player:getCurrentMission(TOAU) == NASHMEIRAS_PLEA and player:hasKeyItem(MYTHRIL_MIRROR) and player:getVar("AhtUrganStatus") == 1) then player:setVar("NashmeirasPlea",1); player:startEvent(405, 59, -10, 0, 99, 5, 0); elseif (player:hasKeyItem(NYZUL_ISLE_ASSAULT_ORDERS)) then local assaultid = player:getCurrentAssault(); local recommendedLevel = getRecommendedAssaultLevel(assaultid); local armband = 0; if (player:hasKeyItem(ASSAULT_ARMBAND)) then armband = 1; end player:startEvent(405, assaultid, -4, 0, recommendedLevel, 5, armband); else player:messageSpecial(NOTHING_HAPPENS); end end; function onEventUpdate(player,csid,option,target) -- printf("UPDATE CSID: %u",csid); -- printf("UPDATE RESULT: %u",option); if(not(csid == 405)) then return; end -- Begin Ugly Hack -- -- For some currently unknown reason, the Nyzul event can -- spam event updates uncontrollably. Until we can figure -- out why, I used a double lock to hack around it. The -- first latch is auto set here, which suppresses future -- updates which the instance is initialized. The 2nd latch -- is set after the instance is created. Then we use that -- to force terminate the event so that we can go into the -- instance successfully. local nyzulReady = player:getVar("NyzulReady"); if(player:getVar("NyzulReady")==1) then -- Latch 2 player:updateEvent(405,3,3,3,3,3,3,3); -- Force terminate the event return; elseif(player:getVar("NyzulLoopGuard")==1) then return; -- Suppress Update Spam else player:setVar("NyzulLoopGuard",1); -- Latch 1 end -- End Ugly Hack local assaultid = player:getCurrentAssault(); local cap = bit.band(option, 0x03); if (cap == 0) then cap = 99; elseif (cap == 1) then cap = 70; elseif (cap == 2) then cap = 60; else cap = 50; end player:setVar("AssaultCap", cap); local pathOfDarkness = player:getVar("PathOfDarkness"); local nashmeirasPlea = player:getVar("NashmeirasPlea"); if(pathOfDarkness == 1) then local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if (v:getID() ~= player:getID()) then if (v:hasKeyItem(NYZUL_ISLE_ROUTE) == false and v:hasCompletedMission(TOAU, PATH_OF_DARKNESS) == false) then player:messageText(target,MEMBER_NO_REQS, false); player:instanceEntry(target,1); return; elseif (v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50) then player:messageText(target,MEMBER_TOO_FAR, false); player:instanceEntry(target,1); return; end end end end player:createInstance(58, 77); elseif(nashmeirasPlea == 1) then local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if (v:getID() ~= player:getID()) then if (v:hasKeyItem(MYTHRIL_MIRROR) == false and v:hasCompletedMission(TOAU, NASHMEIRAS_PLEA) == false) then player:messageText(target,MEMBER_NO_REQS, false); player:instanceEntry(target,1); return; elseif (v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50) then player:messageText(target,MEMBER_TOO_FAR, false); player:instanceEntry(target,1); return; end end end end player:createInstance(59, 77); else local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if (v:getID() ~= player:getID()) then if (not (v:hasKeyItem(NYZUL_ISLE_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then print("NO REQS"); player:messageText(target,MEMBER_NO_REQS, false); player:instanceEntry(target,1); return; elseif (v:getZoneID() == player:getZoneID() and v:checkDistance(player) > 50) then player:messageText(target,MEMBER_TOO_FAR, false); player:instanceEntry(target,1); return; end end end end player:createInstance(player:getCurrentAssault(), 77); end end; function onEventFinish(player,csid,option,target) -- printf("FINISH CSID: %u",csid); -- printf("FINISH RESULT: %u",option); if (csid == 405 and option == 1073741824 and player:getVar("NyzulReady") == 1) then player:startEvent(116, 2); -- This means the event was force terminated. Loop into the entrance animation. elseif (csid == 116 or (csid == 405 and option == 4) and not(option == 1073741824)) then player:setPos(0,0,0,0,77); end end; function onInstanceCreated(player,target,instance) local pathOfDarkness = player:getVar("PathOfDarkness"); local nashmeirasPlea = player:getVar("NashmeirasPlea"); if (instance) then if (pathOfDarkness == 1) then player:setVar("PathOfDarkness", 0); player:delKeyItem(NYZUL_ISLE_ROUTE); elseif (nashmeirasPlea == 1) then player:setVar("NashmeirasPlea", 0); player:delKeyItem(MYTHRIL_MIRROR); else instance:setLevelCap(player:getVar("AssaultCap")); player:setVar("AssaultCap", 0); player:delKeyItem(NYZUL_ISLE_ASSAULT_ORDERS); player:delKeyItem(ASSAULT_ARMBAND); end player:setInstance(instance); player:instanceEntry(target,4); local party = player:getParty(); if (party ~= nil) then for i,v in ipairs(party) do if v:getID() ~= player:getID() and v:getZoneID() == player:getZoneID() then v:setInstance(instance); v:startEvent(116, 2); if (pathOfDarkness == 1) then v:delKeyItem(NYZUL_ISLE_ROUTE); elseif (nashmeirasPlea == 1) then v:delKeyItem(MYTHRIL_MIRROR); else v:delKeyItem(NYZUL_ISLE_ASSAULT_ORDERS); end end end end else player:messageText(target,CANNOT_ENTER, false); player:instanceEntry(target,3); end -- EventUpdate Hack: 2nd latch player:setVar("NyzulReady",1); end;
gpl-3.0
LuaDist2/gntp
src/lua/gntp/connector/lluv.lua
2
2831
------------------------------------------------------------------ -- -- Author: Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Copyright (C) 2015-2016 Alexey Melnichuk <alexeymelnichuck@gmail.com> -- -- Licensed according to the included 'LICENSE' document -- -- This file is part of lua-gntp library. -- ------------------------------------------------------------------ local GNTP = require "gntp" local uv = require "lluv" local ut = require "gntp.utils" local Connector = ut.class() do local EOF = uv.error('LIBUV', uv.EOF) function Connector:__init(app, opt) if getmetatable(app) ~= GNTP.Application then app = GNTP.Application.new(app) end opt = opt or {} self._host = opt.host or "127.0.0.1" self._port = opt.port or "23053" self._enc = opt.encrypt or 'NONE' self._hash = opt.hash or 'MD5' self._pass = opt.pass or '' self._timeout = opt.timeout self._app = app return self end function Connector:_send(msg, only_last, cb) local parser = GNTP.Parser.new() local timer, last_msg, encoded local cli = uv.tcp():connect(self._host, self._port, function(cli, err) if err then cli:close() return cb(self, err) end cli:write(encoded) cli:start_read(function(cli, err, data) if err then cli:close() if timer then timer:close() end if err == EOF then cb(self, nil, last_msg) else cb(self, err) end return end local resp, err = parser:append(data):next_message() if resp == true then return end if not resp then cli:close() if timer then timer:close() end return cb(self, err) end if only_last then if resp:status() == 'END' then cb(self, nil, last_msg) last_msg = nil else last_msg = resp end else cb(self, nil, resp) end end) end) local err encoded, err = msg:encode(self._pass, self._hash, self._enc) if not encoded then cli:close() uv.defer(cb, self, err) end if self._timeout then timer = uv.timer():start(self._timeout, function() timer:close() cli:close() cb(self, "timeout") end) end end function Connector:register(opt, cb) if type(opt) == 'function' then opt, cb = nil, opt end local msg = self._app:register(opt) self:_send(msg, true, cb) end local function opt_add(msg, h, v) if v ~= nil then msg:add_header(h, v) end end function Connector:notify(name, opt, cb) if type(opt) == 'function' then cb, opt = opt end local msg, err = self._app:notify(name, opt) if not msg then uv.defer(cb, self, err) else self:_send(msg, true, cb) end end end return setmetatable({ new = Connector.new },{__call = function(self, ...) return self.new(...) end})
mit
ccyphers/kong
kong/plugins/key-auth/handler.lua
1
4280
local cache = require "kong.tools.database_cache" local responses = require "kong.tools.responses" local constants = require "kong.constants" local singletons = require "kong.singletons" local BasePlugin = require "kong.plugins.base_plugin" local ngx_set_header = ngx.req.set_header local ngx_get_headers = ngx.req.get_headers local set_uri_args = ngx.req.set_uri_args local get_uri_args = ngx.req.get_uri_args local clear_header = ngx.req.clear_header local type = type local _realm = 'Key realm="'.._KONG._NAME..'"' local KeyAuthHandler = BasePlugin:extend() KeyAuthHandler.PRIORITY = 1000 function KeyAuthHandler:new() KeyAuthHandler.super.new(self, "key-auth") end local function load_credential(key) local creds, err = singletons.dao.keyauth_credentials:find_all { key = key } if not creds then return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return creds[1] end local function load_consumer(consumer_id, anonymous) local result, err = singletons.dao.consumers:find { id = consumer_id } if not result then if anonymous and not err then err = 'anonymous consumer "'..consumer_id..'" not found' end return responses.send_HTTP_INTERNAL_SERVER_ERROR(err) end return result end local function set_consumer(consumer, credential) ngx_set_header(constants.HEADERS.CONSUMER_ID, consumer.id) ngx_set_header(constants.HEADERS.CONSUMER_CUSTOM_ID, consumer.custom_id) ngx_set_header(constants.HEADERS.CONSUMER_USERNAME, consumer.username) ngx.ctx.authenticated_consumer = consumer if credential then ngx_set_header(constants.HEADERS.CREDENTIAL_USERNAME, credential.username) ngx.ctx.authenticated_credential = credential ngx_set_header(constants.HEADERS.ANONYMOUS, nil) -- in case of auth plugins concatenation else ngx_set_header(constants.HEADERS.ANONYMOUS, true) end end local function do_authentication(conf) if type(conf.key_names) ~= "table" then ngx.log(ngx.ERR, "[key-auth] no conf.key_names set, aborting plugin execution") return false, {status = 500, message= "Invalid plugin configuration"} end local key local headers = ngx_get_headers() local uri_args = get_uri_args() -- search in headers & querystring for i = 1, #conf.key_names do local name = conf.key_names[i] local v = headers[name] if not v then -- search in querystring v = uri_args[name] end if type(v) == "string" then key = v if conf.hide_credentials then uri_args[name] = nil set_uri_args(uri_args) clear_header(name) end break elseif type(v) == "table" then -- duplicate API key, HTTP 401 return false, {status = 401, message = "Duplicate API key found"} end end -- this request is missing an API key, HTTP 401 if not key then ngx.header["WWW-Authenticate"] = _realm return false, {status = 401, message = "No API key found in headers" .." or querystring"} end -- retrieve our consumer linked to this API key local credential = cache.get_or_set(cache.keyauth_credential_key(key), nil, load_credential, key) -- no credential in DB, for this key, it is invalid, HTTP 403 if not credential then return false, {status = 403, message = "Invalid authentication credentials"} end ----------------------------------------- -- Success, this request is authenticated ----------------------------------------- -- retrieve the consumer linked to this API key, to set appropriate headers local consumer = cache.get_or_set(cache.consumer_key(credential.consumer_id), nil, load_consumer, credential.consumer_id) set_consumer(consumer, credential) return true end function KeyAuthHandler:access(conf) KeyAuthHandler.super.access(self) local ok, err = do_authentication(conf) if not ok then if conf.anonymous ~= "" then -- get anonymous user local consumer = cache.get_or_set(cache.consumer_key(conf.anonymous), nil, load_consumer, conf.anonymous, true) set_consumer(consumer, nil) else return responses.send(err.status, err.message) end end end return KeyAuthHandler
apache-2.0
Ninjistix/darkstar
scripts/globals/items/slice_of_lynx_meat.lua
3
1088
----------------------------------------- -- ID: 5667 -- Item: Slice of Lynx Meat -- Food Effect: 5 Min, Galka only ----------------------------------------- -- Strength 5 -- Intelligence -7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 8) then result = 247; end if (target:getMod(MOD_EAT_RAW_MEAT) == 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5667); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_INT, -7); end; function onEffectLose(target, effect) target:delMod(MOD_STR, 5); target:delMod(MOD_INT, -7); end;
gpl-3.0
PetarTilevRusev/EndlessWar
game/scripts/vscripts/units/human/human_upgrades.lua
1
6749
function ApplyKingUpgrade( event ) local caster = event.caster -- Saving the Caster Handle local ability = event.ability -- Saving The Ability Handle local ability_name = ability:GetName() local modifier_name = ability_name.."_modifier" ability:ApplyDataDrivenModifier(caster, caster, modifier_name, nil) if ability_name == "human_king_health_upgrade" then ApplyHealthUpgrade( caster, ability ) end SetStackCount( caster, caster, modifier_name) end -- Applues upgrades from the Barracks function UpgradeUnit( event ) local caster = event.caster local ability = event.ability local ability_level = ability:GetLevel() local ability_name = ability:GetName() --Don't upgrade if the ability is maxed and replace it with empty one if ability_level == 3 then caster:RemoveAbility(ability_name) caster:AddAbility(ability_name.."_disabled"):SetLevel(ability_level + 1) else ability:SetLevel(ability_level + 1) end end function ApplyBuildingUpgrade( event ) local caster = event.caster local caster_name = caster:GetUnitName() local ability = event.ability local ability_level = ability:GetLevel() local ability_name = ability:GetName() if caster_name == "human_melee_barracks" then if ability_level == 3 then caster:FindAbilityByName("human_siege_engine_disabled"):SetLevel(1) caster:RemoveAbility("human_melee_barracks_upgrade") caster:AddAbility("human_melee_barracks_upgrade_disabled"):SetLevel(4) elseif ability_level == 2 then caster:FindAbilityByName("human_knight_upgrade"):SetLevel(1) caster:FindAbilityByName("human_melee_barracks_upgrade"):SetLevel(3) elseif ability_level == 1 then caster:FindAbilityByName("human_footman_upgrade"):SetLevel(1) caster:FindAbilityByName("human_melee_barracks_upgrade"):SetLevel(2) end end if caster_name == "human_ranged_barracks" then if ability_level == 3 then caster:FindAbilityByName("human_priest_upgrade"):SetLevel(1) caster:RemoveAbility("human_ranged_barracks_upgrade") caster:AddAbility("human_ranged_barracks_upgrade_disabled"):SetLevel(4) elseif ability_level == 2 then caster:FindAbilityByName("human_sorcerer_upgrade"):SetLevel(1) caster:FindAbilityByName("human_ranged_barracks_upgrade"):SetLevel(3) elseif ability_level == 1 then caster:FindAbilityByName("human_rifleman_upgrade"):SetLevel(1) caster:FindAbilityByName("human_ranged_barracks_upgrade"):SetLevel(2) end end end -- Applyes upgrades from the Balacksmith function ApplyBlacksmithUpgrade( event ) local caster = event.caster local ability = event.ability local ability_name = ability:GetName() local ability_level = ability:GetLevel() local modifier_name = ability_name.."_modifier" ability:SetLevel(ability_level + 1) caster:SetModifierStackCount(modifier_name, caster, (ability_level - 1)) -- Loop trough the guard and apply the datadriven modifier for _,guard in pairs(humanMeleeGuards) do -- Check if the guard is alive if IsValidEntity(guard) then ability:ApplyDataDrivenModifier(caster, guard, modifier_name, nil) if ability_name == "human_units_health_upgrade" then ApplyHealthUpgrade( guard, ability ) end SetStackCount( caster, guard, modifier_name) end end for _,guard in pairs(humanRangedGuards) do -- Check if the guard is alive if IsValidEntity(guard) then ability:ApplyDataDrivenModifier(caster, guard, modifier_name, nil) if ability_name == "human_units_health_upgrade" then ApplyHealthUpgrade( guard, ability ) end SetStackCount( caster, guard, modifier_name) end end end -- Adds the ability from Research Facility to the guards function AddAbilityToGuard( event ) local caster = event.caster local ability = event.ability local ability_name = ability:GetName() local ability_level = ability:GetLevel() if ability_name == "human_strength_upgrade" then -- Add human_strength ability melee to the guards for _,guard in pairs(humanMeleeGuards) do -- Check if the guard is alive if IsValidEntity(guard) then if guard:HasAbility("human_strength") then guard:FindAbilityByName("human_strength"):SetLevel( ability_level + 1) else guard:AddAbility("human_strength"):SetLevel( ability_level + 1) end end end elseif ability_name == "knight_strike_upgrade" then -- Add human_knight_strike ability melee to the guards for _,guard in pairs(humanMeleeGuards) do -- Check if the guard is alive if IsValidEntity(guard) then if guard:HasAbility("human_knight_strike") then guard:FindAbilityByName("human_knight_strike"):SetLevel( ability_level + 1) else guard:AddAbility("human_knight_strike"):SetLevel( ability_level + 1) end end end elseif ability_name == "eagle_eye_upgrade" then -- Add eagle_eye ability to the ranged guards for _,guard in pairs(humanRangedGuards) do -- Check if the guard is alive if IsValidEntity(guard) then if guard:HasAbility("eagle_eye") then guard:FindAbilityByName("eagle_eye"):SetLevel( ability_level + 1) else guard:AddAbility("eagle_eye"):SetLevel( ability_level + 1) end end end end -- Level up the ability and if it's maxed then remove it. if ability_level == 3 then caster:RemoveAbility(ability_name) else ability:SetLevel(ability_level + 1) end end function ApplyHealthUpgrade( unit, ability ) local health_bonus = ability:GetLevelSpecialValueFor("health", ability:GetLevel()) local max_health = unit:GetMaxHealth() local current_health = unit:GetHealth() unit:SetMaxHealth(max_health + health_bonus) unit:SetHealth(current_health + health_bonus) end function SetStackCount( caster, unit, modifier ) if unit:HasModifier(modifier) then local stack_count = unit:GetModifierStackCount(modifier, caster) unit:SetModifierStackCount(modifier, caster, (stack_count + 1)) else unit:SetModifierStackCount(modifier, caster, 1) end end
mit
Ninjistix/darkstar
scripts/zones/Northern_San_dOria/npcs/Arachagnon.lua
5
1577
----------------------------------- -- Area: Northern San d'Oria -- NPC: Arachagnon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) player:showText(npc,ARACHAGNON_SHOP_DIALOG); local stock = {0x3159,270, --Elvaan Jerkin 0x315a,270, --Elvaan Bodice 0x31d3,162, --Elvaan Gloves 0x31d7,162, --Elvaan Gauntlets 0x3255,234, --Elvaan M Chausses 0x3259,234, --Elvaan F Chausses 0x32ce,162, --Elvaan M Ledelsens 0x32d3,162} --Elvaan F Ledelsens showShop(player, SANDORIA, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
wangyi0226/skynet
lualib/http/internal.lua
3
7689
local table = table local type = type 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 local function recvbody(interface, code, header, body) local length = header["content-length"] if length then length = tonumber(length) end if length then if #body >= length then body = body:sub(1,length) else local padding = interface.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 else -- no content-length, read all body = body .. interface.readall() end return body end function M.request(interface, method, host, url, recvheader, header, content) 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("Recv header failed") 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 return code, body, header end function M.response(interface, code, body, header) 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(interface.read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode body = recvbody(interface, code, header, body) end return body end local stream = {}; stream.__index = stream function stream:close() if self._onclose then self._onclose(self) self._onclose = nil end end function stream:padding() return self._reading(self), self end stream.__close = stream.close stream.__call = stream.padding local function stream_nobody(stream) stream._reading = stream.close stream.connected = nil return "" end local function stream_length(length) return function(stream) local body = stream._body if body == nil then local ret, padding = stream._interface.read() if not ret then -- disconnected body = padding stream.connected = false else body = ret end end local n = #body if n >= length then stream._reading = stream.close stream.connected = nil return (body:sub(1,length)) else length = length - n stream._body = nil if not stream.connected then stream._reading = stream.close end return body end end end local function stream_read(stream) local ret, padding = stream._interface.read() if ret == "" or not ret then stream.connected = nil stream:close() if padding == "" then return end return padding end return ret end local function stream_all(stream) local body = stream._body stream._body = nil stream._reading = stream_read return body end local function stream_chunked(stream) local read = stream._interface.read local sz, body = chunksize(read, stream._body) if not sz then stream.connected = false stream:close() return end if sz == 0 then -- last chunk local tmpline = {} body = M.recvheader(read, tmpline, body) if not body then stream.connected = false stream:close() return end M.parseheader(tmpline,1, stream.header) stream._reading = stream.close stream.connected = nil return "" end local n = #body local remain if n >= sz then remain = body:sub(sz+1) body = body:sub(1,sz) else body = body .. read(sz - n) remain = "" end remain = readcrln(read, remain) if not remain then stream.connected = false stream:close() return end stream._body = remain return body end function M.response_stream(interface, code, body, header) local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end local read_func if mode == "chunked" then read_func = stream_chunked else -- identity mode local length = header["content-length"] if length then length = tonumber(length) end if length then read_func = stream_length(length) elseif code == 204 or code == 304 or code < 200 then read_func = stream_nobody else read_func = stream_all end end -- todo: timeout return setmetatable({ status = code, _body = body, _interface = interface, _reading = read_func, header = header, connected = true, }, stream) end return M
mit
AlexisBRENON/awesome
spec/wibox/layout/flex_spec.lua
9
2771
--------------------------------------------------------------------------- -- @author Uli Schlachter -- @copyright 2014 Uli Schlachter --------------------------------------------------------------------------- local flex = require("wibox.layout.flex") local utils = require("wibox.test_utils") describe("wibox.layout.flex", function() local layout before_each(function() layout = flex.vertical() end) before_each(utils.stub_draw_widget) after_each(utils.revert_draw_widget) it("empty layout fit", function() assert.widget_fit(layout, { 10, 10 }, { 0, 0 }) utils.check_widgets_drawn({}) end) it("empty layout draw", function() layout:draw(nil, nil, 0, 0) end) describe("with widgets", function() local first, second, third before_each(function() first = utils.widget_stub(10, 10) second = utils.widget_stub(15, 15) third = utils.widget_stub(10, 10) layout:add(first) layout:add(second) layout:add(third) end) describe("with enough space", function() it("fit", function() assert.widget_fit(layout, { 100, 100 }, { 15, 35 }) end) it("draw", function() layout:draw("wibox", "cr", 100, 100) utils.check_widgets_drawn({ { first, 0, 0, 100, 33 }, { second, 0, 33, 100, 33 }, { third, 0, 67, 100, 33 }, }) end) end) describe("without enough height", function() it("fit", function() -- XXX: Is this really what should happen? assert.widget_fit(layout, { 5, 100 }, { 15, 35 }) end) it("draw", function() layout:draw("wibox", "cr", 5, 100) utils.check_widgets_drawn({ { first, 0, 0, 5, 33 }, { second, 0, 33, 5, 33 }, { third, 0, 67, 5, 33 }, }) end) end) describe("without enough width", function() it("fit", function() -- XXX: Is this really what should happen? assert.widget_fit(layout, { 100, 20 }, { 15, 35 }) end) it("draw", function() layout:draw("wibox", "cr", 100, 20) utils.check_widgets_drawn({ { first, 0, 0, 100, 6 }, { second, 0, 7, 100, 6 }, { third, 0, 13, 100, 6 }, }) end) end) end) end) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
Ninjistix/darkstar
scripts/globals/items/plate_of_piscators_paella.lua
3
1226
----------------------------------------- -- ID: 5969 -- Item: Plate of Piscator's Paella -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- HP 45 -- Dexterity 6 -- Accuracy % 16 (cap 85) -- Undead Killer 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5969); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 45); target:addMod(MOD_DEX, 6); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_FOOD_ACC_CAP, 85); target:addMod(MOD_UNDEAD_KILLER, 6); end; function onEffectLose(target, effect) target:delMod(MOD_HP, 45); target:delMod(MOD_DEX, 6); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_FOOD_ACC_CAP, 85); target:delMod(MOD_UNDEAD_KILLER, 6); end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Metalworks/npcs/Hugues.lua
3
1463
----------------------------------- -- Area: Metalworks -- NPC: Hugues -- 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"); ----------------------------------- function onTrade(player,npc,trade) end; 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(104,SkillCap,SkillLevel,1,207,player:getGil(),0,4095,0); else player:startEvent(104,SkillCap,SkillLevel,1,207,player:getGil(),7101,4095,0); end else player:startEvent(104); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 104 and option == 1) then player:messageSpecial(SMITHING_SUPPORT,0,2,1); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,1,0,120); end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/RuLude_Gardens/npcs/Maat.lua
4
9528
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Maat -- Starts and Finishes Quest: Limit Break Quest 1-5 -- Involved in Quests: Beat Around the Bushin -- @zone 243 -- !pos 8 3 118 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) local tradeCount = trade:getItemCount(); if (player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then -- Trade Bomb Coal / Exoray Mold / Ancient Papyrus if (trade:hasItemQty(1090,1) and trade:hasItemQty(1089,1) and trade:hasItemQty(1088,1) and tradeCount == 3) then player:startEvent(81); -- Finish Quest "In Defiant Challenge" end end if (player:getQuestStatus(JEUNO,SHATTERING_STARS) ~= QUEST_AVAILABLE and player:getMainLvl() >= 66 and player:getVar("maatsCap") < 1) then local mJob = player:getMainJob(); if (trade:hasItemQty(1425 + mJob,1) and tradeCount == 1 and mJob <= 15) then player:startEvent(64,mJob); -- Teleport to battlefield for "Shattering Stars" end end end; function onTrigger(player,npc) local LvL = player:getMainLvl(); local mJob = player:getMainJob(); local inDefiantChallenge = player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE); local atopTheHighestMountains = player:getQuestStatus(JEUNO,ATOP_THE_HIGHEST_MOUNTAINS); local whenceBlowsTheWind = player:getQuestStatus(JEUNO,WHENCE_BLOWS_THE_WIND); local ridingOnTheClouds = player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS); local shatteringStars = player:getQuestStatus(JEUNO,SHATTERING_STARS); if (player:getVar("BeatAroundTheBushin") == 5) then player:startEvent(117); elseif (inDefiantChallenge == QUEST_AVAILABLE and LvL >= 50 and player:levelCap() == 50 and MAX_LEVEL >= 55) then player:startEvent(79); -- Start Quest "In Defiant Challenge" elseif (inDefiantChallenge == QUEST_ACCEPTED) then player:startEvent(80); -- During Quest "In Defiant Challenge" elseif (atopTheHighestMountains == QUEST_AVAILABLE and LvL >= 51 and player:levelCap() == 55 and MAX_LEVEL >= 60) then player:startEvent(82); -- Start Quest "Atop the Highest Mountains" elseif (atopTheHighestMountains == QUEST_ACCEPTED) then if (player:hasKeyItem(ROUND_FRIGICITE) and player:hasKeyItem(SQUARE_FRIGICITE) and player:hasKeyItem(TRIANGULAR_FRIGICITE)) then player:startEvent(84); -- Finish Quest "Atop the Highest Mountains" else player:startEvent(83); -- During Quest "Atop the Highest Mountains" end elseif (whenceBlowsTheWind == QUEST_AVAILABLE and LvL >= 56 and player:levelCap() == 60 and MAX_LEVEL >= 65) then player:startEvent(85); -- Start Quest "Whence Blows the Wind" elseif (whenceBlowsTheWind == QUEST_ACCEPTED) then if (player:hasKeyItem(ORCISH_CREST) and player:hasKeyItem(QUADAV_CREST) and player:hasKeyItem(YAGUDO_CREST)) then player:startEvent(87); -- Finish Quest "Whence Blows the Wind" else player:startEvent(86); -- During Quest "Whence Blows the Wind" end elseif (ridingOnTheClouds == QUEST_AVAILABLE and LvL >= 61 and player:levelCap() == 65 and MAX_LEVEL >= 70) then rand1 = math.random(0,7); rand2 = math.random(0,7); rand3 = math.random(0,7); rand4 = math.random(0,7); player:setVar("ridingOnTheClouds_1",rand1 + 1); player:setVar("ridingOnTheClouds_2",rand2 + 1); player:setVar("ridingOnTheClouds_3",rand3 + 1); player:setVar("ridingOnTheClouds_4",rand4 + 1); player:startEvent(88,rand1,rand2,rand4,rand3,180); -- Start Quest "Riding on the Clouds" elseif (ridingOnTheClouds == QUEST_ACCEPTED) then if (player:hasKeyItem(SMILING_STONE) and player:hasKeyItem(SCOWLING_STONE) and player:hasKeyItem(SOMBER_STONE) and player:hasKeyItem(SPIRITED_STONE)) then player:startEvent(90); -- Finish Quest "Riding on the Clouds" else rand1 = player:getVar("ridingOnTheClouds_1") ; rand2 = player:getVar("ridingOnTheClouds_2"); rand3 = player:getVar("ridingOnTheClouds_3"); rand4 = player:getVar("ridingOnTheClouds_4"); if (rand1 == 0) then rand1 = 8; else rand1 = rand1 - 1; end if (rand2 == 0) then rand2 = 8; else rand2 = rand2 - 1; end if (rand3 == 0) then rand3 = 8; else rand3 = rand3 - 1; end if (rand4 == 0) then rand4 = 8; else rand4 = rand4 - 1; end player:startEvent(89,rand1,rand2,rand4,rand3,180); -- During Quest "Riding on the Clouds" end elseif (shatteringStars == QUEST_AVAILABLE and LvL >= 66 and mJob <= 15 and player:levelCap() == 70 and MAX_LEVEL >= 75) then player:startEvent(92,player:getMainJob()); -- Start Quest "Shattering Stars" elseif (shatteringStars == QUEST_ACCEPTED and LvL >= 66 and mJob <= 15 and player:getVar("maatDefeated") == 0) then player:startEvent(91,player:getMainJob()); -- During Quest "Shattering Stars" elseif (shatteringStars == QUEST_ACCEPTED and LvL >= 66 and mJob <= 15 and player:getVar("maatDefeated") >= 1) then player:startEvent(93); -- Finish Quest "Shattering Stars" elseif (player:getQuestStatus(JEUNO,BEYOND_THE_SUN) == QUEST_AVAILABLE and mJob <= 15 and player:getVar("maatsCap") == 32767) then player:startEvent(74); -- Finish Quest "Beyond The Sun" else player:showText(npc,MAAT_DIALOG); end end; -- Maat cap: 74 function onEventUpdate(player,csid,option) -- printf("upCSID: %u",csid); -- printf("upRESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 117) then player:setVar("BeatAroundTheBushin",6); -- Genkai 1 elseif (csid == 79 and option == 1) then player:addQuest(JEUNO,IN_DEFIANT_CHALLENGE); elseif (csid == 81) then player:tradeComplete(); player:addTitle(HORIZON_BREAKER); player:levelCap(55); player:completeQuest(JEUNO,IN_DEFIANT_CHALLENGE); player:addFame(JEUNO, 30); -- Genkai 2 elseif (csid == 82 and option == 1) then player:addQuest(JEUNO,ATOP_THE_HIGHEST_MOUNTAINS); elseif (csid == 84) then player:addTitle(SUMMIT_BREAKER); player:delKeyItem(ROUND_FRIGICITE); player:delKeyItem(SQUARE_FRIGICITE); player:delKeyItem(TRIANGULAR_FRIGICITE); player:levelCap(60); player:messageSpecial(YOUR_LEVEL_LIMIT_IS_NOW_60); player:completeQuest(JEUNO,ATOP_THE_HIGHEST_MOUNTAINS); player:addFame(JEUNO, 40); -- Genkai 3 elseif (csid == 85 and option == 1) then player:addQuest(JEUNO,WHENCE_BLOWS_THE_WIND); elseif (csid == 87) then player:addTitle(SKY_BREAKER); player:delKeyItem(ORCISH_CREST); player:delKeyItem(QUADAV_CREST); player:delKeyItem(YAGUDO_CREST); player:levelCap(65); player:messageSpecial(YOUR_LEVEL_LIMIT_IS_NOW_65); player:completeQuest(JEUNO,WHENCE_BLOWS_THE_WIND); player:addFame(JEUNO, 50); elseif (csid == 88) then if (option == 1) then player:addQuest(JEUNO,RIDING_ON_THE_CLOUDS); else player:setVar("ridingOnTheClouds_1",0); player:setVar("ridingOnTheClouds_2",0); player:setVar("ridingOnTheClouds_3",0); player:setVar("ridingOnTheClouds_4",0); end elseif (csid == 90) then player:addTitle(CLOUD_BREAKER); player:delKeyItem(SMILING_STONE); player:delKeyItem(SCOWLING_STONE); player:delKeyItem(SOMBER_STONE); player:delKeyItem(SPIRITED_STONE); player:levelCap(70); player:messageSpecial(YOUR_LEVEL_LIMIT_IS_NOW_70); player:completeQuest(JEUNO,RIDING_ON_THE_CLOUDS); player:addFame(JEUNO, 60); elseif (csid == 92) then player:addQuest(JEUNO,SHATTERING_STARS); elseif (csid == 64 and option == 1) then local mJob = player:getMainJob(); if (mJob == 2 or mJob == 3 or mJob == 15) then player:setPos(299.316,-123.591,353.760,66,146); elseif (mJob == 1 or mJob == 4 or mJob == 11) then player:setPos(-511.459,159.004,-210.543,10,139); elseif (mJob == 7 or mJob == 8 or mJob == 10) then player:setPos(-225.146,-24.250,20.057,255,206); elseif (mJob == 5 or mJob == 6 or mJob == 9) then player:setPos(-349.899,104.213,-260.150,0,144); elseif (mJob == 12 or mJob == 13 or mJob == 14) then player:setPos(-220.084,-0.645,4.442,191,168); end elseif (csid == 93) then player:addTitle(STAR_BREAKER); player:levelCap(75); player:setVar("maatDefeated",0); player:messageSpecial(YOUR_LEVEL_LIMIT_IS_NOW_75); player:completeQuest(JEUNO,SHATTERING_STARS); player:addFame(JEUNO, 80); elseif (csid==74) then if (player:getFreeSlotsCount() > 0) then player:completeQuest(JEUNO,BEYOND_THE_SUN); player:addTitle(ULTIMATE_CHAMPION_OF_THE_WORLD); player:setVar("maatsCap",0); player:addItem(15194); player:messageSpecial(ITEM_OBTAINED,15194); end end end;
gpl-3.0
hamrah12/hamrah_shoma
plugins/channels.lua
300
1680
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Channel isn\'t disabled' end _config.disabled_channels[receiver] = false save_config() return "Channel re-enabled" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Channel disabled" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is sudo then re-enable the channel if is_sudo(msg) then if msg.text == "!channel enable" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'enable' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'disable' then return disable_channel(receiver) end end return { description = "Plugin to manage channels. Enable or disable channel.", usage = { "!channel enable: enable current channel", "!channel disable: disable current channel" }, patterns = { "^!channel? (enable)", "^!channel? (disable)" }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
Ninjistix/darkstar
scripts/globals/weaponskills/scourge.lua
7
1930
----------------------------------- -- Scourge -- Great Sword weapon skill -- Skill level: N/A -- Additional effect: temporarily improves params.critical hit rate. -- params.critical hit rate boost duration is based on TP when the weapon skill is used. 100% TP will give 20 seconds of params.critical hit rate boost; this scales linearly to 60 seconds of params.critical hit rate boost at 300% TP. 5 TP = 1 Second of Aftermath. -- Parses show the params.critical hit rate increase from the Scourge Aftermath is between 10% and 15%. -- This weapon skill is only available with the stage 5 relic Great Sword Ragnarok or within Dynamis with the stage 4 Valhalla. -- Aligned with the Light Gorget & Flame Gorget. -- Aligned with the Light Belt & Flame Belt. -- Element: None -- Modifiers: STR:40% ; VIT:40% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; params.chr_wsc = 0.4; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.vit_wsc = 0.4; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Ninjistix/darkstar
scripts/zones/Sealions_Den/npcs/_0w0.lua
5
1453
----------------------------------- -- Area: Sealion's Den -- NPC: Iron Gate -- !pos 612 132 774 32 ----------------------------------- package.loaded["scripts/zones/Sealions_Den/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Sealions_Den/TextIDs"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/titles"); require("scripts/globals/bcnm"); ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; function onTrigger(player,npc) if (player:getCurrentMission(COP) == SLANDEROUS_UTTERINGS and player:getVar("PromathiaStatus") == 1) then player:startEvent(13); elseif (EventTriggerBCNM(player,npc)) then return; end end; function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); EventUpdateBCNM(player,csid,option) end; function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end if (csid == 13) then player:setVar("PromathiaStatus",0); player:completeMission(COP,SLANDEROUS_UTTERINGS); player:addMission(COP,THE_ENDURING_TUMULT_OF_WAR); player:addTitle(THE_LOST_ONE); end end;
gpl-3.0
drhelius/bstone-ios
dependencies/SDL-1bc5372ee27f/premake/projects/SDL2.lua
6
10613
-- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org> -- -- This software is provided 'as-is', without any express or implied -- warranty. In no event will the authors be held liable for any damages -- arising from the use of this software. -- -- Permission is granted to anyone to use this software for any purpose, -- including commercial applications, and to alter it and redistribute it -- freely. -- -- Meta-build system using premake created and maintained by -- Benjamin Henning <b.henning@digipen.edu> --[[ SDL2.lua This file provides the project definition for the entire SDL2 library, on all platforms supported by the meta-build system. That includes Windows, MinGW, Cygwin, Mac OS X, iOS, and Linux. This project is responsible for setting up the source trees and the complicated dependencies required to build the final SDL2 library. In order to simplify this process, the library is split into several different segments. Each segment focuses on a different dependency and series of configurations which are thrown into the generated config header file, used to build this project. ]] SDL_project "SDL2" SDL_isos "windows|mingw" -- all other bindings should be a shared library SDL_kind "SharedLib" SDL_isos "macosx|ios" -- macosx employs a static linking SDL_kind "StaticLib" -- the way premake generates project dependencies and how that affects linkage -- makes it difficult to use shared libraries on Linux. Cygwin has issues -- binding to GetProcAddress, so a static library is an easy fix. SDL_isos "linux|cygwin" SDL_kind "StaticLib" SDL_language "C++" SDL_sourcedir "../src" -- primary platforms SDL_isos "ios" SDL_platforms { "iOS" } SDL_isnotos "ios" SDL_platforms { "native" } -- additional platforms SDL_isos "macosx" SDL_platforms { "universal" } SDL_isos "windows|mingw" SDL_defines { "_WINDOWS" } -- Following is the dependency tree for SDL2 -- (no SDL_os call means platform-independent) -- The core and minimal of the SDL2 library. This will not quite build -- standalone, but it's doable with a bit of tweaking to build this using the -- minimal configuration header. This is a good start to adding SDL support to -- new platforms. SDL_config { ["SDL_AUDIO_DRIVER_DISK"] = 1, ["SDL_AUDIO_DRIVER_DUMMY"] = 1, ["SDL_VIDEO_DRIVER_DUMMY"] = 1 } SDL_paths { "/", "/atomic/", "/audio/", "/audio/disk/", "/audio/dummy/", "/cpuinfo/", "/dynapi/", "/events/", "/file/", "/haptic/", "/joystick/", "/power/", "/render/", "/render/software/", "/stdlib/", "/thread/", "/timer/", "/video/", "/video/dummy/" } -- SDL2 on Windows SDL_dependency "windows" SDL_os "windows|mingw" SDL_links { "imm32", "oleaut32", "winmm", "version" } -- these are the links that Visual Studio includes by default SDL_links { "kernel32", "user32", "gdi32", "winspool", "comdlg32", "advapi32", "shell32", "ole32", "oleaut32", "uuid", "odbc32", "odbccp32" } SDL_config { ["SDL_LOADSO_WINDOWS"] = 1, ["SDL_THREAD_WINDOWS"] = 1, ["SDL_TIMER_WINDOWS"] = 1, ["SDL_VIDEO_DRIVER_WINDOWS"] = 1, ["SDL_POWER_WINDOWS"] = 1, ["SDL_AUDIO_DRIVER_WINMM"] = 1, ["SDL_FILESYSTEM_WINDOWS"] = 1 } SDL_paths { "/audio/winmm/", "/core/windows/", "/libm/", "/loadso/windows/", "/power/windows/", "/thread/windows/", "/timer/windows/", "/video/windows/", "/filesystem/windows/" } SDL_files { -- these files have to be specified uniquely to avoid double -- and incorrect linking "/thread/generic/SDL_syscond.c", "/thread/generic/SDL_sysmutex_c.h" } -- DirectX dependency SDL_dependency "directx" SDL_os "windows|mingw" SDL_depfunc "DirectX" SDL_config { ["SDL_AUDIO_DRIVER_DSOUND"] = 1, ["SDL_AUDIO_DRIVER_XAUDIO2"] = 1, ["SDL_JOYSTICK_DINPUT"] = 1, ["SDL_HAPTIC_DINPUT"] = 1, ["SDL_VIDEO_RENDER_D3D"] = 1 } SDL_paths { "/audio/directsound/", "/audio/xaudio2/", "/render/direct3d/", -- these two depend on Xinput "/haptic/windows/", "/joystick/windows/", } -- in case DirectX was not found SDL_dependency "notdirectx" SDL_os "windows|mingw" SDL_notdepfunc "DirectX" SDL_config { -- enable dummy systems (same as disabling them) ["SDL_HAPTIC_DUMMY"] = 1, ["SDL_JOYSTICK_DUMMY"] = 1 } SDL_paths { -- since we don't have Xinput "/haptic/dummy/", "/joystick/dummy/", } -- OpenGL dependency SDL_dependency "opengl" SDL_depfunc "OpenGL" SDL_config { ["SDL_VIDEO_OPENGL"] = 1, ["SDL_VIDEO_RENDER_OGL"] = 1 } SDL_paths { "/render/opengl/" } -- WGL dependency for OpenGL on Windows SDL_dependency "opengl-windows" SDL_os "windows|mingw" SDL_depfunc "OpenGL" SDL_config { ["SDL_VIDEO_OPENGL_WGL"] = 1 } -- GLX dependency for OpenGL on Linux SDL_dependency "opengl-linux" SDL_os "linux" SDL_depfunc "OpenGL" SDL_config { ["SDL_VIDEO_OPENGL_GLX"] = 1 } -- SDL2 on Mac OS X SDL_dependency "macosx" SDL_os "macosx" SDL_config { ["SDL_AUDIO_DRIVER_COREAUDIO"] = 1, ["SDL_JOYSTICK_IOKIT"] = 1, ["SDL_HAPTIC_IOKIT"] = 1, ["SDL_LOADSO_DLOPEN"] = 1, ["SDL_THREAD_PTHREAD"] = 1, ["SDL_THREAD_PTHREAD_RECURSIVE_MUTEX"] = 1, ["SDL_TIMER_UNIX"] = 1, ["SDL_VIDEO_DRIVER_COCOA"] = 1, ["SDL_POWER_MACOSX"] = 1, ["SDL_FILESYSTEM_COCOA"] = 1 } SDL_paths { "/audio/coreaudio/", "/file/cocoa/", "/haptic/darwin/", "/joystick/darwin/", "/loadso/dlopen/", "/power/macosx/", "/render/opengl/", "/thread/pthread/", "/timer/unix/", "/video/cocoa/", "/video/x11/", "/filesystem/cocoa/" } SDL_links { "CoreVideo.framework", "AudioToolbox.framework", "AudioUnit.framework", "Cocoa.framework", "CoreAudio.framework", "IOKit.framework", "Carbon.framework", "ForceFeedback.framework", "CoreFoundation.framework" } -- Linux dependency: DLOpen SDL_dependency "linux-dlopen" SDL_os "linux" SDL_depfunc "DLOpen" SDL_paths { "/loadso/dlopen/" } SDL_config { ["SDL_LOADSO_DLOPEN"] = 1 } -- Linux dependency: ALSA SDL_dependency "linux-alsa" SDL_os "linux" SDL_depfunc "ALSA" SDL_paths { "/audio/alsa/" } SDL_config { ["SDL_AUDIO_DRIVER_ALSA"] = 1, ["SDL_AUDIO_DRIVER_ALSA_DYNAMIC"] = '"libasound.so"' } -- Linux dependency: PulseAudio SDL_dependency "linux-pulseaudio" SDL_os "linux" SDL_depfunc "PulseAudio" SDL_paths { "/audio/pulseaudio/" } SDL_config { ["SDL_AUDIO_DRIVER_PULSEAUDIO"] = 1, ["SDL_AUDIO_DRIVER_PULSEAUDIO_DYNAMIC"] = '"libpulse-simple.so"' } -- Linux dependency: ESD SDL_dependency "linux-esd" SDL_os "linux" SDL_depfunc "ESD" SDL_paths { "/audio/esd/" } SDL_config { ["SDL_AUDIO_DRIVER_ESD"] = 1, ["SDL_AUDIO_DRIVER_ESD_DYNAMIC"] = '"libesd.so"' } -- Linux dependency: NAS SDL_dependency "linux-nas" SDL_os "linux" SDL_depfunc "NAS" SDL_paths { "/audio/nas/" } SDL_config { ["SDL_AUDIO_DRIVER_NAS"] = 1, ["SDL_AUDIO_DRIVER_NAS_DYNAMIC"] = '"libaudio.so"' } -- Linux dependency: OSS SDL_dependency "linux-oss" SDL_os "linux" SDL_depfunc "OSS" SDL_paths { "/audio/dsp/" } SDL_config { ["SDL_AUDIO_DRIVER_OSS"] = 1 } -- Linux dependency: X11 SDL_dependency "linux-x11" SDL_os "linux" SDL_depfunc "X11" SDL_paths { "/video/x11/" } SDL_config { ["SDL_VIDEO_DRIVER_X11"] = 1, ["SDL_VIDEO_DRIVER_X11_DYNAMIC"] = '"libX11.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XEXT"] = '"libXext.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XCURSOR"] = '"libXcursor.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XINERAMA"] = '"libXinerama.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XINPUT2"] = '"libXi.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XRANDR"] = '"libXrandr.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XSS"] = '"libXss.so"', ["SDL_VIDEO_DRIVER_X11_DYNAMIC_XVIDMODE"] = '"libXxf86vm.so"', ["SDL_VIDEO_DRIVER_X11_XCURSOR"] = 1, ["SDL_VIDEO_DRIVER_X11_XINERAMA"] = 1, ["SDL_VIDEO_DRIVER_X11_XINPUT2"] = 1, ["SDL_VIDEO_DRIVER_X11_XINPUT2_SUPPORTS_MULTITOUCH"] = 1, ["SDL_VIDEO_DRIVER_X11_XRANDR"] = 1, ["SDL_VIDEO_DRIVER_X11_XSCRNSAVER"] = 1, ["SDL_VIDEO_DRIVER_X11_XSHAPE"] = 1, ["SDL_VIDEO_DRIVER_X11_XVIDMODE"] = 1, ["SDL_VIDEO_DRIVER_X11_SUPPORTS_GENERIC_EVENTS"] = 1, ["SDL_VIDEO_DRIVER_X11_CONST_PARAM_XEXTADDDISPLAY"] = 1, ["SDL_VIDEO_DRIVER_X11_HAS_XKBKEYCODETOKEYSYM"] = 1 } -- SDL2 on Linux SDL_dependency "linux" SDL_os "linux" SDL_depfunc "DBus" SDL_config { ["SDL_INPUT_LINUXEV"] = 1, ["SDL_JOYSTICK_LINUX"] = 1, ["SDL_HAPTIC_LINUX"] = 1, ["SDL_THREAD_PTHREAD"] = 1, ["SDL_THREAD_PTHREAD_RECURSIVE_MUTEX"] = 1, ["SDL_TIMER_UNIX"] = 1, ["SDL_POWER_LINUX"] = 1, ["SDL_FILESYSTEM_UNIX"] = 1, } SDL_paths { "/haptic/linux/", "/joystick/linux/", "/power/linux/", "/thread/pthread/", "/timer/unix/", "/filesystem/unix/" } SDL_links { "m", "pthread", "rt" } -- SDL2 on Cygwin (not quite working yet) SDL_dependency "cygwin" SDL_os "cygwin" SDL_config { ['SDL_JOYSTICK_DISABLED'] = 1, ['SDL_HAPTIC_DISABLED'] = 1, ['SDL_LOADSO_DLOPEN'] = 1, ['SDL_THREAD_PTHREAD'] = 1, ['SDL_THREAD_PTHREAD_RECURSIVE_MUTEX'] = 1, ['SDL_TIMER_UNIX'] = 1, ['SDL_FILESYSTEM_UNIX'] = 1, ['SDL_POWER_LINUX'] = 1 } SDL_paths { "/loadso/dlopen/", "/power/linux/", "/render/opengl/", "/thread/pthread/", "/timer/unix/", "/filesystem/unix/", "/libm/" } -- SDL2 on iOS SDL_dependency "iphoneos" SDL_os "ios" SDL_config { ["SDL_AUDIO_DRIVER_COREAUDIO"] = 1, ["SDL_JOYSTICK_DISABLED"] = 0, ["SDL_HAPTIC_DISABLED"] = 1, ["SDL_LOADSO_DISABLED"] = 1, ["SDL_THREAD_PTHREAD"] = 1, ["SDL_THREAD_PTHREAD_RECURSIVE_MUTEX"] = 1, ["SDL_TIMER_UNIX"] = 1, ["SDL_VIDEO_DRIVER_UIKIT"] = 1, ["SDL_VIDEO_OPENGL_ES"] = 1, ["SDL_VIDEO_RENDER_OGL_ES"] = 1, ["SDL_VIDEO_RENDER_OGL_ES2"] = 1, ["SDL_POWER_UIKIT"] = 1, ["SDL_IPHONE_KEYBOARD"] = 1, ["SDL_FILESYSTEM_COCOA"] = 1 } SDL_paths { "/audio/coreaudio/", "/file/cocoa/", "/joystick/iphoneos/", "/loadso/dlopen/", "/power/uikit/", "/render/opengles/", "/render/opengles2/", "/thread/pthread/", "/timer/unix/", "/video/uikit/", "/filesystem/cocoa/" } SDL_links { "$(SDKROOT)/AudioToolbox.framework", "$(SDKROOT)/QuartzCore.framework", "$(SDKROOT)/OpenGLES.framework", "$(SDKROOT)/CoreGraphics.framework", "$(SDKROOT)/UIKit.framework", "$(SDKROOT)/Foundation.framework", "$(SDKROOT)/CoreAudio.framework", "$(SDKROOT)/CoreMotion.framework" }
gpl-2.0
Ninjistix/darkstar
scripts/globals/mobskills/sledgehammer.lua
33
1219
--------------------------------------------- -- Sledgehammer -- -- Description: Delivers a sledgehammer blow to all targets in front. Additional effect: Petrification -- Type: Physical -- Utsusemi/Blink absorb: 3 shadows -- Range: Front cone -- Notes: Only used by Gurfurlur the Menacing. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1867) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 3.2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,3 * info.hitslanded); local typeEffect = EFFECT_PETRIFICATION; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/weaponskills/combo.lua
26
1453
----------------------------------- -- Combo -- Hand-to-Hand weapon skill -- Skill level: 5 -- Delivers a threefold attack. Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:20% ; DEX:20% -- 100%TP 200%TP 300%TP -- 1.00 1.50 2.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 3; params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2; params.str_wsc = 0.2; params.dex_wsc = 0.2; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 1; params.ftp200 = 3.75; params.ftp300 = 5.5; params.str_wsc = 0.3; params.dex_wsc = 0.3; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
otservme/global1051
data/npc/scripts/The Oracle.lua
28
3447
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) local vocation = {} local town = {} local destination = {} function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end local function greetCallback(cid) local level = getPlayerLevel(cid) if level < 8 then npcHandler:say("CHILD! COME BACK WHEN YOU HAVE GROWN UP!", cid) return false elseif level > 9 then npcHandler:say(getCreatureName(cid) .. ", I CAN'T LET YOU LEAVE - YOU ARE TOO STRONG ALREADY! YOU CAN ONLY LEAVE WITH LEVEL 9 OR LOWER.", cid) return false elseif getPlayerVocation(cid) > 0 then npcHandler:say("YOU ALREADY HAVE A VOCATION!", cid) return false end return true end local function creatureSayCallback(cid, type, msg) if not npcHandler:isFocused(cid) then return false elseif msgcontains(msg, "yes") and npcHandler.topic[cid] == 0 then npcHandler:say("IN WHICH TOWN DO YOU WANT TO LIVE: {RHYVES}?", cid) npcHandler.topic[cid] = 1 elseif npcHandler.topic[cid] == 1 then if msgcontains(msg, "rhyves") then town[cid] = 2 destination[cid] = {x = 159, y = 387, z = 6} npcHandler:say("IN RHYVES! AND WHAT PROFESSION HAVE YOU CHOSEN: {KNIGHT}, {PALADIN}, {SORCERER}, OR {DRUID}?", cid) npcHandler.topic[cid] = 2 else npcHandler:say("IN WHICH TOWN DO YOU WANT TO LIVE: {RHYVES}?", cid) end elseif npcHandler.topic[cid] == 2 then if msgcontains(msg, "sorcerer") then npcHandler:say("A SORCERER! ARE YOU SURE? THIS DECISION IS IRREVERSIBLE!", cid) npcHandler.topic[cid] = 3 vocation[cid] = 1 elseif msgcontains(msg, "druid") then npcHandler:say("A DRUID! ARE YOU SURE? THIS DECISION IS IRREVERSIBLE!", cid) npcHandler.topic[cid] = 3 vocation[cid] = 2 elseif msgcontains(msg, "paladin") then npcHandler:say("A PALADIN! ARE YOU SURE? THIS DECISION IS IRREVERSIBLE!", cid) npcHandler.topic[cid] = 3 vocation[cid] = 3 elseif msgcontains(msg, "knight") then npcHandler:say("A KNIGHT! ARE YOU SURE? THIS DECISION IS IRREVERSIBLE!", cid) npcHandler.topic[cid] = 3 vocation[cid] = 4 else npcHandler:say("{KNIGHT}, {PALADIN}, {SORCERER}, OR {DRUID}?", cid) end elseif npcHandler.topic[cid] == 3 then if msgcontains(msg, "yes") then npcHandler:say("SO BE IT!", cid) doPlayerSetVocation(cid, vocation[cid]) doPlayerSetTown(cid, town[cid]) local destination = destination[cid] npcHandler:releaseFocus(cid) doSendMagicEffect(getCreaturePosition(cid), CONST_ME_TELEPORT) doTeleportThing(cid, destination) doSendMagicEffect(destination, CONST_ME_TELEPORT) else npcHandler:say("THEN WHAT? {KNIGHT}, {PALADIN}, {SORCERER}, OR {DRUID}?", cid) npcHandler.topic[cid] = 2 end end return true end local function onAddFocus(cid) town[cid] = 0 vocation[cid] = 0 destination[cid] = 0 end local function onReleaseFocus(cid) town[cid] = nil vocation[cid] = nil destination[cid] = nil end npcHandler:setCallback(CALLBACK_ONADDFOCUS, onAddFocus) npcHandler:setCallback(CALLBACK_ONRELEASEFOCUS, onReleaseFocus) npcHandler:setCallback(CALLBACK_GREET, greetCallback) npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback) npcHandler:addModule(FocusModule:new())
gpl-2.0
Ninjistix/darkstar
scripts/globals/items/gold_lobster.lua
3
1155
----------------------------------------- -- ID: 5797 -- Item: gold_lobster -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 3 -- Defense % 16 (Cap 50) ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5797); end; function onEffectGain(target, effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 3); target:addMod(MOD_FOOD_DEFP, 16); target:addMod(MOD_FOOD_DEF_CAP, 50); end; function onEffectLose(target, effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 3); target:delMod(MOD_FOOD_DEFP, 16); target:delMod(MOD_FOOD_DEF_CAP, 50); end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/items/pipira.lua
3
1299
----------------------------------------- -- ID: 5787 -- Item: pipira -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 -- Attack % 14.5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5787); end; function onEffectGain(target, effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); target:addMod(MOD_FOOD_ATTP, 14); target:addMod(MOD_FOOD_ATT_CAP, 60); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 60); end; function onEffectLose(target, effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); target:delMod(MOD_FOOD_ATTP, 14); target:delMod(MOD_FOOD_ATT_CAP, 60); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 60); end;
gpl-3.0
ocurr/hammerspoon
extensions/doc/init.lua
8
14263
--- === hs.doc === --- --- Create documentation objects for interactive help within Hammerspoon --- --- The documentation object created is a table with tostring metamethods allowing access to a specific functions documentation by appending the path to the method or function to the object created. --- --- From the Hammerspoon console: --- --- doc = require("hs.doc").fromRegisteredFiles() --- doc.hs.application --- --- Results in: --- Manipulate running applications --- --- [submodules] --- hs.application.watcher --- --- [subitems] --- hs.application:activate([allWindows]) -> bool --- hs.application:allWindows() -> window[] --- ... --- hs.application:visibleWindows() -> win[] --- --- By default, the internal core documentation and portions of the Lua 5.3 manual, located at http://www.lua.org/manual/5.3/manual.html, are already registered for inclusion within this documentation object, but you can register additional documentation from 3rd party modules with `hs.registerJSONFile(...)` or limit the documentation to a single specific file with `hs.fromJSONFile(...)`. local module = {} -- private variables and methods ----------------------------------------- local json = require("hs.json") local fs = require("hs.fs") local fnutils = require("hs.fnutils") local sortFunction = function(m,n) -- sort function so lua manual toc sorts correctly if m:match("^_%d") and n:match("^_%d") then local a, b = fnutils.split(m:match("^_([^%s]+)"), "_"), fnutils.split(n:match("^_([^%s]+)"), "_") if tonumber(a[1]) ~= tonumber(b[1]) then return tonumber(a[1]) < tonumber(b[1]) elseif a[2] == nil then return true elseif b[2] == nil then return false elseif tonumber(a[2]) ~= tonumber(b[2]) then return tonumber(a[2]) < tonumber(b[2]) elseif a[3] == nil then return true elseif b[3] == nil then return false else return tonumber(a[3]) < tonumber(b[3]) end else return m < n end end local function item_tostring(item) return item[2] .. ": " .. item[1] .. "\n\n" .. item[3] .. "\n" end local function group_tostring(group) local str = group.__doc .. "\n\n" str = str .. "[submodules]\n" for name, item in fnutils.sortByKeys(group, sortFunction) do if name ~= '__doc' and name ~= '__name' and getmetatable(item) == getmetatable(group) then str = str .. item.__name .. "\n" end end str = str .. "\n" .. "[subitems]\n" for name, item in fnutils.sortByKeys(group, sortFunction) do if name ~= '__doc' and name ~= '__name' and getmetatable(item) ~= getmetatable(group) then str = str .. item[1] .. "\n" end end return str .. "\n" end local function doc_tostring(doc) local str = '[modules]\n' for name, group in fnutils.sortByKeys(doc, sortFunction) do str = str .. group.__name .. '\n' end return str end local group_metatable = {__tostring = group_tostring} local item_metatable = {__tostring = item_tostring} local internalBuild = function(rawdocs) local doc = setmetatable({}, {__tostring = doc_tostring}) for _, mod in pairs(rawdocs) do local parts = {} for s in string.gmatch(mod.name, "[%w_]+") do table.insert(parts, s) end local parent = doc local keyname = parts[#parts] parts[#parts] = nil local subname = nil for _, s in ipairs(parts) do subname = subname and subname.."."..s or s if type(parent[s]) == "nil" then parent[s] = setmetatable({__doc = subname, __name = subname}, group_metatable) end parent = parent[s] end local m = setmetatable({__doc = mod.doc, __name = mod.name}, group_metatable) parent[keyname] = m for _, item in pairs(mod.items) do m[item.name] = setmetatable({__name = item.name, item.def, item.type, item.doc}, item_metatable) end end return doc end local __tostring_for_arrays = function(self) local result = "" for i,v in fnutils.sortByKeyValues(self) do result = result..v.."\n" end return result end local registeredJSONFiles = setmetatable({ hs.docstrings_json_file, (hs.docstrings_json_file:gsub("/docs.json$","/extensions/hs/doc/lua.json")) }, {__tostring = __tostring_for_arrays}) local validateJSONFile = function(jsonFile) local f = io.open(jsonFile) if not f then return false, "Unable to open '"..jsonFile.."'" else local content = f:read("*a") f:close() return pcall(json.decode, content) end end -- Public interface ------------------------------------------------------ --- hs.doc.validateJSONFile(jsonfile) -> status, message|table --- Function --- Validate a JSON file potential inclusion in the Hammerspoon internal documentation. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was registered or not. --- * message|table - If the file did not contain valid JSON data, then a message indicating the error is returned; otherwise the parsed JSON data is returned as a table. module.validateJSONFile = function(jsonFile) local f = io.open(jsonFile) if not f then return false, "Unable to open '"..jsonFile.."'" else local content = f:read("*a") f:close() return pcall(json.decode, content) end end --- hs.doc.registerJSONFile(jsonfile) -> status[, message] --- Function --- Register a JSON file for inclusion when Hammerspoon generates internal documentation. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was registered or not. If the file was not registered, then a message indicating the error is also returned. module.registerJSONFile = function(docFile) if type(docFile) ~= "string" then -- most likely this was called with the result of the locateJSONFile function, -- and the locate function was unable to find the JSON file... return false, "Provided path is not a string." end local status, message = module.validateJSONFile(docFile) if status then local alreadyRegistered = false for _, v in ipairs(registeredJSONFiles) do if v == docFile then alreadyRegistered = true break end end if alreadyRegistered then return false, "File '"..docFile.."' already registered" end table.insert(registeredJSONFiles, docFile) return status end return status, message end --- hs.doc.unregisterJSONFile(jsonfile) -> status[, message] --- Function --- Remove a JSON file from the list of registered files. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * status - Boolean flag indicating if the file was unregistered or not. If the file was not unregistered, then a message indicating the error is also returned. module.unregisterJSONFile = function(docFile) local indexNumber, found = false for i, v in ipairs(registeredJSONFiles) do if v == docFile then found = true indexNumber = i break end end if found then table.remove(registeredJSONFiles, indexNumber) return true else return false, "File '"..docFile.."' was not registered" end end --- hs.doc.registeredFiles() -> table --- Function --- Returns the list of registered JSON files. --- --- Parameters: --- * None --- --- Returns: --- * a table containing the list of registered JSON files --- --- Notes: --- * The table returned by this function has a metatable including a __tostring method which allows you to see the list of registered files by simply typing `hs.doc.registeredFiles()` in the Hammerspoon Console. --- --- * By default, the internal core documentation and portions of the Lua 5.3 manual, located at http://www.lua.org/manual/5.3/manual.html, are already registered for inclusion within this documentation object. --- --- * You can unregister these defaults if you wish to start with a clean slate with the following commands: --- * `hs.doc.unregisterJSONFile(hs.docstrings_json_file)` -- to unregister the Hammerspoon API docs --- * `hs.doc.unregisterJSONFile((hs.docstrings_json_file:gsub("/docs.json$","/extensions/hs/doc/lua.json")))` -- to unregister the Lua 5.3 Documentation. module.registeredFiles = function(docFile) return registeredJSONFiles end --- hs.doc.locateJSONFile(module) -> path | false, message --- Function --- Locates the JSON file corresponding to the specified module by searching package.path and package.cpath. --- --- Parameters: --- * module - the name of the module to locate a JSON file for --- --- Returns: --- * the path to the JSON file, or `false, error` if unable to locate a corresponding JSON file. --- --- Notes: --- * The JSON should be named 'full.module.name.json' and located in the same directory as the `lua` or `so` file which is used when the module is loaded via `require`. module.locateJSONFile = function(moduleName) local asLua = package.searchpath(moduleName, package.path) local asC = package.searchpath(moduleName, package.cpath) if asLua then local pathPart = asLua:match("^(.*/).+%.lua$") if pathPart then if fs.attributes(pathPart..moduleName..".json") then return pathPart..moduleName..".json" else return false, "No JSON file for "..moduleName.." found" end else return false, "Unable to parse package.path for "..moduleName end elseif asC then local pathPart = asC:match("^(.*/).+%.so$") if pathPart then if fs.attributes(pathPart..moduleName..".json") then return pathPart..moduleName..".json" else return false, "No JSON file for "..moduleName.." found" end else return false, "Unable to parse package.cpath for "..moduleName end else return false, "Unable to locate module path for "..moduleName end end --- hs.doc.fromJSONFile(jsonfile) -> doc-array --- Function --- Builds a doc array construct from the JSON file provided. --- --- Parameters: --- * jsonfile - A string containing the location of a JSON file --- --- Returns: --- * A table containing the documentation data loaded from the JSON file function module.fromJSONFile(docsfile) local f = io.open(docsfile) if not f then print("Documentation file '"..docsfile.."' not found...") return setmetatable( {"Documentation file '"..docsfile.."' not found..."}, {__tostring = function(a) return a[1] end} ) end local content = f:read("*a") f:close() return internalBuild(json.decode(content)) end --- hs.doc.fromRegisteredFiles() -> doc-array --- Function --- Builds a doc array construct from the registered JSON files. --- --- Parameters: --- * None --- --- Returns: --- * A table containing the documentation data loaded from the registered JSON files --- --- Notes: --- * By default, the internal core documentation is already registered. If you wish to remove it from the list of registered sources, issue the command `hs.doc.unregisterJSONFile(hs.docstrings_json_file)`. --- * The documentation object is created from the sources that are registered at the time of its invocation. If you register additional files later, you will need to reissue this command to build the updated documentation object. function module.fromRegisteredFiles() local docData = {} for _, v in ipairs(registeredJSONFiles) do local f = io.open(v) if not f then print("Documentation file '"..docsfile.."' not found...") return setmetatable( {"Documentation file '"..docsfile.."' not found..."}, {__tostring = function(a) return a[1] end} ) end local content = f:read("*a") f:close() for _, j in pairs(json.decode(content)) do table.insert(docData, j) end end return internalBuild(docData) end local coredocs = module.fromRegisteredFiles() --- hs.doc.help(identifier) --- Function --- Prints the documentation for some part of Hammerspoon's API and Lua 5.3. This function has also been aliased as `hs.help` and `help` as a shorthand for use within the Hammerspoon console. --- --- Parameters: --- * identifier - A string containing the signature of some part of Hammerspoon's API (e.g. `"hs.reload"`) --- --- Returns: --- * None --- --- Notes: --- * This function is mainly for runtime API help while using Hammerspoon's Console --- * This function only returns information about the core Hammerspoon API and Lua 5.3. If you register additional files from 3rd party modules, or deregister the initial files for creating your own `hs.doc` objects, it will not affect the results used by this function. --- --- * You can also access the results of this function by the following methods from the console: --- * help("identifier") -- quotes are required, e.g. `help("hs.reload")` --- * help.identifier.path -- no quotes are required, e.g. `help.hs.reload` --- --- * Lua information can be accessed by using the `lua` prefix, rather than `hs`. --- * the identifier `lua._man` provides the table of contents for the Lua 5.3 manual. You can pull up a specific section of the lua manual by including the chapter (and subsection) like this: `lua._man._3_4_8`. --- * the identifier `lua._C` will provide information specifically about the Lua C API for use when developing modules which require external libraries. function module.help(identifier) local tree = coredocs local result = tree for word in string.gmatch(identifier, '([^.]+)') do result = result[word] end print(result) end -- Return Module Object -------------------------------------------------- return setmetatable(module, { __call = function(_, ...) return module.help(...) end, __index = coredocs, __tostring = function(obj) return tostring(coredocs) end, })
mit
Ninjistix/darkstar
scripts/zones/Valley_of_Sorrows/mobs/Adamantoise.lua
4
1554
----------------------------------- -- Area: Valley of Sorrows -- HNM: Adamantoise ----------------------------------- require("scripts/zones/Valley_of_Sorrows/MobIDs"); require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/titles"); function onMobInitialize(mob) end; function onMobSpawn(mob) if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(ADAMANTOISE_QM):setStatus(STATUS_DISAPPEAR); end end; function onMobDeath(mob, player, isKiller) player:addTitle(TORTOISE_TORTURER); end; function onMobDespawn(mob) local ToD = GetServerVariable("[POP]Aspidochelone"); local kills = GetServerVariable("[PH]Aspidochelone"); local popNow = (math.random(1,5) == 3 or kills > 6); if (LandKingSystem_HQ ~= 1 and ToD <= os.time() and popNow) then -- 0 = timed spawn, 1 = force pop only, 2 = BOTH if (LandKingSystem_NQ == 0) then DisallowRespawn(ADAMANTOISE, true); end DisallowRespawn(ASPIDOCHELONE, false); UpdateNMSpawnPoint(ASPIDOCHELONE); GetMobByID(ASPIDOCHELONE):setRespawnTime(math.random(75600,86400)); else if (LandKingSystem_NQ ~= 1) then UpdateNMSpawnPoint(ADAMANTOISE); mob:setRespawnTime(math.random(75600,86400)); SetServerVariable("[PH]Aspidochelone", kills + 1); end end if (LandKingSystem_NQ > 0 or LandKingSystem_HQ > 0) then GetNPCByID(ADAMANTOISE_QM):updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME); end end;
gpl-3.0