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
h3r2tic/rendertoy
tools/tundra/scripts/tundra/test/t_path.lua
28
2760
module(..., package.seeall) local path = require "tundra.path" local native = require "tundra.native" local function check_path(t, p, expected) p = p:gsub('\\', '/') t:check_equal(p, expected) end unit_test('path.normalize', function (t) check_path(t, path.normalize("foo"), "foo") check_path(t, path.normalize("foo/bar"), "foo/bar") check_path(t, path.normalize("foo//bar"), "foo/bar") check_path(t, path.normalize("foo/./bar"), "foo/bar") check_path(t, path.normalize("foo/../bar"), "bar") check_path(t, path.normalize("../bar"), "../bar") check_path(t, path.normalize("foo/../../bar"), "../bar") end) unit_test('path.join', function (t) check_path(t, path.join("foo", "bar"), "foo/bar") check_path(t, path.join("foo", "../bar"), "bar") check_path(t, path.join("/foo", "bar"), "/foo/bar") end) unit_test('path.split', function (t) local function check_split(p, expected_dir, expected_fn) local dir, fn = path.split(p) dir = dir:gsub('\\', '/') fn = fn:gsub('\\', '/') t:check_equal(dir, expected_dir) t:check_equal(fn, expected_fn) end check_split("", ".", "") check_split("foo", ".", "foo") check_split("foo/bar", "foo", "bar") check_split("/foo/bar", "/foo", "bar") check_split("x:\\foo\\bar", "x:/foo", "bar") end) unit_test('path.get_filename_dir', function (t) t:check_equal(path.get_filename_dir("foo/bar"), "foo") t:check_equal(path.get_filename_dir("foo"), "") end) unit_test('path.get_filename', function (t) t:check_equal(path.get_filename("foo/bar"), "bar") t:check_equal(path.get_filename("foo"), "foo") end) unit_test('path.get_extension', function (t) t:check_equal(path.get_extension("foo"), "") t:check_equal(path.get_extension("foo."), ".") t:check_equal(path.get_extension("foo.c"), ".c") t:check_equal(path.get_extension("foo/bar/.c"), ".c") t:check_equal(path.get_extension("foo/bar/baz.cpp"), ".cpp") end) unit_test('path.drop_suffix', function (t) t:check_equal(path.drop_suffix("foo.c"), "foo") t:check_equal(path.drop_suffix("foo/bar.c"), "foo/bar") t:check_equal(path.drop_suffix("/foo/bar.c"), "/foo/bar") end) unit_test('path.get_filename_base', function (t) t:check_equal(path.get_filename_base("foo1"), "foo1") t:check_equal(path.get_filename_base("foo2.c"), "foo2") t:check_equal(path.get_filename_base("/path/to/foo3"), "foo3") t:check_equal(path.get_filename_base("/path/to/foo4.c"), "foo4") end) unit_test('path.is_absolute', function (t) t:check_equal(path.is_absolute("/foo") and "true" or "false", "true") t:check_equal(path.is_absolute("foo") and "true" or "false", "false") if native.host_platform == "windows" then t:check_equal(path.is_absolute("x:\\foo") and "true" or "false", "true") end end)
mit
AbolDalton/kia
plugins/warn.lua
5
7684
local function warn_by_username(extra, success, result) -- /warn <@username> if success == 1 then local msg = result local target = extra.target local receiver = extra.receiver local hash = 'warn:'..target local value = redis:hget(hash, msg.id) local text = '' local name = '' if msg.first_name then name = string.sub(msg.first_name, 1, 40) else name = string.sub(msg.last_name, 1, 40) end ---------------------------------- if is_momod2(msg.id, target) and not is_admin2(extra.fromid) then return send_msg(receiver, 'شما نمیتوانید به مدیر گروه اخطار بدهید!', ok_cb, false) end --endif-- if is_admin2(msg.id) then return send_msg(receiver, 'شما نمیتوانید به ادمین ربات اخطار بدهید!', ok_cb, false) end --endif-- if value then if value == '1' then redis:hset(hash, msg.id, '2') text = '[ '..name..' ]\n شما به دلیل رعایت نکردن قوانین اخطار دریافت میکنید\nتعداد اخطار های شما : ۲/۴' elseif value == '2' then redis:hset(hash, msg.id, '3') text = '[ '..name..' ]\n شما به دلیل رعایت نکردن قوانین اخطار دریافت میکنید\nتعداد اخطار های شما : ۳/۴' elseif value == '3' then redis:hdel(hash, msg.id, '0') local hash = 'banned:'..target redis:sadd(hash, msg.id) text = '[ '..name..' ]\n به دلیل رعایت نکردن قوانین از گروه اخراج شد (banned)\nتعداد اخطار ها : ۴/۴' chat_del_user(receiver, 'user#id'..msg.id, ok_cb, false) end else redis:hset(hash, msg.id, '1') text = '[ '..name..' ]\n شما به دلیل رعایت نکردن قوانین اخطار دریافت میکنید\nتعداد اخطار های شما : ۱/۴' end send_msg(receiver, text, ok_cb, false) else send_msg(receiver, ' نام کاربری پیدا نشد.', ok_cb, false) end end -- local function warn_by_reply(extra, success, result) -- (on reply) /warn local msg = result local target = extra.target local receiver = extra.receiver local hash = 'warn:'..msg.to.id local value = redis:hget(hash, msg.from.id) local text = '' local name = '' if msg.from.first_name then name = string.sub(msg.from.first_name, 1, 40) else name = string.sub(msg.from.last_name, 1, 40) end ---------------------------------- if is_momod2(msg.from.id, msg.to.id) and not is_admin2(extra.fromid) then return send_msg(receiver, 'شما نمیتوانید به مدیر گروه اخطار بدهید!', ok_cb, false) end --endif-- if is_admin2(msg.from.id) then return send_msg(receiver, 'شما نمیتوانید به ادمین ربات اخطار بدهید!', ok_cb, false) end --endif-- if value then if value == '1' then redis:hset(hash, msg.from.id, '2') text = '[ '..name..' ]\n .شما به دلیل رعایت نکردن قوانین اخطار دریافت میکنید\nتعداد اخطار های شما : ۲/۴' elseif value == '2' then redis:hset(hash, msg.from.id, '3') text = '[ '..name..' ]\n شما به دلیل رعایت نکردن قوانین اخطار دریافت میکنید.\nتعداد اخطار های شما : ۳/۴' elseif value == '3' then redis:hdel(hash, msg.from.id, '0') text = '[ '..name..' ]\n به دلیل رعایت نکردن قوانین از گروه اخراج شد. (banned)\nتعداد اخطار ها : ۴/۴' local hash = 'banned:'..target redis:sadd(hash, msg.from.id) chat_del_user(receiver, 'user#id'..msg.from.id, ok_cb, false) end else redis:hset(hash, msg.from.id, '1') text = '[ '..name..' ]\n شما به دلیل رعایت نکردن قوانین اخطار دریافت میکنید.\nتعداد اخطار های شما : ۱/۴' end reply_msg(extra.Reply, text, ok_cb, false) end -- local function unwarn_by_username(extra, success, result) -- /unwarn <@username> if success == 1 then local msg = result local target = extra.target local receiver = extra.receiver local hash = 'warn:'..target local value = redis:hget(hash, msg.id) local text = '' ---------------------------------- if is_momod2(msg.id, target) and not is_admin2(extra.fromid) then return end --endif-- if is_admin2(msg.id) then return end --endif-- if value then redis:hdel(hash, msg.id, '0') text = 'اخطار های کاربر ('..msg.id..') پاک شد\nتعداد اخطار ها : ۰/۴' else text = 'این کاربر اخطاری دریافت نکرده است' end send_msg(receiver, text, ok_cb, false) else send_msg(receiver, ' نام کاربری پیدا نشد.', ok_cb, false) end end -- local function unwarn_by_reply(extra, success, result) -- (on reply) /unwarn local msg = result local target = extra.target local receiver = extra.receiver local hash = 'warn:'..msg.to.id local value = redis:hget(hash, msg.from.id) local text = '' ---------------------------------- if is_momod2(msg.from.id, msg.to.id) and not is_admin2(extra.fromid) then return end --endif-- if is_admin2(msg.from.id) then return end --endif-- if value then redis:hdel(hash, msg.from.id, '0') text = 'اخطار های کاربر ('..msg.from.id..') پاک شد\nتعداد اخطار ها : ۰/۴' else text = 'این کاربر اخطاری دریافت نکرده است' end reply_msg(extra.Reply, text, ok_cb, false) end -- local function run(msg, matches) local target = msg.to.id local fromid = msg.from.id local user = matches[2] local target = msg.to.id local receiver = get_receiver(msg) if msg.to.type == 'user' then return end --endif-- if not is_momod(msg) then return 'شما مدیر نیستید' end --endif-- ---------------------------------- if matches[1]:lower() == 'warn' and not matches[2] then -- (on reply) /warn if msg.reply_id then local Reply = msg.reply_id msgr = get_message(msg.reply_id, warn_by_reply, {receiver=receiver, Reply=Reply, target=target, fromid=fromid}) else return 'از نام کاربری یا ریپلی کردن پیام کاربر برای اخطار دادن استفاده کنید' end --endif-- end if matches[1]:lower() == 'warn' and matches[2] then -- /warn <@username> if string.match(user, '^%d+$') then return 'از نام کاربری یا ریپلی کردن پیام کاربر برای اخطار دادن استفاده کنید' elseif string.match(user, '^@.+$') then username = string.gsub(user, '@', '') msgr = res_user(username, warn_by_username, {receiver=receiver, user=user, target=target, fromid=fromid}) end end if matches[1]:lower() == 'unwarn' and not matches[2] then -- (on reply) /unwarn if msg.reply_id then local Reply = msg.id msgr = get_message(msg.reply_id, unwarn_by_reply, {receiver=receiver, Reply=Reply, target=target, fromid=fromid}) else return 'از نام کاربری یا ریپلی کردن استفاده کنید' end --endif-- end if matches[1]:lower() == 'unwarn' and matches[2] then -- /unwarn <@username> if string.match(user, '^%d+$') then return 'از نام کاربری یا ریپلی کردن استفاده کنید' elseif string.match(user, '^@.+$') then username = string.gsub(user, '@', '') msgr = res_user(username, unwarn_by_username, {receiver=receiver, user=user, target=target, fromid=fromid}) end end end return { patterns = { "^[!/#]([Ww][Aa][Rr][Nn])$", "^[!/#]([Ww][Aa][Rr][Nn]) (.*)$", "^[!/#]([Uu][Nn][Ww][Aa][Rr][Nn])$", "^[!/#]([Uu][Nn][Ww][Aa][Rr][Nn]) (.*)$" }, run = run }
gpl-2.0
8devices/carambola2-luci
modules/rpc/luasrc/jsonrpcbind/uci.lua
81
1914
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local uci = require "luci.model.uci".cursor() local ucis = require "luci.model.uci".cursor_state() local table = require "table" module "luci.jsonrpcbind.uci" _M, _PACKAGE, _NAME = nil, nil, nil function add(config, ...) uci:load(config) local stat = uci:add(config, ...) return uci:save(config) and stat end function apply(config) return uci:apply(config) end function changes(...) return uci:changes(...) end function commit(config) return uci:load(config) and uci:commit(config) end function delete(config, ...) uci:load(config) return uci:delete(config, ...) and uci:save(config) end function delete_all(config, ...) uci:load(config) return uci:delete_all(config, ...) and uci:save(config) end function foreach(config, stype) uci:load(config) local sections = {} return uci:foreach(config, stype, function(section) table.insert(sections, section) end) and sections end function get(config, ...) uci:load(config) return uci:get(config, ...) end function get_all(config, ...) uci:load(config) return uci:get_all(config, ...) end function get_state(config, ...) ucis:load(config) return ucis:get(config, ...) end function revert(config) return uci:load(config) and uci:revert(config) end function section(config, ...) uci:load(config) return uci:section(config, ...) and uci:save(config) end function set(config, ...) uci:load(config) return uci:set(config, ...) and uci:save(config) end function tset(config, ...) uci:load(config) return uci:tset(config, ...) and uci:save(config) end
apache-2.0
maikerumine/extreme_survival_mini
mods/es/farming.lua
1
2035
local function register_plant(name, min, max, spawnby, num) minetest.register_decoration({ deco_type = "simple", place_on = {"es:strange_grass","es:aiden_grass"}, sidelen = 16, noise_params = { offset = 0, scale = 0.006, spread = {x = 60, y = 60, z = 60}, seed = 329, octaves = 3, persist = 0.6 }, y_min = min, y_max = max, decoration = "farming:" .. name, spawn_by = spawnby, num_spawn_by = num, }) end function farming_register_mgv6_decorations() register_plant("potato_3", 15, 40, "", -1) register_plant("tomato_7", 5, 20, "", -1) register_plant("carrot_8", 1, 30, "group:water", 1) register_plant("cucumber_4", 1, 20, "group:water", 1) register_plant("corn_7", 12, 22, "", -1) register_plant("corn_8", 10, 20, "", -1) register_plant("coffee_5", 20, 45, "", -1) register_plant("melon_8", 1, 20, "group:water", 1) register_plant("pumpkin_8", 1, 20, "group:water", 1) register_plant("raspberry_4", 3, 10, "", -1) register_plant("rhubarb_3", 3, 15, "", -1) register_plant("blueberry_4", 3, 10, "", -1) register_plant("beanbush", 18, 35, "", -1) register_plant("grapebush", 25, 45, "", -1) end -- v7 maps have a beach so plants growing near water is limited to 6 high function farming_register_mgv7_decorations() register_plant("potato_3", 15, 40, "", -1) register_plant("tomato_7", 5, 20, "", -1) register_plant("carrot_8", 1, 6, "", -1) register_plant("cucumber_4", 1, 6, "", -1) register_plant("corn_7", 12, 22, "", -1) register_plant("corn_8", 10, 20, "", -1) register_plant("coffee_5", 20, 45, "", -1) register_plant("melon_8", 1, 6, "", -1) register_plant("pumpkin_8", 1, 6, "", -1) register_plant("raspberry_4", 3, 10, "", -1) register_plant("rhubarb_3", 3, 15, "", -1) register_plant("blueberry_4", 3, 10, "", -1) register_plant("beanbush", 18, 35, "", -1) register_plant("grapebush", 25, 45, "", -1) end -- detect mapgen if minetest.get_mapgen_params().mgname == "v6" then farming.register_mgv6_decorations() else farming.register_mgv7_decorations() end
lgpl-2.1
Fenix-XI/Fenix
scripts/zones/Castle_Zvahl_Baileys/TextIDs.lua
22
1092
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. come back after sorting your inventory. ITEM_OBTAINED = 6543; -- Obtained: <item>. GIL_OBTAINED = 6544; -- Obtained <number> gil. KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7218; -- You unlock the chest! CHEST_FAIL = 7219; -- Fails to open the chest. CHEST_TRAP = 7220; -- The chest was trapped! CHEST_WEAK = 7221; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7222; -- The chest was a mimic! CHEST_MOOGLE = 7223; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7224; -- The chest was but an illusion... CHEST_LOCKED = 7225; -- The chest appears to be locked. -- Quest dialog SENSE_OF_FOREBODING = 6558; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 7548; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/The_Shrine_of_RuAvitau/mobs/Kirin.lua
11
2223
----------------------------------- -- Area: The Shrine of Ru'Avitau -- NM: Kirin ----------------------------------- local ID = require("scripts/zones/The_Shrine_of_RuAvitau/IDs"); mixins = {require("scripts/mixins/job_special")}; require("scripts/globals/titles"); require("scripts/globals/mobs") ----------------------------------- function onMobInitialize( mob ) mob:setMobMod(dsp.mobMod.IDLE_DESPAWN, 180); mob:setMobMod(dsp.mobMod.ADD_EFFECT, 1); end function onMobSpawn(mob) mob:setMod(dsp.mod.WINDRES, -64); mob:setMod(dsp.mod.SILENCERES, 35); mob:setMod(dsp.mod.STUNRES, 35); mob:setMod(dsp.mod.BINDRES, 35); mob:setMod(dsp.mod.GRAVITYRES, 35); mob:addStatusEffect(dsp.effect.REGEN,50,3,0); mob:setLocalVar("numAdds", 1); end function onMobFight( mob, target ) -- spawn gods local numAdds = mob:getLocalVar("numAdds"); if (mob:getBattleTime() / 180 == numAdds) then local godsRemaining = {}; for i = 1, 4 do if (mob:getLocalVar("add"..i) == 0) then table.insert(godsRemaining,i); end end if (#godsRemaining > 0) then local g = godsRemaining[math.random(#godsRemaining)]; local god = SpawnMob(ID.mob.KIRIN + g); god:updateEnmity(target); god:setPos(mob:getXPos(), mob:getYPos(), mob:getZPos()); mob:setLocalVar("add"..g, 1); mob:setLocalVar("numAdds", numAdds + 1); end end -- ensure all spawned pets are doing stuff for i = ID.mob.KIRIN + 1, ID.mob.KIRIN + 4 do local god = GetMobByID(i); if (god:getCurrentAction() == dsp.act.ROAMING) then god:updateEnmity(target); end end end function onAdditionalEffect(mob, target, damage) return dsp.mob.onAddEffect(mob, target, damage, dsp.mob.ae.ENSTONE) end function onMobDeath(mob, player, isKiller) player:addTitle( dsp.title.KIRIN_CAPTIVATOR ); player:showText( mob, ID.text.KIRIN_OFFSET + 1 ); for i = ID.mob.KIRIN + 1, ID.mob.KIRIN + 4 do DespawnMob(i); end; end function onMobDespawn( mob ) for i = ID.mob.KIRIN + 1, ID.mob.KIRIN + 4 do DespawnMob(i); end; end
gpl-3.0
jmachuca77/ardupilot
libraries/AP_Scripting/examples/lidar_control.lua
5
1125
-- enable use of Lidar on quadplanes only for landing, by changing RNGFN_LANDING -- bind a parameter to a variable function bind_param(name) local p = Parameter() assert(p:init(name), string.format('could not find %s parameter', name)) return p end local RNGFND_LANDING = bind_param("RNGFND_LANDING") MODE_QLAND = 20 MODE_QRTL = 21 MODE_AUTO = 10 local NAV_LAND = 21 local NAV_VTOL_LAND = 85 function in_landing() local mode = vehicle:get_mode() if mode == MODE_QRTL or mode == MODE_QLAND then return true end if mode == MODE_AUTO then local id = mission:get_current_nav_id() if id == NAV_VTOL_LAND or id == NAV_LAND then return true end end return false end -- convert a boolean to an int function bool_to_int(v) return v and 1 or 0 end function update() local v = bool_to_int(in_landing()) if v ~= RNGFND_LANDING:get() then if v == 1 then gcs:send_text(0,"Enabling Lidar") else gcs:send_text(0,"Disabling Lidar") end RNGFND_LANDING:set(v) end -- run at 1Hz return update, 1000 end return update()
gpl-3.0
mozilla-services/data-pipeline
hindsight/io_modules/derived_stream/tsv.lua
5
1274
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local M = {} local ipairs = ipairs local tostring = tostring local type = type local read_message = read_message local encode_message = encode_message local gsub = require "string".gsub setfenv(1, M) -- Remove external access to contain everything in the module local esc_chars = { ["\t"] = "\\t", ["\r"] = "\\r", ["\n"] = "\\n", ["\\"] = "\\\\" } function esc_str(v) return gsub(v, "[\t\r\n\\]", esc_chars) end function write_message(fh, schema, nil_value) for i,v in ipairs(schema) do local value if type(v[5]) == "function" then value = v[5]() elseif type(v[5]) == "string" then value = read_message(v[5]) end if value == nil then value = nil_value else value = tostring(value) end if v[2] == "CHAR" or v[2] == "VARCHAR" then value = esc_str(value) end if i > 1 then fh:write("\t", value) else fh:write(value) end end fh:write("\n") end return M
mpl-2.0
Fenix-XI/Fenix
scripts/zones/Meriphataud_Mountains/npcs/Buliame_RK.lua
13
3350
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Buliame, R.K. -- Type: Border Conquest Guards -- @pos -120.393 -25.822 -592.604 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ARAGONEU; local csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
tcatm/luci
applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-app.lua
137
15546
cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true app_alarmreceiver = module:option(ListValue, "app_alarmreceiver", "Alarm Receiver Application", "") app_alarmreceiver:value("yes", "Load") app_alarmreceiver:value("no", "Do Not Load") app_alarmreceiver:value("auto", "Load as Required") app_alarmreceiver.rmempty = true app_authenticate = module:option(ListValue, "app_authenticate", "Authentication Application", "") app_authenticate:value("yes", "Load") app_authenticate:value("no", "Do Not Load") app_authenticate:value("auto", "Load as Required") app_authenticate.rmempty = true app_cdr = module:option(ListValue, "app_cdr", "Make sure asterisk doesnt save CDR", "") app_cdr:value("yes", "Load") app_cdr:value("no", "Do Not Load") app_cdr:value("auto", "Load as Required") app_cdr.rmempty = true app_chanisavail = module:option(ListValue, "app_chanisavail", "Check if channel is available", "") app_chanisavail:value("yes", "Load") app_chanisavail:value("no", "Do Not Load") app_chanisavail:value("auto", "Load as Required") app_chanisavail.rmempty = true app_chanspy = module:option(ListValue, "app_chanspy", "Listen in on any channel", "") app_chanspy:value("yes", "Load") app_chanspy:value("no", "Do Not Load") app_chanspy:value("auto", "Load as Required") app_chanspy.rmempty = true app_controlplayback = module:option(ListValue, "app_controlplayback", "Control Playback Application", "") app_controlplayback:value("yes", "Load") app_controlplayback:value("no", "Do Not Load") app_controlplayback:value("auto", "Load as Required") app_controlplayback.rmempty = true app_cut = module:option(ListValue, "app_cut", "Cuts up variables", "") app_cut:value("yes", "Load") app_cut:value("no", "Do Not Load") app_cut:value("auto", "Load as Required") app_cut.rmempty = true app_db = module:option(ListValue, "app_db", "Database access functions", "") app_db:value("yes", "Load") app_db:value("no", "Do Not Load") app_db:value("auto", "Load as Required") app_db.rmempty = true app_dial = module:option(ListValue, "app_dial", "Dialing Application", "") app_dial:value("yes", "Load") app_dial:value("no", "Do Not Load") app_dial:value("auto", "Load as Required") app_dial.rmempty = true app_dictate = module:option(ListValue, "app_dictate", "Virtual Dictation Machine Application", "") app_dictate:value("yes", "Load") app_dictate:value("no", "Do Not Load") app_dictate:value("auto", "Load as Required") app_dictate.rmempty = true app_directed_pickup = module:option(ListValue, "app_directed_pickup", "Directed Call Pickup Support", "") app_directed_pickup:value("yes", "Load") app_directed_pickup:value("no", "Do Not Load") app_directed_pickup:value("auto", "Load as Required") app_directed_pickup.rmempty = true app_directory = module:option(ListValue, "app_directory", "Extension Directory", "") app_directory:value("yes", "Load") app_directory:value("no", "Do Not Load") app_directory:value("auto", "Load as Required") app_directory.rmempty = true app_disa = module:option(ListValue, "app_disa", "DISA (Direct Inward System Access) Application", "") app_disa:value("yes", "Load") app_disa:value("no", "Do Not Load") app_disa:value("auto", "Load as Required") app_disa.rmempty = true app_dumpchan = module:option(ListValue, "app_dumpchan", "Dump channel variables Application", "") app_dumpchan:value("yes", "Load") app_dumpchan:value("no", "Do Not Load") app_dumpchan:value("auto", "Load as Required") app_dumpchan.rmempty = true app_echo = module:option(ListValue, "app_echo", "Simple Echo Application", "") app_echo:value("yes", "Load") app_echo:value("no", "Do Not Load") app_echo:value("auto", "Load as Required") app_echo.rmempty = true app_enumlookup = module:option(ListValue, "app_enumlookup", "ENUM Lookup", "") app_enumlookup:value("yes", "Load") app_enumlookup:value("no", "Do Not Load") app_enumlookup:value("auto", "Load as Required") app_enumlookup.rmempty = true app_eval = module:option(ListValue, "app_eval", "Reevaluates strings", "") app_eval:value("yes", "Load") app_eval:value("no", "Do Not Load") app_eval:value("auto", "Load as Required") app_eval.rmempty = true app_exec = module:option(ListValue, "app_exec", "Executes applications", "") app_exec:value("yes", "Load") app_exec:value("no", "Do Not Load") app_exec:value("auto", "Load as Required") app_exec.rmempty = true app_externalivr = module:option(ListValue, "app_externalivr", "External IVR application interface", "") app_externalivr:value("yes", "Load") app_externalivr:value("no", "Do Not Load") app_externalivr:value("auto", "Load as Required") app_externalivr.rmempty = true app_forkcdr = module:option(ListValue, "app_forkcdr", "Fork The CDR into 2 seperate entities", "") app_forkcdr:value("yes", "Load") app_forkcdr:value("no", "Do Not Load") app_forkcdr:value("auto", "Load as Required") app_forkcdr.rmempty = true app_getcpeid = module:option(ListValue, "app_getcpeid", "Get ADSI CPE ID", "") app_getcpeid:value("yes", "Load") app_getcpeid:value("no", "Do Not Load") app_getcpeid:value("auto", "Load as Required") app_getcpeid.rmempty = true app_groupcount = module:option(ListValue, "app_groupcount", "Group Management Routines", "") app_groupcount:value("yes", "Load") app_groupcount:value("no", "Do Not Load") app_groupcount:value("auto", "Load as Required") app_groupcount.rmempty = true app_ices = module:option(ListValue, "app_ices", "Encode and Stream via icecast and ices", "") app_ices:value("yes", "Load") app_ices:value("no", "Do Not Load") app_ices:value("auto", "Load as Required") app_ices.rmempty = true app_image = module:option(ListValue, "app_image", "Image Transmission Application", "") app_image:value("yes", "Load") app_image:value("no", "Do Not Load") app_image:value("auto", "Load as Required") app_image.rmempty = true app_lookupblacklist = module:option(ListValue, "app_lookupblacklist", "Look up Caller*ID name/number from black", "") app_lookupblacklist:value("yes", "Load") app_lookupblacklist:value("no", "Do Not Load") app_lookupblacklist:value("auto", "Load as Required") app_lookupblacklist.rmempty = true app_lookupcidname = module:option(ListValue, "app_lookupcidname", "Look up CallerID Name from local databas", "") app_lookupcidname:value("yes", "Load") app_lookupcidname:value("no", "Do Not Load") app_lookupcidname:value("auto", "Load as Required") app_lookupcidname.rmempty = true app_macro = module:option(ListValue, "app_macro", "Extension Macros", "") app_macro:value("yes", "Load") app_macro:value("no", "Do Not Load") app_macro:value("auto", "Load as Required") app_macro.rmempty = true app_math = module:option(ListValue, "app_math", "A simple math Application", "") app_math:value("yes", "Load") app_math:value("no", "Do Not Load") app_math:value("auto", "Load as Required") app_math.rmempty = true app_md5 = module:option(ListValue, "app_md5", "MD5 checksum Application", "") app_md5:value("yes", "Load") app_md5:value("no", "Do Not Load") app_md5:value("auto", "Load as Required") app_md5.rmempty = true app_milliwatt = module:option(ListValue, "app_milliwatt", "Digital Milliwatt (mu-law) Test Application", "") app_milliwatt:value("yes", "Load") app_milliwatt:value("no", "Do Not Load") app_milliwatt:value("auto", "Load as Required") app_milliwatt.rmempty = true app_mixmonitor = module:option(ListValue, "app_mixmonitor", "Record a call and mix the audio during the recording", "") app_mixmonitor:value("yes", "Load") app_mixmonitor:value("no", "Do Not Load") app_mixmonitor:value("auto", "Load as Required") app_mixmonitor.rmempty = true app_parkandannounce = module:option(ListValue, "app_parkandannounce", "Call Parking and Announce Application", "") app_parkandannounce:value("yes", "Load") app_parkandannounce:value("no", "Do Not Load") app_parkandannounce:value("auto", "Load as Required") app_parkandannounce.rmempty = true app_playback = module:option(ListValue, "app_playback", "Trivial Playback Application", "") app_playback:value("yes", "Load") app_playback:value("no", "Do Not Load") app_playback:value("auto", "Load as Required") app_playback.rmempty = true app_privacy = module:option(ListValue, "app_privacy", "Require phone number to be entered", "") app_privacy:value("yes", "Load") app_privacy:value("no", "Do Not Load") app_privacy:value("auto", "Load as Required") app_privacy.rmempty = true app_queue = module:option(ListValue, "app_queue", "True Call Queueing", "") app_queue:value("yes", "Load") app_queue:value("no", "Do Not Load") app_queue:value("auto", "Load as Required") app_queue.rmempty = true app_random = module:option(ListValue, "app_random", "Random goto", "") app_random:value("yes", "Load") app_random:value("no", "Do Not Load") app_random:value("auto", "Load as Required") app_random.rmempty = true app_read = module:option(ListValue, "app_read", "Read Variable Application", "") app_read:value("yes", "Load") app_read:value("no", "Do Not Load") app_read:value("auto", "Load as Required") app_read.rmempty = true app_readfile = module:option(ListValue, "app_readfile", "Read in a file", "") app_readfile:value("yes", "Load") app_readfile:value("no", "Do Not Load") app_readfile:value("auto", "Load as Required") app_readfile.rmempty = true app_realtime = module:option(ListValue, "app_realtime", "Realtime Data Lookup/Rewrite", "") app_realtime:value("yes", "Load") app_realtime:value("no", "Do Not Load") app_realtime:value("auto", "Load as Required") app_realtime.rmempty = true app_record = module:option(ListValue, "app_record", "Trivial Record Application", "") app_record:value("yes", "Load") app_record:value("no", "Do Not Load") app_record:value("auto", "Load as Required") app_record.rmempty = true app_sayunixtime = module:option(ListValue, "app_sayunixtime", "Say time", "") app_sayunixtime:value("yes", "Load") app_sayunixtime:value("no", "Do Not Load") app_sayunixtime:value("auto", "Load as Required") app_sayunixtime.rmempty = true app_senddtmf = module:option(ListValue, "app_senddtmf", "Send DTMF digits Application", "") app_senddtmf:value("yes", "Load") app_senddtmf:value("no", "Do Not Load") app_senddtmf:value("auto", "Load as Required") app_senddtmf.rmempty = true app_sendtext = module:option(ListValue, "app_sendtext", "Send Text Applications", "") app_sendtext:value("yes", "Load") app_sendtext:value("no", "Do Not Load") app_sendtext:value("auto", "Load as Required") app_sendtext.rmempty = true app_setcallerid = module:option(ListValue, "app_setcallerid", "Set CallerID Application", "") app_setcallerid:value("yes", "Load") app_setcallerid:value("no", "Do Not Load") app_setcallerid:value("auto", "Load as Required") app_setcallerid.rmempty = true app_setcdruserfield = module:option(ListValue, "app_setcdruserfield", "CDR user field apps", "") app_setcdruserfield:value("yes", "Load") app_setcdruserfield:value("no", "Do Not Load") app_setcdruserfield:value("auto", "Load as Required") app_setcdruserfield.rmempty = true app_setcidname = module:option(ListValue, "app_setcidname", "load => .so ; Set CallerID Name", "") app_setcidname:value("yes", "Load") app_setcidname:value("no", "Do Not Load") app_setcidname:value("auto", "Load as Required") app_setcidname.rmempty = true app_setcidnum = module:option(ListValue, "app_setcidnum", "load => .so ; Set CallerID Number", "") app_setcidnum:value("yes", "Load") app_setcidnum:value("no", "Do Not Load") app_setcidnum:value("auto", "Load as Required") app_setcidnum.rmempty = true app_setrdnis = module:option(ListValue, "app_setrdnis", "Set RDNIS Number", "") app_setrdnis:value("yes", "Load") app_setrdnis:value("no", "Do Not Load") app_setrdnis:value("auto", "Load as Required") app_setrdnis.rmempty = true app_settransfercapability = module:option(ListValue, "app_settransfercapability", "Set ISDN Transfer Capability", "") app_settransfercapability:value("yes", "Load") app_settransfercapability:value("no", "Do Not Load") app_settransfercapability:value("auto", "Load as Required") app_settransfercapability.rmempty = true app_sms = module:option(ListValue, "app_sms", "SMS/PSTN handler", "") app_sms:value("yes", "Load") app_sms:value("no", "Do Not Load") app_sms:value("auto", "Load as Required") app_sms.rmempty = true app_softhangup = module:option(ListValue, "app_softhangup", "Hangs up the requested channel", "") app_softhangup:value("yes", "Load") app_softhangup:value("no", "Do Not Load") app_softhangup:value("auto", "Load as Required") app_softhangup.rmempty = true app_stack = module:option(ListValue, "app_stack", "Stack Routines", "") app_stack:value("yes", "Load") app_stack:value("no", "Do Not Load") app_stack:value("auto", "Load as Required") app_stack.rmempty = true app_system = module:option(ListValue, "app_system", "Generic System() application", "") app_system:value("yes", "Load") app_system:value("no", "Do Not Load") app_system:value("auto", "Load as Required") app_system.rmempty = true app_talkdetect = module:option(ListValue, "app_talkdetect", "Playback with Talk Detection", "") app_talkdetect:value("yes", "Load") app_talkdetect:value("no", "Do Not Load") app_talkdetect:value("auto", "Load as Required") app_talkdetect.rmempty = true app_test = module:option(ListValue, "app_test", "Interface Test Application", "") app_test:value("yes", "Load") app_test:value("no", "Do Not Load") app_test:value("auto", "Load as Required") app_test.rmempty = true app_transfer = module:option(ListValue, "app_transfer", "Transfer", "") app_transfer:value("yes", "Load") app_transfer:value("no", "Do Not Load") app_transfer:value("auto", "Load as Required") app_transfer.rmempty = true app_txtcidname = module:option(ListValue, "app_txtcidname", "TXTCIDName", "") app_txtcidname:value("yes", "Load") app_txtcidname:value("no", "Do Not Load") app_txtcidname:value("auto", "Load as Required") app_txtcidname.rmempty = true app_url = module:option(ListValue, "app_url", "Send URL Applications", "") app_url:value("yes", "Load") app_url:value("no", "Do Not Load") app_url:value("auto", "Load as Required") app_url.rmempty = true app_userevent = module:option(ListValue, "app_userevent", "Custom User Event Application", "") app_userevent:value("yes", "Load") app_userevent:value("no", "Do Not Load") app_userevent:value("auto", "Load as Required") app_userevent.rmempty = true app_verbose = module:option(ListValue, "app_verbose", "Send verbose output", "") app_verbose:value("yes", "Load") app_verbose:value("no", "Do Not Load") app_verbose:value("auto", "Load as Required") app_verbose.rmempty = true app_voicemail = module:option(ListValue, "app_voicemail", "Voicemail", "") app_voicemail:value("yes", "Load") app_voicemail:value("no", "Do Not Load") app_voicemail:value("auto", "Load as Required") app_voicemail.rmempty = true app_waitforring = module:option(ListValue, "app_waitforring", "Waits until first ring after time", "") app_waitforring:value("yes", "Load") app_waitforring:value("no", "Do Not Load") app_waitforring:value("auto", "Load as Required") app_waitforring.rmempty = true app_waitforsilence = module:option(ListValue, "app_waitforsilence", "Wait For Silence Application", "") app_waitforsilence:value("yes", "Load") app_waitforsilence:value("no", "Do Not Load") app_waitforsilence:value("auto", "Load as Required") app_waitforsilence.rmempty = true app_while = module:option(ListValue, "app_while", "While Loops and Conditional Execution", "") app_while:value("yes", "Load") app_while:value("no", "Do Not Load") app_while:value("auto", "Load as Required") app_while.rmempty = true return cbimap
apache-2.0
DarkstarProject/darkstar
scripts/zones/Upper_Jeuno/npcs/Collet.lua
9
1707
----------------------------------- -- Area: Upper Jeuno -- NPC: Collet -- Involved in Quests: A Clock Most Delicate, Save the Clock Tower -- !pos -44 0 107 244 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then local a = player:getCharVar("saveTheClockTowerNPCz1"); -- NPC zone1 if (a == 0 or (a ~= 2 and a ~= 3 and a ~= 6 and a ~= 10 and a ~= 18 and a ~= 7 and a ~= 26 and a ~= 11 and a ~= 22 and a ~= 14 and a ~= 19 and a ~= 15 and a ~= 23 and a ~= 27 and a ~= 30 and a ~= 31)) then player:startEvent(115,10 - player:getCharVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; function onTrigger(player,npc) if (player:getFameLevel(JEUNO) >= 5 and aClockMostdelicate == QUEST_AVAILABLE and player:getCharVar("aClockMostdelicateVar") == 0) then player:startEvent(112); elseif (player:getCharVar("saveTheClockTowerVar") >= 1) then player:startEvent(164); elseif (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.THE_CLOCKMASTER) == QUEST_COMPLETED) then player:startEvent(163); else player:startEvent(114); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 112) then player:setCharVar("aClockMostdelicateVar", 1); elseif (csid == 115) then player:addCharVar("saveTheClockTowerVar", 1); player:addCharVar("saveTheClockTowerNPCz1", 2); end end;
gpl-3.0
Giorox/AngelionOT-Repo
data/actions/scripts/other/ab.lua
1
1231
local tilepos = {x=32627, y=31699, z=10, stackpos=0} local tilepos2 = {x=32627, y=31699, z=10, stackpos=1} local tilepos3 = {x=32628, y=31699, z=10, stackpos=0} local tilepos4 = {x=32629, y=31699, z=10, stackpos=0} local tilepos5 = {x=32629, y=31699, z=10, stackpos=1} function onUse(cid, item, frompos, item2, topos) local tile = getThingfromPos(tilepos) local tile2 = getThingfromPos(tilepos2) local tile3 = getThingfromPos(tilepos3) local tile4 = getThingfromPos(tilepos4) local tile5 = getThingfromPos(tilepos5) local pos = {x=32629, y=31699, z=10} if (item.uid == 13444 and item.itemid == 1945) then doRemoveItem(tile2.uid,1) doTransformItem(tile.uid,5770) doTransformItem(tile3.uid,5770) doRemoveItem(tile5.uid,1) doTransformItem(tile4.uid,5770) doTransformItem(item.uid,1946) elseif (item.uid == 13444 and item.itemid == 1946) then doTransformItem(tile.uid,493) doCreateItem(4799,1,tilepos2) doTransformItem(tile3.uid,493) doTransformItem(item.uid,1945) doTransformItem(tile4.uid,493) doCreateItem(4797,1,tilepos5) pos.stackpos = 253 if getThingfromPos(pos).itemid > 0 then doMoveCreature(getThingFromPos(pos).uid, EAST) end else doPlayerSendCancel(cid,"Sorry, not possible.") end return 1 end
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Empyreal_Paradox/mobs/Promathia.lua
8
1999
----------------------------------- -- Area: Empyreal Paradox -- Mob: Promathia -- Note: Phase 1 ----------------------------------- local ID = require("scripts/zones/Empyreal_Paradox/IDs") require("scripts/globals/status") require("scripts/globals/titles") ----------------------------------- function onMobInitialize(mob) mob:addMod(dsp.mod.REGAIN, 50) mob:addMod(dsp.mod.UFASTCAST,50) end function onMobEngaged(mob, target) local bcnmAllies = mob:getBattlefield():getAllies() for i,v in pairs(bcnmAllies) do if v:getName() == "Prishe" then if not v:getTarget() then v:entityAnimationPacket("prov") v:showText(v, ID.text.PRISHE_TEXT) v:setLocalVar("ready", mob:getID()) end else v:addEnmity(mob,0,1) end end end function onMobFight(mob, target) if mob:AnimationSub() == 3 and not mob:hasStatusEffect(dsp.effect.STUN) then mob:AnimationSub(0) mob:stun(1500) end local bcnmAllies = mob:getBattlefield():getAllies() for i,v in pairs(bcnmAllies) do if not v:getTarget() then v:addEnmity(mob,0,1) end end end function onSpellPrecast(mob, spell) if spell:getID() == 219 then spell:setMPCost(1) end end function onMobDeath(mob, player, isKiller) local battlefield = player:getBattlefield() player:startEvent(32004, battlefield:getArea()) end function onEventUpdate(player, csid, option) -- printf("updateCSID: %u",csid); end function onEventFinish(player, csid, option, target) -- printf("finishCSID: %u",csid); if csid == 32004 then DespawnMob(target:getID()) mob = SpawnMob(target:getID()+1) local bcnmAllies = mob:getBattlefield():getAllies() for i,v in pairs(bcnmAllies) do v:resetLocalVars() local spawn = v:getSpawnPos() v:setPos(spawn.x, spawn.y, spawn.z, spawn.rot) end end end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Mhaura/npcs/Willah_Maratahya.lua
13
3834
----------------------------------- -- Area: Mhaura -- NPC: Willah Maratahya -- Title Change NPC -- @pos 23 -8 63 249 ----------------------------------- require("scripts/globals/titles"); local title2 = { PURVEYOR_IN_TRAINING , ONESTAR_PURVEYOR , TWOSTAR_PURVEYOR , THREESTAR_PURVEYOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { FOURSTAR_PURVEYOR , FIVESTAR_PURVEYOR , HEIR_OF_THE_GREAT_LIGHTNING , ORCISH_SERJEANT , BRONZE_QUADAV , YAGUDO_INITIATE , MOBLIN_KINSMAN , DYNAMISBUBURIMU_INTERLOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { FODDERCHIEF_FLAYER , WARCHIEF_WRECKER , DREAD_DRAGON_SLAYER , OVERLORD_EXECUTIONER , DARK_DRAGON_SLAYER , ADAMANTKING_KILLER , BLACK_DRAGON_SLAYER , MANIFEST_MAULER , BEHEMOTHS_BANE , ARCHMAGE_ASSASSIN , HELLSBANE , GIANT_KILLER , LICH_BANISHER , JELLYBANE , BOGEYDOWNER , BEAKBENDER , SKULLCRUSHER , MORBOLBANE , GOLIATH_KILLER , MARYS_GUIDE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { SIMURGH_POACHER , ROC_STAR , SERKET_BREAKER , CASSIENOVA , THE_HORNSPLITTER , TORTOISE_TORTURER , MON_CHERRY , BEHEMOTH_DETHRONER , THE_VIVISECTOR , DRAGON_ASHER , EXPEDITIONARY_TROOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { ADAMANTKING_USURPER , OVERLORD_OVERTHROWER , DEITY_DEBUNKER , FAFNIR_SLAYER , ASPIDOCHELONE_SINKER , NIDHOGG_SLAYER , MAAT_MASHER , KIRIN_CAPTIVATOR , CACTROT_DESACELERADOR , LIFTER_OF_SHADOWS , TIAMAT_TROUNCER , VRTRA_VANQUISHER , WORLD_SERPENT_SLAYER , XOLOTL_XTRAPOLATOR , BOROKA_BELEAGUERER , OURYU_OVERWHELMER , VINEGAR_EVAPORATOR , VIRTUOUS_SAINT , BYEBYE_TAISAI , TEMENOS_LIBERATOR , APOLLYON_RAVAGER , WYRM_ASTONISHER , NIGHTMARE_AWAKENER , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2711,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x2711) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Cloister_of_Storms/Zone.lua
30
1738
----------------------------------- -- -- Zone: Cloister_of_Storms (202) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Storms/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(517.957,-18.013,540.045,0); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/spells/dia_ii.lua
26
2226
----------------------------------------- -- Spell: Dia II -- Lowers an enemy's defense and gradually deals light elemental damage. ----------------------------------------- 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(ENFEEBLING_MAGIC_SKILL) / 4; local dmg = calculateMagicDamage(basedmg,3,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false); -- Softcaps at 8, should always do at least 1 dmg = utils.clamp(dmg, 1, 8); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0); --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; local dotBonus = 0; if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then duration = duration * 2; end caster:delStatusEffect(EFFECT_SABOTEUR); dotBonus = dotBonus+caster:getMod(MOD_DIA_DOT); -- Dia Wand -- Check for Bio. local bio = target:getStatusEffect(EFFECT_BIO); -- Do it! if (bio == nil or (DIA_OVERWRITE == 0 and bio:getPower() <= 2) or (DIA_OVERWRITE == 1 and bio:getPower() < 2)) then target:addStatusEffect(EFFECT_DIA,2+dotBonus,3,duration,FLAG_ERASABLE, 10); spell:setMsg(2); else spell:setMsg(75); end -- Try to kill same tier Bio if (BIO_OVERWRITE == 1 and bio ~= nil) then if (bio:getPower() <= 2) then target:delStatusEffect(EFFECT_BIO); end end return final; end;
gpl-3.0
Benyaminat/black-wolf
bot/utils.lua
473
24167
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do local user_info = redis:hgetall('user:'..v) -- vardump(user_info) if user_info then if user_info.username then user = '@'..user_info.username elseif user_info.print_name and not user_info.username then user = string.gsub(user_info.print_name, "_", " ") else user = '' end text = text..k.." - "..user.." ["..v.."]\n" end end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
elapuestojoe/survive
build_temp/deployments/default/android/release/arm/intermediate_files/assets/quicklua/QScene.lua
3
5078
--[[/* * (C) 2012-2013 Marmalade. * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */--]] -------------------------------------------------------------------------------- -- Scene -- NOTE: This file must have no dependencies on the ones loaded after it by -- openquick_init.lua. For example, it must have no dependencies on QDirector.lua -------------------------------------------------------------------------------- QScene = {} table.setValuesFromTable(QScene, QNode) -- previous class in hierarchy QScene.__index = QScene -------------------------------------------------------------------------------- -- Private API -------------------------------------------------------------------------------- QScene.serialize = function(o) local obj = serializeTLMT(getmetatable(o), o) table.setValuesFromTable(obj, serializeTLMT(getmetatable(quick.QScene), o)) return obj end --[[ /* Initialise the peer table for the C++ class QScene. This must be called immediately after the QScene() constructor. */ --]] function QScene:initScene(n) local np = {} local ep = tolua.getpeer(n) table.setValuesFromTable(np, ep) setmetatable(np, QScene) tolua.setpeer(n, np) local mt = getmetatable(n) mt.__serialize = QScene.serialize -- Set the scene width and height to match the screen dimensions n.w = director.displayWidth n.h = director.displayHeight end -------------------------------------------------------------------------------- -- Public API -------------------------------------------------------------------------------- --[[ /** Create a scene node, and set it to be the director's current scene. Note that no transition occurs from any previous scene, and no scene events are thrown. */ --]] function director:createScene(v) dbg.assertFuncVarTypes({"table", "nil"}, v) local n = quick.QScene() QNode:initNode(n) QScene:initScene(n) if type(v) == "table" and v.default==true then n:_init(true) n.name = "globalScene" if not self.globalScene then self.globalScene = n end else n:_init(false) end table.setValuesFromTable(n, v) self:setCurrentScene(n) -- Mark that setUp has NOT been called yet n.isSetUp = false n._atlasList = {} n._animationList = {} n._fontList = {} return n end -- PRIVATE: -- Create default scene. Use of global variable ensures Lua doesn't GC it. -- Doesn't use createScene because of extra parameters function director:_createDefaultScene() local n = self:createScene( { default=true } ) return n end --[[ /*! Play the current assigned animation. @param n (optional) A table containing playback parameters startFrame (optional) = The first frame of the animation to play loopCount (optional) = The number of times to play the animation. 0 = infinate */ --]] function QScene:play(n) local startFrame = 1 local loopCount = 0 if type(n) == "table" then if n.startFrame ~= nil then startFrame = n.startFrame end if n.loopCount ~= nil then loopCount = n.loopCount end end self:_play( startFrame, loopCount) end --[[ /*! Clear the stored resources */ --]] function QScene:releaseResources() -- dbg.print( "Releasing resources from scene "..tostring(self)) self._atlasList = {} self._animationList = {} self._fontList = {} end --[[ /*! Clear the stored QAtlas */ --]] function QScene:releaseAtlas(atlas) if self._atlasList[atlas] == nil then return false end self._atlasList[atlas] = nil return true end --[[ /*! Clear the stored QAnimation */ --]] function QScene:releaseAnimation(anim) if self._animationList[anim] == nil then return false end self._animationList[anim] = nil return true end --[[ /*! Clear the stored QFont */ --]] function QScene:releaseFont(font) if self._fontList[font] == nil then return false end self._fontList[font] = nil return true end
mit
DarkstarProject/darkstar
scripts/zones/Upper_Delkfutts_Tower/Zone.lua
9
1578
----------------------------------- -- -- Zone: Upper_Delkfutts_Tower (158) -- ----------------------------------- local ID = require("scripts/zones/Upper_Delkfutts_Tower/IDs") require("scripts/globals/conquest") require("scripts/globals/treasure") ----------------------------------- function onInitialize(zone) zone:registerRegion(1, -369, -146, 83, -365, -145, 89) -- Tenth Floor F-6 porter to Middle Delkfutt's Tower zone:registerRegion(2, -369, -178, -49, -365, -177, -43) -- Twelfth Floor F-10 porter to Stellar Fulcrum dsp.treasure.initZone(zone) end function onConquestUpdate(zone, updatetype) dsp.conq.onConquestUpdate(zone, updatetype) end function onZoneIn(player, prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(12.098, -105.408, 27.683, 239) end return cs end function onRegionEnter(player, region) switch (region:GetRegionID()): caseof { [1] = function (x) --player:setCharVar("porter_lock",1) player:startEvent(0) end, [2] = function (x) --player:setCharVar("porter_lock",1) player:startEvent(1) end, } end function onRegionLeave(player,region) end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) if csid == 0 and option == 1 then player:setPos(-490, -130, 81, 231, 157) elseif csid == 1 and option == 1 then player:setPos(-520 , 1 , -23, 192, 179) -- to Stellar Fulcrum end end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Norg/npcs/Paleille.lua
13
1031
---------------------------------- -- Area: Norg -- NPC: Paleille -- Type: Item Deliverer -- @zone: 252 -- @pos -82.667 -5.414 52.421 -- ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, PALEILLE_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/irmik_helvasi_+1.lua
11
1329
----------------------------------------- -- ID: 5573 -- Item: irmik_helvasi_+1 -- Food Effect: 4 hours, All Races ----------------------------------------- -- HP +10% (cap 100) -- MP +3% (cap 15) -- INT +2 -- hHP +1 -- hMP +1 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,14400,5573) end function onEffectGain(target,effect) target:addMod(dsp.mod.FOOD_HPP, 10) target:addMod(dsp.mod.FOOD_HP_CAP, 100) target:addMod(dsp.mod.FOOD_MPP, 3) target:addMod(dsp.mod.FOOD_MP_CAP, 15) target:addMod(dsp.mod.INT, 2) target:addMod(dsp.mod.HPHEAL, 1) target:addMod(dsp.mod.MPHEAL, 1) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_HPP, 10) target:delMod(dsp.mod.FOOD_HP_CAP, 100) target:delMod(dsp.mod.FOOD_MPP, 3) target:delMod(dsp.mod.FOOD_MP_CAP, 15) target:delMod(dsp.mod.INT, 2) target:delMod(dsp.mod.HPHEAL, 1) target:delMod(dsp.mod.MPHEAL, 1) end
gpl-3.0
DarkstarProject/darkstar
scripts/zones/West_Ronfaure/npcs/Palcomondau.lua
9
12838
----------------------------------- -- Area: West Ronfaure -- NPC: Palcomondau -- Type: Patrol -- !pos -349.796 -45.345 344.733 100 ----------------------------------- local ID = require("scripts/zones/West_Ronfaure/IDs") require("scripts/globals/pathfind") ----------------------------------- local path = { -373.096863, -45.742077, 340.182159, -361.441864, -46.052444, 340.367371, -360.358276, -46.063702, 340.457428, -359.297211, -46.093231, 340.693817, -358.264465, -46.285988, 341.032928, -357.301941, -45.966343, 341.412994, -356.365295, -45.641331, 341.804657, -353.933533, -45.161453, 342.873901, -346.744659, -45.006634, 346.113251, -345.843506, -44.973419, 346.716309, -345.138519, -44.939915, 347.540436, -344.564056, -44.925575, 348.463470, -344.069366, -44.945713, 349.431824, -343.621704, -45.004826, 350.421936, -343.194946, -45.062874, 351.421173, -342.118958, -45.391632, 354.047485, -334.448578, -44.964996, 373.198242, -333.936615, -45.028484, 374.152283, -333.189636, -45.068111, 374.939209, -332.252838, -45.073158, 375.488129, -331.241516, -45.065205, 375.888031, -330.207855, -45.043056, 376.226532, -329.165100, -45.022049, 376.536011, -328.118622, -45.000935, 376.832428, -323.437805, -45.726982, 378.101166, -305.333038, -49.030193, 382.936646, -304.308228, -49.435581, 383.130188, -303.259979, -49.765697, 383.194305, -302.209290, -50.104950, 383.175659, -301.161774, -50.446033, 383.117767, -300.114624, -50.787590, 383.041473, -298.422943, -51.390713, 382.898590, -281.798126, -56.178822, 381.370544, -280.718414, -56.161697, 381.241425, -279.641785, -56.142433, 381.087341, -278.567627, -56.121262, 380.917938, -261.485809, -55.875919, 378.010284, -260.404205, -55.893314, 377.898254, -259.317078, -55.908813, 377.861389, -258.229248, -55.923473, 377.879669, -257.142151, -55.938625, 377.919037, -254.834976, -55.888081, 378.032623, -224.857941, -56.603645, 379.721832, -194.892044, -59.911034, 381.416382, -178.437729, -61.500011, 382.347656, -- report? -179.524124, -61.500011, 382.285919, -209.530518, -58.837189, 380.588806, -239.543137, -56.145073, 378.891602, -257.769012, -55.930656, 377.861328, -258.856445, -55.915405, 377.839905, -259.943420, -55.900009, 377.884918, -261.025116, -55.882565, 377.999329, -262.102173, -55.864536, 378.151794, -263.193237, -55.845242, 378.320587, -279.088043, -56.134182, 381.021332, -280.165344, -56.153133, 381.172882, -281.246033, -56.168983, 381.299683, -282.302917, -56.181866, 381.408691, -301.977173, -50.175457, 383.230652, -302.993134, -49.847698, 383.246735, -303.998260, -49.580284, 383.147003, -305.083649, -49.109840, 382.933411, -306.061432, -48.755005, 382.706818, -307.152679, -48.355675, 382.435608, -327.497711, -45.027401, 377.016663, -328.548553, -45.009663, 376.735291, -331.569672, -45.071396, 375.927429, -332.566711, -45.084835, 375.500153, -333.347351, -45.055779, 374.749634, -333.952423, -44.990082, 373.848999, -334.454071, -44.958176, 372.884399, -334.909607, -44.930862, 371.896698, -335.338989, -44.939476, 370.897034, -336.319305, -45.033978, 368.508484, -344.092773, -44.934128, 349.103394, -344.599304, -44.920494, 348.142578, -345.289124, -44.948330, 347.305328, -346.152740, -44.981884, 346.646881, -347.087494, -45.014847, 346.091278, -348.052368, -45.047348, 345.589172, -349.030975, -45.039383, 345.114044, -350.016052, -45.036438, 344.652252, -357.274414, -45.947830, 341.359833, -358.277222, -46.126381, 340.958984, -359.326965, -46.091412, 340.679291, -360.404205, -46.072746, 340.529785, -361.488525, -46.061684, 340.441284, -362.575226, -46.055046, 340.388184, -363.662323, -46.050694, 340.353088, -367.288086, -45.562141, 340.276978, -397.408386, -46.031933, 339.796722, -427.522491, -45.366581, 339.319641, -457.651947, -45.910805, 338.841827, -463.498932, -45.831551, 338.757111, -464.580750, -45.752060, 338.776215, -465.656433, -45.603558, 338.822693, -467.953491, -45.463387, 338.967407, -494.403381, -45.661190, 340.958710, -495.442017, -45.667831, 341.254303, -496.256042, -45.713417, 341.966400, -496.865723, -45.720673, 342.866852, -497.385132, -45.755371, 343.821838, -498.376312, -45.856812, 345.908539, -498.820007, -45.996841, 346.899353, -499.174530, -46.197227, 347.923767, -499.352539, -46.093906, 348.989563, -499.416016, -46.074814, 350.073944, -499.423279, -46.070366, 351.161072, -499.397400, -46.084679, 352.248505, -499.358795, -46.133957, 353.335815, -498.771545, -46.025249, 365.000885, -498.687347, -45.804886, 366.615082, -498.166779, -45.846115, 376.640106, -498.109924, -45.862961, 377.726410, -497.697968, -45.951462, 385.738007, -497.694122, -46.004673, 386.825317, -497.737915, -46.056293, 387.912231, -497.809082, -46.020039, 388.997162, -498.192322, -46.074364, 393.595886, -499.513733, -47.018887, 408.449036, -499.682556, -47.223618, 409.509949, -499.959503, -47.415245, 410.549194, -500.307434, -47.595810, 411.566589, -500.686859, -48.017868, 412.545349, -501.077026, -48.478256, 413.506836, -501.873901, -49.394321, 415.425659, -502.207245, -49.737534, 416.425812, -502.382660, -50.058594, 417.464630, -502.406891, -50.394829, 418.516327, -502.342438, -50.724243, 419.565948, -502.251190, -51.088074, 420.607056, -502.139435, -51.460213, 421.645935, -501.954468, -52.022106, 423.198792, -500.171021, -55.784023, 437.153931, -500.033447, -56.010731, 438.356873, -499.879120, -56.021641, 439.981689, -499.679840, -55.963177, 442.392639, -499.790558, -55.536102, 443.497894, -500.205383, -55.237358, 444.453308, -500.785736, -55.148598, 445.369598, -501.427277, -55.099243, 446.246521, -502.103760, -55.051254, 447.097015, -502.791046, -55.003696, 447.939423, -503.574524, -55.015862, 448.879730, -510.872284, -55.089428, 457.484222, -511.691742, -55.159729, 458.188812, -512.678040, -55.280975, 458.628448, -513.720825, -55.419674, 458.910309, -514.785461, -55.554832, 459.097260, -515.851929, -55.741619, 459.240265, -516.923096, -55.906597, 459.366913, -517.998413, -56.087105, 459.482513, -521.921387, -56.035919, 459.879913, -522.965271, -55.886223, 460.131927, -523.947327, -55.785652, 460.568665, -524.886719, -55.581245, 461.082581, -525.805237, -55.438984, 461.645203, -526.824829, -55.279068, 462.300720, -531.560181, -54.945484, 465.464722, -532.406555, -54.961479, 466.143524, -533.060120, -54.995003, 467.010559, -533.618408, -55.030079, 467.943695, -534.158691, -55.026203, 468.887848, -538.343323, -55.609158, 476.336639, -538.852539, -55.920918, 477.273773, -539.335510, -56.089600, 478.277985, -539.767029, -56.035652, 479.274902, -540.283997, -56.042004, 480.532135, -544.975769, -55.047729, 492.510040, -545.471375, -55.034317, 493.475891, -546.206604, -55.009632, 494.270599, -547.121643, -54.949020, 494.853882, -548.100342, -54.921333, 495.329163, -549.105103, -54.930302, 495.747131, -550.121033, -54.979893, 496.133270, -551.140991, -55.035213, 496.507385, -556.089600, -55.924522, 498.256134, -557.125793, -56.028824, 498.568329, -558.182983, -56.208153, 498.806641, -559.256592, -56.133862, 498.981354, -560.335327, -56.116646, 499.118896, -562.091736, -56.104050, 499.314911, -574.530396, -56.559124, 500.553680, -575.606262, -56.603722, 500.706024, -576.649963, -56.813107, 500.963989, -577.670288, -57.037365, 501.291138, -578.679321, -57.266209, 501.647278, -579.683105, -57.510010, 502.019379, -581.321777, -57.800549, 502.643463, -608.199463, -60.061394, 513.086548, -- turn around -607.195618, -59.956524, 512.696411, -579.141602, -57.367210, 501.788940, -578.157959, -57.136345, 501.407318, -577.150146, -56.915344, 501.086304, -576.116089, -56.711021, 500.848358, -575.049622, -56.572414, 500.676178, -573.971497, -56.540531, 500.535004, -572.891418, -56.511803, 500.410767, -571.541260, -56.454227, 500.267334, -559.917480, -56.117676, 499.110870, -558.841248, -56.137356, 498.953400, -557.782593, -56.166878, 498.714447, -556.750061, -55.982758, 498.415985, -555.608704, -55.807209, 498.053894, -553.104614, -55.239231, 497.204651, -547.725464, -54.925472, 495.326019, -546.765625, -54.984024, 494.821899, -546.022339, -55.011047, 494.032928, -545.445923, -55.024132, 493.110931, -544.951660, -55.061985, 492.142212, -544.503357, -55.055382, 491.151031, -544.083557, -55.041119, 490.147827, -543.675354, -55.021049, 489.139801, -540.065735, -56.014805, 479.933258, -539.634155, -56.052246, 478.935516, -539.166565, -56.161896, 477.960266, -538.697327, -55.847233, 477.044403, -538.208557, -55.557598, 476.136658, -537.436646, -55.298710, 474.733032, -533.392761, -55.013466, 467.513885, -532.726868, -54.979912, 466.657013, -531.930054, -54.948929, 465.917389, -531.075134, -54.949390, 465.244354, -530.197693, -54.950920, 464.600464, -529.308838, -54.990524, 463.974792, -525.172791, -55.543240, 461.159485, -524.214478, -55.720425, 460.668243, -523.196838, -55.850220, 460.304413, -522.141357, -56.015007, 460.066986, -521.068726, -56.020702, 459.886475, -519.991577, -56.039570, 459.735687, -518.911011, -56.055336, 459.609558, -517.433777, -55.982838, 459.449738, -513.966614, -55.460213, 459.099396, -512.921997, -55.323360, 458.849701, -512.001587, -55.181244, 458.291351, -511.179230, -55.105251, 457.583893, -510.412476, -55.032543, 456.816132, -509.680267, -54.958725, 456.014191, -508.602783, -54.942749, 454.788452, -500.669189, -55.143158, 445.473999, -500.128296, -55.247131, 444.541412, -499.898651, -55.518276, 443.507935, -499.821869, -55.910942, 442.468292, -499.832764, -56.027439, 441.384308, -499.881256, -56.021374, 440.297485, -499.962463, -56.011227, 439.212982, -500.072205, -56.031265, 438.133789, -500.329163, -55.395157, 435.970062, -502.441742, -50.690495, 419.476440, -502.485474, -50.371307, 418.460999, -502.368835, -50.054039, 417.447144, -502.131531, -49.750740, 416.450317, -501.775696, -49.393009, 415.406342, -501.394318, -48.913757, 414.410278, -500.999023, -48.445408, 413.431396, -500.303253, -47.637516, 411.756561, -499.980103, -47.454823, 410.747284, -499.763947, -47.256901, 409.705627, -499.603699, -47.051754, 408.654358, -499.474274, -46.886150, 407.591583, -499.360931, -46.714558, 406.528320, -497.842590, -45.999271, 389.667542, -497.735077, -46.047218, 388.312012, -497.702972, -46.022728, 387.226166, -497.717407, -45.968018, 386.140686, -497.752014, -45.910450, 385.054596, -498.532532, -45.704178, 369.587616, -498.589294, -45.753151, 368.501129, -499.547089, -46.040310, 350.040375, -499.412354, -46.078503, 348.964417, -499.099609, -46.221172, 347.926239, -498.741913, -46.030338, 346.926208, -498.351959, -45.860306, 345.923828, -497.941467, -45.805256, 344.918884, -497.518524, -45.751751, 343.918427, -497.074768, -45.707314, 342.926636, -496.434631, -45.690395, 342.056549, -495.518555, -45.685642, 341.481903, -494.478638, -45.677624, 341.169525, -493.406281, -45.681431, 340.990509, -492.333801, -46.148170, 340.858154, -491.272858, -45.972626, 340.751801, -490.196564, -45.903652, 340.655212, -466.653748, -45.466057, 338.859863, -465.575256, -45.615093, 338.803314, -464.496521, -45.763508, 338.779785, -463.410126, -45.832458, 338.774506, -433.375122, -45.735828, 339.226624, -403.243805, -46.015915, 339.704468, } function onSpawn(npc) npc:initNpcAi() npc:setPos(dsp.path.first(path)) onPath(npc) end function onPath(npc) if npc:atPoint(dsp.path.get(path, 45)) then GetNPCByID(npc:getID() + 3):showText(npc, ID.text.PALCOMONDAU_REPORT) -- small delay after path finish npc:wait(8000) end dsp.path.patrol(npc, path) end function onTrade(player, npc, trade) end function onTrigger(player, npc) player:showText(npc, ID.text.PALCOMONDAU_DIALOG) --npc:wait(1500) end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Bastok_Mines/npcs/Arva.lua
13
1290
----------------------------------- -- Area: Bastok Mines -- NPC: Arva -- Adventurer's Assistant -- Working 100% ------------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(0x218,1) == true) then player:startEvent(0x0004); player:addGil(GIL_RATE*50); player:tradeComplete(); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0003); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0004) then player:messageSpecial(GIL_OBTAINED,GIL_RATE*50); end end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Norg/npcs/Ranemaud.lua
9
3367
----------------------------------- -- Area: Norg -- NPC: Ranemaud -- Involved in Quest: Forge Your Destiny, The Sacred Katana -- !pos 15 0 23 252 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); local ID = require("scripts/zones/Norg/IDs"); ----------------------------------- function onTrade(player,npc,trade) local questItem = player:getCharVar("ForgeYourDestiny_Event"); local checkItem = testflag(tonumber(questItem),0x02); if (checkItem == true) then if (trade:hasItemQty(738,1) and trade:hasItemQty(737,2) and trade:getItemCount() == 3) then player:startEvent(43,0,0,738,737); -- Platinum Ore, Gold Ore end end if (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.THE_SACRED_KATANA) == QUEST_ACCEPTED and player:hasItem(17809) == false) then if (trade:getGil() == 30000 and trade:getItemCount() == 1 and player:getFreeSlotsCount() >= 1) then player:startEvent(145); end end end; ----------------------------------- -- Event Check ----------------------------------- function testflag(set,flag) return (set % (2*flag) >= flag) end; function onTrigger(player,npc) local swordTimer = player:getCharVar("ForgeYourDestiny_timer") if (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.FORGE_YOUR_DESTINY) == QUEST_ACCEPTED and swordTimer == 0) then if (player:hasItem(1153)) then player:startEvent(48,1153); -- Sacred Branch elseif (player:hasItem(1198) == false) then local questItem = player:getCharVar("ForgeYourDestiny_Event"); local checkItem = testflag(tonumber(questItem),0x02); if (checkItem == false) then player:startEvent(40,1153,1198); -- Sacred Branch, Sacred Sprig elseif (checkItem == true) then player:startEvent(42,0,0,738,737); -- Platinum Ore, Gold Ore end elseif (player:hasItem(1198)) then -- Sacred Sprig player:startEvent(41); end elseif (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.THE_SACRED_KATANA) == QUEST_ACCEPTED and player:hasItem(17809) == false) then player:startEvent(144); else player:startEvent(68); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) local questItem = player:getCharVar("ForgeYourDestiny_Event"); if (csid == 40) then if (player:getFreeSlotsCount(0) >= 1) then player:addItem(1198); player:messageSpecial(ID.text.ITEM_OBTAINED, 1198); -- Sacred Sprig player:setCharVar("ForgeYourDestiny_Event",questItem + 0x02); else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 1151); -- Oriental Steel end elseif (csid == 43) then if (player:getFreeSlotsCount(0) >= 1) then player:tradeComplete(); player:addItem(1198); player:messageSpecial(ID.text.ITEM_OBTAINED, 1198); -- Sacred Sprig else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED, 1198); -- Sacred Sprig end elseif (csid == 145) then player:tradeComplete(); player:addItem(17809); player:messageSpecial(ID.text.ITEM_OBTAINED,17809); -- Mumeito end end;
gpl-3.0
MartinFrancu/BETS
chili_clone/controls/editbox_clone.lua
1
10165
--//============================================================================= --- EditBox module --- EditBox fields. -- Inherits from Control. -- @see control.Control -- @table EditBox -- @tparam {r,g,b,a} cursorColor cursor color, (default {0,0,1,0.7}) -- @tparam {r,g,b,a} selectionColor selection color, (default {0,1,1,0.3}) -- @string[opt="left"] align alignment -- @string[opt="linecenter"] valign vertical alignment -- @string[opt=""] text text contained in the editbox -- @string[opt=""] hint hint to be displayed when there is no text and the control isn't focused -- @int[opt=1] cursor cursor position -- @bool passwordInput specifies whether the text should be treated as a password EditBox = Control:Inherit{ classname= "editbox", defaultWidth = 70, defaultHeight = 20, padding = {3,3,3,3}, cursorColor = {0,0,1,0.7}, selectionColor = {0,1,1,0.3}, align = "left", valign = "linecenter", hintFont = table.merge({ color = {1,1,1,0.7} }, Control.font), text = "", hint = "", cursor = 1, offset = 1, selStart = nil, selEnd = nil, allowUnicode = true, passwordInput = false, } if Script.IsEngineMinVersion == nil or not Script.IsEngineMinVersion(97) then EditBox.allowUnicode = false end local this = EditBox local inherited = this.inherited --//============================================================================= function EditBox:New(obj) obj = inherited.New(self,obj) obj._interactedTime = Spring.GetTimer() --// create font obj.hintFont = Font:New(obj.hintFont) obj.hintFont:SetParent(obj) obj:SetText(obj.text) obj:RequestUpdate() return obj end function EditBox:Dispose(...) Control.Dispose(self) self.hintFont:SetParent() end function EditBox:HitTest(x,y) return self end --//============================================================================= --- Sets the EditBox text -- @string newtext text to be set function EditBox:SetText(newtext) if (self.text == newtext) then return end self.text = newtext self.cursor = 1 self.offset = 1 self.selStart = nil self.selEnd = nil self:UpdateLayout() self:Invalidate() end function EditBox:UpdateLayout() local font = self.font --FIXME if (self.autosize) then local w = math.max(font:GetTextWidth(self.text), self.minWidth or 40); local h, d, numLines = font:GetTextHeight(self.text); if (self.autoObeyLineHeight) then h = math.ceil(numLines * font:GetLineHeight()) else h = math.ceil(h-d) end h = math.max(h, 16) local x = self.x local y = self.y if self.valign == "center" then y = math.round(y + (self.height - h) * 0.5) elseif self.valign == "bottom" then y = y + self.height - h elseif self.valign == "top" then else end if self.align == "left" then elseif self.align == "right" then x = x + self.width - w elseif self.align == "center" then x = math.round(x + (self.width - w) * 0.5) end w = w + self.padding[1] + self.padding[3] h = h + self.padding[2] + self.padding[4] self:_UpdateConstraints(x,y,w,h) end end --//============================================================================= function EditBox:Update(...) --FIXME add special UpdateFocus event? --// redraw every few frames for blinking cursor inherited.Update(self, ...) if self.state.focused then self:RequestUpdate() if (os.clock() >= (self._nextCursorRedraw or -math.huge)) then self._nextCursorRedraw = os.clock() + 0.1 --10FPS self:Invalidate() end end end function EditBox:_SetCursorByMousePos(x, y) local clientX = self.clientArea[1] if x - clientX < 0 then self.offset = self.offset - 1 self.offset = math.max(0, self.offset) self.cursor = self.offset + 1 else local text = self.text -- properly accounts for passworded text where characters are represented as "*" -- TODO: what if the passworded text is displayed differently? this is using assumptions about the skin if #text > 0 and self.passwordInput then text = string.rep("*", #text) end self.cursor = #text + 1 -- at end of text for i = self.offset, #text do local tmp = text:sub(self.offset, i) if self.font:GetTextWidth(tmp) > (x - clientX) then self.cursor = i break end end end end function EditBox:MouseDown(x, y, ...) local _, _, _, shift = Spring.GetModKeyState() local cp = self.cursor self:_SetCursorByMousePos(x, y) if shift then if not self.selStart then self.selStart = cp end self.selEnd = self.cursor elseif self.selStart then self.selStart = nil self.selEnd = nil end self._interactedTime = Spring.GetTimer() inherited.MouseDown(self, x, y, ...) self:Invalidate() return self end function EditBox:MouseMove(x, y, dx, dy, button) if button ~= 1 then return inherited.MouseMove(self, x, y, dx, dy, button) end local _, _, _, shift = Spring.GetModKeyState() local cp = self.cursor self:_SetCursorByMousePos(x, y) if not self.selStart then self.selStart = cp end self.selEnd = self.cursor self._interactedTime = Spring.GetTimer() inherited.MouseMove(self, x, y, dx, dy, button) self:Invalidate() return self end function EditBox:MouseUp(...) inherited.MouseUp(self, ...) self:Invalidate() return self end function EditBox:Select(startIndex, endIndex) self.selStart = startIndex self.selEnd = endIndex self:Invalidate() end function EditBox:ClearSelected() local left = self.selStart local right = self.selEnd if left > right then left, right = right, left end self.cursor = right local i = 0 while self.cursor ~= left do self.text, self.cursor = Utf8BackspaceAt(self.text, self.cursor) i = i + 1 if i > 100 then break end end self.selStart = nil self.selEnd = nil self:Invalidate() end function EditBox:KeyPress(key, mods, isRepeat, label, unicode, ...) local cp = self.cursor local txt = self.text -- enter & return if key == Spring.GetKeyCode("enter") or key == Spring.GetKeyCode("numpad_enter") then return inherited.KeyPress(self, key, mods, isRepeat, label, unicode, ...) or true -- deletions elseif key == Spring.GetKeyCode("backspace") then if self.selStart == nil then if mods.ctrl then repeat self.text, self.cursor = Utf8BackspaceAt(self.text, self.cursor) until self.cursor == 1 or (self.text:sub(self.cursor-2, self.cursor-2) ~= " " and self.text:sub(self.cursor-1, self.cursor-1) == " ") else self.text, self.cursor = Utf8BackspaceAt(self.text, self.cursor) end else self:ClearSelected() end elseif key == Spring.GetKeyCode("delete") then if self.selStart == nil then if mods.ctrl then repeat self.text = Utf8DeleteAt(self.text, self.cursor) until self.cursor >= #self.text-1 or (self.text:sub(self.cursor, self.cursor) == " " and self.text:sub(self.cursor+1, self.cursor+1) ~= " ") else self.text = Utf8DeleteAt(txt, cp) end else self:ClearSelected() end -- cursor movement elseif key == Spring.GetKeyCode("left") then if mods.ctrl then repeat self.cursor = Utf8PrevChar(txt, self.cursor) until self.cursor == 1 or (txt:sub(self.cursor-1, self.cursor-1) ~= " " and txt:sub(self.cursor, self.cursor) == " ") else self.cursor = Utf8PrevChar(txt, cp) end elseif key == Spring.GetKeyCode("right") then if mods.ctrl then repeat self.cursor = Utf8NextChar(txt, self.cursor) until self.cursor >= #txt-1 or (txt:sub(self.cursor-1, self.cursor-1) == " " and txt:sub(self.cursor, self.cursor) ~= " ") else self.cursor = Utf8NextChar(txt, cp) end elseif key == Spring.GetKeyCode("home") then self.cursor = 1 elseif key == Spring.GetKeyCode("end") then self.cursor = #txt + 1 -- copy & paste elseif mods.ctrl and (key == Spring.GetKeyCode("c") or key == Spring.GetKeyCode("x")) then local s = self.selStart local e = self.selEnd if s and e then s,e = math.min(s,e), math.max(s,e) Spring.SetClipboard(txt:sub(s,e-1)) end if key == Spring.GetKeyCode("x") and self.selStart ~= nil then self:ClearSelected() end elseif mods.ctrl and key == Spring.GetKeyCode("v") then self:TextInput(Spring.GetClipboard()) -- select all elseif mods.ctrl and key == Spring.GetKeyCode("a") then self.selStart = 1 self.selEnd = #txt + 1 -- character input elseif unicode and unicode ~= 0 then -- backward compability with Spring <97 self:TextInput(unicode) end -- text selection handling if key == Spring.GetKeyCode("left") or key == Spring.GetKeyCode("right") or key == Spring.GetKeyCode("home") or key == Spring.GetKeyCode("end") then if mods.shift then if not self.selStart then self.selStart = cp end self.selEnd = self.cursor elseif self.selStart then self.selStart = nil self.selEnd = nil end end self._interactedTime = Spring.GetTimer() inherited.KeyPress(self, key, mods, isRepeat, label, unicode, ...) self:UpdateLayout() self:Invalidate() if(self.parent and self.parent.treeNode) then self.parent.treeNode:UpdateDimensions() end return self end function EditBox:TextInput(utf8char, ...) local unicode = utf8char if (not self.allowUnicode) then local success success, unicode = pcall(string.char, utf8char) if success then success = not unicode:find("%c") end if not success then unicode = nil end end if unicode then local cp = self.cursor local txt = self.text if self.selStart ~= nil then self:ClearSelected() txt = self.text cp = self.cursor end self.text = txt:sub(1, cp - 1) .. unicode .. txt:sub(cp, #txt) self.cursor = cp + unicode:len() end self._interactedTime = Spring.GetTimer() inherited.TextInput(self, utf8char, ...) self:UpdateLayout() self:Invalidate() return self end --//=============================================================================
mit
crunchuser/prosody-modules
mod_compat_muc_admin/mod_compat_muc_admin.lua
32
11261
local st = require "util.stanza"; local jid_split = require "util.jid".split; local jid_bare = require "util.jid".bare; local jid_prep = require "util.jid".prep; local log = require "util.logger".init("mod_muc"); local muc_host = module:get_host(); if not hosts[muc_host].modules.muc then -- Not a MUC host module:log("error", "this module can only be used on muc hosts."); return false; end -- Constants and imported functions from muc.lib.lua local xmlns_ma, xmlns_mo = "http://jabber.org/protocol/muc#admin", "http://jabber.org/protocol/muc#owner"; local kickable_error_conditions = { ["gone"] = true; ["internal-server-error"] = true; ["item-not-found"] = true; ["jid-malformed"] = true; ["recipient-unavailable"] = true; ["redirect"] = true; ["remote-server-not-found"] = true; ["remote-server-timeout"] = true; ["service-unavailable"] = true; ["malformed error"] = true; }; local function get_error_condition(stanza) local _, condition = stanza:get_error(); return condition or "malformed error"; end local function is_kickable_error(stanza) local cond = get_error_condition(stanza); return kickable_error_conditions[cond] and cond; end local function build_unavailable_presence_from_error(stanza) local type, condition, text = stanza:get_error(); local error_message = "Kicked: "..(condition and condition:gsub("%-", " ") or "presence error"); if text then error_message = error_message..": "..text; end return st.presence({type='unavailable', from=stanza.attr.from, to=stanza.attr.to}) :tag('status'):text(error_message); end local function getUsingPath(stanza, path, getText) local tag = stanza; for _, name in ipairs(path) do if type(tag) ~= 'table' then return; end tag = tag:child_with_name(name); end if tag and getText then tag = table.concat(tag); end return tag; end local function getText(stanza, path) return getUsingPath(stanza, path, true); end -- COMPAT: iq condensed function hosts[muc_host].modules.muc.stanza_handler.muc_new_room.room_mt["compat_iq"] = function (self, origin, stanza, xmlns) local actor = stanza.attr.from; local affiliation = self:get_affiliation(actor); local current_nick = self._jid_nick[actor]; local role = current_nick and self._occupants[current_nick].role or self:get_default_role(affiliation); local item = stanza.tags[1].tags[1]; if item and item.name == "item" then if stanza.attr.type == "set" then local callback = function() origin.send(st.reply(stanza)); end if item.attr.jid then -- Validate provided JID item.attr.jid = jid_prep(item.attr.jid); if not item.attr.jid then origin.send(st.error_reply(stanza, "modify", "jid-malformed")); return; end end if not item.attr.jid and item.attr.nick then -- COMPAT Workaround for Miranda sending 'nick' instead of 'jid' when changing affiliation local occupant = self._occupants[self.jid.."/"..item.attr.nick]; if occupant then item.attr.jid = occupant.jid; end elseif not item.attr.nick and item.attr.jid then local nick = self._jid_nick[item.attr.jid]; if nick then item.attr.nick = select(3, jid_split(nick)); end end local reason = item.tags[1] and item.tags[1].name == "reason" and #item.tags[1] == 1 and item.tags[1][1]; if item.attr.affiliation and item.attr.jid and not item.attr.role then local success, errtype, err = self:set_affiliation(actor, item.attr.jid, item.attr.affiliation, callback, reason); if not success then origin.send(st.error_reply(stanza, errtype, err)); end elseif item.attr.role and item.attr.nick and not item.attr.affiliation then local success, errtype, err = self:set_role(actor, self.jid.."/"..item.attr.nick, item.attr.role, callback, reason); if not success then origin.send(st.error_reply(stanza, errtype, err)); end else origin.send(st.error_reply(stanza, "cancel", "bad-request")); end elseif stanza.attr.type == "get" then local _aff = item.attr.affiliation; local _rol = item.attr.role; if _aff and not _rol then if affiliation == "owner" or (affiliation == "admin" and _aff ~= "owner" and _aff ~= "admin") then local reply = st.reply(stanza):query(xmlns); for jid, affiliation in pairs(self._affiliations) do if affiliation == _aff then reply:tag("item", {affiliation = _aff, jid = jid}):up(); end end origin.send(reply); else origin.send(st.error_reply(stanza, "auth", "forbidden")); end elseif _rol and not _aff then if role == "moderator" then -- TODO allow admins and owners not in room? Provide read-only access to everyone who can see the participants anyway? if _rol == "none" then _rol = nil; end local reply = st.reply(stanza):query(xmlns); for occupant_jid, occupant in pairs(self._occupants) do if occupant.role == _rol then reply:tag("item", { nick = select(3, jid_split(occupant_jid)), role = _rol or "none", affiliation = occupant.affiliation or "none", jid = occupant.jid }):up(); end end origin.send(reply); else origin.send(st.error_reply(stanza, "auth", "forbidden")); end else origin.send(st.error_reply(stanza, "cancel", "bad-request")); end end elseif stanza.attr.type == "set" or stanza.attr.type == "get" then origin.send(st.error_reply(stanza, "cancel", "bad-request")); end end -- COMPAT: reworked handle_to_room function hosts[muc_host].modules.muc.stanza_handler.muc_new_room.room_mt["handle_to_room"] = function (self, origin, stanza) local type = stanza.attr.type; local xmlns = stanza.tags[1] and stanza.tags[1].attr.xmlns; if stanza.name == "iq" then if xmlns == "http://jabber.org/protocol/disco#info" and type == "get" then origin.send(self:get_disco_info(stanza)); elseif xmlns == "http://jabber.org/protocol/disco#items" and type == "get" then origin.send(self:get_disco_items(stanza)); elseif xmlns == xmlns_ma or xmlns == xmlns_mo then if xmlns == xmlns_ma then self:compat_iq(origin, stanza, xmlns); elseif xmlns == xmlns_mo and (type == "set" or type == "get") and stanza.tags[1].name == "query" then local owner_err = st.error_reply(stanza, "auth", "forbidden", "Only owners can configure rooms"); if #stanza.tags[1].tags == 0 and stanza.attr.type == "get" then if self:get_affiliation(stanza.attr.from) ~= "owner" then origin.send(owner_err); else self:send_form(origin, stanza); end elseif stanza.attr.type == "set" and stanza.tags[1]:get_child("x", "jabber:x:data") then if self:get_affiliation(stanza.attr.from) ~= "owner" then origin.send(owner_err); else self:process_form(origin, stanza); end elseif stanza.tags[1].tags[1].name == "destroy" then if self:get_affiliation(stanza.attr.from) == "owner" then local newjid = stanza.tags[1].tags[1].attr.jid; local reason, password; for _,tag in ipairs(stanza.tags[1].tags[1].tags) do if tag.name == "reason" then reason = #tag.tags == 0 and tag[1]; elseif tag.name == "password" then password = #tag.tags == 0 and tag[1]; end end self:destroy(newjid, reason, password); origin.send(st.reply(stanza)); else origin.send(owner_err); end else self:compat_iq(origin, stanza, xmlns); end else origin.send(st.error_reply(stanza, "modify", "bad-request")); end elseif type == "set" or type == "get" then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end elseif stanza.name == "message" and type == "groupchat" then local from, to = stanza.attr.from, stanza.attr.to; local room = jid_bare(to); local current_nick = self._jid_nick[from]; local occupant = self._occupants[current_nick]; if not occupant then -- not in room origin.send(st.error_reply(stanza, "cancel", "not-acceptable")); elseif occupant.role == "visitor" then origin.send(st.error_reply(stanza, "cancel", "forbidden")); else local from = stanza.attr.from; stanza.attr.from = current_nick; local subject = getText(stanza, {"subject"}); if subject then if occupant.role == "moderator" or ( self._data.changesubject and occupant.role == "participant" ) then -- and participant self:set_subject(current_nick, subject); -- TODO use broadcast_message_stanza else stanza.attr.from = from; origin.send(st.error_reply(stanza, "cancel", "forbidden")); end else self:broadcast_message(stanza, true); end stanza.attr.from = from; end elseif stanza.name == "message" and type == "error" and is_kickable_error(stanza) then local current_nick = self._jid_nick[stanza.attr.from]; log("debug", "%s kicked from %s for sending an error message", current_nick, self.jid); self:handle_to_occupant(origin, build_unavailable_presence_from_error(stanza)); -- send unavailable elseif stanza.name == "presence" then -- hack - some buggy clients send presence updates to the room rather than their nick local to = stanza.attr.to; local current_nick = self._jid_nick[stanza.attr.from]; if current_nick then stanza.attr.to = current_nick; self:handle_to_occupant(origin, stanza); stanza.attr.to = to; elseif type ~= "error" and type ~= "result" then origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end elseif stanza.name == "message" and not stanza.attr.type and #stanza.tags == 1 and self._jid_nick[stanza.attr.from] and stanza.tags[1].name == "x" and stanza.tags[1].attr.xmlns == "http://jabber.org/protocol/muc#user" then local x = stanza.tags[1]; local payload = (#x.tags == 1 and x.tags[1]); if payload and payload.name == "invite" and payload.attr.to then local _from, _to = stanza.attr.from, stanza.attr.to; local _invitee = jid_prep(payload.attr.to); if _invitee then local _reason = payload.tags[1] and payload.tags[1].name == 'reason' and #payload.tags[1].tags == 0 and payload.tags[1][1]; local invite = st.message({from = _to, to = _invitee, id = stanza.attr.id}) :tag('x', {xmlns='http://jabber.org/protocol/muc#user'}) :tag('invite', {from=_from}) :tag('reason'):text(_reason or ""):up() :up(); if self:get_password() then invite:tag("password"):text(self:get_password()):up(); end invite:up() :tag('x', {xmlns="jabber:x:conference", jid=_to}) -- COMPAT: Some older clients expect this :text(_reason or "") :up() :tag('body') -- Add a plain message for clients which don't support invites :text(_from..' invited you to the room '.._to..(_reason and (' ('.._reason..')') or "")) :up(); if self:is_members_only() and not self:get_affiliation(_invitee) then log("debug", "%s invited %s into members only room %s, granting membership", _from, _invitee, _to); self:set_affiliation(_from, _invitee, "member", nil, "Invited by " .. self._jid_nick[_from]) end self:_route_stanza(invite); else origin.send(st.error_reply(stanza, "cancel", "jid-malformed")); end else origin.send(st.error_reply(stanza, "cancel", "bad-request")); end else if type == "error" or type == "result" then return; end origin.send(st.error_reply(stanza, "cancel", "service-unavailable")); end end
mit
Fenix-XI/Fenix
scripts/zones/Metalworks/npcs/Topuru-Kuperu.lua
13
1059
----------------------------------- -- Area: Metalworks -- NPC: Topuru-Kuperu -- Type: Standard NPC -- @zone: 237 -- @pos 28.284 -17.39 42.269 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00fb); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Port_Windurst/npcs/Gold_Skull.lua
13
2432
----------------------------------- -- Area: Port Windurst -- NPC: Gold Skull -- Mission NPC ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(BASTOK) ~= 255) then currentMission = player:getCurrentMission(BASTOK); missionStatus = player:getVar("MissionStatus"); if (player:hasKeyItem(SWORD_OFFERING)) then player:startEvent(0x0035); elseif (player:hasKeyItem(KINDRED_REPORT)) then player:startEvent(0x0044); elseif (currentMission == THE_EMISSARY_WINDURST2) then if (missionStatus == 7) then player:startEvent(0x003e); elseif (missionStatus == 8) then player:showText(npc,GOLD_SKULL_DIALOG + 27); elseif (missionStatus == 9) then player:startEvent(0x0039); end elseif (currentMission == THE_EMISSARY_WINDURST) then if (missionStatus == 2) then player:startEvent(0x0032); elseif (missionStatus == 12) then player:startEvent(0x0036); elseif (missionStatus == 14) then player:showText(npc,GOLD_SKULL_DIALOG); elseif (missionStatus == 15) then player:startEvent(0x0039); end else player:startEvent(0x002b); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0035) then player:addKeyItem(DULL_SWORD); player:messageSpecial(KEYITEM_OBTAINED,DULL_SWORD); player:delKeyItem(SWORD_OFFERING); end end;
gpl-3.0
knl/mjolnir.winter
winter.lua
1
16030
--- === winter === --- --- A module for moving/resizing windows using a fluent interface (see Usage below). --- --- The name winter is a portmanteu of **win**dow mas**ter**. --- --- Usage: --- --- local wintermod = require "winter" --- local winter = wintermod.new() --- --- local cmdalt = {"cmd", "alt"} --- local scmdalt = {"cmd", "alt", "shift"} --- local ccmdalt = {"ctrl", "cmd", "alt"} --- --- -- make the focused window a 200px, full-height window and put it at the left screen edge --- hotkey.bind(cmdalt, 'h', winter:focused():wide(200):tallest():leftmost():place()) --- --- -- make a full-height window and put it at the right screen edge --- hotkey.bind(cmdalt, 'j', winter:focused():tallest():rightmost():place()) --- --- -- full-height window, full-width window, and a combination --- hotkey.bind(scmdalt, '\\', winter:focused():tallest():resize()) --- hotkey.bind(scmdalt, '-', winter:focused():widest():resize()) --- hotkey.bind(scmdalt, '=', winter:focused():widest():tallest():resize()) --- --- -- push to different screen --- hotkey.bind(cmdalt, '[', winter:focused():prevscreen():move()) --- hotkey.bind(cmdalt, ']', winter:focused():nextscreen():move()) --- --- *NOTE*: One must start with `winter:focused()` or `winter:window('title')` --- and end with a command `move()`, `place()`, `resize()`, or `act()` --- (they are all synonyms for the same action). This chain of command ---- will return a function that one can pass to hotkey.bind. --- --- --- @author Nikola Knezevic --- @copyright 2015 --- @license BSD --- --- @module winter -- main module class table local winter = { _VERSION = '0.3.2', _DESCRIPTION = 'A module for moving/resizing windows using a fluent interface', _URL = 'https://github.com/knl/mjolnir.winter', } local appfinder = require "hs.appfinder" local window = require "hs.window" local mscreen = require "hs.screen" -- class that deals with coordinate transformations local CoordTrans = {} function CoordTrans:set(win, screen, f) local screenrect = screen:frame() -- print(string.format("set: screen x=%d, y=%d, w=%d, h=%d", screenrect.x, screenrect.y, screenrect.w, screenrect.h)) -- print(string.format("set: input f x=%d, y=%d, w=%d, h=%d", f.x, f.y, f.w, f.h)) newf = { x = f.x + screenrect.x, y = f.y + screenrect.y, w = f.w, h = f.h, } print(string.format("set: input f x=%d, y=%d, w=%d, h=%d", newf.x, newf.y, newf.w, newf.h)) win:setFrame(newf) end function CoordTrans:get(win, _screen) local f = win:frame() local screen = _screen or win:screen() local screenrect = screen:frame() -- print(string.format("get: screen x=%d, y=%d, w=%d, h=%d", screenrect.x, screenrect.y, screenrect.w, screenrect.h)) -- print(string.format("get: win f x=%d, y=%d, w=%d, h=%d", f.x, f.y, f.w, f.h)) return { x = f.x - screenrect.x, y = f.y - screenrect.y, w = f.w, h = f.h, screenw = screenrect.w, screenh = screenrect.h, } end local function new_coord_trans() local self = {} setmetatable(self, { __index = CoordTrans }) return self end -- class table for the main thing local Winter = {} function winter.new(ct) local self = {} self.ct = ct or new_coord_trans() setmetatable(self, { __index = Winter }) return self end -- class table representing an action on a window WinterAction = {} local function init_winter_action(title) return { -- coord transformer ct = 0, -- title of the window, '' denotes the focused window title = title, -- location x = -1, y = -1, -- dimensions w = 0, h = 0, -- changes accrued in the methods dx = 0, dy = 0, dw = 0, dh = 0, -- centering _vcenter = false, _hcenter = false, -- screen _mainscreen = false, dscreen = 0, -- for prev/next screen_compass = {}, -- for east/west/north/south -- 'mosts' _tallest = false, _widest = false, _leftmost = false, _rightmost = false, _topmost = false, _bottommost = false, } end --- mjolnir.Winter:focused() --- Function --- Creates a new WinterAction object for the focused window function Winter:focused() _self = init_winter_action('') _self.ct = self.ct setmetatable(_self, { __index = WinterAction }) return _self end --- mjolnir.Winter:window(title) --- Function --- Creates a new WinterAction object for the main window of the app titled 'title' function Winter:window(title) print(":window looking for " .. title) assert(title and title ~= '', 'Cannot find a window without a title') _self = init_winter_action(title) _self.ct = self.ct setmetatable(_self, { __index = WinterAction }) return _self end --- mjolnir.winter:snap(win) --- Function --- Snaps the window into a cell function Winter:snap(win) if win:isstandard() then self.ct:set(win, self:get(win), win:screen()) end end --- mjolnir.winteraction:xpos(x) --- Function --- Sets windows' x position to x, defaults to 0 function WinterAction:xpos(x) self.x = x or 0 self._leftmost = false self._rightmost = false return self end --- mjolnir.winteraction:ypos(y) --- Function --- Sets windows' y position to y, defaults to 0 function WinterAction:ypos(y) self.y = y or 0 self._topmost = false self._bottommost = false return self end --- mjolnir.winteraction:right(by) --- Function --- Moves the window to the right 'by' units. 'by' defaults to 1. function WinterAction:right(by) self.dx = self.dx + (by or 1) return self end --- mjolnir.winteraction:left(by) --- Function --- Moves the window to the left 'by' units. 'by' defaults to 1. function WinterAction:left(by) self.dx = self.dx - (by or 1) return self end --- mjolnir.winteraction:up(by) --- Function --- Moves the window to the up 'by' units. 'by' defaults to 1. function WinterAction:up(by) self.dy = self.dy - (by or 1) return self end --- mjolnir.winteraction:down() --- Function --- Moves the window to the down 'by' units. 'by' defaults to 1. function WinterAction:down(by) self.dy = self.dy + (by or 1) return self end --- mjolnir.winteraction:wide(w) --- Function --- Set's the window to be w units wide. function WinterAction:wide(w) self.w = w self._widest = false return self end --- mjolnir.winteraction:tall(h) --- Function --- Set's the window to be h units tall. function WinterAction:tall(h) self.h = h self._tallest = false return self end --- mjolnir.winteraction:thinner(by) --- Function --- Makes the window thinner by 'by' units. --- by can be a negative number, too. --- If by is omitted, defaults to 1. function WinterAction:thinner(by) self.dw = self.dw - (by or 1) self._widest = false return self end --- mjolnir.winteraction:wider(by) --- Function --- Makes the window wider by 'by' units. --- by can be a negative number, too. --- If by is omitted, defaults to 1. function WinterAction:wider(by) self.dw = self.dw + (by or 1) self._widest = false return self end --- mjolnir.winteraction:taller(by) --- Function --- Makes the window taller by 'by' units. --- by can be a negative number, too. --- If by is omitted, defaults to 1. function WinterAction:taller(by) self.dh = self.dh + (by or 1) self._tallest = false return self end --- mjolnir.winteraction:shorter(by) --- Function --- Makes the window taller by 'by' units. --- by can be a negative number, too. --- If by is omitted, defaults to 1. function WinterAction:shorter(by) self.dh = self.dh - (by or 1) self._tallest = false return self end --- mjolnir.winteraction:tallest() --- Function --- Makes windows' height the height of the screen. function WinterAction:tallest() self._tallest = true self.dh = 0 self.h = 0 self.y = 0 return self end --- mjolnir.winteraction:widest() --- Function --- Makes windows' width the width of the screen. function WinterAction:widest() self._widest = true self.dw = 0 self.w = 0 self.x = 0 return self end --- mjolnir.winteraction:leftmost() --- Function --- Makes the window align with the left screen border. Any preceding --- commands to change the horizontal position of the window are --- forgotten. function WinterAction:leftmost() self.dx = 0 self._leftmost = true return self end --- mjolnir.winteraction:rightmost() --- Function --- Makes the window align with the right screen border. Any preceding --- commands to change the horizontal position of the window are --- forgotten. function WinterAction:rightmost() self.dx = 0 self._rightmost = true return self end --- mjolnir.winteraction:topmost() --- Function --- Makes the window align with the top screen border. Any preceding --- commands to change the vertical position of the window are --- forgotten. function WinterAction:topmost() self.dy = 0 self._topmost = true return self end --- mjolnir.winteraction:bottommost() --- Function --- Makes the window align with the bottom screen border. Any preceding --- commands to change the vertical position of the window are --- forgotten. function WinterAction:bottommost() self.dy = 0 self._bottommost = true return self end --- mjolnir.winteraction:nextscreen() --- Function --- Moves the focused window to the next screen, using its current position on that screen. --- Will reset any of the directional commands (screen() with param 'east'/'west'/'south'/'north'). function WinterAction:nextscreen() -- self._mainscreen = false self.screen_compass = {} self.dscreen = self.dscreen + 1 print("dscreen is " .. self.dscreen) return self end --- mjolnir.winteraction:prevscreen() --- Function --- Moves the window to the previous screen, using its current position on that screen. --- Will reset any of the directional commands (screen() with param 'east'/'west'/'south'/'north'). function WinterAction:prevscreen() -- self._mainscreen = false self.screen_compass = {} self.dscreen = self.dscreen - 1 print("dscreen is " .. self.dscreen) return self end --- mjolnir.winteraction:mainscreen() --- Function --- Moves the window to the main screen, using its current position on that screen. --- Will reset any of the directional commands (screen() with param 'east'/'west'/'south'/'north'), --- in addition to reseting any prev/next screen commands. function WinterAction:mainscreen() self._mainscreen = true self.screen_compass = {} self.dscreen = 0 return self end --- mjolnir.winteraction:screen(direction) --- Function --- Moves the window to the screen denoted with direction, using its current position on that screen. --- Direction must be one of 'east', 'west', 'north', or 'south'. If direction is missing, --- the function does nothing. An invocation of this method with a valid parameter will reset actions of --- any previous call to previous or next screen, but not mainscreen(). function WinterAction:screen(direction) if not direction then return self end local directions = { east=true, west=true, north=true, south=true } if not items[direction] then print("Direction " .. direction .. " not recognized for screen(direction)") return self end self.dscreen = 0 table.insert(self.screen_compass, direction) return self end --- mjolnir.winteraction:vcenter() --- Function --- Does a vertical centering of the window on the screen. This method --- might not do anything if it is not sensible for a given setting --- (for example, on a 2x2 grid, where window is 1 cell wide). function WinterAction:vcenter() self._vcenter = true self._dx = 0 self._x = -1 return self end --- mjolnir.winteraction:hcenter() --- Function --- Does a horizontal centering of the window on the screen. This method --- might not do anything if it is not sensible for a given setting --- (for example, on a 2x2 grid, where window is 1 cell high). function WinterAction:hcenter() self._hcenter = true self._dy = 0 self._y = -1 return self end --- mjolnir.winteraction:act() --- Function --- Finalizes all previous commands for changing windows' size and --- position. This command will produce an anonymous, parameterless --- function that can be fed to hotkey.bind method (from hotkey --- package). function WinterAction:act() return function() local f = {} local win = nil print("Now in act") if self.title and self.title ~= '' then print('looking for title ' .. self.title) local app = appfinder.appFromName(self.title) if not app then error(string.format('Could not find application with title "%s"', self.title)) end win = app:mainWindow() if not win then error(string.format('Application "%s" does not have a main window', self.title)) end -- alert.show(string.format('application title for %q is %q, main window %q', title, app:title(), window:title())) else win = window.focusedWindow() end -- first, determine the screen where the window should go local screen = win:screen() print("Currently, I think I'm on " .. screen:name()) -- print("Should place the screen with main = " .. tostring(self._mainscreen)) -- print("Should place the screen with offs = " .. tostring(self.dscreen)) if self._mainscreen then screen = mscreen.mainScreen() end local dscreen = self.dscreen while dscreen < 0 do screen = screen:previous() dscreen = dscreen + 1 end while dscreen > 0 do screen = screen:next() dscreen = dscreen - 1 end for _, v in pairs(self.screen_compass) do if v == 'east' then screen = screen:toeast() elseif v == 'west' then screen = screen:towest() elseif v == 'north' then screen = screen:tonorth() elseif v == 'south' then screen = screen:tosouth() else print("Direction " .. v .. " for screen is not recognized") end end -- now do the window placement local origf = self.ct:get(win, screen) -- print(string.format("origf x=%d, y=%d, w=%d, h=%d", origf.x, origf.y, origf.w, origf.h)) -- print(string.format("self x=%d, y=%d, w=%d, h=%d", self.x, self.y, self.w, self.h)) -- print(string.format("self dx=%d, dy=%d, dw=%d, dh=%d", self.dx, self.dy, self.dw, self.dh)) -- take defaults f.w = (self.w == 0) and origf.w or self.w f.h = (self.h == 0) and origf.h or self.h f.x = (self.x == -1) and origf.x or self.x f.y = (self.y == -1) and origf.y or self.y -- widest and tallest if self._widest then f.w = origf.screenw end if self._tallest then f.h = origf.screenh end -- adjust width and height if self.dw ~= 0 then f.w = math.min(origf.screenw, math.max(1, f.w + self.dw)) end if self.dh ~= 0 then f.h = math.min(origf.screenh, math.max(1, f.h + self.dh)) end -- centering if self._vcenter then print("vcenter called with f.x = ".. f.x .. " origf.sw = " .. origf.screenw) f.x = math.max(0, (origf.screenw - f.w)/2) end if self._hcenter then f.y = math.max(0, (origf.screenh - f.h)/2) end -- and positions if self._topmost then f.y = 0 end if self._leftmost then f.x = 0 end if self._rightmost then f.x = origf.screenw - f.w end if self._bottommost then f.y = origf.screenh - f.h end if self.dx ~= 0 then f.x = math.min(origf.screenw, math.max(0, f.x + self.dx)) end if self.dy ~= 0 then f.y = math.min(origf.screenh, math.max(0, f.y + self.dy)) end -- print(string.format("final f x=%d, y=%d, w=%d, h=%d", f.x, f.y, f.w, f.h)) -- print(string.format("application is '%q'", win:title())) self.ct:set(win, screen, f) end end --- mjolnir.winteraction:resize() --- Function --- Alias for act() WinterAction.resize = WinterAction.act --- mjolnir.winteraction:move() --- Function --- Alias for act() WinterAction.move = WinterAction.act --- mjolnir.winteraction:place() --- Function --- Alias for act() WinterAction.place = WinterAction.act return winter
bsd-2-clause
ai-maker/aima
src/uniform_cost_search.lua
1
1584
---------------------------------------------------------------------- -- File : uniform_cost_search.lua -- Created : 12-Feb-2015 -- By : Alexandre Trilla <alex@atrilla.net> -- -- AIMA - Artificial Intelligence, A Maker's Approach -- -- Copyright (C) 2015 A.I. Maker ---------------------------------------------------------------------- -- -- This file is part of AIMA. -- -- AIMA is free software: you can redistribute it and/or modify it -- under the terms of the MIT/X11 License as published by the -- Massachusetts Institute of Technology. See the MIT/X11 License -- for more details. -- -- You should have received a copy of the MIT/X11 License along with -- this source code distribution of AIMA (see the COPYING file in the -- root directory). If not, see -- <http://www.opensource.org/licenses/mit-license>. ---------------------------------------------------------------------- -- Uniform-cost search algorithm. -- -- PRE: -- problem - cost-weighted adjacency matrix (table). -- start - starting node index (number). -- finish - finishing node index (number). -- treegraph - tree/graph version flag (boolean). -- True for graph search version. -- -- POST: -- solution - solution path (table). State set to zero if failure. require("best_first_search") local function eval_path(cost) return cost[1] end function uniform_cost_search(problem, start, finish, treegraph) -- heuristic is not taken into account zeros = {} for i = 1, #problem do zeros[i] = 0 end return best_first_search(problem, start, finish, treegraph, eval_path, zeros) end
mit
Fenix-XI/Fenix
scripts/zones/Abyssea-Misareaux/npcs/qm18.lua
17
1692
----------------------------------- -- Zone: Abyssea-Misereaux -- NPC: ??? -- Spawns: Amhuluk ----------------------------------- require("scripts/globals/status"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(17662477) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(JAGGED_APKALLU_BEAK) and player:hasKeyItem(CLIPPED_BIRD_WING) and player:hasKeyItem(BLOODIED_BAT_FUR)) then -- I broke it into 3 lines at the 'and' because it was so long. player:startEvent(1021, JAGGED_APKALLU_BEAK, CLIPPED_BIRD_WING, BLOODIED_BAT_FUR); -- Ask if player wants to use KIs else player:startEvent(1020, JAGGED_APKALLU_BEAK, CLIPPED_BIRD_WING, BLOODIED_BAT_FUR); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1021 and option == 1) then SpawnMob(17662477):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(JAGGED_APKALLU_BEAK); player:delKeyItem(CLIPPED_BIRD_WING); player:delKeyItem(BLOODIED_BAT_FUR); end end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/spells/esuna.lua
12
4287
----------------------------------------- -- Spell: Esuna -- ----------------------------------------- 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) if (caster:getID() == target:getID()) then -- much of this should only run once per cast, otherwise it would only delete the debuffs from the caster. local statusNum = -1 local removables = {dsp.effect.FLASH, dsp.effect.BLINDNESS, dsp.effect.PARALYSIS, dsp.effect.POISON, dsp.effect.CURSE_I, dsp.effect.CURSE_II, dsp.effect.DISEASE, dsp.effect.PLAGUE} if (caster:hasStatusEffect(dsp.effect.AFFLATUS_MISERY)) then -- add extra statuses to the list of removables. Elegy and Requiem are specifically absent. removables = {dsp.effect.FLASH, dsp.effect.BLINDNESS, dsp.effect.PARALYSIS, dsp.effect.POISON, dsp.effect.CURSE_I, dsp.effect.CURSE_II, dsp.effect.DISEASE, dsp.effect.PLAGUE, dsp.effect.WEIGHT, dsp.effect.BIND, dsp.effect.BIO, dsp.effect.DIA, dsp.effect.BURN, dsp.effect.FROST, dsp.effect.CHOKE, dsp.effect.RASP, dsp.effect.SHOCK, dsp.effect.DROWN, dsp.effect.STR_DOWN, dsp.effect.DEX_DOWN, dsp.effect.VIT_DOWN, dsp.effect.AGI_DOWN, dsp.effect.INT_DOWN, dsp.effect.MND_DOWN, dsp.effect.CHR_DOWN, dsp.effect.ADDLE, dsp.effect.SLOW, dsp.effect.HELIX, dsp.effect.ACCURACY_DOWN, dsp.effect.ATTACK_DOWN, dsp.effect.EVASION_DOWN, dsp.effect.DEFENSE_DOWN, dsp.effect.MAGIC_ACC_DOWN, dsp.effect.MAGIC_ATK_DOWN, dsp.effect.MAGIC_EVASION_DOWN, dsp.effect.MAGIC_DEF_DOWN, dsp.effect.MAX_TP_DOWN, dsp.effect.MAX_MP_DOWN, dsp.effect.MAX_HP_DOWN} end local has = {} -- collect a list of what caster currently has for i, effect in ipairs(removables) do if (caster:hasStatusEffect(effect)) then statusNum = statusNum + 1 has[statusNum] = removables[i] end end if (statusNum >= 0) then -- make sure this happens once instead of for every target local delEff = math.random(0,statusNum) -- pick a random status to delete caster:setLocalVar("esunaDelEff",has[delEff]) -- this can't be a local because it would only delete from the caster if it were. else -- clear it if the caster has no eligible statuses, otherwise it will remove the status from others if it was previously removed. caster:setLocalVar("esunaDelEff",0) caster:setLocalVar("esunaDelEffMis",0) -- again, this can't be a local because it would only delete from the caster if it were. For extra status deletion under Misery end if (statusNum >= 1 and caster:hasStatusEffect(dsp.effect.AFFLATUS_MISERY)) then -- Misery second status removal. caster:delStatusEffect(has[delEff]) -- delete the first selected effect so it doesn't get selected again. Won't impact the ability to delete it from others at this point. local statusNumMis = - 1 -- need a new var to track the amount of debuffs for the array -- collect a list of what caster currently has, again. has = {} for i, effect in ipairs(removables) do if (caster:hasStatusEffect(effect)) then statusNumMis = statusNumMis + 1 has[statusNumMis] = removables[i] end end local delEffMis = math.random(0,statusNumMis) -- pick another random status to delete caster:setLocalVar("esunaDelEffMis",has[delEffMis]) else caster:setLocalVar("esunaDelEffMis",0) end end local statusDel = caster:getLocalVar("esunaDelEff") local statusDelMis = caster:getLocalVar("esunaDelEffMis") if (statusDel == 0) then -- this gets set to 0 if there's no status to delete. spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) -- no effect elseif (statusDelMis ~= 0) then -- no need to check for statusDelMis because it can't be 0 if this isn't target:delStatusEffect(statusDel) target:delStatusEffect(statusDelMis) else target:delStatusEffect(statusDel) end return statusDel end
gpl-3.0
slachiewicz/wrk
deps/luajit/src/jit/dis_ppc.lua
88
20319
---------------------------------------------------------------------------- -- LuaJIT PPC disassembler module. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT/X license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles all common, non-privileged 32/64 bit PowerPC instructions -- plus the e500 SPE instructions and some Cell/Xenon extensions. -- -- NYI: VMX, VMX128 ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local concat = table.concat local bit = require("bit") local band, bor, tohex = bit.band, bit.bor, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Primary and extended opcode maps ------------------------------------------------------------------------------ local map_crops = { shift = 1, mask = 1023, [0] = "mcrfXX", [33] = "crnor|crnotCCC=", [129] = "crandcCCC", [193] = "crxor|crclrCCC%", [225] = "crnandCCC", [257] = "crandCCC", [289] = "creqv|crsetCCC%", [417] = "crorcCCC", [449] = "cror|crmoveCCC=", [16] = "b_lrKB", [528] = "b_ctrKB", [150] = "isync", } local map_rlwinm = setmetatable({ shift = 0, mask = -1, }, { __index = function(t, x) local rot = band(rshift(x, 11), 31) local mb = band(rshift(x, 6), 31) local me = band(rshift(x, 1), 31) if mb == 0 and me == 31-rot then return "slwiRR~A." elseif me == 31 and mb == 32-rot then return "srwiRR~-A." else return "rlwinmRR~AAA." end end }) local map_rld = { shift = 2, mask = 7, [0] = "rldiclRR~HM.", "rldicrRR~HM.", "rldicRR~HM.", "rldimiRR~HM.", { shift = 1, mask = 1, [0] = "rldclRR~RM.", "rldcrRR~RM.", }, } local map_ext = setmetatable({ shift = 1, mask = 1023, [0] = "cmp_YLRR", [32] = "cmpl_YLRR", [4] = "twARR", [68] = "tdARR", [8] = "subfcRRR.", [40] = "subfRRR.", [104] = "negRR.", [136] = "subfeRRR.", [200] = "subfzeRR.", [232] = "subfmeRR.", [520] = "subfcoRRR.", [552] = "subfoRRR.", [616] = "negoRR.", [648] = "subfeoRRR.", [712] = "subfzeoRR.", [744] = "subfmeoRR.", [9] = "mulhduRRR.", [73] = "mulhdRRR.", [233] = "mulldRRR.", [457] = "divduRRR.", [489] = "divdRRR.", [745] = "mulldoRRR.", [969] = "divduoRRR.", [1001] = "divdoRRR.", [10] = "addcRRR.", [138] = "addeRRR.", [202] = "addzeRR.", [234] = "addmeRR.", [266] = "addRRR.", [522] = "addcoRRR.", [650] = "addeoRRR.", [714] = "addzeoRR.", [746] = "addmeoRR.", [778] = "addoRRR.", [11] = "mulhwuRRR.", [75] = "mulhwRRR.", [235] = "mullwRRR.", [459] = "divwuRRR.", [491] = "divwRRR.", [747] = "mullwoRRR.", [971] = "divwouRRR.", [1003] = "divwoRRR.", [15] = "iselltRRR", [47] = "iselgtRRR", [79] = "iseleqRRR", [144] = { shift = 20, mask = 1, [0] = "mtcrfRZ~", "mtocrfRZ~", }, [19] = { shift = 20, mask = 1, [0] = "mfcrR", "mfocrfRZ", }, [371] = { shift = 11, mask = 1023, [392] = "mftbR", [424] = "mftbuR", }, [339] = { shift = 11, mask = 1023, [32] = "mferR", [256] = "mflrR", [288] = "mfctrR", [16] = "mfspefscrR", }, [467] = { shift = 11, mask = 1023, [32] = "mtxerR", [256] = "mtlrR", [288] = "mtctrR", [16] = "mtspefscrR", }, [20] = "lwarxRR0R", [84] = "ldarxRR0R", [21] = "ldxRR0R", [53] = "lduxRRR", [149] = "stdxRR0R", [181] = "stduxRRR", [341] = "lwaxRR0R", [373] = "lwauxRRR", [23] = "lwzxRR0R", [55] = "lwzuxRRR", [87] = "lbzxRR0R", [119] = "lbzuxRRR", [151] = "stwxRR0R", [183] = "stwuxRRR", [215] = "stbxRR0R", [247] = "stbuxRRR", [279] = "lhzxRR0R", [311] = "lhzuxRRR", [343] = "lhaxRR0R", [375] = "lhauxRRR", [407] = "sthxRR0R", [439] = "sthuxRRR", [54] = "dcbst-R0R", [86] = "dcbf-R0R", [150] = "stwcxRR0R.", [214] = "stdcxRR0R.", [246] = "dcbtst-R0R", [278] = "dcbt-R0R", [310] = "eciwxRR0R", [438] = "ecowxRR0R", [470] = "dcbi-RR", [598] = { shift = 21, mask = 3, [0] = "sync", "lwsync", "ptesync", }, [758] = "dcba-RR", [854] = "eieio", [982] = "icbi-R0R", [1014] = "dcbz-R0R", [26] = "cntlzwRR~", [58] = "cntlzdRR~", [122] = "popcntbRR~", [154] = "prtywRR~", [186] = "prtydRR~", [28] = "andRR~R.", [60] = "andcRR~R.", [124] = "nor|notRR~R=.", [284] = "eqvRR~R.", [316] = "xorRR~R.", [412] = "orcRR~R.", [444] = "or|mrRR~R=.", [476] = "nandRR~R.", [508] = "cmpbRR~R", [512] = "mcrxrX", [532] = "ldbrxRR0R", [660] = "stdbrxRR0R", [533] = "lswxRR0R", [597] = "lswiRR0A", [661] = "stswxRR0R", [725] = "stswiRR0A", [534] = "lwbrxRR0R", [662] = "stwbrxRR0R", [790] = "lhbrxRR0R", [918] = "sthbrxRR0R", [535] = "lfsxFR0R", [567] = "lfsuxFRR", [599] = "lfdxFR0R", [631] = "lfduxFRR", [663] = "stfsxFR0R", [695] = "stfsuxFRR", [727] = "stfdxFR0R", [759] = "stfduxFR0R", [855] = "lfiwaxFR0R", [983] = "stfiwxFR0R", [24] = "slwRR~R.", [27] = "sldRR~R.", [536] = "srwRR~R.", [792] = "srawRR~R.", [824] = "srawiRR~A.", [794] = "sradRR~R.", [826] = "sradiRR~H.", [827] = "sradiRR~H.", [922] = "extshRR~.", [954] = "extsbRR~.", [986] = "extswRR~.", [539] = "srdRR~R.", }, { __index = function(t, x) if band(x, 31) == 15 then return "iselRRRC" end end }) local map_ld = { shift = 0, mask = 3, [0] = "ldRRE", "lduRRE", "lwaRRE", } local map_std = { shift = 0, mask = 3, [0] = "stdRRE", "stduRRE", } local map_fps = { shift = 5, mask = 1, { shift = 1, mask = 15, [0] = false, false, "fdivsFFF.", false, "fsubsFFF.", "faddsFFF.", "fsqrtsF-F.", false, "fresF-F.", "fmulsFF-F.", "frsqrtesF-F.", false, "fmsubsFFFF~.", "fmaddsFFFF~.", "fnmsubsFFFF~.", "fnmaddsFFFF~.", } } local map_fpd = { shift = 5, mask = 1, [0] = { shift = 1, mask = 1023, [0] = "fcmpuXFF", [32] = "fcmpoXFF", [64] = "mcrfsXX", [38] = "mtfsb1A.", [70] = "mtfsb0A.", [134] = "mtfsfiA>>-A>", [8] = "fcpsgnFFF.", [40] = "fnegF-F.", [72] = "fmrF-F.", [136] = "fnabsF-F.", [264] = "fabsF-F.", [12] = "frspF-F.", [14] = "fctiwF-F.", [15] = "fctiwzF-F.", [583] = "mffsF.", [711] = "mtfsfZF.", [392] = "frinF-F.", [424] = "frizF-F.", [456] = "fripF-F.", [488] = "frimF-F.", [814] = "fctidF-F.", [815] = "fctidzF-F.", [846] = "fcfidF-F.", }, { shift = 1, mask = 15, [0] = false, false, "fdivFFF.", false, "fsubFFF.", "faddFFF.", "fsqrtF-F.", "fselFFFF~.", "freF-F.", "fmulFF-F.", "frsqrteF-F.", false, "fmsubFFFF~.", "fmaddFFFF~.", "fnmsubFFFF~.", "fnmaddFFFF~.", } } local map_spe = { shift = 0, mask = 2047, [512] = "evaddwRRR", [514] = "evaddiwRAR~", [516] = "evsubwRRR~", [518] = "evsubiwRAR~", [520] = "evabsRR", [521] = "evnegRR", [522] = "evextsbRR", [523] = "evextshRR", [524] = "evrndwRR", [525] = "evcntlzwRR", [526] = "evcntlswRR", [527] = "brincRRR", [529] = "evandRRR", [530] = "evandcRRR", [534] = "evxorRRR", [535] = "evor|evmrRRR=", [536] = "evnor|evnotRRR=", [537] = "eveqvRRR", [539] = "evorcRRR", [542] = "evnandRRR", [544] = "evsrwuRRR", [545] = "evsrwsRRR", [546] = "evsrwiuRRA", [547] = "evsrwisRRA", [548] = "evslwRRR", [550] = "evslwiRRA", [552] = "evrlwRRR", [553] = "evsplatiRS", [554] = "evrlwiRRA", [555] = "evsplatfiRS", [556] = "evmergehiRRR", [557] = "evmergeloRRR", [558] = "evmergehiloRRR", [559] = "evmergelohiRRR", [560] = "evcmpgtuYRR", [561] = "evcmpgtsYRR", [562] = "evcmpltuYRR", [563] = "evcmpltsYRR", [564] = "evcmpeqYRR", [632] = "evselRRR", [633] = "evselRRRW", [634] = "evselRRRW", [635] = "evselRRRW", [636] = "evselRRRW", [637] = "evselRRRW", [638] = "evselRRRW", [639] = "evselRRRW", [640] = "evfsaddRRR", [641] = "evfssubRRR", [644] = "evfsabsRR", [645] = "evfsnabsRR", [646] = "evfsnegRR", [648] = "evfsmulRRR", [649] = "evfsdivRRR", [652] = "evfscmpgtYRR", [653] = "evfscmpltYRR", [654] = "evfscmpeqYRR", [656] = "evfscfuiR-R", [657] = "evfscfsiR-R", [658] = "evfscfufR-R", [659] = "evfscfsfR-R", [660] = "evfsctuiR-R", [661] = "evfsctsiR-R", [662] = "evfsctufR-R", [663] = "evfsctsfR-R", [664] = "evfsctuizR-R", [666] = "evfsctsizR-R", [668] = "evfststgtYRR", [669] = "evfststltYRR", [670] = "evfststeqYRR", [704] = "efsaddRRR", [705] = "efssubRRR", [708] = "efsabsRR", [709] = "efsnabsRR", [710] = "efsnegRR", [712] = "efsmulRRR", [713] = "efsdivRRR", [716] = "efscmpgtYRR", [717] = "efscmpltYRR", [718] = "efscmpeqYRR", [719] = "efscfdR-R", [720] = "efscfuiR-R", [721] = "efscfsiR-R", [722] = "efscfufR-R", [723] = "efscfsfR-R", [724] = "efsctuiR-R", [725] = "efsctsiR-R", [726] = "efsctufR-R", [727] = "efsctsfR-R", [728] = "efsctuizR-R", [730] = "efsctsizR-R", [732] = "efststgtYRR", [733] = "efststltYRR", [734] = "efststeqYRR", [736] = "efdaddRRR", [737] = "efdsubRRR", [738] = "efdcfuidR-R", [739] = "efdcfsidR-R", [740] = "efdabsRR", [741] = "efdnabsRR", [742] = "efdnegRR", [744] = "efdmulRRR", [745] = "efddivRRR", [746] = "efdctuidzR-R", [747] = "efdctsidzR-R", [748] = "efdcmpgtYRR", [749] = "efdcmpltYRR", [750] = "efdcmpeqYRR", [751] = "efdcfsR-R", [752] = "efdcfuiR-R", [753] = "efdcfsiR-R", [754] = "efdcfufR-R", [755] = "efdcfsfR-R", [756] = "efdctuiR-R", [757] = "efdctsiR-R", [758] = "efdctufR-R", [759] = "efdctsfR-R", [760] = "efdctuizR-R", [762] = "efdctsizR-R", [764] = "efdtstgtYRR", [765] = "efdtstltYRR", [766] = "efdtsteqYRR", [768] = "evlddxRR0R", [769] = "evlddRR8", [770] = "evldwxRR0R", [771] = "evldwRR8", [772] = "evldhxRR0R", [773] = "evldhRR8", [776] = "evlhhesplatxRR0R", [777] = "evlhhesplatRR2", [780] = "evlhhousplatxRR0R", [781] = "evlhhousplatRR2", [782] = "evlhhossplatxRR0R", [783] = "evlhhossplatRR2", [784] = "evlwhexRR0R", [785] = "evlwheRR4", [788] = "evlwhouxRR0R", [789] = "evlwhouRR4", [790] = "evlwhosxRR0R", [791] = "evlwhosRR4", [792] = "evlwwsplatxRR0R", [793] = "evlwwsplatRR4", [796] = "evlwhsplatxRR0R", [797] = "evlwhsplatRR4", [800] = "evstddxRR0R", [801] = "evstddRR8", [802] = "evstdwxRR0R", [803] = "evstdwRR8", [804] = "evstdhxRR0R", [805] = "evstdhRR8", [816] = "evstwhexRR0R", [817] = "evstwheRR4", [820] = "evstwhoxRR0R", [821] = "evstwhoRR4", [824] = "evstwwexRR0R", [825] = "evstwweRR4", [828] = "evstwwoxRR0R", [829] = "evstwwoRR4", [1027] = "evmhessfRRR", [1031] = "evmhossfRRR", [1032] = "evmheumiRRR", [1033] = "evmhesmiRRR", [1035] = "evmhesmfRRR", [1036] = "evmhoumiRRR", [1037] = "evmhosmiRRR", [1039] = "evmhosmfRRR", [1059] = "evmhessfaRRR", [1063] = "evmhossfaRRR", [1064] = "evmheumiaRRR", [1065] = "evmhesmiaRRR", [1067] = "evmhesmfaRRR", [1068] = "evmhoumiaRRR", [1069] = "evmhosmiaRRR", [1071] = "evmhosmfaRRR", [1095] = "evmwhssfRRR", [1096] = "evmwlumiRRR", [1100] = "evmwhumiRRR", [1101] = "evmwhsmiRRR", [1103] = "evmwhsmfRRR", [1107] = "evmwssfRRR", [1112] = "evmwumiRRR", [1113] = "evmwsmiRRR", [1115] = "evmwsmfRRR", [1127] = "evmwhssfaRRR", [1128] = "evmwlumiaRRR", [1132] = "evmwhumiaRRR", [1133] = "evmwhsmiaRRR", [1135] = "evmwhsmfaRRR", [1139] = "evmwssfaRRR", [1144] = "evmwumiaRRR", [1145] = "evmwsmiaRRR", [1147] = "evmwsmfaRRR", [1216] = "evaddusiaawRR", [1217] = "evaddssiaawRR", [1218] = "evsubfusiaawRR", [1219] = "evsubfssiaawRR", [1220] = "evmraRR", [1222] = "evdivwsRRR", [1223] = "evdivwuRRR", [1224] = "evaddumiaawRR", [1225] = "evaddsmiaawRR", [1226] = "evsubfumiaawRR", [1227] = "evsubfsmiaawRR", [1280] = "evmheusiaawRRR", [1281] = "evmhessiaawRRR", [1283] = "evmhessfaawRRR", [1284] = "evmhousiaawRRR", [1285] = "evmhossiaawRRR", [1287] = "evmhossfaawRRR", [1288] = "evmheumiaawRRR", [1289] = "evmhesmiaawRRR", [1291] = "evmhesmfaawRRR", [1292] = "evmhoumiaawRRR", [1293] = "evmhosmiaawRRR", [1295] = "evmhosmfaawRRR", [1320] = "evmhegumiaaRRR", [1321] = "evmhegsmiaaRRR", [1323] = "evmhegsmfaaRRR", [1324] = "evmhogumiaaRRR", [1325] = "evmhogsmiaaRRR", [1327] = "evmhogsmfaaRRR", [1344] = "evmwlusiaawRRR", [1345] = "evmwlssiaawRRR", [1352] = "evmwlumiaawRRR", [1353] = "evmwlsmiaawRRR", [1363] = "evmwssfaaRRR", [1368] = "evmwumiaaRRR", [1369] = "evmwsmiaaRRR", [1371] = "evmwsmfaaRRR", [1408] = "evmheusianwRRR", [1409] = "evmhessianwRRR", [1411] = "evmhessfanwRRR", [1412] = "evmhousianwRRR", [1413] = "evmhossianwRRR", [1415] = "evmhossfanwRRR", [1416] = "evmheumianwRRR", [1417] = "evmhesmianwRRR", [1419] = "evmhesmfanwRRR", [1420] = "evmhoumianwRRR", [1421] = "evmhosmianwRRR", [1423] = "evmhosmfanwRRR", [1448] = "evmhegumianRRR", [1449] = "evmhegsmianRRR", [1451] = "evmhegsmfanRRR", [1452] = "evmhogumianRRR", [1453] = "evmhogsmianRRR", [1455] = "evmhogsmfanRRR", [1472] = "evmwlusianwRRR", [1473] = "evmwlssianwRRR", [1480] = "evmwlumianwRRR", [1481] = "evmwlsmianwRRR", [1491] = "evmwssfanRRR", [1496] = "evmwumianRRR", [1497] = "evmwsmianRRR", [1499] = "evmwsmfanRRR", } local map_pri = { [0] = false, false, "tdiARI", "twiARI", map_spe, false, false, "mulliRRI", "subficRRI", false, "cmpl_iYLRU", "cmp_iYLRI", "addicRRI", "addic.RRI", "addi|liRR0I", "addis|lisRR0I", "b_KBJ", "sc", "bKJ", map_crops, "rlwimiRR~AAA.", map_rlwinm, false, "rlwnmRR~RAA.", "oriNRR~U", "orisRR~U", "xoriRR~U", "xorisRR~U", "andi.RR~U", "andis.RR~U", map_rld, map_ext, "lwzRRD", "lwzuRRD", "lbzRRD", "lbzuRRD", "stwRRD", "stwuRRD", "stbRRD", "stbuRRD", "lhzRRD", "lhzuRRD", "lhaRRD", "lhauRRD", "sthRRD", "sthuRRD", "lmwRRD", "stmwRRD", "lfsFRD", "lfsuFRD", "lfdFRD", "lfduFRD", "stfsFRD", "stfsuFRD", "stfdFRD", "stfduFRD", false, false, map_ld, map_fps, false, false, map_std, map_fpd, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "sp", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15", "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23", "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31", } local map_cond = { [0] = "lt", "gt", "eq", "so", "ge", "le", "ne", "ns", } -- Format a condition bit. local function condfmt(cond) if cond <= 3 then return map_cond[band(cond, 3)] else return format("4*cr%d+%s", rshift(cond, 2), map_cond[band(cond, 3)]) end end ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local pos = ctx.pos local extra = "" if ctx.rel then local sym = ctx.symtab[ctx.rel] if sym then extra = "\t->"..sym end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-7s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-7s %s%s\n", ctx.addr+pos, text, concat(operands, ", "), extra)) end ctx.pos = pos + 4 end -- Fallback for unknown opcodes. local function unknown(ctx) return putop(ctx, ".long", { "0x"..tohex(ctx.op) }) end -- Disassemble a single instruction. local function disass_ins(ctx) local pos = ctx.pos local b0, b1, b2, b3 = byte(ctx.code, pos+1, pos+4) local op = bor(lshift(b0, 24), lshift(b1, 16), lshift(b2, 8), b3) local operands = {} local last = nil local rs = 21 ctx.op = op ctx.rel = nil local opat = map_pri[rshift(b0, 2)] while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] end local name, pat = match(opat, "^([a-z0-9_.]*)(.*)") local altname, pat2 = match(pat, "|([a-z0-9_.]*)(.*)") if altname then pat = pat2 end for p in gmatch(pat, ".") do local x = nil if p == "R" then x = map_gpr[band(rshift(op, rs), 31)] rs = rs - 5 elseif p == "F" then x = "f"..band(rshift(op, rs), 31) rs = rs - 5 elseif p == "A" then x = band(rshift(op, rs), 31) rs = rs - 5 elseif p == "S" then x = arshift(lshift(op, 27-rs), 27) rs = rs - 5 elseif p == "I" then x = arshift(lshift(op, 16), 16) elseif p == "U" then x = band(op, 0xffff) elseif p == "D" or p == "E" then local disp = arshift(lshift(op, 16), 16) if p == "E" then disp = band(disp, -4) end if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p >= "2" and p <= "8" then local disp = band(rshift(op, rs), 31) * p if last == "r0" then last = "0" end operands[#operands] = format("%d(%s)", disp, last) elseif p == "H" then x = band(rshift(op, rs), 31) + lshift(band(op, 2), 4) rs = rs - 5 elseif p == "M" then x = band(rshift(op, rs), 31) + band(op, 0x20) elseif p == "C" then x = condfmt(band(rshift(op, rs), 31)) rs = rs - 5 elseif p == "B" then local bo = rshift(op, 21) local cond = band(rshift(op, 16), 31) local cn = "" rs = rs - 10 if band(bo, 4) == 0 then cn = band(bo, 2) == 0 and "dnz" or "dz" if band(bo, 0x10) == 0 then cn = cn..(band(bo, 8) == 0 and "f" or "t") end if band(bo, 0x10) == 0 then x = condfmt(cond) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") elseif band(bo, 0x10) == 0 then cn = map_cond[band(cond, 3) + (band(bo, 8) == 0 and 4 or 0)] if cond > 3 then x = "cr"..rshift(cond, 2) end name = name..(band(bo, 1) == band(rshift(op, 15), 1) and "-" or "+") end name = gsub(name, "_", cn) elseif p == "J" then x = arshift(lshift(op, 27-rs), 29-rs)*4 if band(op, 2) == 0 then x = ctx.addr + pos + x end ctx.rel = x x = "0x"..tohex(x) elseif p == "K" then if band(op, 1) ~= 0 then name = name.."l" end if band(op, 2) ~= 0 then name = name.."a" end elseif p == "X" or p == "Y" then x = band(rshift(op, rs+2), 7) if x == 0 and p == "Y" then x = nil else x = "cr"..x end rs = rs - 5 elseif p == "W" then x = "cr"..band(op, 7) elseif p == "Z" then x = band(rshift(op, rs-4), 255) rs = rs - 10 elseif p == ">" then operands[#operands] = rshift(operands[#operands], 1) elseif p == "0" then if last == "r0" then operands[#operands] = nil if altname then name = altname end end elseif p == "L" then name = gsub(name, "_", band(op, 0x00200000) ~= 0 and "d" or "w") elseif p == "." then if band(op, 1) == 1 then name = name.."." end elseif p == "N" then if op == 0x60000000 then name = "nop"; break end elseif p == "~" then local n = #operands operands[n-1], operands[n] = operands[n], operands[n-1] elseif p == "=" then local n = #operands if last == operands[n-1] then operands[n] = nil name = altname end elseif p == "%" then local n = #operands if last == operands[n-1] and last == operands[n-2] then operands[n] = nil operands[n-1] = nil name = altname end elseif p == "-" then rs = rs - 5 else assert(false) end if x then operands[#operands+1] = x; last = x end end return putop(ctx, name, operands) end ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code stop = stop - stop % 4 ctx.pos = ofs - ofs % 4 ctx.rel = nil while ctx.pos < stop do disass_ins(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create_(code, addr, out) local ctx = {} ctx.code = code ctx.addr = addr or 0 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 8 return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass_(code, addr, out) create_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 32 then return map_gpr[r] end return "f"..(r-32) end -- Public module functions. module(...) create = create_ disass = disass_ regname = regname_
apache-2.0
crunchuser/prosody-modules
mod_s2s_auth_fingerprint/mod_s2s_auth_fingerprint.lua
31
1380
-- Copyright (C) 2013-2014 Kim Alvefur -- This file is MIT/X11 licensed. module:set_global(); local digest_algo = module:get_option_string(module:get_name().."_digest", "sha1"); local fingerprints = {}; local function hashprep(h) return tostring(h):gsub(":",""):lower(); end local function hashfmt(h) return h:gsub("..",":%0"):sub(2):upper(); end for host, set in pairs(module:get_option("s2s_trusted_fingerprints", {})) do local host_set = {} if type(set) == "table" then -- list of fingerprints for i=1,#set do host_set[hashprep(set[i])] = true; end else -- assume single fingerprint host_set[hashprep(set)] = true; end fingerprints[host] = host_set; end module:hook("s2s-check-certificate", function(event) local session, host, cert = event.session, event.host, event.cert; local host_fingerprints = fingerprints[host]; if host_fingerprints then local digest = cert and cert:digest(digest_algo); if host_fingerprints[digest] then module:log("info", "'%s' matched %s fingerprint %s", host, digest_algo:upper(), hashfmt(digest)); session.cert_chain_status = "valid"; session.cert_identity_status = "valid"; return true; else module:log("warn", "'%s' has unknown %s fingerprint %s", host, digest_algo:upper(), hashfmt(digest)); session.cert_chain_status = "invalid"; session.cert_identity_status = "invalid"; end end end);
mit
Fenix-XI/Fenix
scripts/globals/items/lizard_egg.lua
18
1161
----------------------------------------- -- ID: 4362 -- Item: lizard_egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 5 -- Magic 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4362); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 5); target:addMod(MOD_MP, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 5); target:delMod(MOD_MP, 5); end;
gpl-3.0
abasshacker/abbasend
plugins/img.lua
660
3196
do local mime = require("mime") local google_config = load_from_file('data/google.lua') local cache = {} --[[ local function send_request(url) local t = {} local options = { url = url, sink = ltn12.sink.table(t), method = "GET" } local a, code, headers, status = http.request(options) return table.concat(t), code, headers, status end]]-- local function get_google_data(text) local url = "http://ajax.googleapis.com/ajax/services/search/images?" url = url.."v=1.0&rsz=5" url = url.."&q="..URL.escape(text) url = url.."&imgsz=small|medium|large" if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end local res, code = http.request(url) if code ~= 200 then print("HTTP Error code:", code) return nil end local google = json:decode(res) return google end -- Returns only the useful google data to save on cache local function simple_google_table(google) local new_table = {} new_table.responseData = {} new_table.responseDetails = google.responseDetails new_table.responseStatus = google.responseStatus new_table.responseData.results = {} local results = google.responseData.results for k,result in pairs(results) do new_table.responseData.results[k] = {} new_table.responseData.results[k].unescapedUrl = result.unescapedUrl new_table.responseData.results[k].url = result.url end return new_table end local function save_to_cache(query, data) -- Saves result on cache if string.len(query) <= 7 then local text_b64 = mime.b64(query) if not cache[text_b64] then local simple_google = simple_google_table(data) cache[text_b64] = simple_google end end end local function process_google_data(google, receiver, query) if google.responseStatus == 403 then local text = 'ERROR: Reached maximum searches per day' send_msg(receiver, text, ok_cb, false) elseif google.responseStatus == 200 then local data = google.responseData if not data or not data.results or #data.results == 0 then local text = 'Image not found.' send_msg(receiver, text, ok_cb, false) return false end -- Random image from table local i = math.random(#data.results) local url = data.results[i].unescapedUrl or data.results[i].url local old_timeout = http.TIMEOUT or 10 http.TIMEOUT = 5 send_photo_from_url(receiver, url) http.TIMEOUT = old_timeout save_to_cache(query, google) else local text = 'ERROR!' send_msg(receiver, text, ok_cb, false) end end function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local text_b64 = mime.b64(text) local cached = cache[text_b64] if cached then process_google_data(cached, receiver, text) else local data = get_google_data(text) process_google_data(data, receiver, text) end end return { description = "Search image with Google API and sends it.", usage = "!img [term]: Random search an image with Google API.", patterns = { "^!img (.*)$" }, run = run } end
gpl-2.0
plivo/sharq
sharq/scripts/lua/enqueue.lua
1
3282
-- script to enqueue a job into sharq. -- input: -- KEYS[1] - <key_prefix> -- KEYS[2] - <queue_type> -- -- ARGV[1] - <current_timestamp> -- ARGV[2] - <queue_id> -- ARGV[3] - <job_id> -- ARGV[4] - <serialized_payload> -- ARGV[5] - <interval> -- ARGV[6] - <requeue_limit> -- output: -- nil local prefix = KEYS[1] local queue_type = KEYS[2] local current_timestamp = ARGV[1] local queue_id = ARGV[2] local job_id = ARGV[3] local payload = ARGV[4] local interval = ARGV[5] local requeue_limit = ARGV[6] -- push the job id into the job queue. redis.call('RPUSH', prefix .. ':' .. queue_type .. ':' .. queue_id, job_id) -- update the payload map. redis.call('HSET', prefix .. ':payload', queue_type .. ':' .. queue_id .. ':' .. job_id, payload) -- update the interval map. redis.call('HSET', prefix .. ':interval', queue_type .. ':' .. queue_id, interval) -- update the requeue limit map. redis.call('HSET', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':requeues_remaining', job_id, requeue_limit) -- check if the queue of this job is already present in the ready sorted set. if not redis.call('ZRANK', prefix .. ':' .. queue_type, queue_id) then -- the ready sorted set is empty, update it and add it to metrics ready queue type set. redis.call('SADD', prefix .. ':ready:queue_type', queue_type) if redis.call('EXISTS', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':time') ~= 1 then -- time keeper does not exist -- update the ready sorted set with current time as ready time. redis.call('ZADD', prefix .. ':' .. queue_type, current_timestamp, queue_id) else -- time keeper exists local last_dequeue_time = redis.call('GET', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':time') local ready_time = interval + last_dequeue_time redis.call('ZADD', prefix .. ':' .. queue_type, ready_time, queue_id) end end -- update the metrics counters -- update global counter. local timestamp_minute = math.floor(current_timestamp/60000) * 60000 -- get the epoch for the minute local expiry_time = math.floor((timestamp_minute + 600000) / 1000) -- store the data for 10 minutes. if redis.call('EXISTS', prefix .. ':enqueue_counter:' .. timestamp_minute) ~= 1 then -- counter does not exists. set the initial value and expiry. redis.call('SET', prefix .. ':enqueue_counter:' .. timestamp_minute, 1) redis.call('EXPIREAT', prefix .. ':enqueue_counter:' .. timestamp_minute, expiry_time) else -- counter already exists. just increment the value. redis.call('INCR', prefix .. ':enqueue_counter:' .. timestamp_minute) end -- update the current queue counter. if redis.call('EXISTS', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':enqueue_counter:' .. timestamp_minute) ~= 1 then -- counter does not exists. set the initial value and expiry. redis.call('SET', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':enqueue_counter:' .. timestamp_minute, 1) redis.call('EXPIREAT', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':enqueue_counter:' .. timestamp_minute, expiry_time) else -- counter already exists. just increment the value. redis.call('INCR', prefix .. ':' .. queue_type .. ':' .. queue_id .. ':enqueue_counter:' .. timestamp_minute) end
mit
Fenix-XI/Fenix
scripts/zones/Dynamis-Jeuno/mobs/Goblin_Replica.lua
1
1818
----------------------------------- -- Area: Dynamis Jeuno -- MOB: Goblin Replica -- Map1 Position: http://images3.wikia.nocookie.net/__cb20090312005127/ffxi/images/b/bb/Jeu1.jpg -- Map2 Position: http://images4.wikia.nocookie.net/__cb20090312005155/ffxi/images/3/31/Jeu2.jpg -- Vanguard Position: http://faranim.livejournal.com/39860.html ----------------------------------- package.loaded["scripts/zones/Dynamis-Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Jeuno/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) dynamis.spawnGroup(mob, jeunoList, 1); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) mobID = mob:getID(); -- Time Bonus (30min): 002 if (mobID == 17547531 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(30); mob:addInBattlefieldList(); -- Time Bonus (30min): 004 elseif (mobID == 17547533 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(30); mob:addInBattlefieldList(); -- Time Bonus (30min): 029 elseif (mobID == 17547558 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(30); mob:addInBattlefieldList(); -- Time Bonus (30min): 045 elseif (mobID == 17547574 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(30); mob:addInBattlefieldList(); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/LaLoff_Amphitheater/npcs/qm1_4.lua
13
2440
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: Shimmering Circle (BCNM Entrances) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; package.loaded["scripts/globals/bcnm"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/LaLoff_Amphitheater/TextIDs"); -- Death cutscenes: -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might -- param 1: entrance # -- param 2: fastest time -- param 3: unknown -- param 4: clear time -- param 5: zoneid -- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM) -- param 7: skip (0 - no skip, 1 - prompt, 2 - force) -- param 8: 0 ----------------------------------- -- 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 (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option,4)) 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
Fenix-XI/Fenix
scripts/zones/Castle_Oztroja/Zone.lua
19
1745
----------------------------------- -- -- Zone: Castle_Oztroja (151) -- ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Castle_Oztroja/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- Yagudo Avatar SetRespawnTime(17396134, 900, 10800); UpdateTreasureSpawnPoint(17396206); UpdateTreasureSpawnPoint(17396207); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-162.895,22.136,-139.923,2); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
SkzKatsushiro/OpenRA
mods/cnc/maps/nod06a/nod06a.lua
25
7746
NodStartUnitsRight = { 'ltnk', 'bike', 'e1', 'e1', 'e3', 'e3' } NodStartUnitsLeft = { 'ltnk', 'ltnk', 'bggy', 'e1', 'e1', 'e1', 'e1', 'e3', 'e3', 'e3', 'e3' } Chn1Units = { 'e1', 'e1', 'e1', 'e1', 'e1' } Chn2Units = { 'e2', 'e2', 'e2', 'e2', 'e2' } Obj2Units = { 'ltnk', 'bike', 'e1', 'e1', 'e1' } Chn3CellTriggerActivator = { CPos.New(49,58), CPos.New(48,58), CPos.New(49,57), CPos.New(48,57), CPos.New(49,56), CPos.New(48,56), CPos.New(49,55), CPos.New(48,55) } DzneCellTriggerActivator = { CPos.New(61,45), CPos.New(60,45), CPos.New(59,45), CPos.New(58,45), CPos.New(57,45), CPos.New(61,44), CPos.New(60,44), CPos.New(59,44), CPos.New(58,44), CPos.New(57,44), CPos.New(61,43), CPos.New(60,43), CPos.New(58,43), CPos.New(57,43), CPos.New(61,42), CPos.New(60,42), CPos.New(59,42), CPos.New(58,42), CPos.New(57,42), CPos.New(61,41), CPos.New(60,41), CPos.New(59,41), CPos.New(58,41), CPos.New(57,41) } Win1CellTriggerActivator = { CPos.New(59,43) } Win2CellTriggerActivator = { CPos.New(54,58), CPos.New(53,58), CPos.New(52,58), CPos.New(54,57), CPos.New(53,57), CPos.New(52,57), CPos.New(54,56), CPos.New(53,56), CPos.New(52,56), CPos.New(54,55), CPos.New(53,55), CPos.New(52,55) } Grd2ActorTriggerActivator = { Guard1, Guard2, Guard3 } Atk1ActorTriggerActivator = { Atk1Activator1, Atk1Activator2 } Atk2ActorTriggerActivator = { Atk2Activator1, Atk2Activator2 } Chn1ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5 } Chn2ActorTriggerActivator = { Chn2Activator1, Chn2Activator2, Chn2Activator3 } Obj2ActorTriggerActivator = { Chn1Activator1, Chn1Activator2, Chn1Activator3, Chn1Activator4, Chn1Activator5, Chn2Activator1, Chn2Activator2, Chn2Activator3, Atk3Activator } Chn1Waypoints = { ChnEntry.Location, waypoint5.Location } Chn2Waypoints = { ChnEntry.Location, waypoint6.Location } Gdi3Waypoints = { waypoint1, waypoint3, waypoint7, waypoint8, waypoint9 } Gdi4Waypoints = { waypoint4, waypoint10, waypoint9, waypoint11, waypoint9, waypoint10 } Gdi5Waypoints = { waypoint1, waypoint4 } Gdi6Waypoints = { waypoint2, waypoints3 } Grd1TriggerFunctionTime = DateTime.Seconds(3) Grd1TriggerFunction = function() MyActors = Utils.Take(2, enemy.GetActorsByType('mtnk')) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi3Waypoints) end) end Grd2TriggerFunction = function() if not Grd2Switch then for type, count in pairs({ ['e1'] = 2, ['e2'] = 1, ['jeep'] = 1 }) do MyActors = Utils.Take(count, enemy.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi4Waypoints) end) end Grd2Swicth = true end end Atk1TriggerFunction = function() if not Atk1Switch then for type, count in pairs({ ['e1'] = 3, ['e2'] = 3, ['jeep'] = 1 }) do MyActors = Utils.Take(count, enemy.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi5Waypoints) end) end Atk1Switch = true end end Atk2TriggerFunction = function() if not Atk2Switch then for type, count in pairs({ ['mtnk'] = 1, ['jeep'] = 1 }) do MyActors = Utils.Take(count, enemy.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MovementAndHunt(actor, Gdi6Waypoints) end) end Atk2Switch = true end end Atk3TriggerFunction = function() if not Atk3Switch then Atk3Switch = true if not Radar.IsDead then local targets = player.GetGroundAttackers() local target = targets[DateTime.GameTime % #targets + 1].CenterPosition if target then Radar.SendAirstrike(target, false, Facing.NorthEast + 4) end end end end Chn1TriggerFunction = function() local cargo = Reinforcements.ReinforceWithTransport(enemy, 'tran', Chn1Units, Chn1Waypoints, { waypoint14.Location })[2] Utils.Do(cargo, function(actor) IdleHunt(actor) end) end Chn2TriggerFunction = function() local cargo = Reinforcements.ReinforceWithTransport(enemy, 'tran', Chn2Units, Chn2Waypoints, { waypoint14.Location })[2] Utils.Do(cargo, function(actor) IdleHunt(actor) end) end Obj2TriggerFunction = function() player.MarkCompletedObjective(NodObjective2) Reinforcements.Reinforce(player, Obj2Units, { Obj2UnitsEntry.Location, waypoint13.Location }, 15) end MovementAndHunt = function(unit, waypoints) if unit ~= nil then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end InsertNodUnits = function() Camera.Position = UnitsRallyRight.CenterPosition Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.Reinforce(player, NodStartUnitsLeft, { UnitsEntryLeft.Location, UnitsRallyLeft.Location }, 15) Reinforcements.Reinforce(player, NodStartUnitsRight, { UnitsEntryRight.Location, UnitsRallyRight.Location }, 15) end WorldLoaded = function() player = Player.GetPlayer("Nod") enemy = Player.GetPlayer("GDI") Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(player, function() Media.PlaySpeechNotification(player, "Win") end) Trigger.OnPlayerLost(player, function() Media.PlaySpeechNotification(player, "Lose") end) NodObjective1 = player.AddPrimaryObjective("Steal the GDI nuclear detonator.") NodObjective2 = player.AddSecondaryObjective("Destroy the houses of the GDI supporters\nin the village.") GDIObjective = enemy.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.") InsertNodUnits() Trigger.AfterDelay(Grd1TriggerFunctionTime, Grd1TriggerFunction) Utils.Do(Grd2ActorTriggerActivator, function(actor) Trigger.OnDiscovered(actor, Grd2TriggerFunction) end) OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction) OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction) Trigger.OnDamaged(Atk3Activator, Atk3TriggerFunction) Trigger.OnAllKilled(Chn1ActorTriggerActivator, Chn1TriggerFunction) Trigger.OnAllKilled(Chn2ActorTriggerActivator, Chn2TriggerFunction) Trigger.OnEnteredFootprint(Chn3CellTriggerActivator, function(a, id) if a.Owner == player then Media.PlaySpeechNotification(player, "Reinforce") Reinforcements.ReinforceWithTransport(player, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id) if a.Owner == player then Actor.Create('flare', true, { Owner = player, Location = waypoint17.Location }) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnAllRemovedFromWorld(Obj2ActorTriggerActivator, Obj2TriggerFunction) Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id) if a.Owner == player then NodObjective3 = player.AddPrimaryObjective("Move to the evacuation point.") player.MarkCompletedObjective(NodObjective1) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id) if a.Owner == player and NodObjective3 then player.MarkCompletedObjective(NodObjective3) Trigger.RemoveFootprintTrigger(id) end end) end Tick = function() if DateTime.GameTime > 2 and player.HasNoRequiredUnits() then enemy.MarkCompletedObjective(GDIObjective) end end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end OnAnyDamaged = function(actors, func) Utils.Do(actors, function(actor) Trigger.OnDamaged(actor, func) end) end
gpl-3.0
Oarcinae/FactorioScenarioMultiplayerSpawn
lib/rocket_launch.lua
1
3201
-- rocket_launch.lua -- May 2019 -- This is meant to extract out any rocket launch related logic to support my oarc scenario designs. require("lib/oarc_utils") require("config") -------------------------------------------------------------------------------- -- Rocket Launch Event Code -- Controls the "win condition" -------------------------------------------------------------------------------- function RocketLaunchEvent(event) local force = event.rocket.force -- Notify players on force if rocket was launched without sat. if event.rocket.get_item_count("satellite") == 0 then for index, player in pairs(force.players) do player.print("You launched the rocket, but you didn't put a satellite inside.") end return end -- First ever sat launch if not global.ocore.satellite_sent then global.ocore.satellite_sent = {} SendBroadcastMsg("Team " .. force.name .. " was the first to launch a rocket!") ServerWriteFile("rocket_events", "Team " .. force.name .. " was the first to launch a rocket!" .. "\n") for name,player in pairs(game.players) do SetOarcGuiTabEnabled(player, OARC_ROCKETS_GUI_TAB_NAME, true) end end -- Track additional satellites launched by this force if global.ocore.satellite_sent[force.name] then global.ocore.satellite_sent[force.name] = global.ocore.satellite_sent[force.name] + 1 SendBroadcastMsg("Team " .. force.name .. " launched another rocket. Total " .. global.ocore.satellite_sent[force.name]) ServerWriteFile("rocket_events", "Team " .. force.name .. " launched another rocket. Total " .. global.ocore.satellite_sent[force.name] .. "\n") -- First sat launch for this force. else -- game.set_game_state{game_finished=true, player_won=true, can_continue=true} global.ocore.satellite_sent[force.name] = 1 SendBroadcastMsg("Team " .. force.name .. " launched their first rocket!") ServerWriteFile("rocket_events", "Team " .. force.name .. " launched their first rocket!" .. "\n") -- Unlock research and recipes if global.ocfg.lock_goodies_rocket_launch then for _,v in ipairs(LOCKED_TECHNOLOGIES) do EnableTech(force, v.t) end for _,v in ipairs(LOCKED_RECIPES) do if (force.technologies[v.r].researched) then AddRecipe(force, v.r) end end end end end function CreateRocketGuiTab(tab_container, player) -- local frame = tab_container.add{type="frame", name="rocket-panel", caption="Satellites Launched:", direction = "vertical"} AddLabel(tab_container, nil, "Satellites Launched:", my_label_header_style) if (global.ocore.satellite_sent == nil) then AddLabel(tab_container, nil, "No launches yet.", my_label_style) else for force_name,sat_count in pairs(global.ocore.satellite_sent) do AddLabel(tab_container, "rc_"..force_name, "Team " .. force_name .. ": " .. tostring(sat_count), my_label_style) end end end
mit
mrrigealijan/nnso
bot/permissions.lua
8
1312
local sudos = { "plugins", "rank_admin", "bot", "lang_install", "set_lang", "tosupergroup", "gban_installer" } local admins = { "rank_mod", "gban", "ungban", "setrules", "setphoto", "creategroup", "setname", "addbots", "setlink", "rank_guest", "description", "export_gban" } local mods = { "whois", "kick", "add", "ban", "unban", "lockmember", "mute", "unmute", "admins", "members", "mods", "flood", "commands", "lang", "link", "settings", "mod_commands", "no_flood_ban", "muteall", "rules" } local function get_tag(plugin_tag) for v,tag in pairs(sudos) do if tag == plugin_tag then return 3 end end for v,tag in pairs(admins) do if tag == plugin_tag then return 2 end end for v,tag in pairs(mods) do if tag == plugin_tag then return 1 end end return 0 end local function user_num(user_id, chat_id) if new_is_sudo(user_id) then return 3 elseif is_admin(user_id) then return 2 elseif is_mod(chat_id, user_id) then return 1 else return 0 end end function permissions(user_id, chat_id, plugin_tag) local user_is = get_tag(plugin_tag) local user_n = user_num(user_id, chat_id) if user_n >= user_is then return true else return false end end
gpl-2.0
8devices/carambola2-luci
applications/luci-watchcat/luasrc/model/cbi/watchcat/watchcat.lua
30
2105
--[[ LuCI - Lua Configuration Interface Copyright 2012 Christian Gagneraud <chris@techworks.ie> 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$ ]]-- m = Map("system", translate("Watchcat"), translate("Watchcat allows configuring a periodic reboot when the " .. "Internet connection has been lost for a certain period of time." )) s = m:section(TypedSection, "watchcat") s.anonymous = true s.addremove = true mode = s:option(ListValue, "mode", translate("Operating mode")) mode.default = "allways" mode:value("ping", "Reboot on internet connection lost") mode:value("allways", "Periodic reboot") forcedelay = s:option(Value, "forcedelay", translate("Forced reboot delay"), translate("When rebooting the system, the watchcat will trigger a soft reboot. " .. "Entering a non zero value here will trigger a delayed hard reboot " .. "if the soft reboot fails. Enter a number of seconds to enable, " .. "use 0 to disable")) forcedelay.datatype = "uinteger" forcedelay.default = "0" period = s:option(Value, "period", translate("Period"), translate("In periodic mode, it defines the reboot period. " .. "In internet mode, it defines the longest period of " .. "time without internet access before a reboot is engaged." .. "Default unit is seconds, you can use the " .. "suffix 'm' for minutes, 'h' for hours or 'd' " .. "for days")) pinghost = s:option(Value, "pinghost", translate("Ping host"), translate("Host address to ping")) pinghost.datatype = "host" pinghost.default = "8.8.8.8" pinghost:depends({mode="ping"}) pingperiod = s:option(Value, "pingperiod", translate("Ping period"), translate("How often to check internet connection. " .. "Default unit is seconds, you can you use the " .. "suffix 'm' for minutes, 'h' for hours or 'd' " .. "for days")) pingperiod:depends({mode="ping"}) return m
apache-2.0
DarkstarProject/darkstar
scripts/zones/Mount_Zhayolm/mobs/Sarameya.lua
11
2571
----------------------------------- -- Area: Mount Zhayolm -- NM: Sarameya -- !pos 322 -14 -581 61 -- Spawned with Buffalo Corpse: !additem 2583 -- Wiki: http://ffxiclopedia.wikia.com/wiki/Sarameya -- TODO: PostAIRewrite: Code the Howl effect and gradual resists. ----------------------------------- mixins = {require("scripts/mixins/rage")} require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------- function onMobInitialize(mob) mob:setMobMod(dsp.mobMod.GA_CHANCE, 50) mob:setMobMod(dsp.mobMod.ADD_EFFECT, 1) end function onMobSpawn(mob) mob:addMod(dsp.mod.MEVA, 95) mob:addMod(dsp.mod.MDEF, 30) mob:addMod(dsp.mod.SILENCERES, 20) mob:addMod(dsp.mod.GRAVITYRES, 20) mob:addMod(dsp.mod.LULLABYRES, 30) mob:setLocalVar("[rage]timer", 3600) -- 60 minutes end function onMobRoam(mob) end function onMobFight(mob, target) local hpp = mob:getHPP() local useChainspell = false if hpp < 90 and mob:getLocalVar("chainspell89") == 0 then mob:setLocalVar("chainspell89", 1) useChainspell = true elseif hpp < 70 and mob:getLocalVar("chainspell69") == 0 then mob:setLocalVar("chainspell69", 1) useChainspell = true elseif hpp < 50 and mob:getLocalVar("chainspell49") == 0 then mob:setLocalVar("chainspell49", 1) useChainspell = true elseif hpp < 30 and mob:getLocalVar("chainspell29") == 0 then mob:setLocalVar("chainspell29", 1) useChainspell = true elseif hpp < 10 and mob:getLocalVar("chainspell9") == 0 then mob:setLocalVar("chainspell9", 1) useChainspell = true end if useChainspell then mob:useMobAbility(692) -- Chainspell mob:setMobMod(dsp.mobMod.GA_CHANCE, 100) end -- Spams TP moves and -ga spells if mob:hasStatusEffect(dsp.effect.CHAINSPELL) then mob:setTP(2000) else if mob:getMobMod(dsp.mobMod.GA_CHANCE) == 100 then mob:setMobMod(dsp.mobMod.GA_CHANCE, 50) end end -- Regens 1% of his HP a tick with Blaze Spikes on if mob:hasStatusEffect(dsp.effect.BLAZE_SPIKES) then mob:setMod(dsp.mod.REGEN, math.floor(mob:getMaxHP()/100)) else if mob:getMod(dsp.mod.REGEN) > 0 then mob:setMod(dsp.mod.REGEN, 0) end end end function onAdditionalEffect(mob, target, damage) return dsp.mob.onAddEffect(mob, target, damage, dsp.mob.ae.POISON, {chance = 40, power = 50}) end function onMobDeath(mob, player, isKiller) end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Jade_Sepulcher/Zone.lua
32
1271
----------------------------------- -- -- Zone: Jade_Sepulcher (67) -- ----------------------------------- package.loaded["scripts/zones/Jade_Sepulcher/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Jade_Sepulcher/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(340.383,-13.625,-157.447,189); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Ranguemont_Pass/npcs/Perchond.lua
9
1205
----------------------------------- -- Area: Ranguemont Pass -- NPC: Perchond -- !pos -182.844 4 -164.948 166 ----------------------------------- local ID = require("scripts/zones/Ranguemont_Pass/IDs") require("scripts/globals/keyitems") ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1107,1) and trade:getItemCount() == 1) then -- glitter sand local SinHunting = player:getCharVar("sinHunting"); -- RNG AF1 if (SinHunting == 2) then player:startEvent(5); end end end; function onTrigger(player,npc) local SinHunting = player:getCharVar("sinHunting"); -- RNG AF1 if (SinHunting == 1) then player:startEvent(3, 0, 1107); else player:startEvent(2); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 3) then player:setCharVar("sinHunting",2); elseif (csid == 5) then player:tradeComplete(); player:addKeyItem(dsp.ki.PERCHONDS_ENVELOPE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.PERCHONDS_ENVELOPE); player:setCharVar("sinHunting",3); end end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Yhoator_Jungle/npcs/qm3.lua
6
1078
----------------------------------- -- Area: Yhoator Jungle -- NPC: ??? (qm3) -- Involved in Quest: True will -- !pos 203 0.1 82 124 ----------------------------------- local ID = require("scripts/zones/Yhoator_Jungle/IDs") require("scripts/globals/keyitems") require("scripts/globals/npc_util") require("scripts/globals/quests") ----------------------------------- function onTrade(player,npc,trade) end function onTrigger(player,npc) if player:getQuestStatus(OUTLANDS, dsp.quest.id.outlands.TRUE_WILL) == QUEST_ACCEPTED and not player:hasKeyItem(dsp.ki.OLD_TRICK_BOX) then if player:getCharVar("trueWillKilledNM") > 0 then npcUtil.giveKeyItem(player, dsp.ki.OLD_TRICK_BOX) player:setCharVar("trueWillKilledNM", 0) else npcUtil.popFromQM(player, npc, {ID.mob.KAPPA_AKUSO, ID.mob.KAPPA_BONZE, ID.mob.KAPPA_BIWA}, { hide = 0 }) end else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
Giorox/AngelionOT-Repo
data/npc/scripts/Pydar.lua
1
1610
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) 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 node1 = keywordHandler:addKeyword({'fifth bless'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Here you may receive the blessing Spark of The Phoenix. But we must ask of you to sacrifice 2000 gold. Are you still interested?'}) node1:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, number = 2, premium = true, baseCost = 2000, levelCost = 200, startLevel = 30, endLevel = 120}) node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Too expensive, eh?'}) local node2 = keywordHandler:addKeyword({'spark of the phoenix'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Here you may receive the blessing Spark of The Phoenix. But we must ask of you to sacrifice 2000 gold. Are you still interested?'}) node1:addChildKeyword({'yes'}, StdModule.bless, {npcHandler = npcHandler, number = 2, premium = true, baseCost = 2000, levelCost = 200, startLevel = 30, endLevel = 120}) node1:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Oh. You do not have enough money.'}) npcHandler:addModule(FocusModule:new())
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Port_Jeuno/npcs/Leyla.lua
13
1496
----------------------------------- -- Area: Port Jeuno -- NPC: Leyla -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,LEYLA_SHOP_DIALOG); stock = {0x439c,55, -- Hawkeye 0x43a8,7, -- Iron Arrow 0x43b8,5, -- Crossbow Bolt 0x119d,10, -- Distilled Water 0x13ae,1000, -- Enchanting Etude 0x13ad,1265, -- Spirited Etude 0x13ac,1567, -- Learned Etude 0x13ab,1913, -- Quick Etude 0x13aa,2208, -- Vivacious Etude 0x13a9,2815, -- Dextrous Etude 0x13a8,3146} -- Sinewy Etude showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Norg/npcs/Edal-Tahdal.lua
9
4243
----------------------------------- -- Area: Norg -- NPC: Edal-Tahdal -- Starts and Finishes Quest: Trial by Water -- !pos -13 1 -20 252 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Norg/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local TrialByWater = player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WATER); local WhisperOfTides = player:hasKeyItem(dsp.ki.WHISPER_OF_TIDES); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day if ((TrialByWater == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4) or (TrialByWater == QUEST_COMPLETED and realday ~= player:getCharVar("TrialByWater_date"))) then player:startEvent(109,0,dsp.ki.TUNING_FORK_OF_WATER); -- Start and restart quest "Trial by Water" elseif (TrialByWater == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.TUNING_FORK_OF_WATER) == false and WhisperOfTides == false) then player:startEvent(190,0,dsp.ki.TUNING_FORK_OF_WATER); -- Defeat against Avatar : Need new Fork elseif (TrialByWater == QUEST_ACCEPTED and WhisperOfTides == false) then player:startEvent(110,0,dsp.ki.TUNING_FORK_OF_WATER,2); elseif (TrialByWater == QUEST_ACCEPTED and WhisperOfTides) then numitem = 0; if (player:hasItem(17439)) then numitem = numitem + 1; end -- Leviathan's Rod if (player:hasItem(13246)) then numitem = numitem + 2; end -- Water Belt if (player:hasItem(13565)) then numitem = numitem + 4; end -- Water Ring if (player:hasItem(1204)) then numitem = numitem + 8; end -- Eye of Nept if (player:hasSpell(300)) then numitem = numitem + 32; end -- Ability to summon Leviathan player:startEvent(112,0,dsp.ki.TUNING_FORK_OF_WATER,2,0,numitem); else player:startEvent(113); -- Standard dialog end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 109 and option == 1) then if (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WATER) == QUEST_COMPLETED) then player:delQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WATER); end player:addQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WATER); player:setCharVar("TrialByWater_date", 0); player:addKeyItem(dsp.ki.TUNING_FORK_OF_WATER); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.TUNING_FORK_OF_WATER); elseif (csid == 190) then player:addKeyItem(dsp.ki.TUNING_FORK_OF_WATER); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.TUNING_FORK_OF_WATER); elseif (csid == 112) then local item = 0; if (option == 1) then item = 17439; -- Leviathan's Rod elseif (option == 2) then item = 13246; -- Water Belt elseif (option == 3) then item = 13565; -- Water Ring elseif (option == 4) then item = 1204; -- Eye of Nept end if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,item); else if (option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif (option == 6) then player:addSpell(300); -- Avatar player:messageSpecial(ID.text.AVATAR_UNLOCKED,0,0,2); else player:addItem(item); player:messageSpecial(ID.text.ITEM_OBTAINED,item); -- Item end player:addTitle(dsp.title.HEIR_OF_THE_GREAT_WATER); player:delKeyItem(dsp.ki.WHISPER_OF_TIDES); --Whisper of Tides, as a trade for the above rewards player:setCharVar("TrialByWater_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(NORG,30); player:completeQuest(OUTLANDS,dsp.quest.id.outlands.TRIAL_BY_WATER); end end end;
gpl-3.0
SamuelePilleri/sysdig
userspace/sysdig/chisels/v_spy_syslog.lua
3
2003
--[[ Copyright (C) 2013-2015 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] view_info = { id = "spy_syslog", name = "Spy Syslog", description = "Show the entries written to syslog.", tips = {"This view can be applied to the whole system, to watch overall syslog activity, but is also useful when applied to a container or a process. In that case, the view will only show the syslog writes generated by the selected entity."}, tags = {"Default"}, view_type = "list", applies_to = {"", "container.id", "proc.pid", "proc.name", "thread.tid", "fd.sport", "fd.sproto", "k8s.pod.id", "k8s.rc.id", "k8s.svc.id", "k8s.ns.id"}, filter = "fd.name contains /dev/log and evt.is_io_write=true and evt.dir=< and evt.failed=false", columns = { { name = "PID", field = "proc.pid", description = "PID of the process generating the message.", colsize = 8, }, { name = "PROC", field = "proc.name", description = "Name of the process generating the message.", colsize = 8, }, { name = "FAC", field = "syslog.facility.str", description = "syslog facility of the message.", colsize = 8, }, { name = "SEV", field = "syslog.severity.str", description = "syslog severity of the message.", colsize = 8, }, { tags = {"containers"}, name = "Container", field = "container.name", colsize = 20 }, { name = "MESSAGE", field = "syslog.message", description = "Message sent to syslog", colsize = 0 } } }
gpl-2.0
Fenix-XI/Fenix
scripts/zones/Windurst_Waters_[S]/npcs/Ampiro-Mapiro.lua
13
1068
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ampiro-Mapiro -- Type: Standard NPC -- @zone: 94 -- @pos 131.380 -6.75 174.169 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01a7); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/items/bowl_of_humpty_soup.lua
18
1385
----------------------------------------- -- ID: 4521 -- Item: Bowl of Humpty Soup -- Food Effect: 240Min, All Races ----------------------------------------- -- Health % 6 -- Health Cap 35 -- Magic 5 -- Health Regen While Healing 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4521); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 6); target:addMod(MOD_FOOD_HP_CAP, 35); target:addMod(MOD_MP, 5); target:addMod(MOD_HPHEAL, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 6); target:delMod(MOD_FOOD_HP_CAP, 35); target:delMod(MOD_MP, 5); target:delMod(MOD_HPHEAL, 5); end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/mobskills/geotic_breath.lua
11
1287
--------------------------------------------- -- Geotic Breath -- -- Description: Deals Earth damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Ouryu --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") require("scripts/globals/utils") --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(dsp.effect.INVINCIBLE)) then return 1 elseif (target:isBehind(mob, 48) == true) then return 1 elseif (mob:AnimationSub() ~= 0) then return 1 end return 0 end function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, dsp.magic.ele.EARTH, 1400) local angle = mob:getAngle(target) angle = mob:getRotPos() - angle dmgmod = dmgmod * ((128-math.abs(angle))/128) dmgmod = utils.clamp(dmgmod, 50, 1600) local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,dsp.attackType.BREATH,dsp.damageType.EARTH,MOBPARAM_IGNORE_SHADOWS) target:takeDamage(dmg, mob, dsp.attackType.BREATH, dsp.damageType.EARTH) return dmg end
gpl-3.0
Fenix-XI/Fenix
scripts/globals/items/plate_of_mushroom_paella_+1.lua
18
1378
----------------------------------------- -- ID: 5971 -- Item: Plate of Mushroom Paella +1 -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- HP 43 -- Mind 6 -- Magic Accuracy 6 -- Undead Killer 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5971); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 45); target:addMod(MOD_MND, 6); target:addMod(MOD_MACC, 6); target:addMod(MOD_UNDEAD_KILLER, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 45); target:delMod(MOD_MND, 6); target:delMod(MOD_MACC, 6); target:delMod(MOD_UNDEAD_KILLER, 6); end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Windurst_Waters/npcs/Ohbiru-Dohbiru.lua
28
12066
----------------------------------- -- Area: Windurst Waters -- NPC: Ohbiru-Dohbiru -- Involved in quest: Food For Thought, Say It with Flowers -- Starts and finishes quest: Toraimarai Turmoil ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/common"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL); local count = trade:getItemCount(); if (player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_ACCEPTED) then if (trade:hasItemQty(4351,1) and count == 1) then player:startEvent(0x0163,900); end elseif (player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT) == QUEST_ACCEPTED) then local OhbiruFood = player:getVar("Ohbiru_Food_var"); if (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3 and OhbiruFood ~= 2) then -- Traded all 3 items & Didn't ask for order rand = math.random(1,2); if (rand == 1) then player:startEvent(0x0145,440); else player:startEvent(0x0146); end elseif (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3 and OhbiruFood == 2) then -- Traded all 3 items after receiving order player:startEvent(0x0142,440); end elseif (turmoil == QUEST_ACCEPTED) then if (count == 3 and trade:getGil() == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded player:startEvent(0x0317); else player:startEvent(0x0312,4500,267,906); -- Reminder of needed items end elseif (turmoil == QUEST_COMPLETED) then if (count == 3 and trade:getGil () == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded player:startEvent(0x0317); else player:startEvent(0x031b,4500,0,906); -- Reminder of needed items for repeated quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Check for Missions first (priority?) -- If the player has started the mission or not local pfame = player:getFameLevel(WINDURST); local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL); local FoodForThought = player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT); local needToZone = player:needToZone(); local OhbiruFood = player:getVar("Ohbiru_Food_var"); -- Variable to track progress of Ohbiru-Dohbiru in Food for Thought local waterWayToGo = player:getQuestStatus(WINDURST,WATER_WAY_TO_GO); local overnightDelivery = player:getQuestStatus(WINDURST,OVERNIGHT_DELIVERY); local SayFlowers = player:getQuestStatus(WINDURST,SAY_IT_WITH_FLOWERS); local FlowerProgress = player:getVar("FLOWER_PROGRESS"); if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==2) then player:startEvent(0x0368); elseif (player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE) then if (player:getVar("ohbiru_dohbiru_talk") == 1) then player:startEvent(0x8f); else player:startEvent(0x90); end elseif (SayFlowers == QUEST_ACCEPTED or FlowerProgress == 2) then if (needToZone) then player:startEvent(0x0206); elseif (player:getVar("FLOWER_PROGRESS") == 1) then player:startEvent(0x0205,0,0,0,0,950); else player:startEvent(0x0204,0,0,0,0,950); end elseif (waterWayToGo == QUEST_COMPLETED and needToZone) then player:startEvent(0x0164,0,4351); elseif (waterWayToGo == QUEST_ACCEPTED) then if (player:hasItem(504) == false and player:hasItem(4351) == false) then player:startEvent(0x0162); else player:startEvent(0x0161); end elseif (waterWayToGo == QUEST_AVAILABLE and overnightDelivery == QUEST_COMPLETED and pfame >= 3) then player:startEvent(0x0160,0,4351); elseif (FoodForThought == QUEST_AVAILABLE and OhbiruFood == 0) then player:startEvent(0x0134); -- Hungry; mentions the experiment. First step in quest for this NPC. player:setVar("Ohbiru_Food_var",1); elseif (FoodForThought == QUEST_AVAILABLE and OhbiruFood == 1) then player:startEvent(0x0135); -- Hungry. The NPC complains of being hungry before the quest is active. elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood < 2) then player:startEvent(0x013c,0,4493,624,4408); -- Gives Order player:setVar("Ohbiru_Food_var",2); elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood == 2) then player:startEvent(0x013d,0,4493,624,4408); -- Repeats Order elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood == 3) then player:startEvent(0x0144); -- Reminds player to check on friends if he has been given his food. elseif (FoodForThought == QUEST_COMPLETED and needToZone == true) then player:startEvent(0x0158); -- Post Food for Thought Dialogue elseif (overnightDelivery == QUEST_COMPLETED and pfame < 6) then player:startEvent(0x015f); -- Post Overnight Delivery Dialogue -- -- Begin Toraimarai Turmoil Section -- elseif (turmoil == QUEST_AVAILABLE and pfame >= 6 and needToZone == false) then player:startEvent(0x0311,4500,267,906); elseif (turmoil == QUEST_ACCEPTED) then player:startEvent(0x0312,4500,267,906); -- Reminder of needed items elseif (turmoil == QUEST_COMPLETED) then player:startEvent(0x031b,4500,0,906); -- Allows player to initiate repeat of Toraimarai Turmoil else player:startEvent(0x0158); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- Check Missions first (priority?) local turmoil = player:getQuestStatus(WINDURST,TORAIMARAI_TURMOIL); if (csid == 0x8f) then player:setVar("ohbiru_dohbiru_talk",2); elseif (csid == 0x0142 or csid == 0x0145) then if (player:getVar("Kerutoto_Food_var") == 3 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 2) then -- If this is the last NPC to be fed player:tradeComplete(); player:completeQuest(WINDURST,FOOD_FOR_THOUGHT); player:addTitle(FAST_FOOD_DELIVERER); player:addGil(GIL_RATE*440); player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------ player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------ player:addFame(WINDURST,100); player:needToZone(true); else player:tradeComplete(); player:addGil(GIL_RATE*440); player:setVar("Ohbiru_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed. end elseif (csid == 0x0146) then if (player:getVar("Kerutoto_Food_var") == 3 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 2) then -- If this is the last NPC to be fed player:tradeComplete(); player:completeQuest(WINDURST,FOOD_FOR_THOUGHT); player:addTitle(FAST_FOOD_DELIVERER); player:addGil(GIL_RATE*440); player:messageSpecial(GIL_OBTAINED,GIL_RATE*440); player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------ player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------ player:addFame(WINDURST,100); player:needToZone(true); else player:tradeComplete(); player:addGil(GIL_RATE*440); player:messageSpecial(GIL_OBTAINED,GIL_RATE*440); player:setVar("Ohbiru_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed. end elseif (csid == 0x0311 and option == 1) then -- Adds Toraimarai turmoil player:addQuest(WINDURST,TORAIMARAI_TURMOIL); player:messageSpecial(KEYITEM_OBTAINED,267); player:addKeyItem(267); -- Rhinostery Certificate elseif (csid == 0x0317 and turmoil == QUEST_ACCEPTED) then -- Completes Toraimarai turmoil - first time player:addGil(GIL_RATE*4500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*4500); player:completeQuest(WINDURST,TORAIMARAI_TURMOIL); player:addFame(WINDURST,100); player:addTitle(CERTIFIED_RHINOSTERY_VENTURER); player:tradeComplete(); elseif (csid == 0x0317 and turmoil == 2) then -- Completes Toraimarai turmoil - repeats player:addGil(GIL_RATE*4500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*4500); player:addFame(WINDURST,50); player:tradeComplete(); elseif (csid == 0x0160 and option == 0 or csid == 0x0162) then if (player:getFreeSlotsCount() >= 1) then if (player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_AVAILABLE) then player:addQuest(WINDURST,WATER_WAY_TO_GO); end player:addItem(504); player:messageSpecial(ITEM_OBTAINED,504); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,504); end elseif (csid == 0x0163) then player:addGil(GIL_RATE*900); player:completeQuest(WINDURST,WATER_WAY_TO_GO); player:addFame(WINDURST,40); player:tradeComplete(); player:needToZone(true); elseif (csid == 0x0368) then player:setVar("MEMORIES_OF_A_MAIDEN_Status",3); elseif (csid == 0x0204) then if (option == 0) then player:delGil(300); player:addItem(948); -- Carnation player:messageSpecial(ITEM_OBTAINED,948); player:needToZone(true); elseif (option == 1) then player:delGil(200); player:addItem(941); -- Red Rose player:messageSpecial(ITEM_OBTAINED,941); player:needToZone(true); elseif (option == 2) then player:delGil(250); player:addItem(949); -- Rain Lily player:messageSpecial(ITEM_OBTAINED,949); player:needToZone(true); elseif (option == 3) then player:delGil(150); player:addItem(956); -- Lilac player:messageSpecial(ITEM_OBTAINED,956); player:needToZone(true); elseif (option == 4) then player:delGil(200); player:addItem(957); -- Amaryllis player:messageSpecial(ITEM_OBTAINED,957); player:needToZone(true); elseif (option == 5) then player:delGil(100); player:addItem(958); -- Marguerite player:messageSpecial(ITEM_OBTAINED,958); player:needToZone(true); elseif (option == 7) then player:setVar("FLOWER_PROGRESS",1); end end end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/spells/sinewy_etude.lua
27
1843
----------------------------------------- -- Spell: Sinewy Etude -- Static STR Boost, BRD 24 ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 0; if (sLvl+iLvl <= 181) then power = 3; elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then power = 4; elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then power = 5; elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then power = 6; elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then power = 7; elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then power = 8; elseif (sLvl+iLvl >= 450) then power = 9; end local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_STR, 1)) then spell:setMsg(75); end return EFFECT_ETUDE; end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/_0z0.lua
9
1306
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: _0z0 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); function onTrade(player,npc,trade) if (TradeBCNM(player,npc,trade)) then return; end end; function onTrigger(player,npc) --player:addMission(COP, dsp.mission.id.cop.WHEN_ANGELS_FALL); --player:setCharVar("PromathiaStatus",3); if (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus")==3) then player:startEvent(203); elseif (EventTriggerBCNM(player,npc)) then elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus")==5) then player:startEvent(205); end return 1; end; function onEventUpdate(player,csid,option,extras) EventUpdateBCNM(player,csid,option,extras); end; function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); if ( csid == 203) then player:setCharVar("PromathiaStatus",4); elseif (EventFinishBCNM(player,csid,option)) then return; end end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Yhoator_Jungle/Zone.lua
17
4099
----------------------------------- -- -- Zone: Yhoator_Jungle (124) -- ----------------------------------- package.loaded[ "scripts/zones/Yhoator_Jungle/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/Yhoator_Jungle/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/zone"); require("scripts/globals/conquest"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 880, 282, DIGREQ_NONE }, { 689, 177, DIGREQ_NONE }, { 4432, 140, DIGREQ_NONE }, { 923, 90, DIGREQ_NONE }, { 702, 41, DIGREQ_NONE }, { 700, 44, DIGREQ_NONE }, { 4450, 47, DIGREQ_NONE }, { 703, 26, DIGREQ_NONE }, { 4449, 12, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 4374, 17, DIGREQ_BURROW }, { 4373, 41, DIGREQ_BURROW }, { 4375, 15, DIGREQ_BURROW }, { 4566, 3, DIGREQ_BURROW }, { 688, 23, DIGREQ_BORE }, { 696, 17, DIGREQ_BORE }, { 690, 3, DIGREQ_BORE }, { 699, 12, DIGREQ_BORE }, { 701, 9, DIGREQ_BORE }, { 1446, 3, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17285698,17285699,17285700}; SetFieldManual(manuals); -- Bright-handed Kunberry SetRespawnTime(17285220, 900, 10800); -- Bisque-heeled Sunberry SetRespawnTime(17285460, 900, 10800); -- Bright-handed Kunberry SetRespawnTime(17285526, 900, 10800); SetRegionalConquestOverseers(zone:getRegionID()) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( 299.997, -5.838, -622.998, 190); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; end return cs; end; ------------------------ ----------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Abyssea-Altepa/Zone.lua
33
1470
----------------------------------- -- -- Zone: Abyssea - Altepa -- ----------------------------------- package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Abyssea-Altepa/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(435 ,0 ,320 ,136) end if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED and player:getVar("1stTimeAyssea") == 0) then player:setVar("1stTimeAyssea",1); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Upper_Jeuno/npcs/Deadly_Minnow.lua
9
1232
----------------------------------- -- Area: Upper Jeuno -- NPC: Deadly Minnow -- Standard Merchant NPC -- Involved in Quest: Borghertz's Hands (1st quest only) -- !pos -5 1 48 244 ----------------------------------- local ID = require("scripts/zones/Upper_Jeuno/IDs") require("scripts/globals/shop") function onTrade(player,npc,trade) end function onTrigger(player,npc) if player:getCharVar("BorghertzHandsFirstTime") == 1 then player:startEvent(24) player:setCharVar("BorghertzHandsFirstTime", 2) else local stock = { 12442, 13179, -- Studded Bandana 12425, 22800, -- Silver Mask 12426, 47025, -- Banded Helm 12570, 20976, -- Studded Vest 12553, 35200, -- Silver Mail 12554, 66792, -- Banded Mail 12698, 11012, -- Studded Gloves 12681, 18800, -- Silver Mittens 12672, 23846, -- Gauntlets 12682, 35673, -- Mufflers } player:showText(npc, ID.text.DEADLYMINNOW_SHOP_DIALOG) dsp.shop.general(player, stock) end end function onEventUpdate(player,csid,option) end function onEventFinish(player,csid,option) end
gpl-3.0
emender/emender
test/TestRequires6.lua
1
1440
-- TestRequires6.lua - check if all required tools are available. -- This test contains 'requires' metadata which has wrong type. -- -- Copyright (C) 2014, 2015 Pavel Tisnovsky -- -- This file is part of Emender. -- -- Emender is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 3 of the License. -- -- Emender 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 Emender. If not, see <http://www.gnu.org/licenses/>. -- TestRequires6 = { -- required field metadata = { description = "Check that docunit core works correctly.", authors = "Pavel Tisnovsky", emails = "ptisnovs@redhat.com", changed = "2015-05-27", tags = {"BasicTest", "SmokeTest", "RequireMetadataTest"}, }, -- check if the Emender core work properly with 'requires' attribute -- that has wrong type requires = 1 } -- -- Just a dummy test function that shoult always pass. This function is -- included here because we would like to have non-empty test. -- function TestRequires6.testA() pass("TestRequires6.testA()") end
gpl-3.0
ZACTELEGRAM1/-EMAM-ALI-1
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
Giorox/AngelionOT-Repo
data/npc/scripts/Bruce.lua
1
1771
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) -- OTServ event handling functions start function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- OTServ event handling functions end -- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions! local travelNode = keywordHandler:addKeyword({'cemetery quarter'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want pass on to Cemetery Quarter?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = true, level = 0, cost = 0, destination = {x=32743, y=31113, z=7} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Then not.'}) local travelNode = keywordHandler:addKeyword({'alchemist quarter'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want pass on to Alchemist Quarter?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = true, level = 0, cost = 0, destination = {x=32738, y=31113, z=7} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Then not.'}) npcHandler:addModule(FocusModule:new())
gpl-3.0
jkprg/prosody-modules
mod_firewall/conditions.lib.lua
31
6103
local condition_handlers = {}; local jid = require "util.jid"; -- Return a code string for a condition that checks whether the contents -- of variable with the name 'name' matches any of the values in the -- comma/space/pipe delimited list 'values'. local function compile_comparison_list(name, values) local conditions = {}; for value in values:gmatch("[^%s,|]+") do table.insert(conditions, ("%s == %q"):format(name, value)); end return table.concat(conditions, " or "); end function condition_handlers.KIND(kind) return compile_comparison_list("name", kind), { "name" }; end local wildcard_equivs = { ["*"] = ".*", ["?"] = "." }; local function compile_jid_match_part(part, match) if not match then return part.." == nil" end local pattern = match:match("<(.*)>"); if pattern then if pattern == "*" then return part; end if pattern:match("^<.*>$") then pattern = pattern:match("^<(.*)>$"); else pattern = pattern:gsub("%p", "%%%0"):gsub("%%(%p)", wildcard_equivs); end return ("%s:match(%q)"):format(part, "^"..pattern.."$"); else return ("%s == %q"):format(part, match); end end local function compile_jid_match(which, match_jid) local match_node, match_host, match_resource = jid.split(match_jid); local conditions = {}; conditions[#conditions+1] = compile_jid_match_part(which.."_node", match_node); conditions[#conditions+1] = compile_jid_match_part(which.."_host", match_host); if match_resource then conditions[#conditions+1] = compile_jid_match_part(which.."_resource", match_resource); end return table.concat(conditions, " and "); end function condition_handlers.TO(to) return compile_jid_match("to", to), { "split_to" }; end function condition_handlers.FROM(from) return compile_jid_match("from", from), { "split_from" }; end function condition_handlers.TYPE(type) return compile_comparison_list("(type or (name == 'message' and 'normal') or (name == 'presence' and 'available'))", type), { "type", "name" }; end local function zone_check(zone, which) local which_not = which == "from" and "to" or "from"; return ("(zone_%s[%s_host] or zone_%s[%s] or zone_%s[bare_%s]) " .."and not(zone_%s[%s_host] or zone_%s[%s] or zone_%s[%s])" ) :format(zone, which, zone, which, zone, which, zone, which_not, zone, which_not, zone, which_not), { "split_to", "split_from", "bare_to", "bare_from", "zone:"..zone }; end function condition_handlers.ENTERING(zone) return zone_check(zone, "to"); end function condition_handlers.LEAVING(zone) return zone_check(zone, "from"); end function condition_handlers.PAYLOAD(payload_ns) return ("stanza:get_child(nil, %q)"):format(payload_ns); end function condition_handlers.INSPECT(path) if path:find("=") then local path, match = path:match("(.-)=(.*)"); return ("stanza:find(%q) == %q"):format(path, match); end return ("stanza:find(%q)"):format(path); end function condition_handlers.FROM_GROUP(group_name) return ("group_contains(%q, bare_from)"):format(group_name), { "group_contains", "bare_from" }; end function condition_handlers.TO_GROUP(group_name) return ("group_contains(%q, bare_to)"):format(group_name), { "group_contains", "bare_to" }; end function condition_handlers.FROM_ADMIN_OF(host) return ("is_admin(bare_from, %s)"):format(host ~= "*" and host or nil), { "is_admin", "bare_from" }; end function condition_handlers.TO_ADMIN_OF(host) return ("is_admin(bare_to, %s)"):format(host ~= "*" and host or nil), { "is_admin", "bare_to" }; end local day_numbers = { sun = 0, mon = 2, tue = 3, wed = 4, thu = 5, fri = 6, sat = 7 }; local function current_time_check(op, hour, minute) hour, minute = tonumber(hour), tonumber(minute); local adj_op = op == "<" and "<" or ">="; -- Start time inclusive, end time exclusive if minute == 0 then return "(current_hour"..adj_op..hour..")"; else return "((current_hour"..op..hour..") or (current_hour == "..hour.." and current_minute"..adj_op..minute.."))"; end end local function resolve_day_number(day_name) return assert(day_numbers[day_name:sub(1,3):lower()], "Unknown day name: "..day_name); end function condition_handlers.DAY(days) local conditions = {}; for day_range in days:gmatch("[^,]+") do local day_start, day_end = day_range:match("(%a+)%s*%-%s*(%a+)"); if day_start and day_end then local day_start_num, day_end_num = resolve_day_number(day_start), resolve_day_number(day_end); local op = "and"; if day_end_num < day_start_num then op = "or"; end table.insert(conditions, ("current_day >= %d %s current_day <= %d"):format(day_start_num, op, day_end_num)); elseif day_range:match("%a") then local day = resolve_day_number(day_range:match("%a+")); table.insert(conditions, "current_day == "..day); else error("Unable to parse day/day range: "..day_range); end end assert(#conditions>0, "Expected a list of days or day ranges"); return "("..table.concat(conditions, ") or (")..")", { "time:day" }; end function condition_handlers.TIME(ranges) local conditions = {}; for range in ranges:gmatch("([^,]+)") do local clause = {}; range = range:lower() :gsub("(%d+):?(%d*) *am", function (h, m) return tostring(tonumber(h)%12)..":"..(tonumber(m) or "00"); end) :gsub("(%d+):?(%d*) *pm", function (h, m) return tostring(tonumber(h)%12+12)..":"..(tonumber(m) or "00"); end); local start_hour, start_minute = range:match("(%d+):(%d+) *%-"); local end_hour, end_minute = range:match("%- *(%d+):(%d+)"); local op = tonumber(start_hour) > tonumber(end_hour) and " or " or " and "; if start_hour and end_hour then table.insert(clause, current_time_check(">", start_hour, start_minute)); table.insert(clause, current_time_check("<", end_hour, end_minute)); end if #clause == 0 then error("Unable to parse time range: "..range); end table.insert(conditions, "("..table.concat(clause, " "..op.." ")..")"); end return table.concat(conditions, " or "), { "time:hour,min" }; end function condition_handlers.LIMIT(name) return ("not throttle_%s:poll(1)"):format(name), { "throttle:"..name }; end return condition_handlers;
mit
Fenix-XI/Fenix
scripts/globals/mobskills/Spike_Flail.lua
33
1247
--------------------------------------------------- -- Spike Flail -- Deals extreme damage in a threefold attack to targets behind the user. --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then return 1; elseif (mob:hasStatusEffect(EFFECT_SUPER_BUFF)) then return 1; elseif (mob:hasStatusEffect(EFFECT_INVINCIBLE)) then return 1; elseif (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then return 1; elseif (target:isBehind(mob, 48) == false) then return 1; elseif (mob:AnimationSub() == 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 2; local dmgmod = math.random(5,7); local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,2,3,4); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW); target:delHP(dmg); return dmg; end;
gpl-3.0
eugeneia/snabbswitch
src/lib/ptree/worker.lua
3
3489
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(...,package.seeall) local S = require("syscall") local engine = require("core.app") local app_graph = require("core.config") local counter = require("core.counter") local histogram = require('core.histogram') local lib = require('core.lib') local timer = require('core.timer') local channel = require("lib.ptree.channel") local action_codec = require("lib.ptree.action_codec") local alarm_codec = require("lib.ptree.alarm_codec") local Worker = {} local worker_config_spec = { duration = {}, measure_latency = {default=true}, no_report = {default=false}, report = {default={showapps=true,showlinks=true}}, Hz = {default=1000}, } function new_worker (conf) local conf = lib.parse(conf, worker_config_spec) local ret = setmetatable({}, {__index=Worker}) ret.period = 1/conf.Hz ret.duration = conf.duration or 1/0 ret.no_report = conf.no_report ret.channel = channel.create('config-worker-channel', 1e6) ret.alarms_channel = alarm_codec.get_channel() ret.pending_actions = {} ret.breathe = engine.breathe if conf.measure_latency then local latency = histogram.create('engine/latency.histogram', 1e-6, 1e0) ret.breathe = latency:wrap_thunk(ret.breathe, engine.now) end return ret end function Worker:shutdown() -- This will call stop() on all apps. engine.configure(app_graph.new()) -- Now we can exit. S.exit(0) end function Worker:commit_pending_actions() local to_apply = {} local should_flush = false for _,action in ipairs(self.pending_actions) do local name, args = unpack(action) if name == 'call_app_method_with_blob' then if #to_apply > 0 then engine.apply_config_actions(to_apply) to_apply = {} end local callee, method, blob = unpack(args) local obj = assert(engine.app_table[callee]) assert(obj[method])(obj, blob) elseif name == "shutdown" then self:shutdown() else if name == 'start_app' or name == 'reconfig_app' then should_flush = true end table.insert(to_apply, action) end end if #to_apply > 0 then engine.apply_config_actions(to_apply) end self.pending_actions = {} if should_flush then require('jit').flush() end end function Worker:handle_actions_from_manager() local channel = self.channel for i=1,4 do local buf, len = channel:peek_message() if not buf then break end local action = action_codec.decode(buf, len) if action[1] == 'commit' then self:commit_pending_actions() else table.insert(self.pending_actions, action) end channel:discard_message(len) end end function Worker:main () local stop = engine.now() + self.duration local next_time = engine.now() repeat self.breathe() if next_time < engine.now() then next_time = engine.now() + self.period self:handle_actions_from_manager() timer.run() end if not engine.busywait then engine.pace_breathing() end until stop < engine.now() counter.commit() if not self.no_report then engine.report(self.report) end end function main (opts) return new_worker(opts):main() end function selftest () print('selftest: lib.ptree.worker') main({duration=0.005}) print('selftest: ok') end
apache-2.0
Fenix-XI/Fenix
scripts/zones/Mamook/npcs/qm2.lua
30
1323
----------------------------------- -- Area: Mamook -- NPC: ??? (Spawn Iriri Samariri(ZNM T2)) -- @pos -118 7 -80 65 ----------------------------------- package.loaded["scripts/zones/Mamook/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mamook/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17043888; if (trade:hasItemQty(2579,1) and trade:getItemCount() == 1) then -- Trade Samariri Corpsehair if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
8devices/carambola2-luci
applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo.lua
141
1038
--[[ smap_devinfo - SIP Device Information (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.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("SIP Device Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", false, debug) luci.controller.luci_diag.smap_common.action_links(m, false) return m
apache-2.0
Fenix-XI/Fenix
scripts/zones/Xarcabard/TextIDs.lua
13
1203
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6392; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6397; -- Obtained: <item>. GIL_OBTAINED = 6398; -- Obtained <number> gil. KEYITEM_OBTAINED = 6400; -- Obtained key item: <keyitem>. BEASTMEN_BANNER = 7137; -- There was a curse on the beastmen's banner! ALREADY_OBTAINED_TELE = 7267; -- You already possess the gate crystal for this telepoint. -- Conquest CONQUEST = 7280; -- You've earned conquest points! -- Other NOTHING_OUT_OF_ORDINARY = 6411; -- There is nothing out of the ordinary here. ONLY_SHARDS = 7613; -- Only shards of ice lie upon the ground. BLOCKS_OF_ICE = 7614; -- You can hear blocks of ice moving from deep within the cave. -- Dynamis dialogs YOU_CANNOT_ENTER_DYNAMIS = 7740; -- You cannot enter Dynamis PLAYERS_HAVE_NOT_REACHED_LEVEL = 7742; -- Players who have not reached levelare prohibited from entering Dynamis UNUSUAL_ARRANGEMENT_OF_PEBBLES = 7753; -- There is an unusual arrangement of pebbles here. -- conquest Base CONQUEST_BASE = 7058; -- Tallying conquest results...
gpl-3.0
DarkstarProject/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/Ebon_Panel.lua
9
3451
----------------------------------- -- Area: The Garden of RuHmet -- NPC: Ebon_Panel -- !pos 100.000 -5.180 -337.661 35 | Mithra Tower -- !pos 740.000 -5.180 -342.352 35 | Elvaan Tower -- !pos 257.650 -5.180 -699.999 35 | Tarutaru Tower -- !pos 577.648 -5.180 -700.000 35 | Galka Tower ----------------------------------- local ID = require("scripts/zones/The_Garden_of_RuHmet/IDs") require("scripts/globals/keyitems") require("scripts/globals/missions") require("scripts/globals/status") require("scripts/globals/titles") ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local Race = player:getRace(); local xPos = npc:getXPos(); if (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus") == 1) then player:startEvent(202); elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus") == 2) then if (xPos > 99 and xPos < 101) then -- Mithra Tower if ( Race==dsp.race.MITHRA ) then player:startEvent(124); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end elseif (xPos > 739 and xPos < 741) then -- Elvaan Tower if ( Race==dsp.race.ELVAAN_M or Race==dsp.race.ELVAAN_F) then player:startEvent(121); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end elseif (xPos > 256 and xPos < 258) then -- Tarutaru Tower if ( Race==dsp.race.TARU_M or Race==dsp.race.TARU_F ) then player:startEvent(123); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end elseif (xPos > 576 and xPos < 578) then -- Galka Tower if ( Race==dsp.race.GALKA) then player:startEvent(122); else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end end else player:messageSpecial(ID.text.NO_NEED_INVESTIGATE); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 202) then player:setCharVar("PromathiaStatus",2); elseif (124 and option ~=0) then -- Mithra player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_DEM); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_DEM); elseif (121 and option ~=0) then -- Elvaan player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_MEA); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_MEA); elseif (123 and option ~=0) then -- Tarutaru player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_HOLLA); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_HOLLA); elseif (122 and option ~=0) then -- Galka player:addTitle(dsp.title.WARRIOR_OF_THE_CRYSTAL); player:setCharVar("PromathiaStatus",3); player:addKeyItem(dsp.ki.LIGHT_OF_ALTAIEU); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LIGHT_OF_ALTAIEU); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Eastern_Altepa_Desert/npcs/Field_Manual.lua
29
1067
----------------------------------- -- Field Manual -- Area: Eastern Altepa Desert ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startFov(FOV_EVENT_EAST_ALTEPA,player); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,menuchoice) updateFov(player,csid,menuchoice,109,110,111,112,113); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) finishFov(player,csid,option,109,110,111,112,113,FOV_MSG_EAST_ALTEPA); end;
gpl-3.0
emender/emender
test/TestRequiresD.lua
1
1538
-- TestRequiresD.lua - check if all required tools are available. -- This test contains 'requires' metadata which has wrong type. -- -- Copyright (C) 2014, 2015 Pavel Tisnovsky -- -- This file is part of Emender. -- -- Emender is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation; version 3 of the License. -- -- Emender 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 Emender. If not, see <http://www.gnu.org/licenses/>. -- TestRequiresD = { -- required field metadata = { description = "Check that docunit core works correctly.", authors = "Pavel Tisnovsky", emails = "ptisnovs@redhat.com", changed = "2015-05-27", tags = {"BasicTest", "SmokeTest", "RequireMetadataTest"}, }, -- check if the Emender core work properly with 'requires' attribute -- that has wrong type requires = 1 } -- -- Set up function. -- function TestRequiresD.setUp() pass("TestRequiresD.setUp()") end -- -- Just a dummy test function that shoult always pass. This function is -- included here because we would like to have non-empty test. -- function TestRequiresD.testA() pass("TestRequiresD.testA()") end
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Rabao/TextIDs.lua
15
2028
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6401; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6406; -- Obtained: <item> GIL_OBTAINED = 6407; -- Obtained <number> gil KEYITEM_OBTAINED = 6409; -- Obtained key item: <keyitem> NOT_HAVE_ENOUGH_GIL = 6411; -- You do not have enough gil. HOMEPOINT_SET = 2; -- Home point set! FISHING_MESSAGE_OFFSET = 6654; -- You can't fish here. -- Other Texts PAKHI_DELIVERY_DIALOG = 10017; -- When your pack is fit to burrrst, send your non-essential items to your delivery box and bam, prrroblem solved! SPIRIT_DELIVERY_DIALOG = 10018; -- We can deliver goods to your residence or to the residences of your friends -- Quest Dialog GARUDA_UNLOCKED = 10102; -- You are now able to summon NOMAD_MOOGLE_DIALOG = 10170; -- 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 SHINY_TEETH_SHOP_DIALOG = 10022; -- Well met, adventurer. If you're looking for a weapon to carve through those desert beasts, you've come to the right place. BRAVEWOLF_SHOP_DIALOG = 10023; -- For rainy days and windy days, or for days when someone tries to thrust a spear in your guts, having a good set of armor can set your mind at ease. BRAVEOX_SHOP_DIALOG = 10024; -- These days, you can get weapons and armor cheap at the auction houses. But magic is expensive no matter where you go. SCAMPLIX_SHOP_DIALOG = 10025; -- No problem, Scamplix not bad guy. Scamplix is good guy, sells stuff to adventurers. Scamplix got lots of good stuff for you. GENEROIT_SHOP_DIALOG = 10288; -- Ho there! I am called Generoit. I have everything here for the chocobo enthusiast, and other rare items galore. -- conquest Base CONQUEST_BASE = 6495; -- Tallying conquest results... -- Porter Moogle RETRIEVE_DIALOG_ID = 10744; -- You retrieve a <item> from the porter moogle's care.
gpl-3.0
punisherbot/-
plugins/id.lua
226
4260
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' for k,v in pairs(result.members) do text = text .. v.print_name .. " (user#id" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = user_print_name(msg.from) .. ' (user#id' .. msg.from.id .. ')' if is_chat_msg(msg) then text = text .. "\nYou are in group " .. user_print_name(msg.to) .. " (chat#id" .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end elseif matches[1] == "member" and matches[2] == "@" then local nick = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local receiver = extra.receiver local nick = extra.nick local found for k,user in pairs(result.members) do if user.username == nick then found = user end end if not found then send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "ID: "..found.id send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, nick=nick}) elseif matches[1] == "members" and matches[2] == "name" then local text = matches[3] local chat = get_receiver(msg) if not is_chat_msg(msg) then return "You are not in a group." end chat_info(chat, function (extra, success, result) local members = result.members local receiver = extra.receiver local text = extra.text local founds = {} for k,member in pairs(members) do local fields = {'first_name', 'print_name', 'username'} for k,field in pairs(fields) do if member[field] and type(member[field]) == "string" then if member[field]:match(text) then local id = tostring(member.id) founds[id] = member end end end end if next(founds) == nil then -- Empty table send_msg(receiver, "User not found on this chat.", ok_cb, false) else local text = "" for k,user in pairs(founds) do local first_name = user.first_name or "" local print_name = user.print_name or "" local user_name = user.user_name or "" local id = user.id or "" -- This would be funny text = text.."First name: "..first_name.."\n" .."Print name: "..print_name.."\n" .."User name: "..user_name.."\n" .."ID: "..id end send_msg(receiver, text, ok_cb, false) end end, {receiver=chat, text=text}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id member @<user_name>: Return the member @<user_name> ID from the current chat", "!id members name <text>: Search for users with <text> on first_name, print_name or username on current chat" }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (member) (@)(.+)", "^!id (members) (name) (.+)" }, run = run }
gpl-2.0
eugeneia/snabbswitch
lib/ljsyscall/syscall/linux/errors.lua
24
5242
-- Linux error messages return { PERM = "Operation not permitted", NOENT = "No such file or directory", SRCH = "No such process", INTR = "Interrupted system call", IO = "Input/output error", NXIO = "No such device or address", ["2BIG"] = "Argument list too long", NOEXEC = "Exec format error", BADF = "Bad file descriptor", CHILD = "No child processes", AGAIN = "Resource temporarily unavailable", NOMEM = "Cannot allocate memory", ACCES = "Permission denied", FAULT = "Bad address", NOTBLK = "Block device required", BUSY = "Device or resource busy", EXIST = "File exists", XDEV = "Invalid cross-device link", NODEV = "No such device", NOTDIR = "Not a directory", ISDIR = "Is a directory", INVAL = "Invalid argument", NFILE = "Too many open files in system", MFILE = "Too many open files", NOTTY = "Inappropriate ioctl for device", TXTBSY = "Text file busy", FBIG = "File too large", NOSPC = "No space left on device", SPIPE = "Illegal seek", ROFS = "Read-only file system", MLINK = "Too many links", PIPE = "Broken pipe", DOM = "Numerical argument out of domain", RANGE = "Numerical result out of range", DEADLK = "Resource deadlock avoided", NAMETOOLONG = "File name too long", NOLCK = "No locks available", NOSYS = "Function not implemented", NOTEMPTY = "Directory not empty", LOOP = "Too many levels of symbolic links", NOMSG = "No message of desired type", IDRM = "Identifier removed", CHRNG = "Channel number out of range", L2NSYNC = "Level 2 not synchronized", L3HLT = "Level 3 halted", L3RST = "Level 3 reset", LNRNG = "Link number out of range", UNATCH = "Protocol driver not attached", NOCSI = "No CSI structure available", L2HLT = "Level 2 halted", BADE = "Invalid exchange", BADR = "Invalid request descriptor", XFULL = "Exchange full", NOANO = "No anode", BADRQC = "Invalid request code", BADSLT = "Invalid slot", BFONT = "Bad font file format", NOSTR = "Device not a stream", NODATA = "No data available", TIME = "Timer expired", NOSR = "Out of streams resources", NONET = "Machine is not on the network", NOPKG = "Package not installed", REMOTE = "Object is remote", NOLINK = "Link has been severed", ADV = "Advertise error", SRMNT = "Srmount error", COMM = "Communication error on send", PROTO = "Protocol error", MULTIHOP = "Multihop attempted", DOTDOT = "RFS specific error", BADMSG = "Bad message", OVERFLOW = "Value too large for defined data type", NOTUNIQ = "Name not unique on network", BADFD = "File descriptor in bad state", REMCHG = "Remote address changed", LIBACC = "Can not access a needed shared library", LIBBAD = "Accessing a corrupted shared library", LIBSCN = ".lib section in a.out corrupted", LIBMAX = "Attempting to link in too many shared libraries", LIBEXEC = "Cannot exec a shared library directly", ILSEQ = "Invalid or incomplete multibyte or wide character", RESTART = "Interrupted system call should be restarted", STRPIPE = "Streams pipe error", USERS = "Too many users", NOTSOCK = "Socket operation on non-socket", DESTADDRREQ = "Destination address required", MSGSIZE = "Message too long", PROTOTYPE = "Protocol wrong type for socket", NOPROTOOPT = "Protocol not available", PROTONOSUPPORT = "Protocol not supported", SOCKTNOSUPPORT = "Socket type not supported", OPNOTSUPP = "Operation not supported", PFNOSUPPORT = "Protocol family not supported", AFNOSUPPORT = "Address family not supported by protocol", ADDRINUSE = "Address already in use", ADDRNOTAVAIL = "Cannot assign requested address", NETDOWN = "Network is down", NETUNREACH = "Network is unreachable", NETRESET = "Network dropped connection on reset", CONNABORTED = "Software caused connection abort", CONNRESET = "Connection reset by peer", NOBUFS = "No buffer space available", ISCONN = "Transport endpoint is already connected", NOTCONN = "Transport endpoint is not connected", SHUTDOWN = "Cannot send after transport endpoint shutdown", TOOMANYREFS = "Too many references: cannot splice", TIMEDOUT = "Connection timed out", CONNREFUSED = "Connection refused", HOSTDOWN = "Host is down", HOSTUNREACH = "No route to host", ALREADY = "Operation already in progress", INPROGRESS = "Operation now in progress", STALE = "Stale NFS file handle", UCLEAN = "Structure needs cleaning", NOTNAM = "Not a XENIX named type file", NAVAIL = "No XENIX semaphores available", ISNAM = "Is a named type file", REMOTEIO = "Remote I/O error", DQUOT = "Disk quota exceeded", NOMEDIUM = "No medium found", MEDIUMTYPE = "Wrong medium type", CANCELED = "Operation canceled", NOKEY = "Required key not available", KEYEXPIRED = "Key has expired", KEYREVOKED = "Key has been revoked", KEYREJECTED = "Key was rejected by service", OWNERDEAD = "Owner died", NOTRECOVERABLE = "State not recoverable", RFKILL = "Operation not possible due to RF-kill", -- only on some platforms DEADLOCK = "File locking deadlock error", INIT = "Reserved EINIT", -- what is correct message? REMDEV = "Remote device", -- what is correct message? HWPOISON = "Reserved EHWPOISON", -- what is correct message? }
apache-2.0
Fenix-XI/Fenix
scripts/zones/QuBia_Arena/mobs/Maat.lua
1
1206
----------------------------------- -- Area: Qu'Bia Arena -- MOB: Maat -- Genkai 5 Fight ----------------------------------- package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil; ----------------------------------- require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) target:showText(mob,YOU_DECIDED_TO_SHOW_UP); printf("Maat Qubia Arena works"); -- When he take damage: target:showText(mob,THAT_LL_HURT_IN_THE_MORNING); -- He use dragon kick or tackle: target:showText(mob,TAKE_THAT_YOU_WHIPPERSNAPPER); -- He use spining attack: target:showText(mob,TEACH_YOU_TO_RESPECT_ELDERS); -- If you dying: target:showText(mob,LOOKS_LIKE_YOU_WERENT_READY); end; function onMobFight(mob,target) if (mob:getHPP() <= 10) then mob:setHP(0); end end; ----------------------------------- -- onMobDeath Action ----------------------------------- function onMobDeath(mob,killer,ally) killer:showText(mob,YOUVE_COME_A_LONG_WAY); end;
gpl-3.0
SkzKatsushiro/OpenRA
mods/d2k/maps/atreides-03a/atreides03a.lua
13
5114
OrdosBase = { OBarracks, OWindTrap1, OWindTrap2, OWindTrap3, OWindTrap4, OLightFactory, OOutpost, OConyard, ORefinery, OSilo1, OSilo2, OSilo3, OSilo4 } OrdosReinforcements = { Easy = { { "light_inf", "raider", "trooper" }, { "light_inf", "raider", "quad" }, { "light_inf", "light_inf", "trooper", "raider", "raider", "quad" } }, Normal = { { "light_inf", "raider", "trooper" }, { "light_inf", "raider", "raider" }, { "light_inf", "light_inf", "trooper", "raider", "raider", "quad" }, { "light_inf", "light_inf", "trooper", "trooper" }, { "light_inf", "light_inf", "light_inf", "light_inf" }, { "light_inf", "raider", "quad", "quad" } }, Hard = { { "raider", "raider", "quad" }, { "light_inf", "raider", "raider" }, { "trooper", "trooper", "light_inf", "raider" }, { "light_inf", "light_inf", "light_inf", "raider", "raider" }, { "light_inf", "light_inf", "trooper", "trooper" }, { "raider", "raider", "quad", "quad", "quad", "raider" }, { "light_inf", "light_inf", "light_inf", "raider", "raider" }, { "light_inf", "raider", "light_inf", "trooper", "trooper", "quad" }, { "raider", "raider", "quad", "quad", "quad", "raider" } } } OrdosAttackDelay = { Easy = DateTime.Minutes(5), Normal = DateTime.Minutes(2) + DateTime.Seconds(40), Hard = DateTime.Minutes(1) + DateTime.Seconds(20) } OrdosAttackWaves = { Easy = 3, Normal = 6, Hard = 9 } ToHarvest = { Easy = 5000, Normal = 6000, Hard = 7000 } InitialOrdosReinforcements = { "light_inf", "light_inf", "quad", "quad", "raider", "raider", "trooper", "trooper" } OrdosPaths = { { OrdosEntry1.Location, OrdosRally1.Location }, { OrdosEntry2.Location, OrdosRally2.Location } } AtreidesReinforcements = { "quad", "quad", "trike", "trike" } AtreidesPath = { AtreidesEntry.Location, AtreidesRally.Location } AtreidesBaseBuildings = { "barracks", "light_factory" } AtreidesUpgrades = { "upgrade.barracks", "upgrade.light" } wave = 0 SendOrdos = function() Trigger.AfterDelay(OrdosAttackDelay[Map.Difficulty], function() if player.IsObjectiveCompleted(KillOrdos) then return end wave = wave + 1 if wave > OrdosAttackWaves[Map.Difficulty] then return end local units = Reinforcements.ReinforceWithTransport(ordos, "carryall.reinforce", OrdosReinforcements[Map.Difficulty][wave], OrdosPaths[1], { OrdosPaths[1][1] })[2] Utils.Do(units, IdleHunt) SendOrdos() end) end MessageCheck = function(index) return #player.GetActorsByType(AtreidesBaseBuildings[index]) > 0 and not player.HasPrerequisites({ AtreidesUpgrades[index] }) end Tick = function() if player.HasNoRequiredUnits() then ordos.MarkCompletedObjective(KillAtreides) end if ordos.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillOrdos) then Media.DisplayMessage("The Ordos have been annihilated!", "Mentat") player.MarkCompletedObjective(KillOrdos) end if DateTime.GameTime % DateTime.Seconds(30) and HarvesterKilled then local units = ordos.GetActorsByType("harvester") if #units > 0 then HarvesterKilled = false ProtectHarvester(units[1]) end end if player.Resources > ToHarvest[Map.Difficulty] - 1 then player.MarkCompletedObjective(GatherSpice) end if DateTime.GameTime % DateTime.Seconds(32) == 0 and (MessageCheck(1) or MessageCheck(2)) then Media.DisplayMessage("Upgrade barracks and light factory to produce more advanced units.", "Mentat") end UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.Difficulty], player.Color) end WorldLoaded = function() ordos = Player.GetPlayer("Ordos") player = Player.GetPlayer("Atreides") InitObjectives() Camera.Position = AConyard.CenterPosition Trigger.OnAllKilled(OrdosBase, function() Utils.Do(ordos.GetGroundAttackers(), IdleHunt) end) SendOrdos() ActivateAI() Trigger.AfterDelay(DateTime.Minutes(2) + DateTime.Seconds(30), function() Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", AtreidesReinforcements, AtreidesPath, { AtreidesPath[1] }) end) end InitObjectives = function() Trigger.OnObjectiveAdded(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) KillAtreides = ordos.AddPrimaryObjective("Kill all Atreides units.") GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.Difficulty]) .. " Solaris worth of Spice.") KillOrdos = player.AddSecondaryObjective("Eliminate all Ordos units and reinforcements\nin the area.") Trigger.OnObjectiveCompleted(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(player, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Lose") end) end) Trigger.OnPlayerWon(player, function() Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(player, "Win") end) end) end
gpl-3.0
MartinFrancu/BETS
BtCreator/role_manager.lua
1
12812
--[[READ ME: Role manager is used in BtCreator for displaying window for attaching categories to roles and possibly definition of new categories. System is that function showing window is called with a parameter of return function which is then called once user did his thing. Function of particular importance: roleManager.showRolesManagement or showRoleManagementWindow Entry point. doneRoleManagerWindow Leaving point, callas the returnFunction. roleManager.showCategoryDefinitionWindow This function will hide roles window and sets up new category definition window. roleManager.createNewCategoryCallback Called when user specified new category and gived it new name. --]] local sanitizer = Utils.Sanitizer.forCurrentWidget() local Chili = Utils.Chili local Logger = Utils.Debug.Logger local dump = Utils.Debug.dump local roleManager = {} local IMAGE_PATH = LUAUI_DIRNAME.."Widgets/BtUtils/" local BACKGROUND_IMAGE_NAME = "black.png" local CHECKED_COLOR = { 1,0.69999999,0.1,0.80000001} local NORMAL_COLOR = {1,1,1,1} local showRoleManagementWindow local categoryCheckBoxes local unitCheckBoxes local returnFunction local xOffBasic = 10 local yOffBasic = 10 local xCheckBoxOffSet = 180 local xLocOffsetMod = 250 local function trimStringToScreenSpace(str, font, limit) if(font:GetTextWidth(str) < limit) then -- it is ok as it is return str end local dots = "..." local trimmed = str local length repeat -- make it littlebit shorter trimmed = string.sub(trimmed, 1, -2) length = font:GetTextWidth(trimmed .. dots) until length < limit return trimmed .. dots end local function changeColor(checkBox) if(checkBox.checked)then -- it is called before the changed (checked -> unchecked) checkBox.font.color = NORMAL_COLOR else checkBox.font.color = CHECKED_COLOR end checkBox:Invalidate() end function roleManager.showCategoryDefinitionWindow() roleManager.rolesWindow:Hide() roleManager.categoryDefinitionWindow = Chili.Window:New{ parent = roleManager.rolesWindow.parent, x = 150, y = 300, width = 1250, height = 600, skinName = 'DarkGlass' } roleManager.categoryDefinitionWindow.backgroundColor = {1,1,1,1} roleManager.categoryDefinitionWindow.TileImage = IMAGE_PATH .. BACKGROUND_IMAGE_NAME roleManager.categoryDefinitionWindow:Invalidate() local categoryDoneButton = Chili.Button:New{ parent = roleManager.categoryDefinitionWindow, x = 0, y = 0, caption = "SAVE AS", OnClick = {sanitizer:AsHandler(roleManager.doneCategoryDefinition)}, } --categoryDoneButton.categoryNameEditBox = nameEditBox categoryDoneButton.window = roleManager.categoryDefinitionWindow returnFunction = showRoleManagementWindow -- plus checkboxes added later in categoryDoneButton local categoryCancelButton = Chili.Button:New{ parent = roleManager.categoryDefinitionWindow, x = categoryDoneButton.x + categoryDoneButton.width, y = 0, caption = "CANCEL", OnClick = {sanitizer:AsHandler(roleManager.cancelCategoryDefinition)}, } categoryCancelButton.window = roleManager.categoryDefinitionWindow categoryCancelButton.returnFunction = showRoleManagementWindow local categoryScrollPanel = Chili.ScrollPanel:New{ parent = roleManager.categoryDefinitionWindow, x = 0, y = 30, width = '100%', height = '100%', skinName='DarkGlass' } xOffSet = 5 yOffSet = 0 local unitsD = {} for _,unitDef in pairs(UnitDefs) do unitsD[#unitsD+1] = unitDef end local nameOrder = function (a,b) return a.name < b.name end table.sort(unitsD, nameOrder) local xLocalOffSet = 0 local columnHeight = #unitsD / 5 local currentHeight = 0 unitCheckBoxes = {} for i,unitDef in ipairs(unitsD) do local unitEntry = unitDef.name .. "(" .. unitDef.humanName .. ")" local typeCheckBox = Chili.Checkbox:New{ parent = categoryScrollPanel, x = xOffSet + (xLocalOffSet * 250), y = yOffSet + currentHeight * 20, caption = "PLACEHOLDER", checked = false, width = 200, OnChange = {changeColor}, } typeCheckBox.font.color = NORMAL_COLOR local font = typeCheckBox.font local trimmedName = trimStringToScreenSpace(unitEntry, font , typeCheckBox.width - 20) typeCheckBox.caption = trimmedName typeCheckBox:Invalidate() typeCheckBox.unitName = unitDef.name typeCheckBox.unitHumanName = unitDef.humanName currentHeight = currentHeight +1 if(currentHeight > columnHeight) then xLocalOffSet = xLocalOffSet + 1 currentHeight = 0 end unitCheckBoxes[i] = typeCheckBox end -- add small placeholder at end: local placeholder = Chili.Label:New{ parent = categoryScrollPanel, x = xOffSet, y = yOffSet + (columnHeight * 20)+80, caption = "=== end ===", skinName='DarkGlass', } -- check old checked checkboxes: categoryDoneButton.Checkboxes = typesCheckboxes end function roleManager.createNewCategoryCallback(projectName, categoryName) local pM = Utils.ProjectManager if(projectName and categoryName)then -- user selected a project and category name, lets save it if(not pM.isProject(projectName))then -- if new project I should create it pM.createProject(projectName) end local qualifiedName = projectName .. "." .. categoryName --create project if necessary -- add new category to unitCategories local unitTypes = {} for _,unitTypeCheckBox in pairs(unitCheckBoxes) do if(unitTypeCheckBox.checked == true) then local typeRecord = {name = unitTypeCheckBox.unitName} table.insert(unitTypes, typeRecord) end end -- add check for category name? local newCategory = { project = projectName, name = categoryName, types = unitTypes, } Utils.UnitCategories.saveCategory(newCategory) roleManager.categoryDefinitionWindow:Dispose() -- return after returnFunction() else -- user hit cancel, lets return to category definition roleManager.categoryDefinitionWindow:Show() end end function roleManager.doneCategoryDefinition(self) local ProjectDialog = Utils.ProjectDialog local ProjectManager = Utils.ProjectManager -- show save dialog: roleManager.categoryDefinitionWindow:Hide() local contentType = ProjectManager.makeRegularContentType("UnitCategories", "json") ProjectDialog.showDialog({ visibilityHandler = BtCreator.setDisableChildrenHitTest, contentType = contentType, dialogType = ProjectDialog.NEW_DIALOG, title = "Save category as:", }, roleManager.createNewCategoryCallback) end function roleManager.cancelCategoryDefinition(self) self.window:Hide() self.window:Dispose() self.returnFunction() end function doneRoleManagerWindow(self) self.window:Hide() local result = {} for _,roleRecord in pairs(self.rolesData) do local roleName = roleRecord.nameEditBox.text local checkedCategories = {} for _, categoryCB in pairs(roleRecord.CheckBoxes) do if(categoryCB.checked) then local catName = categoryCB.caption table.insert(checkedCategories, catName) end end local roleResult = {name = roleName, categories = checkedCategories} table.insert(result, roleResult) end -- call return function self.returnFunction(callbackObject, result) end local function maxRoleSplit(tree) local roleCount = 1 local function visit(node) if(not node) then return end if(node.nodeType == "roleSplit" and roleCount < #node.children)then roleCount = #node.children end for _, child in ipairs(node.children) do visit(child) end end visit(tree.root) return roleCount end local parent, tree, rolesOfCurrentTree, returnFunction, callbackObject -- set up checkboxes and name edit box for role, index and roles is used to prefill if applicable.. local function setUpRoleChiliComponents(parent, xOff, yOff, index, roles) local xOffSet = xOff local yOffSet = yOff local nameEditBox = Chili.EditBox:New{ parent = parent, x = xOffSet, y = yOffSet, text = "Role ".. index, width = 150 } local checkedCategories = {} if(roles[index]) then nameEditBox:SetText(roles[index].name) for _,catName in pairs(roles[index].categories) do checkedCategories[catName] = true end end local categoryNames = Utils.UnitCategories.getAllCategoryNames() categoryCheckBoxes = {} local xLocalOffSet = 0 for _,categoryName in pairs(categoryNames) do local categoryCheckBox = Chili.Checkbox:New{ parent = parent, x = xOffSet + xCheckBoxOffSet + (xLocalOffSet * xLocOffsetMod), y = yOffSet, caption = categoryName, checked = false, width = 200, OnChange = {changeColor}, } if(checkedCategories[categoryName] ~= nil) then categoryCheckBox:Toggle() end xLocalOffSet = xLocalOffSet + 1 if(xLocalOffSet == 4) then xLocalOffSet = 0 yOffSet = yOffSet + 20 end table.insert(categoryCheckBoxes, categoryCheckBox) end yOffSet = yOffSet + 50 local roleCategories = {} roleCategories["nameEditBox"] = nameEditBox roleCategories["CheckBoxes"] = categoryCheckBoxes roleCategories["yEnd"] = yOffSet return roleCategories end -- this should try to add new role record local function listenerPlusButton(self) local rolesData = self.doneButton.rolesData local newUI = setUpRoleChiliComponents(rolesScrollPanel, xOffBasic , rolesData[#rolesData].yEnd, #rolesData+1, rolesOfCurrentTree) rolesData[#rolesData+1] = newUI end local function listenerMinusButton(self) local rolesData = self.doneButton.rolesData if #rolesData < 2 then return -- at least one role should be there else local data = rolesData[#rolesData] --Logger.log("roles", dump(data) ) local parent = data["nameEditBox"].parent data["nameEditBox"]:Dispose() for _,checkBox in ipairs(data["CheckBoxes"]) do checkBox:Dispose() end parent:Invalidate() rolesData[#rolesData]= nil end end showRoleManagementWindow = function() -- remove old children: if( roleManager.rolesWindow) then parent:RemoveChild(roleManager.rolesWindow) end roleManager.rolesWindow = Chili.Window:New{ parent = parent, x = 150, y = 300, width = 1200, height = 600, skinName = 'DarkGlass' } roleManager.rolesWindow.backgroundColor = {1,1,1,1} roleManager.rolesWindow.TileImage = IMAGE_PATH .. BACKGROUND_IMAGE_NAME roleManager.rolesWindow:Invalidate() local window = roleManager.rolesWindow -- now I just need to save it roleManagementDoneButton = Chili.Button:New{ parent = window, x = 0, y = 0, caption = "DONE", OnClick = {sanitizer:AsHandler(doneRoleManagerWindow)}, returnFunction = returnFunction, callbackObject = callbackObject, } roleManagementDoneButton.window = roleManager.rolesWindow local plusButton = Chili.Button:New{ parent = window, x = roleManagementDoneButton.x + roleManagementDoneButton.width, y = roleManagementDoneButton.y, caption = "+", width = 40, OnClick = {sanitizer:AsHandler(listenerPlusButton)}, --sanitizer:AsHandler(roleManager.doneCategoryDefinition)}, doneButton = roleManagementDoneButton, } local minusButton = Chili.Button:New{ parent = window, x = plusButton.x + plusButton.width, y = plusButton.y, caption = "-", width = 40, OnClick = {sanitizer:AsHandler(listenerMinusButton)},--sanitizer:AsHandler(roleManager.doneCategoryDefinition)}, doneButton = roleManagementDoneButton, } local categoryDoneButton = Chili.Button:New{ parent = roleManager.categoryDefinitionWindow, x = 0, y = 0, caption = "SAVE AS", OnClick = {sanitizer:AsHandler(roleManager.doneCategoryDefinition)}, } newCategoryButton = Chili.Button:New{ parent = window, x = minusButton.x + minusButton.width, y = 0, width = 150, caption = "Define new Category", OnClick = {sanitizer:AsHandler(roleManager.showCategoryDefinitionWindow)}, } rolesScrollPanel = Chili.ScrollPanel:New{ parent = window, x = 0, y = 30, width = '100%', height = '100%', skinName='DarkGlass' } local rolesCategoriesCB = {} local xOffSet = xOffBasic local yOffSet = yOffBasic -- set up checkboxes for all roles and categories local roleCount = maxRoleSplit(tree) if(roleCount < #rolesOfCurrentTree) then roleCount = #rolesOfCurrentTree end for roleIndex=1, roleCount do local newRoleUI newRoleUI = setUpRoleChiliComponents( rolesScrollPanel, xOffSet, yOffSet, roleIndex, rolesOfCurrentTree) yOffSet = newRoleUI.yEnd table.insert(rolesCategoriesCB, newRoleUI) end roleManagementDoneButton.rolesData = rolesCategoriesCB end -- This shows the role manager window, returnFunction is used to export specified roles data after user clicked "done". (returnFunction(rolesData)) function roleManager.showRolesManagement(parentIn, treeIn, rolesOfCurrentTreeIn, callbackObjectIn, callbackFunction) parent, tree, rolesOfCurrentTree, callbackObject, returnFunction = parentIn, treeIn, rolesOfCurrentTreeIn, callbackObjectIn, callbackFunction showRoleManagementWindow() end return roleManager
mit
Fenix-XI/Fenix
scripts/commands/addmission.lua
1
1143
--------------------------------------------------------------------------------------------------- -- func: @addmission <logID> <missionID> <player> -- desc: Adds a mission to the GM or target players log. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 3, parameters = "iis" }; function onTrigger(player, logId, missionId, target) if (missionId == nil or logId == nil) then player:PrintToPlayer( "You must enter a valid log id and mission id!" ); player:PrintToPlayer( "@addmission <logID> <missionID> <player>" ); return; end if (target == nil) then target = player:getName(); end local targ = GetPlayerByName( target ); if (targ ~= nil) then targ:addMission( logId, missionId ); player:PrintToPlayer( string.format( "Added Mission for log %u with ID %u to %s", logId, missionId, target ) ); else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@addmission <logID> <missionID> <player>" ); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/items/piece_of_cascade_candy.lua
18
1175
----------------------------------------- -- ID: 5942 -- Item: Piece of Cascade Candy -- Food Effect: 30Min, All Races ----------------------------------------- -- Mind +4 -- Charisma +4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5942); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MND, 4); target:addMod(MOD_CHR, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MND, 4); target:delMod(MOD_CHR, 4); end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/PsoXja/npcs/_09c.lua
13
2831
----------------------------------- -- Area: Pso'Xja -- NPC: _09c (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos 290.000 -1.925 -18.400 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if ((trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1 and player:getMainJob() == 6) then local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z <= -19) then if (GetMobAction(16814093) == 0) then local Rand = math.random(1,2); -- estimated 50% success as per the wiki if (Rand == 1) then -- Spawn Gargoyle player:messageSpecial(DISCOVER_DISARM_FAIL + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814093,120):updateClaim(player); -- Gargoyle else player:messageSpecial(DISCOVER_DISARM_SUCCESS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end player:tradeComplete(); else player:messageSpecial(DOOR_LOCKED); end end end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local Z=player:getZPos(); if (npc:getAnimation() == 9) then if (Z <= -19) then if (GetMobAction(16814093) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED + 0x8000, 0, 0, 0, 0, true); SpawnMob(16814093,120):updateClaim(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS + 0x8000, 0, 0, 0, 0, true); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif (Z >= -18) then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/broiled_carp.lua
11
1070
----------------------------------------- -- ID: 4586 -- Item: Broiled Carp -- Food Effect: 60Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -1 -- Ranged ATT % 14 (cap 45) ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,4586) end function onEffectGain(target,effect) target:addMod(dsp.mod.DEX, 2) target:addMod(dsp.mod.MND, -1) target:addMod(dsp.mod.FOOD_RATTP, 14) target:addMod(dsp.mod.FOOD_RATT_CAP, 45) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 2) target:delMod(dsp.mod.MND, -1) target:delMod(dsp.mod.FOOD_RATTP, 14) target:delMod(dsp.mod.FOOD_RATT_CAP, 45) end
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/death_scythe.lua
12
1066
----------------------------------------- -- ID: 16777 -- Item: Death Scythe -- Additional Effect: Drains HP ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10 if (math.random(0,99) >= chance) then return 0,0,0 else local power = 10 local params = {} params.bonusmab = 0 params.includemab = false power = addBonusesAbility(player, dsp.magic.ele.DARK, target, power, params) power = power * applyResistanceAddEffect(player,target,dsp.magic.ele.DARK,0) power = adjustForTarget(target,power,dsp.magic.ele.DARK) power = finalMagicNonSpellAdjustments(player,target,dsp.magic.ele.DARK,power ) if (power < 0) then power = 0 else player:addHP(power) end return dsp.subEffect.HP_DRAIN, dsp.msg.basic.ADD_EFFECT_HP_DRAIN, power end end
gpl-3.0
Giorox/AngelionOT-Repo
data/npc/scripts/Jack Fate Goroma.lua
3
1799
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) -- OTServ event handling functions start function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- OTServ event handling functions end -- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions! local travelNode = keywordHandler:addKeyword({'liberty bay'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to travel back to Liberty Bay?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, premium = true, level = 0, cost = 0, destination = {x=32285, y=32892, z=6} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'We would like to serve you some time.'}) keywordHandler:addKeyword({'sail'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Just ask me for a passage to Liberty Bay once you want to leave Goroma.'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I\'m the captain of this - well, wreck. Argh.'}) keywordHandler:addKeyword({'captain'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I\'m the captain of this - well, wreck. Argh'}) npcHandler:addModule(FocusModule:new())
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Orias.lua
5
1296
----------------------------------- -- Area: Dynamis Xarcabard -- MOB: Marquis Orias ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger"); if (mob:isInBattlefieldList() == false) then mob:addInBattlefieldList(); Animate_Trigger = Animate_Trigger + 16; SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger); if (Animate_Trigger == 32767) then SpawnMob(17330911); -- 142 SpawnMob(17330912); -- 143 SpawnMob(17330183); -- 177 SpawnMob(17330184); -- 178 activateAnimatedWeapon(); -- Change subanim of all animated weapon end end if (Animate_Trigger == 32767) then ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE); end end;
gpl-3.0
SamuelePilleri/sysdig
userspace/sysdig/chisels/v_kubernetes_controllers.lua
6
3094
--[[ Copyright (C) 2013-2014 Draios inc. This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. --]] view_info = { id = "kubernetes_controllers", name = "K8s Controllers", description = "List all Kubernetes controllers running on this machine, and the resources that each of them uses.", tips = {"Select a controller and click enter to drill down into it. At that point, you will be able to access several views that will show you the details of the selected controller."}, view_type = "table", applies_to = {"", "evt.res", "k8s.pod.id", "k8s.svc.id", "k8s.ns.id"}, filter = "k8s.rc.id != ''", use_defaults = true, drilldown_target = "kubernetes_pods", columns = { { name = "NA", field = "thread.tid", is_key = true }, { name = "CPU", field = "thread.cpu", description = "Amount of CPU used by the controller.", colsize = 8, aggregation = "AVG", groupby_aggregation = "SUM", is_sorting = true }, { name = "VIRT", field = "thread.vmsize.b", description = "Total virtual memory for the controller.", aggregation = "MAX", groupby_aggregation = "SUM", colsize = 9 }, { name = "RES", field = "thread.vmrss.b", description = "Resident non-swapped memory for the controller.", aggregation = "MAX", groupby_aggregation = "SUM", colsize = 9 }, { name = "FILE", field = "evt.buflen.file", description = "Total (input+output) file I/O bandwidth generated by the controller, in bytes per second.", colsize = 8, aggregation = "TIME_AVG", groupby_aggregation = "SUM" }, { name = "NET", field = "evt.buflen.net", description = "Total (input+output) network bandwidth generated by the controller, in bytes per second.", colsize = 8, aggregation = "TIME_AVG", groupby_aggregation = "SUM" }, { name = "NA", field = "k8s.rc.id", is_groupby_key = true }, { name = "ID", field = "k8s.rc.id", description = "Controller id.", colsize = 38 }, { name = "NAME", field = "k8s.rc.name", description = "Controller name.", colsize = 25 }, { name = "NAMESPACE", field = "k8s.ns.name", description = "Controller namespace.", colsize = 20 }, { name = "LABELS", field = "k8s.rc.labels", description = "Controller labels.", colsize = 0 }, }, actions = { { hotkey = "d", command = "kubectl --namespace=%k8s.ns.name describe rc %k8s.rc.name", description = "describe" }, { hotkey = "x", command = "kubectl --namespace=%k8s.ns.name delete rc %k8s.rc.name", description = "delete" } } }
gpl-2.0
MartinFrancu/BETS
chili_clone/controls/trackbar_clone.lua
3
4217
--//============================================================================= --- Trackbar module --- Trackbar fields. -- Inherits from Control. -- @see control.Control -- @table Trackbar -- @int[opt=0] min minimum value of the Trackbar -- @int[opt=100] max maximum value of the Trackbar -- @int[opt=50] value value of the Trackbar -- @int[opt=50] step step value -- @tparam {func1,fun2,...} OnChange function listeners for value change (default {}) Trackbar = Control:Inherit{ classname = "trackbar", value = 50, min = 0, max = 100, step = 1, useValueTooltip = nil, defaultWidth = 90, defaultHeight = 20, hitpadding = {0, 0, 0, 0}, OnChange = {}, } local this = Trackbar local inherited = this.inherited --//============================================================================= local function FormatNum(num) if (num == 0) then return "0" else local strFormat = string.format local absNum = math.abs(num) if (absNum < 0.01) then return strFormat("%.3f", num) elseif (absNum < 1) then return strFormat("%.2f", num) elseif (absNum < 10) then return strFormat("%.1f", num) else return strFormat("%.0f", num) end end end function Trackbar:New(obj) obj = inherited.New(self,obj) if ((not obj.tooltip) or (obj.tooltip == '')) and (obj.useValueTooltip ~= false) then obj.useValueTooltip = true end obj:SetMinMax(obj.min,obj.max) obj:SetValue(obj.value) return obj end --//============================================================================= function Trackbar:_Clamp(v) if (self.min<self.max) then if (v<self.min) then v = self.min elseif (v>self.max) then v = self.max end else if (v>self.min) then v = self.min elseif (v<self.max) then v = self.max end end return v end --//============================================================================= function Trackbar:_GetPercent(x,y) if (x) then local pl,pt,pr,pb = unpack4(self.hitpadding) if (x<pl) then return 0 end if (x>self.width-pr) then return 1 end local cx = x - pl local barWidth = self.width - (pl + pr) return (cx/barWidth) else return (self.value-self.min)/(self.max-self.min) end end --//============================================================================= --- Sets the minimum and maximum value of the track bar -- @int[opt=0] min minimum value -- @int[opt=1] max maximum value (why is 1 the default?) function Trackbar:SetMinMax(min,max) self.min = tonumber(min) or 0 self.max = tonumber(max) or 1 self:SetValue(self.value) end --- Sets the value of the track bar -- @int v value of the track abr function Trackbar:SetValue(v) if type(v) ~= "number" then Spring.Log("Chili", "error", "Wrong param to Trackbar:SetValue(number v)") return end local r = v % self.step if (r > 0.5*self.step) then v = v + self.step - r else v = v - r end v = self:_Clamp(v) local oldvalue = self.value self.value = v if self.useValueTooltip then self.tooltip = "Current: "..FormatNum(self.value) end self:CallListeners(self.OnChange,v,oldvalue) self:Invalidate() end --//============================================================================= function Trackbar:DrawControl() end --//============================================================================= function Trackbar:HitTest() return self end function Trackbar:MouseDown(x,y,button) if (button==1) then inherited.MouseDown(self,x,y) local percent = self:_GetPercent(x,y) self:SetValue(self.min + percent*(self.max-self.min)) end return self end function Trackbar:MouseMove(x,y,dx,dy,button) if (button==1) then inherited.MouseMove(self,x,y,dx,dy,button) local percent = self:_GetPercent(x,y) self:SetValue(self.min + percent*(self.max-self.min)) end return self end --//=============================================================================
mit
MT-Axinite/staff_tools
tools.lua
1
3438
-- tools.lua: Tool definitions -- Copyright (c) 2015 Calinou -- CC0 1.0 Universal minetest.register_tool("staff_tools:tool", { description = "Staff tool", inventory_image = "staff_tool.png", range = 15, tool_capabilities = { full_punch_interval = 0.0, max_drop_level = 3, groupcaps = { cracky = {times = {[1] = 0.0, [2] = 0.0, [3] = 0.0}, uses = 0, maxlevel = 3}, crumbly = {times = {[1] = 0.0, [2] = 0.0, [3] = 0.0}, uses = 0, maxlevel = 3}, choppy= {times = {[1] = 0.0, [2] = 0.0, [3] = 0.0}, uses = 0, maxlevel = 3}, }, damage_groups = {fleshy = 1}, }, }) screwdriver = {} local function nextrange(x, max) x = x + 1 if x > max then x = 0 end return x end screwdriver.ROTATE_FACE = 1 screwdriver.ROTATE_AXIS = 2 screwdriver.disallow = function(pos, node, user, mode, new_param2) return false end screwdriver.rotate_simple = function(pos, node, user, mode, new_param2) if mode ~= screwdriver.ROTATE_FACE then return false end end -- Handles rotation screwdriver.handler = function(itemstack, user, pointed_thing, mode, uses) if pointed_thing.type ~= "node" then return end local pos = pointed_thing.under if minetest.is_protected(pos, user:get_player_name()) then minetest.record_protection_violation(pos, user:get_player_name()) return end local node = minetest.get_node(pos) local ndef = minetest.registered_nodes[node.name] -- verify node is facedir (expected to be rotatable) if not ndef or ndef.paramtype2 ~= "facedir" then return end -- Compute param2 local rotationPart = node.param2 % 32 -- get first 4 bits local preservePart = node.param2 - rotationPart local axisdir = math.floor(rotationPart / 4) local rotation = rotationPart - axisdir * 4 if mode == screwdriver.ROTATE_FACE then rotationPart = axisdir * 4 + nextrange(rotation, 3) elseif mode == screwdriver.ROTATE_AXIS then rotationPart = nextrange(axisdir, 5) * 4 end local new_param2 = preservePart + rotationPart local should_rotate = true if ndef and ndef.on_rotate then -- Node provides a handler, so let the handler decide instead if the node can be rotated -- Copy pos and node because callback can modify it local result = ndef.on_rotate(vector.new(pos), {name = node.name, param1 = node.param1, param2 = node.param2}, user, mode, new_param2) if result == false then -- Disallow rotation return elseif result == true then should_rotate = false end else if not ndef or not ndef.paramtype2 == "facedir" or (ndef.drawtype == "nodebox" and not ndef.node_box.type == "fixed") or node.param2 == nil then return end if ndef.can_dig and not ndef.can_dig(pos, user) then return end end if should_rotate then node.param2 = new_param2 minetest.swap_node(pos, node) end if not minetest.setting_getbool("creative_mode") then itemstack:add_wear(65535 / ((uses or 200) - 1)) end return itemstack end -- Screwdriver minetest.register_tool("staff_tools:screwdriver", { description = "Staff Screwdriver (left-click rotates face, right-click rotates axis)", inventory_image = "staff_screwdriver.png", range = 15, on_use = function(itemstack, user, pointed_thing) screwdriver.handler(itemstack, user, pointed_thing, screwdriver.ROTATE_FACE, 0) return itemstack end, on_place = function(itemstack, user, pointed_thing) screwdriver.handler(itemstack, user, pointed_thing, screwdriver.ROTATE_AXIS, 0) return itemstack end, })
cc0-1.0
Fenix-XI/Fenix
scripts/globals/spells/cure_vi.lua
26
3921
----------------------------------------- -- Spell: Cure VI -- Restores target's HP. -- 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"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; 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 = 600; power = getCurePower(caster); if (power < 210) then divisor = 1.5; constant = 600; basepower = 90; elseif (power < 300) then divisor = 0.9; constant = 680; basepower = 210; elseif (power < 400) then divisor = 10/7; constant = 780; basepower = 300; elseif (power < 500) then divisor = 2.5; constant = 850; basepower = 400; elseif (power < 700) then divisor = 5/3; constant = 890; basepower = 500; else divisor = 999999; constant = 1010; basepower = 0; end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then basecure = getBaseCure(power,divisor,constant,basepower); final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; 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); else if (target:isUndead()) then spell:setMsg(2); local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/Upper_Jeuno/npcs/Mailloquetat.lua
13
1398
----------------------------------- -- Area: Upper Jeuno -- NPC: Mailloquetat -- Involved in Quests: Save my Sister -- @zone 244 -- @pos -31 -1 8 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getFameLevel(JEUNO) >= 4 and player:getVar("saveMySisterVar") == 1) then player:startEvent(0x009f); -- For "Save my Sister" quest else player:startEvent(0x0019); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x009f) then player:setVar("saveMySisterVar", 2); end end;
gpl-3.0
LazyShpee/discord-egobot
libs/png_encode.lua
1
9735
--- A PNG encoder. -- -- Permission is hereby granted, free of charge, to any person obtaining -- a copy of this software and associated documentation files (the -- "Software"), to deal in the Software without restriction, including -- without limitation the rights to use, copy, modify, merge, publish, -- distribute, sublicense, and/or sell copies of the Software, and to -- permit persons to whom the Software is furnished to do so, subject to -- the following conditions: -- -- The above copyright notice and this permission notice shall be -- included in all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -- EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -- MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -- IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY -- CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, -- TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE -- SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- -- [ MIT license: http://www.opensource.org/licenses/mit-license.php ] -- -- Standard library imports -- local byte = string.byte local ceil = math.ceil local char = string.char local concat = table.concat local floor = math.floor local gmatch = string.gmatch local ipairs = ipairs local min = math.min local open = io.open local unpack = unpack -- Modules -- local operators = require("./libs/operators") -- Imports -- local band = operators.band local bnot = operators.bnot local bxor = operators.bxor local rshift = operators.rshift -- Cached module references -- local _ToString_Interleaved_ local _ToString_RGBA_ -- Exports -- local M = {} --[[ From http://www.chrfr.de/software/midp_png.html: /* * Minimal PNG encoder to create PNG streams (and MIDP images) from RGBA arrays. * * Copyright 2006-2009 Christian Fröschlin * * www.chrfr.de * * * Changelog: * * 09/22/08: Fixed Adler checksum calculation and byte order * for storing length of zlib deflate block. Thanks * to Miloslav Ruzicka for noting this. * * 05/12/09: Split PNG and ZLIB functionality into separate classes. * Added support for images > 64K by splitting the data into * multiple uncompressed deflate blocks. * * Terms of Use: * * You may use the PNG encoder free of charge for any purpose you desire, as long * as you do not claim credit for the original sources and agree not to hold me * responsible for any damage arising out of its use. * * If you have a suitable location in GUI or documentation for giving credit, * I'd appreciate a mention of * * PNG encoder (C) 2006-2009 by Christian Fröschlin, www.chrfr.de * * but that's not mandatory. * */ --]] -- Common save-to-file logic local function SaveStr (name, str) local file = open(name, "wb") if file then file:write(str) file:close() end return file ~= nil end --- Saves color data as a PNG. -- @string name Name of file to save. -- @array colors Color values, stored as { _red1_, _green1_, _blue1_, _alpha1_, _red2_, ... } -- @uint w Width of saved image. The height is computed automatically from this and #_colors_. -- @ptable[opt] opts Save options. Fields: -- -- * **from_01**: If true, color values are interpreted as being &isin; [0, 1], instead of -- [0, 255] (the default). -- * **yfunc**: Yield function, called periodically during the save (no arguments), e.g. to -- yield within a coroutine. If absent, a no-op. -- @treturn boolean Was the file written? function M.Save_Interleaved (name, colors, w, opts) return SaveStr(name, _ToString_Interleaved_(colors, w, opts)) end --- Variant of @{Save_Interleaved}, with colors as separate channels. -- @string name Name of file to save. -- @array r Array of red values... -- @array g ...green values... -- @array b ...blue values... -- @array a ...and alpha values. -- @uint w Width of saved image. The height is computed automatically from this and the -- minimum of #_r_, #_g_, #_b_, #_a_ (typically, these will all be the same). -- @ptable[opt] opts As per @{Save_Interleaved}. -- @treturn boolean Was the file written? function M.Save_RGBA (name, r, g, b, a, w, opts) return SaveStr(name, _ToString_RGBA_(r, g, b, a, w, opts)) end -- Computes the Adler checksum local function Adler (data) local s1, s2 = 1, 0 for _, b in ipairs(data) do local abs = b >= 0 and b or b + 256 s1 = (s1 + abs) % 65521 s2 = (s2 + s1) % 65521 end return s2 * 2^16 + s1 end -- Serializes a 32-bit number to bytes local function U32 (num) local low1, low2, low3 = num % 2^8, num % 2^16, num % 2^24 return char((num - low3) / 2^24, (low3 - low2) / 2^16, (low2 - low1) / 2^8, low1) end -- Writes up to 32K of an uncompressed block local function WriteUncompressedBlock (stream, is_last, data, offset, len) local nlen = band(bnot(len), 0xFFFF) local lenFF, nlenFF = band(len, 0xFF), band(nlen, 0xFF) stream[#stream + 1] = char(is_last and 1 or 0) -- Final flag, Compression type 0 stream[#stream + 1] = char(lenFF) -- Length LSB stream[#stream + 1] = char(rshift(len - lenFF, 8)) -- Length MSB stream[#stream + 1] = char(nlenFF) -- Length 1st complement LSB stream[#stream + 1] = char(rshift(nlen - nlenFF, 8)) -- Length 1st complement MSB for i = 1, len, 512 do -- Break up data into unpack-supported sizes stream[#stream + 1] = char(unpack(data, offset + i, offset + min(i + 511, len))) -- Data end end -- Maximum number of uncompressed bytes to write at once -- local BlockSize = 32000 -- Hard-coded first bytes in uncompressed block -- local Bytes = char(8, (31 - (8 * 256) % 31) % 31) -- CM = 8, CMINFO = 0; FCHECK (FDICT / FLEVEL = 0) -- Built-in "zlib" for uncompressed blocks local function UncompressedWrite (data, yfunc) local subs, pos, n = { Bytes }, 0, #data repeat yfunc() local left = n - pos local is_last = left <= BlockSize WriteUncompressedBlock(subs, is_last, data, pos, is_last and left or BlockSize) pos = pos + BlockSize until is_last subs[#subs + 1] = U32(Adler(data)) return concat(subs, "") end -- LUT for CRC -- local CRC -- Generates CRC table local function CreateCRCTable () local t = {} for i = 0, 255 do local c = i for _ = 1, 8 do local bit = band(c, 0x1) c = .5 * (c - bit) if bit ~= 0 then c = bxor(c, 0xEDB88320) end end t[#t + 1] = c end return t end -- Update the CRC with new data local function UpdateCRC (crc, bytes) CRC = CRC or CreateCRCTable() for b in gmatch(bytes, ".") do crc = bxor(CRC[band(bxor(crc, byte(b)), 0xFF) + 1], rshift(crc, 8)) end return crc end -- Serialize data as a PNG chunk local function ToChunk (stream, id, bytes) stream[#stream + 1] = U32(#bytes) stream[#stream + 1] = id stream[#stream + 1] = bytes local crc = 0xFFFFFFFF crc = UpdateCRC(crc, id) crc = UpdateCRC(crc, bytes) stream[#stream + 1] = U32(bnot(crc)) end -- Default yield function: no-op local function DefYieldFunc () end -- Common string serialize behavior after canonicalizing data local function Finish (data, extra, w, h, yfunc, opts) local n = #data -- Do any [0, 1] to [0, 255] conversion. if opts then for i = 1, opts.from_01 and n or 0 do data[i] = min(floor(data[i] * 255), 255) end end -- Pad the last row with 0, if necessary. for _ = 1, extra do data[n], data[n + 1], data[n + 2], data[n + 3], n = 0, 0, 0, 0, n + 4 end -- Process the data, gather it into chunks, and emit the final byte stream. local stream = { "\137\080\078\071\013\010\026\010" } ToChunk(stream, "IHDR", U32(w) .. U32(h) .. char(8, 6, 0, 0, 0)) -- Bit depth, colortype (ARGB), compression, filter, interlace ToChunk(stream, "IDAT", UncompressedWrite(data, yfunc)) ToChunk(stream, "IEND", "") return concat(stream, "") end --- Variant of @{Save_Interleaved} that emits a raw byte stream, instead of saving to file. -- @array colors As per @{Save_Interleaved}. -- @uint w As per @{Save_Interleaved}. -- @ptable[opt] opts As per @{Save_Interleaved}. -- @treturn string Byte stream. function M.ToString_Interleaved (colors, w, opts) local ncolors = floor(#colors / 4) local h, data = ceil(ncolors / w), {} local si, di, extra = 1, 1, w * h - ncolors local yfunc = (opts and opts.yfunc) or DefYieldFunc -- Inject filters and do a standard write. repeat data[di], di = 0, di + 1 -- No filter local count = min(w, ncolors) for _ = 1, count * 4 do data[di], si, di = colors[si], si + 1, di + 1 end ncolors = ncolors - count yfunc() until ncolors == 0 return Finish(data, extra, w, h, yfunc, opts) end --- Variant of @{Save_RGBA} that emits a raw byte stream, instead of saving to file. -- @array r Array of red values... -- @array g ...green values... -- @array b ...blue values... -- @array a ...and alpha values. -- @uint w As per @{Save_RGBA}. -- @ptable[opt] opts As per @{Save_RGBA}. -- @treturn string Byte stream. function M.ToString_RGBA (r, g, b, a, w, opts) local ncolors = min(#r, #g, #b, #a) local h, data = ceil(ncolors / w), {} local si, di, extra = 1, 1, w * h - ncolors local yfunc = (opts and opts.yfunc) or DefYieldFunc -- Interleave color streams, inject filters, and do a standard write. repeat data[di], di = 0, di + 1 -- No filter for _ = 1, min(w, ncolors) do data[di], data[di + 1], data[di + 2], data[di + 3] = r[si], g[si], b[si], a[si] si, di, ncolors = si + 1, di + 4, ncolors - 1 end yfunc() until ncolors == 0 return Finish(data, extra, w, h, yfunc, opts) end -- Cache module members. _ToString_Interleaved_ = M.ToString_Interleaved _ToString_RGBA_ = M.ToString_RGBA -- Export the module. return M
mit
DarkstarProject/darkstar
scripts/zones/Grauberg_[S]/npcs/Indescript_Markings.lua
9
1504
---------------------------------- -- Area: Grauberg [S] -- NPC: Indescript Markings -- Type: Quest ----------------------------------- local ID = require("scripts/zones/Grauberg_[S]/IDs"); require("scripts/globals/keyitems"); require("scripts/globals/npc_util"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local gownQuestProgress = player:getCharVar("AF_SCH_BODY"); player:delStatusEffect(dsp.effect.SNEAK); -- SCH AF Quest - Boots if (gownQuestProgress > 0 and gownQuestProgress < 3 and not player:hasKeyItem(dsp.ki.SAMPLE_OF_GRAUBERG_CHERT)) then npcUtil.giveKeyItem(player, dsp.ki.SAMPLE_OF_GRAUBERG_CHERT); player:setCharVar("AF_SCH_BODY", gownQuestProgress + 1); -- Move the markings around local positions = { [1] = {-517, -167, 209}, [2] = {-492, -168, 190}, [3] = {-464, -166, 241}, [4] = {-442, -156, 182}, [5] = {-433, -151, 162}, [6] = {-416, -143, 146}, [7] = {-535, -167, 227}, [8] = {-513, -170, 255} }; local newPosition = npcUtil.pickNewPosition(npc:getID(), positions); npc:setPos(newPosition.x, newPosition.y, newPosition.z); else player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) end;
gpl-3.0
DarkstarProject/darkstar
scripts/zones/Windurst_Waters/npcs/Chamama.lua
9
6288
----------------------------------- -- Area: Windurst Waters -- NPC: Chamama -- Involved In Quest: Inspector's Gadget -- Starts Quest: In a Pickle ----------------------------------- local ID = require("scripts/zones/Windurst_Waters/IDs"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/titles"); ----------------------------------- function onTrade(player,npc,trade) local FakeMoustache = player:hasKeyItem(dsp.ki.FAKE_MOUSTACHE); local InvisibleManSticker = player:hasKeyItem(dsp.ki.INVISIBLE_MAN_STICKER); local InAPickle = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.IN_A_PICKLE); local count = trade:getItemCount(); local gil = trade:getGil(); if ((InAPickle == QUEST_ACCEPTED or InAPickle == QUEST_COMPLETED) and trade:hasItemQty(583,1) == true and count == 1 and gil == 0) then local rand = math.random(1,4); if (rand <= 2) then if (InAPickle == QUEST_ACCEPTED) then player:startEvent(659); -- IN A PICKLE: Quest Turn In (1st Time) elseif (InAPickle == QUEST_COMPLETED) then player:startEvent(662,200); end elseif (rand == 3) then player:startEvent(657); -- IN A PICKLE: Too Light player:tradeComplete(trade); elseif (rand == 4) then player:startEvent(658); -- IN A PICKLE: Too Small player:tradeComplete(trade); end elseif (FakeMoustache == false) then local InspectorsGadget = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.INSPECTOR_S_GADGET); if (InspectorsGadget == QUEST_ACCEPTED) then local SarutaCotton = trade:hasItemQty(834,4); if (SarutaCotton == true and count == 4) then player:startEvent(552); end end elseif (InvisibleManSticker == false) then local ThePromise = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.THE_PROMISE); if (ThePromise == QUEST_ACCEPTED) then local ShoalWeed = trade:hasItemQty(1148,1); if (ShoalWeed == true and count == 1) then player:startEvent(799,0,0,dsp.ki.INVISIBLE_MAN_STICKER); end end end end; function onTrigger(player,npc) local InspectorsGadget = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.INSPECTOR_S_GADGET); local ThePromise = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.THE_PROMISE); local InAPickle = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.IN_A_PICKLE); local NeedToZone = player:needToZone(); if (ThePromise == QUEST_ACCEPTED) then local InvisibleManSticker = player:hasKeyItem(dsp.ki.INVISIBLE_MAN_STICKER); if (InvisibleManSticker == true) then player:startEvent(800); else local ThePromiseVar = player:getCharVar("ThePromise"); if (ThePromiseVar == 1) then player:startEvent(798,0,1148,dsp.ki.INVISIBLE_MAN_STICKER); else player:startEvent(797,0,1148,dsp.ki.INVISIBLE_MAN_STICKER); end end elseif (InspectorsGadget == QUEST_ACCEPTED) then local FakeMoustache = player:hasKeyItem(dsp.ki.FAKE_MOUSTACHE); -- printf("mustach check"); if (FakeMoustache == true) then player:startEvent(553); else player:startEvent(551,0,dsp.ki.FAKE_MOUSTACHE); end elseif (InAPickle == QUEST_AVAILABLE and NeedToZone == false) then local rand = math.random(1,2); if (rand == 1) then player:startEvent(654,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Begin else player:startEvent(651); -- Standard Conversation end elseif (InAPickle == QUEST_ACCEPTED or player:getCharVar("QuestInAPickle_var") == 1) then player:startEvent(655,0,4444); -- IN A PICKLE + RARAB TAIL: Quest Objective Reminder elseif (InAPickle == QUEST_COMPLETED and NeedToZone) then player:startEvent(660); -- IN A PICKLE: After Quest elseif (InAPickle == QUEST_COMPLETED and NeedToZone == false and player:getCharVar("QuestInAPickle_var") ~= 1) then local rand = math.random(1,2) if (rand == 1) then player:startEvent(661); -- IN A PICKLE: Repeatable Quest Begin else player:startEvent(651); -- Standard Conversation end else player:startEvent(651); -- Standard Conversation end -- player:delQuest(WINDURST,dsp.quest.id.windurst.IN_A_PICKLE); [[[[[[[[[[[[[ FOR TESTING ONLY ]]]]]]]]]]]]] end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) if (csid == 552) then player:tradeComplete(); player:addKeyItem(dsp.ki.FAKE_MOUSTACHE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.FAKE_MOUSTACHE); elseif (csid == 797) then player:setCharVar("ThePromise",1); elseif (csid == 799) then player:tradeComplete(); player:addKeyItem(dsp.ki.INVISIBLE_MAN_STICKER); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.INVISIBLE_MAN_STICKER); elseif (csid == 654 and option == 1) then -- IN A PICKLE + RARAB TAIL: Quest Begin player:addQuest(WINDURST,dsp.quest.id.windurst.IN_A_PICKLE); elseif (csid == 659) then -- IN A PICKLE: Quest Turn In (1st Time) player:tradeComplete(trade); player:completeQuest(WINDURST,dsp.quest.id.windurst.IN_A_PICKLE); player:needToZone(true); player:addItem(12505); player:messageSpecial(ID.text.ITEM_OBTAINED,12505); player:addGil(GIL_RATE*200); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*200); player:addFame(WINDURST,75); elseif (csid == 661 and option == 1) then player:setCharVar("QuestInAPickle_var",1) elseif (csid == 662) then -- IN A PICKLE + 200 GIL: Repeatable Quest Turn In player:tradeComplete(trade); player:needToZone(true); player:addGil(GIL_RATE*200); player:addFame(WINDURST,8); player:setCharVar("QuestInAPickle_var",0) end end;
gpl-3.0
Fenix-XI/Fenix
scripts/globals/effects/healing.lua
10
1837
----------------------------------- -- -- EFFECT_HEALING -- -- Activated through the /heal command ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:setAnimation(33); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) local healtime = effect:getTickCount(); if (healtime > 1) then -- curse II also known as "zombie" if (not(target:hasStatusEffect(EFFECT_DISEASE)) and target:hasStatusEffect(EFFECT_PLAGUE) == false and target:hasStatusEffect(EFFECT_CURSE_II) == false) then local healHP = 0; if (target:getContinentID() == 1 and target:hasStatusEffect(EFFECT_SIGNET)) then healHP = 10+(3*math.floor(target:getMainLvl()/10))+(healtime-2)*(1+math.floor(target:getMaxHP()/300))+(target:getMod(MOD_HPHEAL)); else target:addTP(-100); healHP = 10+(healtime-2)+(target:getMod(MOD_HPHEAL)); end target:addHP(healHP); target:updateEnmityFromCure(target, healHP); -- Each rank of Clear Mind provides +3 hMP (via MOD_MPHEAL) -- Each tic of healing should be +1mp more than the last -- Clear Mind III increases this to +2, and Clear Mind V to +3 (via MOD_CLEAR_MIND) target:addMP(12+((healtime-2) * (1+target:getMod(MOD_CLEAR_MIND)))+(target:getMod(MOD_MPHEAL))); end end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:setAnimation(0); target:delStatusEffect(EFFECT_LEAVEGAME); end;
gpl-3.0
br101/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/bmx7.lua
76
2091
#!/usr/bin/lua local json = require "cjson" local function interpret_suffix(rate) if rate ~= nil then local value = string.sub(rate, 1, -2) local suffix = string.sub(rate, -1) if suffix == "K" then return tonumber(value) * 10^3 end if suffix == "M" then return tonumber(value) * 10^6 end if suffix == "G" then return tonumber(value) * 10^9 end end return rate end local function scrape() local status = json.decode(get_contents("/var/run/bmx7/json/status")).status local labels = { id = status.shortId, name = status.name, address = status.primaryIp, revision = status.revision, } metric("bmx7_status", "gauge", labels, 1) metric("bmx7_cpu_usage", "gauge", nil, status.cpu) metric("bmx7_mem_usage", "gauge", nil, interpret_suffix(status.mem)) local links = json.decode(get_contents("/var/run/bmx7/json/links")).links local metric_bmx7_rxRate = metric("bmx7_link_rxRate","gauge") local metric_bmx7_txRate = metric("bmx7_link_txRate","gauge") for _, link in pairs(links) do local labels = { source = status.shortId, target = link.shortId, name = link.name, dev = link.dev } metric_bmx7_rxRate(labels, interpret_suffix(link.rxRate)) metric_bmx7_txRate(labels, interpret_suffix(link.txRate)) end local metric_bmx7_tunIn = metric("bmx7_tunIn", "gauge") local parameters = json.decode(get_contents("/var/run/bmx7/json/parameters")).OPTIONS for _, option in pairs(parameters) do if option.name == "tunIn" then for _, instance in pairs(option.INSTANCES) do for _, child_instance in pairs(instance.CHILD_INSTANCES) do local labels = { name = instance.value, network = child_instance.value } metric_bmx7_tunIn(labels, 1) end end elseif option.name == "plugin" then local metric_bmx7_plugin = metric("bmx7_plugin", "gauge") for _, instance in pairs(option.INSTANCES) do metric_bmx7_plugin({ name = instance.value }, 1) end end end end return { scrape = scrape }
gpl-2.0
Fenix-XI/Fenix
scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua
30
2268
----------------------------------- -- Area: The_Garden_of_RuHmet -- Name: when_angels_fall ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0); player:setVar("PromathiaStatus",5); else player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- end elseif (leavecode == 4) then player:startEvent(0x7d02); end --printf("leavecode: %u",leavecode); end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid== 0x7d01) then player:setPos(420,0,445,192); end end;
gpl-3.0
Fenix-XI/Fenix
scripts/zones/South_Gustaberg/mobs/Rock_Lizard.lua
6
1374
----------------------------------- -- Area: South Gustaberg -- MOB: Rock Lizard -- Note: Place holder Leaping Lizzy ----------------------------------- require("scripts/zones/South_Gustaberg/MobIDs"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkRegime(ally,mob,80,1); -- Get Rock Lizard ID and check if it is a PH of LL local mobID = mob:getID(); -- Check if Rock Lizard is within the Leaping_Lizzy_PH table if (Leaping_Lizzy_PH[mobID] ~= nil) then -- printf("%u is a PH",mob); -- Get LL's previous ToD local LL_ToD = GetServerVariable("[POP]Leaping_Lizzy"); -- Check if LL window is open, and there is not an LL popped already(ACTION_NONE = 0) if (LL_ToD <= os.time(t) and GetMobAction(Leaping_Lizzy) == 0) then -- printf("LL window open"); -- Give Rock_Lizard 5 percent chance to pop LL if (math.random(1,20) == 5) then -- printf("LL will pop"); UpdateNMSpawnPoint(Leaping_Lizzy); GetMobByID(Leaping_Lizzy):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Leaping_Lizzy", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
DarkstarProject/darkstar
scripts/globals/items/bowl_of_oceanfin_soup.lua
11
1615
----------------------------------------- -- ID: 6070 -- Item: Bowl of Oceanfin Soup -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- Accuracy % 15 Cap 95 -- Ranged Accuracy % 15 Cap 95 -- Attack % 19 Cap 85 -- Ranged Attack % 19 Cap 85 -- Amorph Killer 6 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,14400,6070) end function onEffectGain(target,effect) target:addMod(dsp.mod.FOOD_ACCP, 15) target:addMod(dsp.mod.FOOD_ACC_CAP, 95) target:addMod(dsp.mod.FOOD_RACCP, 15) target:addMod(dsp.mod.FOOD_RACC_CAP, 95) target:addMod(dsp.mod.FOOD_ATTP, 19) target:addMod(dsp.mod.FOOD_ATT_CAP, 85) target:addMod(dsp.mod.FOOD_RATTP, 19) target:addMod(dsp.mod.FOOD_RATT_CAP, 85) target:addMod(dsp.mod.AMORPH_KILLER, 6) end function onEffectLose(target, effect) target:delMod(dsp.mod.FOOD_ACCP, 15) target:delMod(dsp.mod.FOOD_ACC_CAP, 95) target:delMod(dsp.mod.FOOD_RACCP, 15) target:delMod(dsp.mod.FOOD_RACC_CAP, 95) target:delMod(dsp.mod.FOOD_ATTP, 19) target:delMod(dsp.mod.FOOD_ATT_CAP, 85) target:delMod(dsp.mod.FOOD_RATTP, 19) target:delMod(dsp.mod.FOOD_RATT_CAP, 85) target:delMod(dsp.mod.AMORPH_KILLER, 6) end
gpl-3.0