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
zeustm/zeusbot
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
benjamingwynn/XelLib
xellib_core/xelres.lua
1
2206
-- > XelLib -- >> Created by Benjamin Gwynn -- >> Licensed under the GNU GENERAL PUBLIC LICENSE V2 -- >>> xellib_core/xelres.lua -- >>> Screen resolution management function setupGraphics() -- Clean up older stuff if love.filesystem.exists("XelLib/y_res.dat") then love.filesystem.remove("XelLib/y_res.dat") end if love.filesystem.exists("XelLib/x_res.dat") then love.filesystem.remove("XelLib/x_res.dat") end if love.filesystem.exists("XelLib/xelres_settings.dat") then consoleLog("Previously created screen data exists.", "I", "XelLib") readGraphicsData() else consoleLog("Previously created screen data does not exist.", "W", "XelLib") createGraphicsData() end refreshGraphics() end function createGraphicsData() consoleLog("Creating graphics data.", "I", "XelLib") xelres_settings = {} xelres_settings.fullscreen = false xelres_settings.resizable = false xelres_settings.fullscreentype = "normal" xelres_settings.vsync = false xelres_settings.fsaa = 0 xelres_settings.borderless = false xelres_settings.centered = true xelres_settings.display = 1 xelres_settings.minwidth = 800 xelres_settings.minheight = 600 writeGraphicsData() end function refreshGraphics_default() love.window.setMode(xelres_settings.minwidth, xelres_settings.minheight, xelres_settings) end function refreshGraphics() readGraphicsData() consoleLog("Refreshing screen.", "I", "XelLib") love.window.setMode(love.graphics.getWidth(), love.graphics.getHeight(), xelres_settings) end -- These older functions below have been modified to work with the newer code. -- fullscreenToggle (quick fullscreen toggle) function fullscreenToggle() xelres_settings.fullscreen = not xelres_settings.fullscreen writeGraphicsData() refreshGraphics_default() end -- fsWindowToggle function fsWindowToggle() if xelres_settings.fullscreentype == "normal" then consoleLog("Will now change res to fill screen.", "I", "XelLib") xelres_settings.fullscreentype = "desktop" else consoleLog("Will now strech to fill screen.", "I", "XelLib") xelres_settings.fullscreentype = "normal" end writeGraphicsData() refreshGraphics_default() end
gpl-2.0
ffxiphoenix/darkstar
scripts/globals/mobskills/PL_Heavy_Stomp.lua
25
1203
--------------------------------------------- -- Heavy Stomp -- -- Description: Deals heavy damage to targets within an area of effect. Additional effect: Paralysis -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown radial -- Notes: Paralysis effect has a very long duration. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 421) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = math.random(2,3); local accmod = 1; local dmgmod = .7; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); local typeEffect = EFFECT_PARALYSIS; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 15, 0, 360); target:delHP(dmg); return dmg; end;
gpl-3.0
Quenty/NevermoreEngine
src/color3utils/src/Shared/luv/LuvColor3Utils.lua
1
1561
--[=[ Handles color manipulation in the HpLuv space. https://www.hsluv.org/comparison/ @class LuvColor3Utils ]=] local require = require(script.Parent.loader).load(script) local LuvUtils = require("LuvUtils") local Math = require("Math") local LuvColor3Utils = {} --[=[ Interpolates in LUV space. @param color0 Color3 @param color1 Color3 @param t number @return Color3 ]=] function LuvColor3Utils.lerp(color0, color1, t) assert(typeof(color0) == "Color3", "Bad color0") assert(typeof(color1) == "Color3", "Bad color0") assert(type(t) == "number", "Bad t") if t == 0 then return color0 elseif t == 1 then return color1 else local l0, u0, v0 = unpack(LuvColor3Utils.fromColor3(color0)) local l1, u1, v1 = unpack(LuvColor3Utils.fromColor3(color1)) local l = Math.lerp(l0, l1, t) local u = Math.lerp(u0, u1, t) local v = Math.lerp(v0, v1, t) return LuvColor3Utils.toColor3({l, u, v}) end end --[=[ Converts from Color3 to LUV @param color3 Color3 @return { number, number, number } ]=] function LuvColor3Utils.fromColor3(color3) assert(typeof(color3) == "Color3", "Bad color3") return LuvUtils.rgb_to_hsluv({ color3.r, color3.g, color3.b }) end --[=[ Converts from LUV to Color3 @param luv { number, number, number } @return Color3 ]=] function LuvColor3Utils.toColor3(luv) assert(type(luv) == "table", "Bad luv") local r, g, b = unpack(LuvUtils.hsluv_to_rgb(luv)) -- deal with floating point numbers return Color3.new(math.clamp(r, 0, 1), math.clamp(g, 0, 1), math.clamp(b, 0, 1)) end return LuvColor3Utils
mit
ffxiphoenix/darkstar
scripts/globals/weaponskills/metatron_torment.lua
18
2542
----------------------------------- -- Metatron Torment -- Hand-to-Hand Skill level: 5 Description: Delivers a threefold attack. Damage varies wit weapon skill -- Great Axe Weapon Skill -- Skill Level: N/A -- Lowers target's defense. Additional effect: temporarily lowers damage taken from enemies. -- Defense Down effect is 18.5%, 1 minute duration. -- Damage reduced is 20.4% or 52/256. -- Lasts 20 seconds at 100TP, 40 seconds at 200TP and 60 seconds at 300TP. -- Available only when equipped with the Relic Weapons Abaddon Killer (Dynamis use only) or Bravura. -- Also available as a Latent effect on Barbarus Bhuj -- Since these Relic Weapons are only available to Warriors, only Warriors may use this Weapon Skill. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:60% -- 100%TP 200%TP 300%TP -- 2.75 2.75 2.75 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 2.75; params.ftp200 = 2.75; params.ftp300 = 2.75; params.str_wsc = 0.6; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 and (target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then target:addStatusEffect(EFFECT_DEFENSE_DOWN, 18.5, 0, 120); end if ((player:getEquipID(SLOT_MAIN) == 18294) and (player:getMainJob() == JOB_WAR)) then if (damage > 0) then if (player:getTP() >= 100 and player:getTP() < 200) then player:addStatusEffect(EFFECT_AFTERMATH, -21, 0, 20, 0, 5); elseif (player:getTP() >= 200 and player:getTP() < 300) then player:addStatusEffect(EFFECT_AFTERMATH, -21, 0, 40, 0, 5); elseif (player:getTP() == 300) then player:addStatusEffect(EFFECT_AFTERMATH, -21, 0, 60, 0, 5); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
ffxiphoenix/darkstar
scripts/zones/Grauberg_[S]/npcs/qm5.lua
48
1159
----------------------------------- -- Area: Grauberg [S] -- NPC: ??? -- Quest - Fires of Discontent -- pos 258 33 516 ----------------------------------- package.loaded["scripts/zones/Grauberg_[S]/TextIDs"] = nil; ------------------------------------- require("scripts/globals/harvesting"); require("scripts/zones/Grauberg_[S]/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_ACCEPTED) then if (player:getVar("FiresOfDiscProg") == 3) then player:startEvent(0x000B); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid==0x000B) then player:setVar("FiresOfDiscProg",4); end end;
gpl-3.0
0x0mar/ettercap
src/lua/share/third-party/stdlib/src/getopt.lua
12
8613
--- Simplified getopt, based on Svenne Panne's Haskell GetOpt.<br> -- Usage: -- <ul> -- <li><code>prog = {< -- name = <progname>, -- [usage = <usage line>,] -- [options = { -- {{<name>[, ...]}, <desc>, [<type> [, <var>]]}, -- ... -- },] -- [banner = <banner string>,] -- [purpose = <purpose string>,] -- [notes = <additional notes>] -- }</code></li> -- <li>The <code>type</code> of option argument is one of <code>Req</code>(uired), -- <code>Opt</code>(ional)</li> -- <li>The <code>var</code>is a descriptive name for the option argument.</li> -- <li><code>getopt.processArgs (prog)</code></li> -- <li>Options take a single dash, but may have a double dash.</li> -- <li>Arguments may be given as <code>-opt=arg</code> or <code>-opt arg</code>.</li> -- <li>If an option taking an argument is given multiple times, only the -- last value is returned; missing arguments are returned as 1.</li> -- </ul> -- getOpt, usageInfo and usage can be called directly (see -- below, and the example at the end). Set _DEBUG.std to a non-nil -- value to run the example. -- <ul> -- <li>TODO: Wrap all messages; do all wrapping in processArgs, not -- usageInfo; use sdoc-like library (see string.format todos).</li> -- <li>TODO: Don't require name to be repeated in banner.</li> -- <li>TODO: Store version separately (construct banner?).</li> -- </ul> require "base" local list = require "list" require "string_ext" local Object = require "object" local M = { opt = {}, } --- Perform argument processing -- @param argIn list of command-line args -- @param options options table -- @param stop_at_nonopt if true, stop option processing at first non-option -- @return table of remaining non-options -- @return table of option key-value list pairs -- @return table of error messages local function getOpt (argIn, options, stop_at_nonopt) local noProcess = nil local argOut, optOut, errors = {[0] = argIn[0]}, {}, {} -- get an argument for option opt local function getArg (o, opt, arg, oldarg) if o.type == nil then if arg ~= nil then table.insert (errors, "option `" .. opt .. "' doesn't take an argument") end else if arg == nil and argIn[1] and string.sub (argIn[1], 1, 1) ~= "-" then arg = argIn[1] table.remove (argIn, 1) end if arg == nil and o.type == "Req" then table.insert (errors, "option `" .. opt .. "' requires an argument `" .. o.var .. "'") return nil end end return arg or 1 -- make sure arg has a value end local function parseOpt (opt, arg) local o = options.name[opt] if o ~= nil then o = o or {name = {opt}} optOut[o.name[1]] = optOut[o.name[1]] or {} table.insert (optOut[o.name[1]], getArg (o, opt, arg, optOut[o.name[1]])) else table.insert (errors, "unrecognized option `-" .. opt .. "'") end end while argIn[1] do local v = argIn[1] table.remove (argIn, 1) local _, _, dash, opt = string.find (v, "^(%-%-?)([^=-][^=]*)") local _, _, arg = string.find (v, "=(.*)$") if not dash and stop_at_nonopt then noProcess = true end if v == "--" then noProcess = true elseif not dash or noProcess then -- non-option table.insert (argOut, v) else -- option parseOpt (opt, arg) end end return argOut, optOut, errors end -- Object that defines a single Option entry. local Option = Object {_init = {"name", "desc", "type", "var"}} --- Options table constructor: adds lookup tables for the option names local function makeOptions (t) local options, name = {}, {} local function appendOpt (v, nodupes) local dupe = false v = Option (v) for s in list.elems (v.name) do if name[s] then dupe = true end name[s] = v end if not dupe or nodupes ~= true then if dupe then warn ("duplicate option '%s'", s) end for s in list.elems (v.name) do name[s] = v end options = list.concat (options, {v}) end end for v in list.elems (t or {}) do appendOpt (v) end -- Unless they were supplied already, add version and help options appendOpt ({{"version", "V"}, "print version information, then exit"}, true) appendOpt ({{"help", "h"}, "print this help, then exit"}, true) options.name = name return options end --- Produce usage info for the given options -- @param header header string -- @param optDesc option descriptors -- @param pageWidth width to format to [78] -- @return formatted string local function usageInfo (header, optDesc, pageWidth) pageWidth = pageWidth or 78 -- Format the usage info for a single option -- @param opt the option table -- @return options -- @return description local function fmtOpt (opt) local function fmtName (o) return (#o > 1 and "--" or "-") .. o end local function fmtArg () if opt.type == nil then return "" elseif opt.type == "Req" then return "=" .. opt.var else return "[=" .. opt.var .. "]" end end local textName = list.reverse (list.map (fmtName, opt.name)) textName[#textName] = textName[#textName] .. fmtArg () local indent = "" if #opt.name == 1 and #opt.name[1] > 1 then indent = " " end return {indent .. table.concat ({table.concat (textName, ", ")}, ", "), opt.desc} end local function sameLen (xs) local n = math.max (unpack (list.map (string.len, xs))) for i, v in pairs (xs) do xs[i] = string.sub (v .. string.rep (" ", n), 1, n) end return xs, n end local function paste (x, y) return " " .. x .. " " .. y end local function wrapper (w, i) return function (s) return string.wrap (s, w, i, 0) end end local optText = "" if #optDesc > 0 then local cols = list.transpose (list.map (fmtOpt, optDesc)) local width cols[1], width = sameLen (cols[1]) cols[2] = list.map (wrapper (pageWidth, width + 4), cols[2]) optText = "\n\n" .. table.concat (list.mapWith (paste, list.transpose ({sameLen (cols[1]), cols[2]})), "\n") end return header .. optText end --- Emit a usage message. -- @param prog table of named parameters local function usage (prog) local usage = "[OPTION]... [FILE]..." local purpose, description, notes = "", "", "" if prog.usage then usage = prog.usage end usage = "Usage: " .. prog.name .. " " .. usage if prog.purpose then purpose = "\n\n" .. prog.purpose end if prog.description then for para in list.elems (string.split (prog.description, "\n")) do description = description .. "\n\n" .. string.wrap (para) end end if prog.notes then notes = "\n\n" if not string.find (prog.notes, "\n") then notes = notes .. string.wrap (prog.notes) else notes = notes .. prog.notes end end local header = usage .. purpose .. description io.writelines (usageInfo (header, prog.options) .. notes) end local function version (prog) local version = prog.version or prog.name or "unknown version!" if prog.copyright then version = version .. "\n\n" .. prog.copyright end io.writelines (version) end --- Simple getOpt wrapper. -- If the caller didn't supply their own already, -- adds <code>--version</code>/<code>-V</code> and -- <code>--help</code>/<code>-h</code> options automatically; -- stops program if there was an error, or if <code>--help</code> or -- <code>--version</code> was used. -- @param prog table of named parameters -- @param ... extra arguments for getOpt local function processArgs (prog, ...) local totArgs = #_G.arg local errors prog.options = makeOptions (prog.options) _G.arg, M.opt, errors = getOpt (_G.arg, prog.options, ...) local opt = M.opt if (opt.version or opt.help) and prog.banner then io.writelines (prog.banner) end if #errors > 0 then local name = prog.name prog.name = nil if #errors > 0 then warn (name .. ": " .. table.concat (errors, "\n")) warn (name .. ": Try '" .. (arg[0] or name) .. " --help' for more help") end if #errors > 0 then error () end elseif opt.version then version (prog) elseif opt.help then usage (prog) end if opt.version or opt.help then os.exit () end end -- Public interface return table.merge (M, { getOpt = getOpt, processArgs = processArgs, usage = usage, usageInfo = usageInfo, })
gpl-2.0
vilarion/Illarion-Content
npc/base/consequence/spawn.lua
3
1389
--[[ Illarion Server This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]] local class = require("base.class") local common = require("base.common") local consequence = require("npc.base.consequence.consequence") local _spawn_helper local spawn = class(consequence, function(self, id, count, radius, x, y, z) consequence:init(self) self["id"] = tonumber(id) self["count"] = tonumber(count) self["radius"] = tonumber(radius) self["x"] = tonumber(x) self["y"] = tonumber(y) self["z"] = tonumber(z) self["perform"] = _spawn_helper end) function _spawn_helper(self, npcChar, player) for i = 1, self.count do local monPos = common.getFreePos(position(self.x, self.y, self.z), self.radius) world:createMonster(self.id, monPos, 0) end end return spawn
agpl-3.0
amiranony/anonybot
plugins/steam.lua
645
2117
-- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI do local BASE_URL = 'http://store.steampowered.com/api/appdetails/' local DESC_LENTH = 200 local function unescape(str) str = string.gsub( str, '&lt;', '<' ) str = string.gsub( str, '&gt;', '>' ) str = string.gsub( str, '&quot;', '"' ) str = string.gsub( str, '&apos;', "'" ) str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end ) str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end ) str = string.gsub( str, '&amp;', '&' ) -- Be sure to do this after all others return str end local function get_steam_data (appid) local url = BASE_URL url = url..'?appids='..appid url = url..'&cc=us' local res,code = http.request(url) if code ~= 200 then return nil end local data = json:decode(res)[appid].data return data end local function price_info (data) local price = '' -- If no data is empty if data then local initial = data.initial local final = data.final or data.initial local min = math.min(data.initial, data.final) price = tostring(min/100) if data.discount_percent and initial ~= final then price = price..data.currency..' ('..data.discount_percent..'% OFF)' end price = price..' (US)' end return price end local function send_steam_data(data, receiver) local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...' local title = data.name local price = price_info(data.price_overview) local text = title..' '..price..'\n'..description local image_url = data.header_image local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end local function run(msg, matches) local appid = matches[1] local data = get_steam_data(appid) local receiver = get_receiver(msg) send_steam_data(data, receiver) end return { description = "Grabs Steam info for Steam links.", usage = "", patterns = { "http://store.steampowered.com/app/([0-9]+)", }, run = run } end
gpl-2.0
Quenty/NevermoreEngine
src/loader/src2/Replication/Replicator.lua
1
15760
--[=[ Monitors dependencies primarily for replication. Handles the following scenarios. This system dynamically replicates whatever state exists in the tree except we filter out server-specific assets while any client-side assets are still replicated even if deeper in the tree. By separating out the replication component of the loader from the loading logic we can more easily support hot reloading and future loading scenarios. Repliation rules: 1. Replicate the whole tree, including any changes 2. Module scripts named Server are replaced with a folder 3. Module scripts that are in server mode won't replicate unless a client dependency is needed or found. 4. Once we hit a "Template" object we stop trying to be smart since Mesh parts are not API accessible. 5. References are preserved for ObjectValues. This system is designed to minimize changes such that hot reloading can be easily implemented. Right now it fails to be performance friendly with module scripts under another module script. @class Replicator ]=] local Maid = require(script.Parent.Parent.Maid) local ReplicationType = require(script.Parent.ReplicationType) local ReplicationTypeUtils = require(script.Parent.ReplicationTypeUtils) local ReplicatorUtils = require(script.Parent.ReplicatorUtils) local ReplicatorReferences = require(script.Parent.ReplicatorReferences) local Replicator = {} Replicator.ClassName = "Replicator" Replicator.__index = Replicator --[=[ Constructs a new Replicator which will do the syncing. @param references ReplicatorReferences @return Replicator ]=] function Replicator.new(references) local self = setmetatable({}, Replicator) assert(ReplicatorReferences.isReplicatorReferences(references), "Bad references") self._maid = Maid.new() self._references = references self._target = Instance.new("ObjectValue") self._target.Value = nil self._maid:GiveTask(self._target) self._replicatedDescendantCount = Instance.new("IntValue") self._replicatedDescendantCount.Value = 0 self._maid:GiveTask(self._replicatedDescendantCount) self._hasReplicatedDescendants = Instance.new("BoolValue") self._hasReplicatedDescendants.Value = false self._maid:GiveTask(self._hasReplicatedDescendants) self._replicationType = Instance.new("StringValue") self._replicationType.Value = ReplicationType.SHARED self._maid:GiveTask(self._replicationType) self._maid:GiveTask(self._replicatedDescendantCount.Changed:Connect(function() self._hasReplicatedDescendants.Value = self._replicatedDescendantCount.Value > 0 end)) return self end --[=[ Replicates children from the given root @param root Instance ]=] function Replicator:ReplicateFrom(root) assert(typeof(root) == "Instance", "Bad root") assert(not self._replicationStarted, "Already bound events") self._replicationStarted = true self._maid:GiveTask(root.ChildAdded:Connect(function(child) self:_handleChildAdded(child) end)) self._maid:GiveTask(root.ChildRemoved:Connect(function(child) self:_handleChildRemoved(child) end)) for _, child in pairs(root:GetChildren()) do self:_handleChildAdded(child) end end --[=[ Returns true if the argument is a replicator @param replicator any? @return boolean ]=] function Replicator.isReplicator(replicator) return type(replicator) == "table" and getmetatable(replicator) == Replicator end --[=[ Returns the replicated descendant count value. @return IntValue ]=] function Replicator:GetReplicatedDescendantCountValue() return self._replicatedDescendantCount end --[=[ Sets the replication type for this replicator @param replicationType ReplicationType ]=] function Replicator:SetReplicationType(replicationType) assert(ReplicationTypeUtils.isReplicationType(replicationType), "Bad replicationType") self._replicationType.Value = replicationType end --[=[ Sets the target for the replicator where the results will be parented. @param target Instance? ]=] function Replicator:SetTarget(target) assert(typeof(target) == "Instance" or target == nil, "Bad target") self._target.Value = target end --[=[ Gets the current target for the replicator. @return Instance? ]=] function Replicator:GetTarget() return self._target.Value end --[=[ Gets a value representing if there's any replicated children. Used to avoid leaking more server-side information than needed for the user. @return BoolValue ]=] function Replicator:GetHasReplicatedChildrenValue() return self._hasReplicatedDescendants end function Replicator:GetReplicationTypeValue() return self._replicationType end function Replicator:_handleChildRemoved(child) self._maid[child] = nil end function Replicator:_handleChildAdded(child) assert(typeof(child) == "Instance", "Bad child") local maid = Maid.new() if child.Archivable then maid._current = self:_renderChild(child) end maid:GiveTask(child:GetPropertyChangedSignal("Archivable"):Connect(function() if child.Archivable then maid._current = self:_renderChild(child) else maid._current = nil end end)) self._maid[child] = maid end function Replicator:_renderChild(child) local maid = Maid.new() local replicator = Replicator.new(self._references) self:_setupReplicatorDescendantCount(maid, replicator) maid:GiveTask(replicator) if child:IsA("Folder") then self:_setupReplicatorTypeFromFolderName(maid, replicator, child) else self:_setupReplicatorType(maid, replicator) end local replicationTypeValue = replicator:GetReplicationTypeValue() maid._current = self:_replicateBasedUponMode(replicator, replicationTypeValue.Value, child) maid:GiveTask(replicationTypeValue.Changed:Connect(function() maid._current = nil maid._current = self:_replicateBasedUponMode(replicator, replicationTypeValue.Value, child) end)) replicator:ReplicateFrom(child) return maid end function Replicator:_replicateBasedUponMode(replicator, replicationType, child) assert(Replicator.isReplicator(replicator), "Bad replicator") assert(ReplicationTypeUtils.isReplicationType(replicationType), "Bad replicationType") assert(typeof(child) == "Instance", "Bad child") if replicationType == ReplicationType.SERVER then return self:_doReplicationServer(replicator, child) elseif replicationType == ReplicationType.SHARED or replicationType == ReplicationType.CLIENT then return self:_doReplicationClient(replicator, child) else error("[Replicator] - Unknown replicationType") end end function Replicator:_doReplicationServer(replicator, child) local maid = Maid.new() local hasReplicatedChildren = replicator:GetHasReplicatedChildrenValue() maid:GiveTask(hasReplicatedChildren.Changed:Connect(function() if hasReplicatedChildren.Value then maid._current = nil maid._current = self:_doServerClone(replicator, child) else maid._current = nil end end)) if hasReplicatedChildren.Value then maid._current = self:_doServerClone(replicator, child) end end function Replicator:_doServerClone(replicator, child) -- Always a folder to prevent information from leaking... local maid = Maid.new() local copy = Instance.new("Folder") self:_setupNameReplication(maid, child, copy) self:_setupParentReplication(maid, copy) self:_setupReference(maid, child, copy) maid:GiveTask(copy) -- Setup replication for this specific instance. self:_setupReplicatorTarget(maid, replicator, copy) return maid end function Replicator:_doReplicationClient(replicator, child) local maid = Maid.new() if child:IsA("ModuleScript") then self:_setupReplicatedDescendantCountAdd(maid, 1) maid._current = self:_doModuleScriptCloneClient(replicator, child) maid:GiveTask(child.Changed:Connect(function(property) if property == "Source" then maid._current = nil maid._current = self:_doModuleScriptCloneClient(replicator, child) end end)) elseif child:IsA("Folder") then local copy = Instance.new("Folder") self:_doStandardReplication(maid, replicator, child, copy) elseif child:IsA("ObjectValue") then local copy = Instance.new("ObjectValue") self:_setupObjectValueReplication(maid, child, copy) self:_doStandardReplication(maid, replicator, child, copy) else local copy = ReplicatorUtils.cloneWithoutChildren(child) -- TODO: Maybe do better self:_setupReplicatedDescendantCountAdd(maid, 1) self:_doStandardReplication(maid, replicator, child, copy) end return maid end function Replicator:_doModuleScriptCloneClient(replicator, child) assert(Replicator.isReplicator(replicator), "Bad replicator") assert(typeof(child) == "Instance", "Bad child") local copy = ReplicatorUtils.cloneWithoutChildren(child) local maid = Maid.new() self:_doStandardReplication(maid, replicator, child, copy) return maid end function Replicator:_doStandardReplication(maid, replicator, child, copy) assert(Replicator.isReplicator(replicator), "Bad replicator") assert(typeof(copy) == "Instance", "Bad copy") assert(typeof(child) == "Instance", "Bad child") self:_setupAttributeReplication(maid, child, copy) self:_setupNameReplication(maid, child, copy) self:_setupParentReplication(maid, copy) self:_setupReference(maid, child, copy) maid:GiveTask(copy) -- Setup replication for this specific instance. self:_setupReplicatorTarget(maid, replicator, copy) end function Replicator:_setupReplicatedDescendantCountAdd(maid, amount) assert(Maid.isMaid(maid), "Bad maid") assert(type(amount) == "number", "Bad amount") -- Do this replication count here so when the source changes we don't -- have any flickering. self._replicatedDescendantCount.Value = self._replicatedDescendantCount.Value + amount maid:GiveTask(function() self._replicatedDescendantCount.Value = self._replicatedDescendantCount.Value - amount end) end --[[ Sets up the replicator target so children can be parented into the instance. Sets the target to the copy @param maid Maid @param replicator Replicator @param copy Instance ]] function Replicator:_setupReplicatorTarget(maid, replicator, copy) assert(Maid.isMaid(maid), "Bad maid") assert(Replicator.isReplicator(replicator), "Bad replicator") assert(typeof(copy) == "Instance", "Bad copy") replicator:SetTarget(copy) maid:GiveTask(function() if replicator.Destroy and replicator:GetTarget() == copy then replicator:SetTarget(nil) end end) end --[[ Adds the children count of a child replicator to this replicators count. We use this to determine if we need to build the whole tree or not. @param maid Maid @param replicator Replicator ]] function Replicator:_setupReplicatorDescendantCount(maid, replicator) assert(Maid.isMaid(maid), "Bad maid") assert(Replicator.isReplicator(replicator), "Bad replicator") local replicatedChildrenCount = replicator:GetReplicatedDescendantCountValue() local lastValue = replicatedChildrenCount.Value self._replicatedDescendantCount.Value = self._replicatedDescendantCount.Value + lastValue maid:GiveTask(replicatedChildrenCount.Changed:Connect(function() local value = replicatedChildrenCount.Value local delta = value - lastValue lastValue = value self._replicatedDescendantCount.Value = self._replicatedDescendantCount.Value + delta end)) maid:GiveTask(function() local value = lastValue lastValue = 0 self._replicatedDescendantCount.Value = self._replicatedDescendantCount.Value - value end) end --[[ Sets up references from original to the copy. This allows @param maid Maid @param child Instance @param copy Instance ]] function Replicator:_setupReference(maid, child, copy) assert(Maid.isMaid(maid), "Bad maid") assert(typeof(child) == "Instance", "Bad child") assert(typeof(copy) == "Instance", "Bad copy") -- Setup references self._references:SetReference(child, copy) maid:GiveTask(function() self._references:UnsetReference(child, copy) end) end --[[ Sets up replication type from the folder name. This sort of thing controls replication hierarchy for instances we want to have. @param maid Maid @param replicator @param child Instance ]] function Replicator:_setupReplicatorTypeFromFolderName(maid, replicator, child) assert(Maid.isMaid(maid), "Bad maid") assert(Replicator.isReplicator(replicator), "Bad replicator") assert(typeof(child) == "Instance", "Bad child") maid:GiveTask(self._replicationType.Changed:Connect(function() replicator:SetReplicationType(self:_getFolderReplicationType(child.Name)) end)) maid:GiveTask(child:GetPropertyChangedSignal("Name"):Connect(function() replicator:SetReplicationType(self:_getFolderReplicationType(child.Name)) end)) replicator:SetReplicationType(self:_getFolderReplicationType(child.Name)) end function Replicator:_setupReplicatorType(maid, replicator) assert(Maid.isMaid(maid), "Bad maid") assert(Replicator.isReplicator(replicator), "Bad replicator") replicator:SetReplicationType(self._replicationType.Value) maid:GiveTask(self._replicationType.Changed:Connect(function() replicator:SetReplicationType(self._replicationType.Value) end)) end --[[ Sets up name replication explicitly. @param maid Maid @param child Instance @param copy Instance ]] function Replicator:_setupNameReplication(maid, child, copy) assert(Maid.isMaid(maid), "Bad maid") assert(typeof(child) == "Instance", "Bad child") assert(typeof(copy) == "Instance", "Bad copy") copy.Name = child.Name maid:GiveTask(child:GetPropertyChangedSignal("Name"):Connect(function() copy.Name = child.Name end)) end --[[ Sets up the parent replication. @param maid Maid @param copy Instance ]] function Replicator:_setupParentReplication(maid, copy) assert(Maid.isMaid(maid), "Bad maid") assert(typeof(copy) == "Instance", "Bad copy") maid:GiveTask(self._target.Changed:Connect(function() copy.Parent = self._target.Value end)) copy.Parent = self._target.Value end --[[ Sets up the object value replication to point towards new values. @param maid Maid @param child Instance @param copy Instance ]] function Replicator:_setupObjectValueReplication(maid, child, copy) assert(Maid.isMaid(maid), "Bad maid") assert(typeof(child) == "Instance", "Bad child") assert(typeof(copy) == "Instance", "Bad copy") local symbol = newproxy(true) maid:GiveTask(child:GetPropertyChangedSignal("Value"):Connect(function() maid[symbol] = self:_doObjectValueReplication(child, copy) end)) maid[symbol] = self:_doObjectValueReplication(child, copy) end function Replicator:_doObjectValueReplication(child, copy) assert(typeof(child) == "Instance", "Bad child") assert(typeof(copy) == "Instance", "Bad copy") local childValue = child.Value if childValue then local maid = Maid.new() maid:GiveTask(self._references:ObserveReferenceChanged(childValue, function(newValue) if newValue then copy.Value = newValue else -- Fall back to original value (pointing outside of tree) newValue = childValue end end)) return maid else copy.Value = nil return nil end end --[[ Computes folder replication type based upon the folder name and inherited folder replication type. @param childName string ]] function Replicator:_getFolderReplicationType(childName) assert(type(childName) == "string", "Bad childName") return ReplicationTypeUtils.getFolderReplicationType( childName, self._replicationType.Value) end function Replicator:_setupAttributeReplication(maid, child, copy) for key, value in pairs(child:GetAttributes()) do child:SetAttribute(key, value) end maid:GiveTask(child.AttributeChanged:Connect(function(attribute) copy:SetAttribute(attribute, child:GetAttribute(attribute)) end)) end --[=[ Cleans up the replicator disconnecting all events and cleaning up created instances. ]=] function Replicator:Destroy() self._maid:DoCleaning() setmetatable(self, nil) end return Replicator
mit
crzang/awesome-config
pl/operator.lua
37
4310
--- Lua operators available as functions. -- -- (similar to the Python module of the same name) -- -- There is a module field `optable` which maps the operator strings -- onto these functions, e.g. `operator.optable['()']==operator.call` -- -- Operator strings like '>' and '{}' can be passed to most Penlight functions -- expecting a function argument. -- -- Dependencies: `pl.utils` -- @module pl.operator local strfind = string.find local utils = require 'pl.utils' local operator = {} --- apply function to some arguments **()** -- @param fn a function or callable object -- @param ... arguments function operator.call(fn,...) return fn(...) end --- get the indexed value from a table **[]** -- @param t a table or any indexable object -- @param k the key function operator.index(t,k) return t[k] end --- returns true if arguments are equal **==** -- @param a value -- @param b value function operator.eq(a,b) return a==b end --- returns true if arguments are not equal **~=** -- @param a value -- @param b value function operator.neq(a,b) return a~=b end --- returns true if a is less than b **<** -- @param a value -- @param b value function operator.lt(a,b) return a < b end --- returns true if a is less or equal to b **<=** -- @param a value -- @param b value function operator.le(a,b) return a <= b end --- returns true if a is greater than b **>** -- @param a value -- @param b value function operator.gt(a,b) return a > b end --- returns true if a is greater or equal to b **>=** -- @param a value -- @param b value function operator.ge(a,b) return a >= b end --- returns length of string or table **#** -- @param a a string or a table function operator.len(a) return #a end --- add two values **+** -- @param a value -- @param b value function operator.add(a,b) return a+b end --- subtract b from a **-** -- @param a value -- @param b value function operator.sub(a,b) return a-b end --- multiply two values __*__ -- @param a value -- @param b value function operator.mul(a,b) return a*b end --- divide first value by second **/** -- @param a value -- @param b value function operator.div(a,b) return a/b end --- raise first to the power of second **^** -- @param a value -- @param b value function operator.pow(a,b) return a^b end --- modulo; remainder of a divided by b **%** -- @param a value -- @param b value function operator.mod(a,b) return a%b end --- concatenate two values (either strings or `__concat` defined) **..** -- @param a value -- @param b value function operator.concat(a,b) return a..b end --- return the negative of a value **-** -- @param a value function operator.unm(a) return -a end --- false if value evaluates as true **not** -- @param a value function operator.lnot(a) return not a end --- true if both values evaluate as true **and** -- @param a value -- @param b value function operator.land(a,b) return a and b end --- true if either value evaluate as true **or** -- @param a value -- @param b value function operator.lor(a,b) return a or b end --- make a table from the arguments **{}** -- @param ... non-nil arguments -- @return a table function operator.table (...) return {...} end --- match two strings **~**. -- uses @{string.find} function operator.match (a,b) return strfind(a,b)~=nil end --- the null operation. -- @param ... arguments -- @return the arguments function operator.nop (...) return ... end ---- Map from operator symbol to function. -- Most of these map directly from operators; -- But note these extras -- -- * __'()'__ `call` -- * __'[]'__ `index` -- * __'{}'__ `table` -- * __'~'__ `match` -- -- @table optable -- @field operator operator.optable = { ['+']=operator.add, ['-']=operator.sub, ['*']=operator.mul, ['/']=operator.div, ['%']=operator.mod, ['^']=operator.pow, ['..']=operator.concat, ['()']=operator.call, ['[]']=operator.index, ['<']=operator.lt, ['<=']=operator.le, ['>']=operator.gt, ['>=']=operator.ge, ['==']=operator.eq, ['~=']=operator.neq, ['#']=operator.len, ['and']=operator.land, ['or']=operator.lor, ['{}']=operator.table, ['~']=operator.match, ['']=operator.nop, } return operator
apache-2.0
ffxiphoenix/darkstar
scripts/zones/Windurst_Woods/npcs/Bopa_Greso.lua
19
1725
----------------------------------- -- Area: Windurst Woods -- NPC: Bopa Greso -- Type: Standard NPC -- @zone: 241 -- @pos 59.773 -6.249 216.766 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES); thickAsThievesCS = player:getVar("thickAsThievesCS"); if (thickAsThieves == QUEST_ACCEPTED) then player:startEvent(0x01FA); if (thickAsThievesCS == 1) then player:setVar("thickAsThievesCS",2); elseif (thickAsThievesCS == 3) then player:setVar("thickAsThievesCS",4); rand1 = math.random(2,7); player:setVar("thickAsThievesGrapplingCS",rand1); player:setVar("thickAsThievesGamblingCS",1); end else player:startEvent(0x004d); -- standard cs end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/abilities/dancers_roll.lua
9
3136
----------------------------------- -- Ability: Dancer's Roll -- Grants Regen status to party members within area of effect -- Optimal Job: Dancer -- Lucky Number: 3 -- Unlucky Number: 7 -- Level: 61 -- -- Die Roll |No DNC |With DNC -- -------- ---------- ---------- -- 1 |3HP/Tick |7HP/Tick -- 2 |4HP/Tick |8HP/Tick -- 3 |12HP/Tick |16HP/Tick -- 4 |5HP/Tick |9HP/Tick -- 5 |6HP/Tick |10HP/Tick -- 6 |7HP/Tick |11HP/Tick -- 7 |1HP/Tick |5HP/Tick -- 8 |8HP/Tick |12HP/Tick -- 9 |9HP/Tick |13HP/Tick -- 10 |10HP/Tick |14HP/Tick -- 11 |16HP/Tick |20HP/Tick -- 12+ |-4hp(regen)/Tick |-4hp(regen)/Tick -- A bust will cause a regen effect on you to be reduced by 4, it will not drain HP from you if no regen effect is active. ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else player:setLocalVar("DNC_roll_bonus", 0); return 0,0; end end; ----------------------------------- -- onUseAbilityRoll ----------------------------------- function onUseAbilityRoll(caster,target,ability,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {3, 4, 12, 5, 6, 7, 1, 8, 9, 10, 16, 4}; local effectpower = effectpowers[total] local jobBonus = caster:getLocalVar("DNC_roll_bonus"); if (total < 12) then -- see chaos_roll.lua for comments if (jobBonus == 0) then if (caster:hasPartyJob(JOB_DNC) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then jobBonus = 1; else jobBonus = 2; end end if (jobBonus == 1) then effectpower = effectpower + 4; end if (target:getID() == caster:getID()) then caster:setLocalVar("DNC_roll_bonus", jobBonus); end end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_DANCERS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_REGEN) == false) then ability:setMsg(423); end end;
gpl-3.0
ffxiphoenix/darkstar
scripts/globals/items/bar_of_campfire_chocolate.lua
36
1080
----------------------------------------- -- ID: 5941 -- Item: Bar of Campfire Chocolate -- Food Effect: 30Min, All Races ----------------------------------------- -- Mind +1 ----------------------------------------- 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,5941); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MND, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MND, 1); end;
gpl-3.0
morteza1377/titann
libs/XMLElement.lua
569
4025
-- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence. -- updated for module-free world of lua 5.3 on April 2 2015 -- Not documented at all, but not interesting enough to warrant documentation anyway. local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error local table, string = table, string local XMLElement={} local mt XMLElement.new = function(lom) return setmetatable({lom=lom or {}}, mt) end local function filter(filtery_thing, lom) filtery_thing=filtery_thing or '*' for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do if thing == "text()" then if type(lom)=='string' then return true end elseif thing == '*' then if type(lom)=='table' then return true end else if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end end end return nil end mt ={ __index = { getAttr = function(self, attribute) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end return self.lom.attr[attribute] end, setAttr = function(self, attribute, value) if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if value == nil then return self:removeAttr(attribute) end self.lom.attr[attribute]=tostring(value) return self end, removeAttr = function(self, attribute) local lom = self.lom if type(attribute) ~= "string" then return nil, "attribute name must be a string." end if not lom.attr[attribute] then return self end for i,v in ipairs(lom.attr) do if v == attribute then table.remove(lom.attr, i) break end end lom.attr[attribute]=nil end, removeAllAttributes = function(self) local attr = self.lom.attr for i, v in pairs(self.lom.attr) do attr[i]=nil end return self end, getAttributes = function(self) local attr = {} for i, v in ipairs(self.lom.attr) do table.insert(attr,v) end return attr end, getXML = function(self) local function getXML(lom) local attr, inner = {}, {} for i, attribute in ipairs(lom.attr) do table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute])) end for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getXML(v)) else error("oh shit") end end local tagcontents = table.concat(inner) local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or "" if #tagcontents>0 then return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag) else return string.format("<%s%s />", lom.tag, attrstring) end end return getXML(self.lom) end, getText = function(self) local function getText(lom) local inner = {} for i, v in ipairs(lom) do local t = type(v) if t == "string" then table.insert(inner, v) elseif t == "table" then table.insert(inner, getText(v)) end end return table.concat(inner) end return getText(self.lom) end, getChildren = function(self, filter_thing) local res = {} for i, node in ipairs(self.lom) do if filter(filter_thing, node) then table.insert(res, type(node)=='table' and XMLElement.new(node) or node) end end return res end, getDescendants = function(self, filter_thing) local res = {} local function descendants(lom) for i, child in ipairs(lom) do if filter(filter_thing, child) then table.insert(res, type(child)=='table' and XMLElement.new(child) or child) if type(child)=='table' then descendants(child) end end end end descendants(self.lom) return res end, getChild = function(self, filter_thing) for i, node in ipairs(self.lom) do if filter(filter_thing, node) then return type(node)=='table' and XMLElement.new(node) or node end end end, getTag = function(self) return self.lom.tag end }} return XMLElement
agpl-3.0
azekillDIABLO/Voxellar
mods/NODES/xtend/xfurniture/furniture/window_stuff.lua
1
3389
local _register = _xtend.f.xfurniture.register local _p2r = _xtend.f.xfurniture.pattern_to_recipe -- One step is 0.0625 because 1/16 = 0.0625 local _indent_setting = _xtend.g('xfurniture_window_stuff_indent') local _indent = tonumber(_indent_setting:match("^(%w+)")) * 0.0625 -- Apply indentiation to a nodebox definition -- -- The indentahas to be added to the third and the 6th value on each line of -- the single nodebox definitions to move the part back by the wanted amount of -- fractions. This function does exactly that. -- -- @param nodebox_table The nodebox table you want to process -- @param float|int The desired indent value -- @return nodebox_table The processed nodebox table -- -- @see <http://dev.minetest.net/Node_boxes> for how a nodox table has to -- be created (`{box1, box2, ...}`) local _apply_indent = function(nodebox_table, indent) local new_nodebox_table = {} for _,b in pairs(nodebox_table) do local new_box = {b[1], b[2], b[3] + indent, b[4], b[5], b[6] + indent} table.insert(new_nodebox_table, new_box) end return new_nodebox_table end for node in pairs(_xtend.v.xfurniture.nodes) do ---------------------------------------------------------------------------- _register({ _xtend.t('Window Screen Bars'), _apply_indent({ {-0.5, 0.4375, 0.375, 0.5, 0.5, 0.4375}, -- line_1 {-0.5, 0.3125, 0.375, 0.5, 0.375, 0.4375}, -- line_2 {-0.5, 0.1875, 0.375, 0.5, 0.25, 0.4375}, -- line_3 {-0.5, 0.0625, 0.375, 0.5, 0.125, 0.4375}, -- line_4 {-0.5, -0.0625, 0.375, 0.5, 0, 0.4375}, -- line_5 {-0.5, -0.1875, 0.375, 0.5, -0.125, 0.4375}, -- line_6 {-0.5, -0.3125, 0.375, 0.5, -0.25, 0.4375}, -- line_7 {-0.5, -0.4375, 0.375, 0.5, -0.375, 0.4375} -- line_8 }, _indent), _p2r(node, 'window_screen_bars') }) _register({ _xtend.t('Window Screen Frame Part'), _apply_indent({ {-0.5, -0.5, 0.3125, 0.5, -0.3125, 0.5} -- frame_part }, _indent), _p2r(node, 'window_screen_frame_part') }) _register({ _xtend.t('Window Screen Frame Corner'), _apply_indent({ {-0.5, -0.5, 0.3125, -0.3125, -0.3125, 0.5}, -- frame_corner }, _indent), _p2r(node, 'window_screen_frame_corner') }) ---------------------------------------------------------------------------- _register({ _xtend.t('Window Sill Sill Part'), _apply_indent({ {-0.5, 0.375, 0.1875, 0.5, 0.5, 0.5} -- sill_part }, _indent), _p2r(node, 'window_sill_sill_part') }) _register({ _xtend.t('Window Sill End Part Right'), _apply_indent({ {-0.5, 0.375, 0.1875, -0.25, 0.5, 0.5}, -- end_part_right_top {-0.375, 0.25, 0.1875, -0.25, 0.4375, 0.5} -- end_part_right_end }, _indent), _p2r(node, 'window_sill_end_part_right') }) _register({ _xtend.t('Window Sill End Part Left'), _apply_indent({ {0.25, 0.375, 0.1875, 0.5, 0.5, 0.5}, -- end_part_left_top {0.25, 0.25, 0.1875, 0.375, 0.4375, 0.5} -- end_part_left_end }, _indent), _p2r(node, 'window_sill_end_part_left') }) ---------------------------------------------------------------------------- end
lgpl-2.1
ffxiphoenix/darkstar
scripts/zones/Heavens_Tower/npcs/_6q1.lua
17
1377
----------------------------------- -- Area: Heaven's Tower -- NPC: Starway Stairway -- @pos -10 0.1 30 242 ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Heavens_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == 2) then if (player:hasKeyItem(STARWAY_STAIRWAY_BAUBLE)) then if (player:getXPos() < -14) then player:startEvent(0x006A); else player:startEvent(0x0069); end; else player:messageSpecial(STAIRWAY_LOCKED); end; else player:messageSpecial(STAIRWAY_ONLY_CITIZENS); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Arzizah.lua
34
1032
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Arzizah -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00F6); 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
kitala1/darkstar
scripts/zones/Kuftal_Tunnel/npcs/Grounds_Tome.lua
34
1136
----------------------------------- -- Area: Kuftal Tunnel -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_KUFTAL_TUNNEL,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,735,736,737,738,739,740,741,742,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,735,736,737,738,739,740,741,742,0,0,GOV_MSG_KUFTAL_TUNNEL); end;
gpl-3.0
kitala1/darkstar
scripts/zones/RuAun_Gardens/npcs/Treasure_Coffer.lua
12
3318
----------------------------------- -- Area: Ru'Aun Gardens -- NPC: Treasure Coffer -- @zone 130 -- @pos ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/RuAun_Gardens/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1058,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1058,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local zone = player:getZoneID(); if(player:hasKeyItem(MAP_OF_THE_RUAUN_GARDENS) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if(questItemNeeded == 1) then player:addKeyItem(MAP_OF_THE_RUAUN_GARDENS); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_RUAUN_GARDENS); -- Map of the Ru'Aun Gardens (KI) else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1058); 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
kitala1/darkstar
scripts/globals/weaponskills/stringing_pummel.lua
12
4577
----------------------------------- -- Stringing Pummel -- Sword weapon skill -- Skill Level: N/A -- Delivers a sixfold attack. Damage varies with TP. Kenkonken: Aftermath effect varies with TP. -- Available only after completing the Unlocking a Myth (Puppetmaster) quest. -- Aligned with the Shadow Gorget, Soil Gorget & Flame Gorget. -- Aligned with the Shadow Belt, Soil Belt & Flame Belt. -- Element: Darkness -- Modifiers: STR:32% VIT:32% -- 100%TP 200%TP 300%TP -- 1 1 1 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 6; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.32; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.15; params.crit200 = 0.45; params.crit300 = 0.65; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 0.75; params.ftp200 = 0.75; params.ftp300 = 0.75; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if((player:getEquipID(SLOT_MAIN) == 19008) and (player:getMainJob() == JOB_PUP)) then if(damage > 0) then -- AFTERMATH LEVEL 1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 1); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 1); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 1); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 1); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 1); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 1); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 1); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 1); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 1); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 1); -- AFTERMATH LEVEL 2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 1); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 1); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 1); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 1); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 1); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 1); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 1); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 1); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 1); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 1); -- AFTERMATH LEVEL 3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
khwangster/wrk2
deps/luajit/src/jit/v.lua
74
5614
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20003, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..oex..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then out:write(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else out:write(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif link == tr or link == 0 then out:write(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then out:write(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else out:write(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else out:write(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. module(...) on = dumpon off = dumpoff start = dumpon -- For -j command line option.
apache-2.0
libcg/gSquare
game/levels/canon5.lua
1
2608
function getInfo() -- Title local title = { "Day 24.", "Jour 24." } levelText(title[getLanguageID()+1]) end function setGame() -- Music setMusic("./audio/c418-peanuts.mp3") -- Player varPlayerX(16*11) varPlayerY(16*5) -- Gravity varGravityDir(4) end function setLevel() -- Temporary level matrix local lvl_w, lvl_h = 25, 16 local lvl = {{0,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1}, {1,0,4,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1}, {1,0,4,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,1,1,1}, {1,0,0,0,0,0,0,0,0,0,0,7,1,1,1,0,0,0,0,0,0,0,0,1,4}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,0,0,0,1,4}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,1,1,0,0,1,1,1}, {1,0,0,0,0,0,0,4,0,0,0,0,0,1,1,1,0,0,1,1,0,0,1,1,1}, {1,0,0,2,2,0,0,4,0,0,4,0,0,1,1,0,0,0,0,0,0,0,0,1,4}, {1,0,0,2,2,0,0,4,0,0,4,0,0,1,1,0,0,0,0,0,0,0,0,1,4}, {1,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,1,1,1,1,1}, {1,0,0,2,2,0,0,4,0,0,4,0,0,4,4,4,1,1,0,0,1,1,1,1,0}, {1,0,0,2,2,0,0,9,0,0,4,0,0,0,0,0,0,0,0,0,9,0,3,1,0}, {1,0,0,2,2,2,2,2,2,2,2,1,1,2,2,0,2,0,2,2,2,2,1,1,0}, {1,2,2,2,2,2,2,2,2,2,2,4,4,4,4,4,4,4,4,4,4,4,4,4,0}} -- Reset level initObject() -- Init objects using the matrix for i=1,lvl_w do for j=1,lvl_h do if lvl[j][i]>0 then createObjectAligned(16*(i-1),16*(j-1),0,0,lvl[j][i],16) end end end -- Finish createObjectAligned(16*2,16*14,0,0,b,16) objectText("./levels/canon6.lua") -- Init checkpoints createObjectAligned(16*7,16*3,0,0,9,16) local t1 = { "Marshmallow cannons would be funnier.", "Des canons en guimauve seraient plus drôles." } objectText(t1[getLanguageID()+1]) -- Init Canons createObjectAligned(16*0,16*2,0,0,f,16) createObjectAligned(16*0,16*11,0,0,f,16) createObjectAligned(16*1,16*7,0,0,g,16) createObjectAligned(16*2,16*7,0,0,g,16) createObjectAligned(16*4,16*4,0,0,g,16) createObjectAligned(16*5,16*6,0,0,e,16) createObjectAligned(16*5,16*14,0,0,e,16) createObjectAligned(16*6,16*4,0,0,g,16) createObjectAligned(16*6,16*7,0,0,g,16) createObjectAligned(16*13,16*8,0,0,h,16) createObjectAligned(16*14,16*5,0,0,f,16) createObjectAligned(16*14,16*10,0,0,f,16) createObjectAligned(16*16,16*4,0,0,g,16) createObjectAligned(16*16,16*11,0,0,e,16) createObjectAligned(16*21,16*4,0,0,g,16) createObjectAligned(16*21,16*11,0,0,e,16) createObjectAligned(16*23,16*5,0,0,h,16) createObjectAligned(16*23,16*10,0,0,h,16) end
gpl-3.0
Taracque/epgp
modules/ui.lua
1
47553
--[[ EPGP User Interface ]]-- local mod = EPGP:NewModule("ui") local L = LibStub("AceLocale-3.0"):GetLocale("EPGP") local GS = LibStub("LibGuildStorage-1.2") local GP = LibStub("LibGearPoints-1.2") local DLG = LibStub("LibDialog-1.0") local GUI = LibStub("AceGUI-3.0") local EPGPWEB = "http://www.epgpweb.com" local BUTTON_TEXT_PADDING = 20 local BUTTON_HEIGHT = 22 local ROW_TEXT_PADDING = 5 local function Debug(fmt, ...) DEFAULT_CHAT_FRAME:AddMessage(string.format(fmt, ...)) end local function DebugFrame(frame, r, g, b) local t = frame:CreateTexture() t:SetAllPoints(frame) t:SetTexture(r or 0, g or 1, b or 0, 0.05) end local function DebugPoints(frame, name) Debug("%s top=%d bottom=%d left=%d right=%d height=%d width=%d", name, frame:GetTop(), frame:GetBottom(), frame:GetLeft(), frame:GetRight(), frame:GetHeight(), frame:GetWidth()) end local SIDEFRAMES = {} local function ToggleOnlySideFrame(frame) for _,f in ipairs(SIDEFRAMES) do if f == frame then if f:IsShown() then f:Hide() else f:Show() end else f:Hide() end end end local function CreateEPGPFrame() -- EPGPFrame local f = CreateFrame("Frame", "EPGPFrame", UIParent) f:Hide() f:SetToplevel(true) f:EnableMouse(true) f:SetMovable(true) f:SetAttribute("UIPanelLayout-defined", true) f:SetAttribute("UIPanelLayout-enabled", true) f:SetAttribute("UIPanelLayout-area", "left") f:SetAttribute("UIPanelLayout-pushable", 5) f:SetAttribute("UIPanelLayout-whileDead", true) f:SetWidth(384) f:SetHeight(512) f:SetPoint("TOPLEFT", nil, "TOPLEFT", 0, -104) f:SetHitRectInsets(0, 30, 0, 45) local t = f:CreateTexture(nil, "BACKGROUND") t:SetTexture("Interface\\PetitionFrame\\GuildCharter-Icon") t:SetWidth(60) t:SetHeight(60) t:SetPoint("TOPLEFT", f, "TOPLEFT", 7, -6) t = f:CreateTexture(nil, "ARTWORK") t:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopLeft") t:SetWidth(256) t:SetHeight(256) t:SetPoint("TOPLEFT", f, "TOPLEFT", 0, 0) t = f:CreateTexture(nil, "ARTWORK") t:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-TopRight") t:SetWidth(128) t:SetHeight(256) t:SetPoint("TOPRIGHT", f, "TOPRIGHT", 0, 0) t = f:CreateTexture(nil, "ARTWORK") t:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-General-BottomLeft") t:SetWidth(256) t:SetHeight(256) t:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 0, 0) t = f:CreateTexture(nil, "ARTWORK") t:SetTexture( "Interface\\PaperDollInfoFrame\\UI-Character-General-BottomRight") t:SetWidth(128) t:SetHeight(256) t:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0, 0) t = f:CreateFontString(nil, "OVERLAY", "GameFontNormal") t:SetWidth(250) t:SetHeight(16) t:SetPoint("TOP", f, "TOP", 3, -16) t:SetText("EPGP "..EPGP.version) local cb = CreateFrame("Button", nil, f, "UIPanelCloseButton") cb:SetPoint("TOPRIGHT", f, "TOPRIGHT", -30, -8) f:SetScript("OnHide", ToggleOnlySideFrame) end local function CreateEPGPExportImportFrame() local f = CreateFrame("Frame", "EPGPExportImportFrame", UIParent) f:Hide() f:SetPoint("CENTER") f:SetFrameStrata("TOOLTIP") f:SetHeight(350) f:SetWidth(500) f:SetBackdrop({ bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32, insets = { left=11, right=12, top=12, bottom=11 }, }) f:SetBackdropColor(0, 0, 0, 1) local help = f:CreateFontString(nil, "ARTWORK", "GameFontNormal") help:SetPoint("TOP", f, "TOP", 0, -20) help:SetWidth(f:GetWidth() - 40) f.help = help local button1 = CreateFrame("Button", nil, f, "StaticPopupButtonTemplate") button1:SetPoint("BOTTOM", f, "BOTTOM", 0, 15) local button2 = CreateFrame("Button", nil, f, "StaticPopupButtonTemplate") button2:SetPoint("BOTTOM", button1, "BOTTOM") f.button1 = button1 f.button2 = button2 local s = CreateFrame("ScrollFrame", "EPGPExportScrollFrame", f, "UIPanelScrollFrameTemplate2") s:SetPoint("TOPLEFT", help, "BOTTOMLEFT", 0, -10) s:SetPoint("TOPRIGHT", help, "BOTTOMRIGHT", -20, 0) s:SetPoint("BOTTOM", button1, "TOP", 0, 10) local b = CreateFrame("EditBox", nil, s) b:SetPoint("TOPLEFT") b:SetWidth(425) b:SetHeight(s:GetHeight()) b:SetMultiLine(true) b:SetAutoFocus(false) b:SetFontObject(GameFontHighlight) b:SetScript("OnEscapePressed", function (self) self:ClearFocus() end) s:SetScrollChild(b) f.editbox = b f:SetScript( "OnShow", function (self) if self.export then self.help:SetText(L["To export the current standings, copy the text below and post it to: %s"]:format(EPGPWEB)) self.button1:Show() self.button1:SetText(CLOSE) self.button1:SetPoint("CENTER", self, "CENTER") self.button1:SetScript("OnClick", function (self) self:GetParent():Hide() end) self.button2:Hide() self.editbox:SetText(EPGP:GetModule("log"):Export()) self.editbox:HighlightText() self.editbox:SetScript("OnTextChanged", function (self) local text = EPGP:GetModule("log"):Export() self:SetText(text) end) else self.help:SetText(L["To restore to an earlier version of the standings, copy and paste the text from: %s"]:format(EPGPWEB)) self.editbox:SetText(L["Paste import data here"]) self.button1:Show() self.button1:SetText(ACCEPT) self.button1:SetPoint("CENTER", self, "CENTER", -self.button1:GetWidth()/2 - 5, 0) self.button1:SetScript("OnClick", function (self) local text = self:GetParent().editbox:GetText() EPGP:GetModule("log"):Import(text) self:GetParent():Hide() end) self.button2:Show() self.button2:SetText(CANCEL) self.button2:SetPoint("LEFT", self.button1, "RIGHT", 10, 0) self.button2:SetScript("OnClick", function (self) self:GetParent():Hide() end) self.editbox:SetScript("OnTextChanged", nil) end end) f:SetScript( "OnHide", function (self) self.editbox:SetText("") end) end local function CreateTableHeader(parent) local h = CreateFrame("Button", nil, parent) h:SetHeight(24) local tl = h:CreateTexture(nil, "BACKGROUND") tl:SetTexture("Interface\\FriendsFrame\\WhoFrame-ColumnTabs") tl:SetWidth(5) tl:SetHeight(24) tl:SetPoint("TOPLEFT") tl:SetTexCoord(0, 0.07815, 0, 0.75) local tr = h:CreateTexture(nil, "BACKGROUND") tr:SetTexture("Interface\\FriendsFrame\\WhoFrame-ColumnTabs") tr:SetWidth(5) tr:SetHeight(24) tr:SetPoint("TOPRIGHT") tr:SetTexCoord(0.90625, 0.96875, 0, 0.75) local tm = h:CreateTexture(nil, "BACKGROUND") tm:SetTexture("Interface\\FriendsFrame\\WhoFrame-ColumnTabs") tm:SetHeight(24) tm:SetPoint("LEFT", tl, "RIGHT") tm:SetPoint("RIGHT", tr, "LEFT") tm:SetTexCoord(0.07815, 0.90625, 0, 0.75) h:SetHighlightTexture( "Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight", "ADD") return h end local function CreateTableRow(parent, rowHeight, widths, justifiesH) local row = CreateFrame("Button", nil, parent) row:SetHighlightTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight", "ADD") row:SetHeight(rowHeight) row:SetPoint("LEFT") row:SetPoint("RIGHT") row.cells = {} for i,w in ipairs(widths) do local c = row:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") c:SetHeight(rowHeight) c:SetWidth(w - (2 * ROW_TEXT_PADDING)) c:SetJustifyH(justifiesH[i]) if #row.cells == 0 then c:SetPoint("LEFT", row, "LEFT", ROW_TEXT_PADDING, 0) else c:SetPoint("LEFT", row.cells[#row.cells], "RIGHT", 2 * ROW_TEXT_PADDING, 0) end table.insert(row.cells, c) c:SetText(w) end return row end local function CreateTable(parent, texts, widths, justfiesH, rightPadding) assert(#texts == #widths and #texts == #justfiesH, "All specification tables must be the same size") -- Compute widths local totalFixedWidths = rightPadding or 0 local numDynamicWidths = 0 for i,w in ipairs(widths) do if w > 0 then totalFixedWidths = totalFixedWidths + w else numDynamicWidths = numDynamicWidths + 1 end end local remainingWidthSpace = parent:GetWidth() - totalFixedWidths assert(remainingWidthSpace >= 0, "Widths specified exceed parent width") local dynamicWidth = math.floor(remainingWidthSpace / numDynamicWidths) local leftoverWidth = remainingWidthSpace % numDynamicWidths for i,w in ipairs(widths) do if w <= 0 then numDynamicWidths = numDynamicWidths - 1 if numDynamicWidths then widths[i] = dynamicWidth else widths[i] = dynamicWidth + leftoverWidth end end end -- Make headers parent.headers = {} for i=1,#texts do local text, width, justifyH = texts[i], widths[i], justfiesH[i] local h = CreateTableHeader(parent, text, width) h:SetNormalFontObject("GameFontHighlightSmall") h:SetText(text) h:GetFontString():SetJustifyH(justifyH) h:SetWidth(width) if #parent.headers == 0 then h:SetPoint("TOPLEFT") else h:SetPoint("TOPLEFT", parent.headers[#parent.headers], "TOPRIGHT") end table.insert(parent.headers, h) end -- Make a frame for the rows local rowFrame = CreateFrame("Frame", nil, parent) rowFrame:SetPoint("TOP", parent.headers[#parent.headers], "BOTTOM") rowFrame:SetPoint("BOTTOMLEFT") rowFrame:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", -rightPadding, 0) parent.rowFrame = rowFrame -- Compute number of rows local fontHeight = select(2, GameFontNormalSmall:GetFont()) local rowHeight = fontHeight + 4 rowFrame.rowHeight = rowHeight local numRows = math.floor(rowFrame:GetHeight() / rowHeight) -- Make rows rowFrame.rows = {} for i=1,numRows do local r = CreateTableRow(rowFrame, rowHeight, widths, justfiesH) if #rowFrame.rows == 0 then r:SetPoint("TOP") else r:SetPoint("TOP", rowFrame.rows[#rowFrame.rows], "BOTTOM") end table.insert(rowFrame.rows, r) end end local function CreateEPGPLogFrame() local f = CreateFrame("Frame", "EPGPLogFrame", EPGPFrame) table.insert(SIDEFRAMES, f) f:SetResizable(true) f:SetMinResize(600, 435) f:SetMaxResize(1200, 435) f:Hide() f:SetWidth(600) f:SetHeight(435) f:SetPoint("TOPLEFT", EPGPFrame, "TOPRIGHT", -37, -6) local t = f:CreateTexture(nil, "OVERLAY") t:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Corner") t:SetWidth(32) t:SetHeight(32) t:SetPoint("TOPRIGHT", f, "TOPRIGHT", -6, -7) t = f:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall") t:SetPoint("TOPLEFT", f, "TOPLEFT", 17, -17) t:SetText(L["Personal Action Log"]) f:SetBackdrop( { bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32, insets = { left=11, right=12, top=12, bottom=11 } }) local sizer = CreateFrame("Button", nil, f) sizer:SetHeight(16) sizer:SetWidth(16) sizer:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", 0, 0) sizer:SetScript( "OnMouseDown", function (self) self:GetParent():StartSizing("BOTTOMRIGHT") end) sizer:SetScript( "OnMouseUp", function (self) self:GetParent():StopMovingOrSizing() end) local line1 = sizer:CreateTexture(nil, "BACKGROUND") line1:SetWidth(14) line1:SetHeight(14) line1:SetPoint("BOTTOMRIGHT", -8, 8) line1:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 14/17 line1:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local line2 = sizer:CreateTexture(nil, "BACKGROUND") line2:SetWidth(8) line2:SetHeight(8) line2:SetPoint("BOTTOMRIGHT", -8, 8) line2:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border") local x = 0.1 * 8/17 line2:SetTexCoord(0.05 - x, 0.5, 0.05, 0.5 + x, 0.05, 0.5 - x, 0.5 + x, 0.5) local cb = CreateFrame("Button", nil, f, "UIPanelCloseButton") cb:SetPoint("TOPRIGHT", f, "TOPRIGHT", -2, -3) local export = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") export:SetNormalFontObject("GameFontNormalSmall") export:SetHighlightFontObject("GameFontHighlightSmall") export:SetDisabledFontObject("GameFontDisableSmall") export:SetHeight(BUTTON_HEIGHT) export:SetPoint("BOTTOMLEFT", f, "BOTTOMLEFT", 17, 13) export:SetText(L["Export"]) export:SetWidth(export:GetTextWidth() + BUTTON_TEXT_PADDING) export:SetScript( "OnClick", function(self, button, down) EPGPExportImportFrame.export = true EPGPExportImportFrame:Hide() EPGPExportImportFrame:Show() end) local import = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") import:SetNormalFontObject("GameFontNormalSmall") import:SetHighlightFontObject("GameFontHighlightSmall") import:SetDisabledFontObject("GameFontDisableSmall") import:SetHeight(BUTTON_HEIGHT) import:SetPoint("LEFT", export, "RIGHT") import:SetText(L["Import"]) import:SetWidth(import:GetTextWidth() + BUTTON_TEXT_PADDING) import:SetScript( "OnClick", function(self, button, down) EPGPExportImportFrame.export = false EPGPExportImportFrame:Hide() EPGPExportImportFrame:Show() end) local undo = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") undo:SetNormalFontObject("GameFontNormalSmall") undo:SetHighlightFontObject("GameFontHighlightSmall") undo:SetDisabledFontObject("GameFontDisableSmall") undo:SetHeight(BUTTON_HEIGHT) undo:SetText(L["Undo"]) undo:SetWidth(undo:GetTextWidth() + BUTTON_TEXT_PADDING) undo:SetPoint("BOTTOMRIGHT", f, "BOTTOMRIGHT", -17, 13) undo:SetScript( "OnClick", function (self, value) EPGP:GetModule("log"):UndoLastAction() end) undo:SetScript( "OnUpdate", function (self) if EPGP:GetModule("log"):CanUndo() then self:Enable() else self:Disable() end end) local redo = CreateFrame("Button", nil, f, "UIPanelButtonTemplate") redo:SetNormalFontObject("GameFontNormalSmall") redo:SetHighlightFontObject("GameFontHighlightSmall") redo:SetDisabledFontObject("GameFontDisableSmall") redo:SetHeight(BUTTON_HEIGHT) redo:SetText(L["Redo"]) redo:SetWidth(redo:GetTextWidth() + BUTTON_TEXT_PADDING) redo:SetPoint("RIGHT", undo, "LEFT") redo:SetScript( "OnClick", function (self, value) EPGP:GetModule("log"):RedoLastUndo() end) redo:SetScript( "OnUpdate", function (self) if EPGP:GetModule("log"):CanRedo() then self:Enable() else self:Disable() end end) local scrollParent = CreateFrame("Frame", nil, f) scrollParent:SetPoint("TOP", t, "TOP", 0, -16) scrollParent:SetPoint("BOTTOM", redo, "TOP", 0, 0) scrollParent:SetPoint("LEFT", f, "LEFT", 16, 0) scrollParent:SetPoint("RIGHT", f, "RIGHT", -16, 0) scrollParent:SetBackdrop( { bgFile = "Interface\\Tooltips\\UI-Tooltip-Background", edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border", tile = true, tileSize = 16, edgeSize = 16, insets = { left=5, right=5, top=5, bottom=5 } }) scrollParent:SetBackdropBorderColor(TOOLTIP_DEFAULT_COLOR.r, TOOLTIP_DEFAULT_COLOR.g, TOOLTIP_DEFAULT_COLOR.b) scrollParent:SetBackdropColor(TOOLTIP_DEFAULT_BACKGROUND_COLOR.r, TOOLTIP_DEFAULT_BACKGROUND_COLOR.g, TOOLTIP_DEFAULT_BACKGROUND_COLOR.b) local font = "ChatFontSmall" local fontHeight = select(2, getglobal(font):GetFont()) local recordHeight = fontHeight + 2 local recordWidth = scrollParent:GetWidth() - 35 local numLogRecordFrames = math.floor( (scrollParent:GetHeight() - 3) / recordHeight) local record = scrollParent:CreateFontString("EPGPLogRecordFrame1", "OVERLAY", font) record:SetHeight(recordHeight) record:SetWidth(recordWidth) record:SetNonSpaceWrap(false) record:SetPoint("TOPLEFT", scrollParent, "TOPLEFT", 5, -3) for i=2,numLogRecordFrames do record = scrollParent:CreateFontString("EPGPLogRecordFrame"..i, "OVERLAY", font) record:SetHeight(recordHeight) record:SetWidth(recordWidth) record:SetNonSpaceWrap(false) record:SetPoint("TOPLEFT", "EPGPLogRecordFrame"..(i-1), "BOTTOMLEFT") end local scrollBar = CreateFrame("ScrollFrame", "EPGPLogRecordScrollFrame", scrollParent, "FauxScrollFrameTemplateLight") scrollBar:SetWidth(scrollParent:GetWidth() - 35) scrollBar:SetHeight(scrollParent:GetHeight() - 10) scrollBar:SetPoint("TOPRIGHT", scrollParent, "TOPRIGHT", -28, -6) function LogChanged() if not EPGPLogFrame:IsVisible() then return end local log = EPGP:GetModule("log") local offset = FauxScrollFrame_GetOffset(scrollBar) local numRecords = log:GetNumRecords() local numDisplayedRecords = math.min(numLogRecordFrames, numRecords - offset) local recordWidth = scrollParent:GetWidth() - 35 for i=1,numLogRecordFrames do local record = getglobal("EPGPLogRecordFrame"..i) record:SetWidth(recordWidth) local logIndex = i + offset - 1 if logIndex < numRecords then record:SetText(log:GetLogRecord(logIndex)) record:SetJustifyH("LEFT") record:Show() else record:Hide() end end FauxScrollFrame_Update( scrollBar, numRecords, numDisplayedRecords, recordHeight) end EPGPLogFrame:SetScript("OnShow", LogChanged) EPGPLogFrame:SetScript("OnSizeChanged", LogChanged) scrollBar:SetScript( "OnVerticalScroll", function(self, value) FauxScrollFrame_OnVerticalScroll(scrollBar, value, recordHeight, LogChanged) end) EPGP:GetModule("log"):RegisterCallback("LogChanged", LogChanged) end local function EPGPSideFrameGPDropDown_SetList(dropDown) local list = {} for i=1,GP:GetNumRecentItems() do tinsert(list, GP:GetRecentItemLink(i)) end local empty = #list == 0 if empty then list[1] = EMPTY end dropDown:SetList(list) dropDown:SetItemDisabled(1, empty) if empty then dropDown:SetValue(nil) else local text = dropDown.text:GetText() for i=1,#list do if list[i] == text then dropDown:SetValue(i) break end end end end local function AddGPControls(frame) local reasonLabel = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") reasonLabel:SetText(L["GP Reason"]) reasonLabel:SetPoint("TOPLEFT") local dropDown = GUI:Create("Dropdown") dropDown:SetWidth(168) dropDown.frame:SetParent(frame) dropDown:SetPoint("TOP", reasonLabel, "BOTTOM") dropDown:SetPoint("LEFT", frame, "LEFT", 15, 0) dropDown.text:SetJustifyH("LEFT") dropDown:SetCallback( "OnValueChanged", function(self, event, ...) local parent = self.frame:GetParent() local itemLink = self.text:GetText() if itemLink and itemlink ~= "" then local gp1, gp2 = GP:GetValue(itemLink) if not gp1 then parent.editBox:SetText("") elseif not gp2 then parent.editBox:SetText(tostring(gp1)) else parent.editBox:SetText(L["%d or %d"]:format(gp1, gp2)) end parent.editBox:SetFocus() parent.editBox:HighlightText() end end) dropDown.button:HookScript( "OnMouseDown", function(self) if not self.obj.open then EPGPSideFrameGPDropDown_SetList(self.obj) end end) dropDown.button:HookScript( "OnClick", function(self) if self.obj.open then self.obj.pullout:SetWidth(285) end end) dropDown:SetCallback( "OnEnter", function(self) local itemLink = self.text:GetText() if itemLink then local anchor = self.open and self.pullout.frame or self.frame:GetParent() GameTooltip:SetOwner(anchor, "ANCHOR_RIGHT", 5) GameTooltip:SetHyperlink(itemLink) end end) dropDown:SetCallback("OnLeave", function() GameTooltip:Hide() end) local label = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") label:SetText(L["Value"]) label:SetPoint("LEFT", reasonLabel) label:SetPoint("TOP", dropDown.frame, "BOTTOM", 0, -2) local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate") button:SetNormalFontObject("GameFontNormalSmall") button:SetHighlightFontObject("GameFontHighlightSmall") button:SetDisabledFontObject("GameFontDisableSmall") button:SetHeight(BUTTON_HEIGHT) button:SetText(L["Credit GP"]) button:SetWidth(button:GetTextWidth() + BUTTON_TEXT_PADDING) button:SetPoint("RIGHT", dropDown.frame, "RIGHT", 0, 0) button:SetPoint("TOP", label, "BOTTOM") local editBox = CreateFrame("EditBox", "$parentGPControlEditBox", frame, "InputBoxTemplate") editBox:SetFontObject("GameFontHighlightSmall") editBox:SetHeight(24) editBox:SetAutoFocus(false) editBox:SetPoint("LEFT", frame, "LEFT", 25, 0) editBox:SetPoint("RIGHT", button, "LEFT") editBox:SetPoint("TOP", label, "BOTTOM") button:SetScript( "OnUpdate", function(self) if EPGP:CanIncGPBy(dropDown.text:GetText(), editBox:GetNumber()) then self:Enable() else self:Disable() end end) frame:SetHeight( reasonLabel:GetHeight() + dropDown.frame:GetHeight() + label:GetHeight() + button:GetHeight()) frame.reasonLabel = reasonLabel frame.dropDown = dropDown frame.label = label frame.button = button frame.editBox = editBox frame.OnShow = function(self) self.editBox:SetText("") self.dropDown:SetValue(nil) self.dropDown.frame:Show() end end local function EPGPSideFrameEPDropDown_SetList(dropDown) local list = {} local seen = {} local dungeons = {CalendarEventGetTextures(1)} for i=1,#dungeons,4 do if dungeons[i+2] == GetExpansionLevel() and not seen[dungeons[i]] and dungeons[i+3] ~= "Looking For Raid" then seen[dungeons[i]] = true tinsert(list, dungeons[i]) end end tinsert(list, OTHER) dropDown:SetList(list) local text = dropDown.text:GetText() for i=1,#list do if list[i] == text then dropDown:SetValue(i) break end end end local function AddEPControls(frame, withRecurring) local reasonLabel = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") reasonLabel:SetText(L["EP Reason"]) reasonLabel:SetPoint("TOPLEFT") local dropDown = GUI:Create("Dropdown") dropDown:SetWidth(168) dropDown.frame:SetParent(frame) dropDown:SetPoint("TOP", reasonLabel, "BOTTOM") dropDown:SetPoint("LEFT", frame, "LEFT", 15, 0) dropDown.text:SetJustifyH("LEFT") dropDown:SetCallback( "OnValueChanged", function(self, event, ...) local parent = self.frame:GetParent() local reason = self.text:GetText() local other = reason == OTHER parent.otherLabel:SetAlpha(other and 1 or 0.25) parent.otherEditBox:SetAlpha(other and 1 or 0.25) parent.otherEditBox:EnableKeyboard(other) parent.otherEditBox:EnableMouse(other) if other then parent.otherEditBox:SetFocus() reason = parent.otherEditBox:GetText() else parent.otherEditBox:ClearFocus() end local last_award = EPGP.db.profile.last_awards[reason] if last_award then parent.editBox:SetText(last_award) end end) dropDown.button:HookScript( "OnMouseDown", function(self) if not self.obj.open then EPGPSideFrameEPDropDown_SetList(self.obj) end end) dropDown.button:HookScript( "OnClick", function(self) if self.obj.open then self.obj.pullout:SetWidth(285) end end) local otherLabel = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") otherLabel:SetText(OTHER) otherLabel:SetPoint("LEFT", reasonLabel) otherLabel:SetPoint("TOP", dropDown.frame, "BOTTOM", 0, -2) local otherEditBox = CreateFrame("EditBox", "$parentEPControlOtherEditBox", frame, "InputBoxTemplate") otherEditBox:SetFontObject("GameFontHighlightSmall") otherEditBox:SetHeight(24) otherEditBox:SetAutoFocus(false) otherEditBox:SetPoint("LEFT", frame, "LEFT", 25, 0) otherEditBox:SetPoint("RIGHT", frame, "RIGHT", -15, 0) otherEditBox:SetPoint("TOP", otherLabel, "BOTTOM") otherEditBox:SetScript( "OnTextChanged", function(self) local last_award = EPGP.db.profile.last_awards[self:GetText()] if last_award then frame.editBox:SetText(last_award) end end) local label = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") label:SetText(L["Value"]) label:SetPoint("LEFT", reasonLabel) label:SetPoint("TOP", otherEditBox, "BOTTOM") local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate") button:SetNormalFontObject("GameFontNormalSmall") button:SetHighlightFontObject("GameFontHighlightSmall") button:SetDisabledFontObject("GameFontDisableSmall") button:SetHeight(BUTTON_HEIGHT) button:SetText(L["Award EP"]) button:SetWidth(button:GetTextWidth() + BUTTON_TEXT_PADDING) button:SetPoint("RIGHT", otherEditBox, "RIGHT") button:SetPoint("TOP", label, "BOTTOM") local editBox = CreateFrame("EditBox", "$parentEPControlEditBox", frame, "InputBoxTemplate") editBox:SetFontObject("GameFontHighlightSmall") editBox:SetHeight(24) editBox:SetAutoFocus(false) editBox:SetPoint("LEFT", frame, "LEFT", 25, 0) editBox:SetPoint("RIGHT", button, "LEFT") editBox:SetPoint("TOP", label, "BOTTOM") local function EnabledStatus(self) local reason = dropDown.text:GetText() if reason == OTHER then reason = otherEditBox:GetText() end local amount = editBox:GetNumber() if EPGP:CanIncEPBy(reason, amount) then self:Enable() else self:Disable() end end button:SetScript("OnUpdate", EnabledStatus) if withRecurring then local recurring = CreateFrame("CheckButton", nil, frame, "UICheckButtonTemplate") recurring:SetWidth(20) recurring:SetHeight(20) recurring:SetPoint("TOP", editBox, "BOTTOMLEFT") recurring:SetPoint("LEFT", reasonLabel) recurring:SetScript( "OnUpdate", function (self) if EPGP:RunningRecurringEP() then self:Enable() else EnabledStatus(self) end end) local label = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") label:SetText(L["Recurring"]) label:SetPoint("LEFT", recurring, "RIGHT") local timePeriod = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") timePeriod:SetJustifyH("RIGHT") local incButton = CreateFrame("Button", nil, frame) incButton:SetNormalTexture( "Interface\\MainMenuBar\\UI-MainMenu-ScrollUpButton-Up") incButton:SetPushedTexture( "Interface\\MainMenuBar\\UI-MainMenu-ScrollUpButton-Down") incButton:SetDisabledTexture( "Interface\\MainMenuBar\\UI-MainMenu-ScrollUpButton-Disabled") incButton:SetWidth(24) incButton:SetHeight(24) local decButton = CreateFrame("Button", nil, frame) decButton:SetNormalTexture( "Interface\\MainMenuBar\\UI-MainMenu-ScrollDownButton-Up") decButton:SetPushedTexture( "Interface\\MainMenuBar\\UI-MainMenu-ScrollDownButton-Down") decButton:SetDisabledTexture( "Interface\\MainMenuBar\\UI-MainMenu-ScrollDownButton-Disabled") decButton:SetWidth(24) decButton:SetHeight(24) decButton:SetPoint("RIGHT", -15, 0) decButton:SetPoint("TOP", recurring, "TOP") incButton:SetPoint("RIGHT", decButton, "LEFT", 8, 0) timePeriod:SetPoint("RIGHT", incButton, "LEFT") function frame:UpdateTimeControls() local period_mins = EPGP:RecurringEPPeriodMinutes() local fmt, val = SecondsToTimeAbbrev(period_mins * 60) timePeriod:SetText(fmt:format(val)) recurring:SetChecked(EPGP:RunningRecurringEP()) if period_mins == 1 or EPGP:RunningRecurringEP() then decButton:Disable() else decButton:Enable() end if EPGP:RunningRecurringEP() then incButton:Disable() else incButton:Enable() end end incButton:SetScript( "OnClick", function(self) local period_mins = EPGP:RecurringEPPeriodMinutes() EPGP:RecurringEPPeriodMinutes(period_mins + 1) self:GetParent():UpdateTimeControls() end) decButton:SetScript( "OnClick", function(self) local period_mins = EPGP:RecurringEPPeriodMinutes() EPGP:RecurringEPPeriodMinutes(period_mins - 1) self:GetParent():UpdateTimeControls() end) frame.recurring = recurring frame.incButton = incButton frame.decButton = decButton end frame:SetHeight( reasonLabel:GetHeight() + dropDown.frame:GetHeight() + otherLabel:GetHeight() + otherEditBox:GetHeight() + label:GetHeight() + button:GetHeight() + (withRecurring and frame.recurring:GetHeight() or 0)) frame.reasonLabel = reasonLabel frame.dropDown = dropDown frame.otherLabel = otherLabel frame.otherEditBox = otherEditBox frame.label = label frame.editBox = editBox frame.button = button frame.OnShow = function(self) self.editBox:SetText("") self.dropDown:SetValue(nil) self.dropDown.frame:Show() self.otherLabel:SetAlpha(0.25) self.otherEditBox:SetAlpha(0.25) self.otherEditBox:EnableKeyboard(false) self.otherEditBox:EnableMouse(false) if self.UpdateTimeControls then self:UpdateTimeControls() end end end local function CreateEPGPSideFrame(self) local f = CreateFrame("Frame", "EPGPSideFrame", EPGPFrame) table.insert(SIDEFRAMES, f) f:Hide() f:SetWidth(225) f:SetHeight(255) f:SetPoint("TOPLEFT", EPGPFrame, "TOPRIGHT", -33, -20) local h = f:CreateTexture(nil, "ARTWORK") h:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Header") h:SetWidth(300) h:SetHeight(68) h:SetPoint("TOP", -9, 12) f.title = f:CreateFontString(nil, "ARTWORK", "GameFontNormal") f.title:SetPoint("TOP", h, "TOP", 0, -15) local t = f:CreateTexture(nil, "OVERLAY") t:SetTexture("Interface\\DialogFrame\\UI-DialogBox-Corner") t:SetWidth(32) t:SetHeight(32) t:SetPoint("TOPRIGHT", f, "TOPRIGHT", -6, -7) f:SetBackdrop( { bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32, insets = { left=11, right=12, top=12, bottom=11 } }) local cb = CreateFrame("Button", nil, f, "UIPanelCloseButton") cb:SetPoint("TOPRIGHT", f, "TOPRIGHT", -2, -3) local gpFrame = CreateFrame("Frame", nil, f) gpFrame:SetPoint("TOPLEFT", f, "TOPLEFT", 15, -30) gpFrame:SetPoint("TOPRIGHT", f, "TOPRIGHT", -15, -30) local epFrame = CreateFrame("Frame", nil, f) epFrame:SetPoint("TOPLEFT", gpFrame, "BOTTOMLEFT", 0, -15) epFrame:SetPoint("TOPRIGHT", gpFrame, "BOTTOMRIGHT", 0, -15) f:SetScript("OnShow", function(self) self.title:SetText(self.name) if not epFrame.button then AddGPControls(gpFrame) gpFrame.button:SetScript( "OnClick", function(self) EPGP:IncGPBy(f.name, gpFrame.dropDown.text:GetText(), gpFrame.editBox:GetNumber()) end) end if not epFrame.button then AddEPControls(epFrame) epFrame.button:SetScript( "OnClick", function(self) local reason = epFrame.dropDown.text:GetText() if reason == OTHER then reason = epFrame.otherEditBox:GetText() end local amount = epFrame.editBox:GetNumber() EPGP:IncEPBy(f.name, reason, amount) end) end if gpFrame.OnShow then gpFrame:OnShow() end if epFrame.OnShow then epFrame:OnShow() end end) end local function CreateEPGPSideFrame2() local f = CreateFrame("Frame", "EPGPSideFrame2", EPGPFrame) table.insert(SIDEFRAMES, f) f:Hide() f:SetWidth(225) f:SetHeight(165) f:SetPoint("BOTTOMLEFT", EPGPFrame, "BOTTOMRIGHT", -33, 72) f:SetBackdrop( { bgFile = "Interface\\DialogFrame\\UI-DialogBox-Background", edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border", tile = true, tileSize = 32, edgeSize = 32, insets = { left=11, right=12, top=12, bottom=11 } }) local cb = CreateFrame("Button", nil, f, "UIPanelCloseButton") cb:SetPoint("TOPRIGHT", f, "TOPRIGHT", -2, -3) local epFrame = CreateFrame("Frame", nil, f) epFrame:SetPoint("TOPLEFT", f, "TOPLEFT", 15, -15) epFrame:SetPoint("TOPRIGHT", f, "TOPRIGHT", -15, -15) epFrame:SetScript("OnShow", function() if not epFrame.button then AddEPControls(epFrame, true) epFrame.button:SetScript( "OnClick", function(self) local reason = epFrame.dropDown.text:GetText() if reason == OTHER then reason = epFrame.otherEditBox:GetText() end local amount = epFrame.editBox:GetNumber() EPGP:IncMassEPBy(reason, amount) end) epFrame.recurring:SetScript( "OnClick", function(self) if not EPGP:RunningRecurringEP() then local reason = epFrame.dropDown.text:GetText() if reason == OTHER then reason = epFrame.otherEditBox:GetText() end local amount = epFrame.editBox:GetNumber() EPGP:StartRecurringEP(reason, amount) else EPGP:StopRecurringEP() end self:GetParent():UpdateTimeControls() end) end if epFrame.OnShow then epFrame:OnShow() end end) end local function CreateEPGPFrameStandings() -- Make the show everyone checkbox local f = CreateFrame("Frame", nil, EPGPFrame) f:SetHeight(28) f:SetPoint("TOPRIGHT", EPGPFrame, "TOPRIGHT", -42, -38) local tr = f:CreateTexture(nil, "BACKGROUND") tr:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-FilterBorder") tr:SetWidth(12) tr:SetHeight(28) tr:SetPoint("TOPRIGHT") tr:SetTexCoord(0.90625, 1, 0, 1) local tl = f:CreateTexture(nil, "BACKGROUND") tl:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-FilterBorder") tl:SetWidth(12) tl:SetHeight(28) tl:SetPoint("TOPLEFT") tl:SetTexCoord(0, 0.09375, 0, 1) local tm = f:CreateTexture(nil, "BACKGROUND") tm:SetTexture("Interface\\ClassTrainerFrame\\UI-ClassTrainer-FilterBorder") tm:SetHeight(28) tm:SetPoint("RIGHT", tr, "LEFT") tm:SetPoint("LEFT", tl, "RIGHT") tm:SetTexCoord(0.09375, 0.90625, 0, 1) local cb = CreateFrame("CheckButton", nil, f, "UICheckButtonTemplate") cb:SetWidth(20) cb:SetHeight(20) cb:SetPoint("RIGHT", f, "RIGHT", -8, 0) cb:SetScript( "OnShow", function(self) self:SetChecked(EPGP:StandingsShowEveryone()) end) cb:SetScript( "OnClick", function(self) EPGP:StandingsShowEveryone(not not self:GetChecked()) end) local t = cb:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall") t:SetText(L["Show everyone"]) t:SetPoint("RIGHT", cb, "LEFT", 0, 2) f:SetWidth(t:GetStringWidth() + 4 * tl:GetWidth() + cb:GetWidth()) local function HideWhileNotInRaid(self) if UnitInRaid("player") then self:Show() else self:Hide() end end f:RegisterEvent("RAID_ROSTER_UPDATE") f:SetScript("OnEvent", HideWhileNotInRaid) f:SetScript("OnShow", HideWhileNotInRaid) -- Make the log frame CreateEPGPLogFrame() -- Make the side frame CreateEPGPSideFrame() -- Make the second side frame CreateEPGPSideFrame2() -- Make the main frame local main = CreateFrame("Frame", nil, EPGPFrame) main:SetWidth(325) main:SetHeight(358) main:SetPoint("TOPLEFT", EPGPFrame, 19, -72) local award = CreateFrame("Button", nil, main, "UIPanelButtonTemplate") award:SetNormalFontObject("GameFontNormalSmall") award:SetHighlightFontObject("GameFontHighlightSmall") award:SetDisabledFontObject("GameFontDisableSmall") award:SetHeight(BUTTON_HEIGHT) award:SetPoint("BOTTOMLEFT") award:SetText(L["Mass EP Award"]) award:SetWidth(award:GetTextWidth() + BUTTON_TEXT_PADDING) award:RegisterEvent("RAID_ROSTER_UPDATE") award:SetScript( "OnClick", function() ToggleOnlySideFrame(EPGPSideFrame2) end) local log = CreateFrame("Button", nil, main, "UIPanelButtonTemplate") log:SetNormalFontObject("GameFontNormalSmall") log:SetHighlightFontObject("GameFontHighlightSmall") log:SetDisabledFontObject("GameFontDisableSmall") log:SetHeight(BUTTON_HEIGHT) log:SetPoint("BOTTOMRIGHT") log:SetText(GUILD_BANK_LOG) log:SetWidth(log:GetTextWidth() + BUTTON_TEXT_PADDING) log:SetScript( "OnClick", function(self, button, down) ToggleOnlySideFrame(EPGPLogFrame) end) local decay = CreateFrame("Button", nil, main, "UIPanelButtonTemplate") decay:SetNormalFontObject("GameFontNormalSmall") decay:SetHighlightFontObject("GameFontHighlightSmall") decay:SetDisabledFontObject("GameFontDisableSmall") decay:SetHeight(BUTTON_HEIGHT) decay:SetPoint("RIGHT", log, "LEFT") decay:SetText(L["Decay"]) decay:SetWidth(decay:GetTextWidth() + BUTTON_TEXT_PADDING) decay:SetScript( "OnClick", function(self, button, down) DLG:Spawn("EPGP_DECAY_EPGP", EPGP:GetDecayPercent()) end) decay:SetScript( "OnUpdate", function(self) if EPGP:CanDecayEPGP() then self:Enable() else self:Disable() end end) local fontHeight = select(2, GameFontNormal:GetFont()) local recurringTime = main:CreateFontString(nil, "OVERLAY", "GameFontNormal") recurringTime:SetHeight(fontHeight) recurringTime:SetJustifyH("CENTER") recurringTime:SetPoint("LEFT", award, "RIGHT") recurringTime:SetPoint("RIGHT", decay, "LEFT") recurringTime:Hide() function recurringTime:StartRecurringAward() self:Show() end function recurringTime:ResumeRecurringAward() self:Show() end function recurringTime:StopRecurringAward() self:Hide() end function recurringTime:RecurringAwardUpdate( event_type, reason, amount, time_left) local fmt, val = SecondsToTimeAbbrev(time_left) self:SetFormattedText(L["Next award in "] .. fmt, val) end EPGP.RegisterCallback(recurringTime, "StartRecurringAward") EPGP.RegisterCallback(recurringTime, "ResumeRecurringAward") EPGP.RegisterCallback(recurringTime, "StopRecurringAward") EPGP.RegisterCallback(recurringTime, "RecurringAwardUpdate") -- Make the status text local statusText = main:CreateFontString(nil, "ARTWORK", "GameFontNormal") statusText:SetHeight(fontHeight) statusText:SetJustifyH("CENTER") statusText:SetPoint("BOTTOMLEFT", award, "TOPLEFT") statusText:SetPoint("BOTTOMRIGHT", log, "TOPRIGHT") function statusText:TextUpdate() self:SetFormattedText( L["Decay=%s%% BaseGP=%s MinEP=%s Extras=%s%%"], "|cFFFFFFFF"..EPGP:GetDecayPercent().."|r", "|cFFFFFFFF"..EPGP:GetBaseGP().."|r", "|cFFFFFFFF"..EPGP:GetMinEP().."|r", "|cFFFFFFFF"..EPGP:GetExtrasPercent().."|r") end EPGP.RegisterCallback(statusText, "DecayPercentChanged", "TextUpdate") EPGP.RegisterCallback(statusText, "BaseGPChanged", "TextUpdate") EPGP.RegisterCallback(statusText, "MinEPChanged", "TextUpdate") EPGP.RegisterCallback(statusText, "ExtrasPercentChanged", "TextUpdate") -- Make the mode text local modeText = main:CreateFontString(nil, "ARTWORK", "GameFontNormal") modeText:SetHeight(fontHeight) modeText:SetJustifyH("CENTER") modeText:SetPoint("BOTTOMLEFT", statusText, "TOPLEFT") modeText:SetPoint("BOTTOMRIGHT", statusText, "TOPRIGHT") function modeText:TextUpdate() local mode if UnitInRaid("player") then mode = "|cFFFF0000"..RAID.."|r" else mode = "|cFF00FF00"..GUILD.."|r" end self:SetFormattedText("%s (%s)", mode, "|cFFFFFFFF"..EPGP:GetNumMembersInAwardList().."|r") end -- Make the table frame local tabl = CreateFrame("Frame", nil, main) tabl:SetPoint("TOPLEFT") tabl:SetPoint("TOPRIGHT") tabl:SetPoint("BOTTOM", modeText, "TOP") -- Also hook the status texts to update on show tabl:SetScript( "OnShow", function (self) statusText:TextUpdate() modeText:TextUpdate() end) -- Populate the table CreateTable(tabl, {"Name", "EP", "GP", "PR"}, {0, 64, 64, 64}, {"LEFT", "RIGHT", "RIGHT", "RIGHT"}, 27) -- The scrollBarWidth -- Make the scrollbar local rowFrame = tabl.rowFrame rowFrame.needUpdate = true local scrollBar = CreateFrame("ScrollFrame", "EPGPScrollFrame", rowFrame, "FauxScrollFrameTemplateLight") scrollBar:SetWidth(rowFrame:GetWidth()) scrollBar:SetPoint("TOPRIGHT", rowFrame, "TOPRIGHT", 0, -2) scrollBar:SetPoint("BOTTOMRIGHT") -- Make all our rows have a check on them and setup the OnClick -- handler for each row. for i,r in ipairs(rowFrame.rows) do r.check = r:CreateTexture(nil, "BACKGROUND") r.check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check") r.check:SetWidth(r:GetHeight()) r.check:SetHeight(r:GetHeight()) r.check:SetPoint("RIGHT", r.cells[1]) r:RegisterForClicks("LeftButtonDown") r:SetScript( "OnClick", function(self, value) if IsModifiedClick("QUESTWATCHTOGGLE") then if self.check:IsShown() then EPGP:DeSelectMember(self.name) else EPGP:SelectMember(self.name) end else if EPGPSideFrame.name ~= self.name then self:LockHighlight() EPGPSideFrame:Hide() EPGPSideFrame.name = self.name end ToggleOnlySideFrame(EPGPSideFrame) end end) r:SetScript( "OnEnter", function(self) GameTooltip_SetDefaultAnchor(GameTooltip, self) GameTooltip:AddLine(GS:GetRank(self.name)) if EPGP:GetNumAlts(self.name) > 0 then GameTooltip:AddLine("\n"..L["Alts"]) for i=1,EPGP:GetNumAlts(self.name) do GameTooltip:AddLine(Ambiguate(EPGP:GetAlt(self.name, i), "short"), 1, 1, 1) end end GameTooltip:ClearAllPoints() GameTooltip:SetPoint("TOPLEFT", self, "TOPRIGHT") GameTooltip:Show() end) r:SetScript("OnLeave", function() GameTooltip:Hide() end) end -- Hook up the headers tabl.headers[1]:SetScript( "OnClick", function(self) EPGP:StandingsSort("NAME") end) tabl.headers[2]:SetScript( "OnClick", function(self) EPGP:StandingsSort("EP") end) tabl.headers[3]:SetScript( "OnClick", function(self) EPGP:StandingsSort("GP") end) tabl.headers[4]:SetScript( "OnClick", function(self) EPGP:StandingsSort("PR") end) -- Install the update function on rowFrame. local function UpdateStandings() if not rowFrame.needUpdate then return end modeText:TextUpdate() local offset = FauxScrollFrame_GetOffset(EPGPScrollFrame) local numMembers = EPGP:GetNumMembers() local numDisplayedMembers = math.min(#rowFrame.rows, numMembers - offset) local minEP = EPGP:GetMinEP() for i=1,#rowFrame.rows do local row = rowFrame.rows[i] local j = i + offset if j <= numMembers then row.name = EPGP:GetMember(j) row.cells[1]:SetText(Ambiguate(row.name, "short")) local c = RAID_CLASS_COLORS[EPGP:GetClass(row.name)] row.cells[1]:SetTextColor(c.r, c.g, c.b) local ep, gp = EPGP:GetEPGP(row.name) row.cells[2]:SetText(ep) row.cells[3]:SetText(gp) local pr = 0 if gp then pr = ep / gp end if pr > 9999 then row.cells[4]:SetText(math.floor(pr)) else row.cells[4]:SetFormattedText("%.4g", pr) end row.check:Hide() if UnitInRaid("player") and EPGP:StandingsShowEveryone() then if EPGP:IsMemberInAwardList(row.name) then row.check:Show() end elseif EPGP:IsAnyMemberInExtrasList() then if EPGP:IsMemberInAwardList(row.name) then row.check:Show() end end row:SetAlpha(ep < minEP and 0.6 or 1) row:Show() else row:Hide() end -- Fix the highlighting of the rows if row.name == EPGPSideFrame.name then row:LockHighlight() else row:UnlockHighlight() end end FauxScrollFrame_Update(EPGPScrollFrame, numMembers, numDisplayedMembers, rowFrame.rowHeight, nil, nil, nil, nil, nil, nil, true) EPGPSideFrame:SetScript( "OnHide", function(self) self.name = nil rowFrame.needUpdate = true UpdateStandings() end) rowFrame.needUpdate = nil end rowFrame:SetScript("OnUpdate", UpdateStandings) EPGP.RegisterCallback(rowFrame, "StandingsChanged", function() rowFrame.needUpdate = true end) rowFrame:SetScript("OnShow", UpdateStandings) scrollBar:SetScript( "OnVerticalScroll", function(self, value) rowFrame.needUpdate = true FauxScrollFrame_OnVerticalScroll( self, value, rowFrame.rowHeight, UpdateStandings) end) end function mod:OnEnable() if not EPGPFrame then CreateEPGPFrame() CreateEPGPFrameStandings() CreateEPGPExportImportFrame() end HideUIPanel(EPGPFrame) EPGPFrame:SetScript("OnShow", GuildRoster) end
bsd-3-clause
kitala1/darkstar
scripts/zones/Upper_Jeuno/npcs/Rouliette.lua
17
2205
----------------------------------- -- Area: Upper Jeuno -- NPC: Rouliette -- Starts and Finishes Quest: Candle-making -- @zone 244 -- @pos -24 -2 11 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,CANDLE_MAKING) == QUEST_ACCEPTED and trade:hasItemQty(531,1) == true and trade:getItemCount() == 1) then player:startEvent(0x0025); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --Prerequisites for this quest : A_CANDLELIGHT_VIGIL ACCEPTED if(player:getQuestStatus(JEUNO,CANDLE_MAKING) ~= QUEST_COMPLETED and player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL) == QUEST_ACCEPTED) then player:startEvent(0x0024); -- Start Quest Candle-making else player:startEvent(0x001e); --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 == 0x0024 and player:getQuestStatus(JEUNO,CANDLE_MAKING) == QUEST_AVAILABLE) then player:addQuest(JEUNO,CANDLE_MAKING); elseif(csid == 0x0025) then player:addTitle(BELIEVER_OF_ALTANA); player:addKeyItem(HOLY_CANDLE); player:messageSpecial(KEYITEM_OBTAINED,HOLY_CANDLE); player:addFame(JEUNO, JEUNO_FAME*30); player:tradeComplete(trade); player:completeQuest(JEUNO,CANDLE_MAKING); end end;
gpl-3.0
cjkoenig/packages
net/luci-app-e2guardian/files/e2guardian-cbi.lua
55
18594
--[[ LuCI E2Guardian module Copyright (C) 2015, Itus Networks, Inc. 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 Author: Marko Ratkaj <marko.ratkaj@sartura.hr> Luka Perkov <luka.perkov@sartura.hr> ]]-- local fs = require "nixio.fs" local sys = require "luci.sys" m = Map("e2guardian", translate("E2Guardian")) m.on_after_commit = function() luci.sys.call("/etc/init.d/e2guardian restart") end s = m:section(TypedSection, "e2guardian") s.anonymous = true s.addremove = false s:tab("tab_general", translate("General Settings")) s:tab("tab_additional", translate("Additional Settings")) s:tab("tab_logs", translate("Logs")) ----------------- General Settings Tab ----------------------- filterip = s:taboption("tab_general", Value, "filterip", translate("IP that E2Guardian listens")) filterip.datatype = "ip4addr" filterports = s:taboption("tab_general", Value, "filterports", translate("Port that E2Guardian listens")) filterports.datatype = "portrange" filterports.placeholder = "0-65535" proxyip = s:taboption("tab_general", Value, "proxyip", translate("IP address of the proxy")) proxyip.datatype = "ip4addr" proxyip.default = "127.0.0.1" proxyport = s:taboption("tab_general", Value, "proxyport", translate("Port of the proxy")) proxyport.datatype = "portrange" proxyport.placeholder = "0-65535" languagedir = s:taboption("tab_general", Value, "languagedir", translate("Language dir")) languagedir.datatype = "string" languagedir.default = "/usr/share/e2guardian/languages" language = s:taboption("tab_general", Value, "language", translate("Language to use")) language.datatype = "string" language.default = "ukenglish" loglevel = s:taboption("tab_general", ListValue, "loglevel", translate("Logging Settings")) loglevel:value("0", translate("none")) loglevel:value("1", translate("just denied")) loglevel:value("2", translate("all text based")) loglevel:value("3", translate("all requests")) loglevel.default = "2" logexceptionhits = s:taboption("tab_general", ListValue, "logexceptionhits", translate("Log Exception Hits")) logexceptionhits:value("0", translate("never")) logexceptionhits:value("1", translate("log, but dont mark as exceptions")) logexceptionhits:value("2", translate("log and mark")) logexceptionhits.default = "2" logfileformat = s:taboption("tab_general", ListValue, "logfileformat", translate("Log File Format")) logfileformat:value("1", translate("DansgGuardian format, space delimited")) logfileformat:value("2", translate("CSV-style format")) logfileformat:value("3", translate("Squid Log File Format")) logfileformat:value("4", translate("Tab delimited")) logfileformat:value("5", translate("Protex format")) logfileformat:value("6", translate("Protex format with server field blanked")) logfileformat.default = "1" accessdeniedaddress = s:taboption("tab_general", Value, "accessdeniedaddress", translate("Access denied address"), translate("Server to which the cgi e2guardian reporting script was copied. Reporting levels 1 and 2 only")) accessdeniedaddress.datatype = "string" accessdeniedaddress.default = "http://YOURSERVER.YOURDOMAIN/cgi-bin/e2guardian.pl" usecustombannedimage = s:taboption("tab_general", ListValue, "usecustombannedimage", translate("Banned image replacement")) usecustombannedimage:value("on", translate("Yes")) usecustombannedimage:value("off", translate("No")) usecustombannedimage.default = "on" custombannedimagefile = s:taboption("tab_general", Value, "custombannedimagefile", translate("Custom banned image file")) custombannedimagefile.datatype = "string" custombannedimagefile.default = "/usr/share/e2guardian/transparent1x1.gif" usecustombannedflash = s:taboption("tab_general", ListValue, "usecustombannedflash", translate("Banned flash replacement")) usecustombannedflash:value("on", translate("Yes")) usecustombannedflash:value("off", translate("No")) usecustombannedflash.default = "on" custombannedflashfile = s:taboption("tab_general", Value, "custombannedflashfile", translate("Custom banned flash file")) custombannedflashfile.datatype = "string" custombannedflashfile.default = "/usr/share/e2guardian/blockedflash.swf" filtergroups = s:taboption("tab_general", Value, "filtergroups", translate("Number of filter groups")) filtergroups.datatype = "and(uinteger,min(1))" filtergroups.default = "1" filtergroupslist = s:taboption("tab_general", Value, "filtergroupslist", translate("List of filter groups")) filtergroupslist.datatype = "string" filtergroupslist.default = "/etc/e2guardian/lists/filtergroupslist" bannediplist = s:taboption("tab_general", Value, "bannediplist", translate("List of banned IPs")) bannediplist.datatype = "string" bannediplist.default = "/etc/e2guardian/lists/bannediplist" exceptioniplist = s:taboption("tab_general", Value, "exceptioniplist", translate("List of IP exceptions")) exceptioniplist.datatype = "string" exceptioniplist.default = "/etc/e2guardian/lists/exceptioniplist" perroomblockingdirectory = s:taboption("tab_general", Value, "perroomblockingdirectory", translate("Per-Room blocking definition directory")) perroomblockingdirectory.datatype = "string" perroomblockingdirectory.default = "/etc/e2guardian/lists/bannedrooms/" showweightedfound = s:taboption("tab_general", ListValue, "showweightedfound", translate("Show weighted phrases found")) showweightedfound:value("on", translate("Yes")) showweightedfound:value("off", translate("No")) showweightedfound.default = "on" weightedphrasemode = s:taboption("tab_general", ListValue, "weightedphrasemode", translate("Weighted phrase mode")) weightedphrasemode:value("0", translate("off")) weightedphrasemode:value("1", translate("on, normal operation")) weightedphrasemode:value("2", translate("on, phrase found only counts once on a page")) weightedphrasemode.default = "2" urlcachenumber = s:taboption("tab_general", Value, "urlcachenumber", translate("Clean result caching for URLs")) urlcachenumber.datatype = "and(uinteger,min(0))" urlcachenumber.default = "1000" urlcacheage = s:taboption("tab_general", Value, "urlcacheage", translate("Age before they should be ignored in seconds")) urlcacheage.datatype = "and(uinteger,min(0))" urlcacheage.default = "900" scancleancache = s:taboption("tab_general", ListValue, "scancleancache", translate("Cache for content (AV) scans as 'clean'")) scancleancache:value("on", translate("Yes")) scancleancache:value("off", translate("No")) scancleancache.default = "on" phrasefiltermode = s:taboption("tab_general", ListValue, "phrasefiltermode", translate("Filtering options")) phrasefiltermode:value("0", translate("raw")) phrasefiltermode:value("1", translate("smart")) phrasefiltermode:value("2", translate("both raw and smart")) phrasefiltermode:value("3", translate("meta/title")) phrasefiltermode.default = "2" preservecase = s:taboption("tab_general", ListValue, "perservecase", translate("Lower caseing options")) preservecase:value("0", translate("force lower case")) preservecase:value("1", translate("dont change")) preservecase:value("2", translate("scan fist in lower, then in original")) preservecase.default = "0" hexdecodecontent = s:taboption("tab_general", ListValue, "hexdecodecontent", translate("Hex decoding options")) hexdecodecontent:value("on", translate("Yes")) hexdecodecontent:value("off", translate("No")) hexdecodecontent.default = "off" forcequicksearch = s:taboption("tab_general", ListValue, "forcequicksearch", translate("Quick search")) forcequicksearch:value("on", translate("Yes")) forcequicksearch:value("off", translate("No")) forcequicksearch.default = "off" reverseaddresslookups= s:taboption("tab_general", ListValue, "reverseaddresslookups", translate("Reverse lookups for banned site and URLs")) reverseaddresslookups:value("on", translate("Yes")) reverseaddresslookups:value("off", translate("No")) reverseaddresslookups.default = "off" reverseclientiplookups = s:taboption("tab_general", ListValue, "reverseclientiplookups", translate("Reverse lookups for banned and exception IP lists")) reverseclientiplookups:value("on", translate("Yes")) reverseclientiplookups:value("off", translate("No")) reverseclientiplookups.default = "off" logclienthostnames = s:taboption("tab_general", ListValue, "logclienthostnames", translate("Perform reverse lookups on client IPs for successful requests")) logclienthostnames:value("on", translate("Yes")) logclienthostnames:value("off", translate("No")) logclienthostnames.default = "off" createlistcachefiles = s:taboption("tab_general", ListValue, "createlistcachefiles", translate("Build bannedsitelist and bannedurllist cache files")) createlistcachefiles:value("on",translate("Yes")) createlistcachefiles:value("off",translate("No")) createlistcachefiles.default = "on" prefercachedlists = s:taboption("tab_general", ListValue, "prefercachedlists", translate("Prefer cached list files")) prefercachedlists:value("on", translate("Yes")) prefercachedlists:value("off", translate("No")) prefercachedlists.default = "off" maxuploadsize = s:taboption("tab_general", Value, "maxuploadsize", translate("Max upload size (in Kbytes)")) maxuploadsize:value("-1", translate("no blocking")) maxuploadsize:value("0", translate("complete block")) maxuploadsize.default = "-1" maxcontentfiltersize = s:taboption("tab_general", Value, "maxcontentfiltersize", translate("Max content filter size"), translate("The value must not be higher than max content ram cache scan size or 0 to match it")) maxcontentfiltersize.datatype = "and(uinteger,min(0))" maxcontentfiltersize.default = "256" maxcontentramcachescansize = s:taboption("tab_general", Value, "maxcontentramcachescansize", translate("Max content ram cache scan size"), translate("This is the max size of file that DG will download and cache in RAM")) maxcontentramcachescansize.datatype = "and(uinteger,min(0))" maxcontentramcachescansize.default = "2000" maxcontentfilecachescansize = s:taboption("tab_general", Value, "maxcontentfilecachescansize", translate("Max content file cache scan size")) maxcontentfilecachescansize.datatype = "and(uinteger,min(0))" maxcontentfilecachescansize.default = "20000" proxytimeout = s:taboption("tab_general", Value, "proxytimeout", translate("Proxy timeout (5-100)")) proxytimeout.datatype = "range(5,100)" proxytimeout.default = "20" proxyexchange = s:taboption("tab_general", Value, "proxyexchange", translate("Proxy header excahnge (20-300)")) proxyexchange.datatype = "range(20,300)" proxyexchange.default = "20" pcontimeout = s:taboption("tab_general", Value, "pcontimeout", translate("Pconn timeout"), translate("How long a persistent connection will wait for other requests")) pcontimeout.datatype = "range(5,300)" pcontimeout.default = "55" filecachedir = s:taboption("tab_general", Value, "filecachedir", translate("File cache directory")) filecachedir.datatype = "string" filecachedir.default = "/tmp" deletedownloadedtempfiles = s:taboption("tab_general", ListValue, "deletedownloadedtempfiles", translate("Delete file cache after user completes download")) deletedownloadedtempfiles:value("on", translate("Yes")) deletedownloadedtempfiles:value("off", translate("No")) deletedownloadedtempfiles.default = "on" initialtrickledelay = s:taboption("tab_general", Value, "initialtrickledelay", translate("Initial Trickle delay"), translate("Number of seconds a browser connection is left waiting before first being sent *something* to keep it alive")) initialtrickledelay.datatype = "and(uinteger,min(0))" initialtrickledelay.default = "20" trickledelay = s:taboption("tab_general", Value, "trickledelay", translate("Trickle delay"), translate("Number of seconds a browser connection is left waiting before being sent more *something* to keep it alive")) trickledelay.datatype = "and(uinteger,min(0))" trickledelay.default = "10" downloadmanager = s:taboption("tab_general", Value, "downloadmanager", translate("Download manager")) downloadmanager.datatype = "string" downloadmanager.default = "/etc/e2guardian/downloadmanagers/default.conf" contentscannertimeout = s:taboption("tab_general", Value, "contentscannertimeout", translate("Content scanner timeout")) contentscannertimeout.datatype = "and(uinteger,min(0))" contentscannertimeout.default = "60" contentscanexceptions = s:taboption("tab_general", ListValue, "contentscanexceptions", translate("Content scan exceptions")) contentscanexceptions:value("on", translate("Yes")) contentscanexceptions:value("off", translate("No")) contentscanexceptions.default = "off" recheckreplacedurls = s:taboption("tab_general", ListValue, "recheckreplacedurls", translate("e-check replaced URLs")) recheckreplacedurls:value("on", translate("Yes")) recheckreplacedurls:value("off", translate("No")) recheckreplacedurls.default = "off" forwardedfor = s:taboption("tab_general", ListValue, "forwardedfor", translate("Misc setting: forwardedfor"), translate("If on, it may help solve some problem sites that need to know the source ip.")) forwardedfor:value("on", translate("Yes")) forwardedfor:value("off", translate("No")) forwardedfor.default = "off" usexforwardedfor = s:taboption("tab_general", ListValue, "usexforwardedfor", translate("Misc setting: usexforwardedfor"), translate("This is for when you have squid between the clients and E2Guardian")) usexforwardedfor:value("on", translate("Yes")) usexforwardedfor:value("off", translate("No")) usexforwardedfor.default = "off" logconnectionhandlingerrors = s:taboption("tab_general", ListValue, "logconnectionhandlingerrors", translate("Log debug info about log()ing and accept()ing")) logconnectionhandlingerrors:value("on", translate("Yes")) logconnectionhandlingerrors:value("off", translate("No")) logconnectionhandlingerrors.default = "on" logchildprocesshandling = s:taboption("tab_general", ListValue, "logchildprocesshandling", translate("Log child process handling")) logchildprocesshandling:value("on", translate("Yes")) logchildprocesshandling:value("off", translate("No")) logchildprocesshandling.default = "off" maxchildren = s:taboption("tab_general", Value, "maxchildren", translate("Max number of processes to spawn")) maxchildren.datatype = "and(uinteger,min(0))" maxchildren.default = "180" minchildren = s:taboption("tab_general", Value, "minchildren", translate("Min number of processes to spawn")) minchildren.datatype = "and(uinteger,min(0))" minchildren.default = "20" minsparechildren = s:taboption("tab_general", Value, "minsparechildren", translate("Min number of processes to keep ready")) minsparechildren.datatype = "and(uinteger,min(0))" minsparechildren.default = "16" preforkchildren = s:taboption("tab_general", Value, "preforkchildren", translate("Sets minimum nuber of processes when it runs out")) preforkchildren.datatype = "and(uinteger,min(0))" preforkchildren.default = "10" maxsparechildren = s:taboption("tab_general", Value, "maxsparechildren", translate("Sets the maximum number of processes to have doing nothing")) maxsparechildren.datatype = "and(uinteger,min(0))" maxsparechildren.default = "32" maxagechildren = s:taboption("tab_general", Value, "maxagechildren", translate("Max age of child process")) maxagechildren.datatype = "and(uinteger,min(0))" maxagechildren.default = "500" maxips = s:taboption("tab_general", Value, "maxips", translate("Max number of clinets allowed to connect")) maxips:value("0", translate("no limit")) maxips.default = "0" ipipcfilename = s:taboption("tab_general", Value, "ipipcfilename", translate("IP list IPC server directory and filename")) ipipcfilename.datatype = "string" ipipcfilename.default = "/tmp/.dguardianipc" urlipcfilename = s:taboption("tab_general", Value, "urlipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process")) urlipcfilename.datatype = "string" urlipcfilename.default = "/tmp/.dguardianurlipc" ipcfilename = s:taboption("tab_general", Value, "ipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process")) ipcfilename.datatype = "string" ipcfilename.default = "/tmp/.dguardianipipc" nodeamon = s:taboption("tab_general", ListValue, "nodeamon", translate("Disable deamoning")) nodeamon:value("on", translate("Yes")) nodeamon:value("off", translate("No")) nodeamon.default = "off" nologger = s:taboption("tab_general", ListValue, "nologger", translate("Disable logger")) nologger:value("on", translate("Yes")) nologger:value("off", translate("No")) nologger.default = "off" logadblock = s:taboption("tab_general", ListValue, "logadblock", translate("Enable logging of ADs")) logadblock:value("on", translate("Yes")) logadblock:value("off", translate("No")) logadblock.default = "off" loguseragent = s:taboption("tab_general", ListValue, "loguseragent", translate("Enable logging of client user agent")) loguseragent:value("on", translate("Yes")) loguseragent:value("off", translate("No")) loguseragent.default = "off" softrestart = s:taboption("tab_general", ListValue, "softrestart", translate("Enable soft restart")) softrestart:value("on", translate("Yes")) softrestart:value("off", translate("No")) softrestart.default = "off" ------------------------ Additional Settings Tab ---------------------------- e2guardian_config_file = s:taboption("tab_additional", TextValue, "_data", "") e2guardian_config_file.wrap = "off" e2guardian_config_file.rows = 25 e2guardian_config_file.rmempty = false function e2guardian_config_file.cfgvalue() local uci = require "luci.model.uci".cursor_state() file = "/etc/e2guardian/e2guardianf1.conf" if file then return fs.readfile(file) or "" else return "" end end function e2guardian_config_file.write(self, section, value) if value then local uci = require "luci.model.uci".cursor_state() file = "/etc/e2guardian/e2guardianf1.conf" fs.writefile(file, value:gsub("\r\n", "\n")) end end ---------------------------- Logs Tab ----------------------------- e2guardian_logfile = s:taboption("tab_logs", TextValue, "lines", "") e2guardian_logfile.wrap = "off" e2guardian_logfile.rows = 25 e2guardian_logfile.rmempty = true function e2guardian_logfile.cfgvalue() local uci = require "luci.model.uci".cursor_state() file = "/tmp/e2guardian/access.log" if file then return fs.readfile(file) or "" else return "Can't read log file" end end function e2guardian_logfile.write() return "" end return m
gpl-2.0
umbrellaTG/sphero
plugins/p2s.lua
1
1120
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local file = '/root/robot/data/stickers/'..msg.from.id..'.webp' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) send_document(get_receiver(msg), file, ok_cb, false) redis:del("photo:sticker") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and redis:get("photo:sticker") then if redis:get("photo:sticker") == 'waiting' then load_photo(msg.id, tosticker, msg) end end end if matches[1] == "tosticker" then redis:set("photo:sticker", "waiting") return 'Please send your photo now' end end return { descroption = "photo too sticker", usage = { "!tosticker : create sticker by photo", }, patterns = { "^[!/](tosticker)$", "%[(photo)%]", }, run = run, }
gpl-2.0
kitala1/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Komalata.lua
37
1496
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Komalata -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,KOMALATA_SHOP_DIALOG); stock = {0x1118,110, -- Meat Jerky 0x03a8,14, -- Rock Salt 0x0263,36, -- Rye Flour 0x119d,10, -- Distilled Water 0x0271,91, -- Apple Vinegar (COP 4+ only) 0x110c,110, -- Black Bread (COP 4+ only) 0x0262,55, -- San d'Orian Flour (COP 4+ only) 0x1125,29, -- San d'Orian Carrot (COP 4+ only) 0x0275,44, -- Millioncorn (COP 4+ only) 0x05f3,290} -- Apple Mint (COP 4+ only) 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
kitala1/darkstar
scripts/zones/Attohwa_Chasm/mobs/Alastor_Antlion.lua
14
1929
----------------------------------- -- Area: Attohwa Chasm -- NPC: Alastor Antlion -- ID: ----------------------------------- ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); mob:setMobMod(MOBMOD_GA_CHANCE,50); mob:setMobMod(MOBMOD_MUG_GIL,10000); mob:addMod(MOD_FASTCAST,10); mob:addMod(MOD_BINDRES,40); mob:addMod(MOD_SILENCERES,40); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setTP(100); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob, killer) mob:useMobAbility(22); -- Pit Ambush end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) end; ----------------------------------- -- onAdditionalEffect ----------------------------------- function onAdditionalEffect(mob, player) local chance = 25; local resist = applyResistanceAddEffect(mob,player,ELE_EARTH,EFFECT_PETRIFICATION); if (math.random(0,99) >= chance or resist <= 0.5) then return 0,0,0; else local duration = 30; if (mob:getMainLvl() > player:getMainLvl()) then duration = duration + (mob:getMainLvl() - player:getMainLvl()) end utils.clamp(duration,1,45); duration = duration * resist; if (not player:hasStatusEffect(EFFECT_PETRIFICATION)) then player:addStatusEffect(EFFECT_PETRIFICATION, 1, 0, duration); end return SUBEFFECT_PETRIFY, 160, EFFECT_PETRIFICATION; end end;
gpl-3.0
marczych/PeggleDamacy
states/play.lua
1
5707
local BallParticle = require "entities.ballparticle" local BackGround = require "entities.background" local Cannon = require "entities.cannon" local Bucket = require "entities.bucket" local Ball = require "entities.ball" local Peg = require "entities.peg" local Hud = require "entities.hud" local background local blueBucket local ball local pegs local score local hud local availableSpectrum local ballsRemaining local powerupCharges local trailParticles local lastTrailParticleTime local flash local Play = {} local pegsCollected function Play:enter() pegs = {} -- Initialize all of the pegs for i = 1, Constants.NUM_STARTING_PEGS do newPeg = Peg() newPeg.position = Utils.randomPegLocation(pegs) table.insert(pegs, newPeg) end score = 0 powerupCharges = 0 -- A set of lower and upper wavelength bounds that define what color -- pegs the player can collect -- Start with the greens. availableSpectrum = { { lower = Constants.STARTING_LOWER_WAVELENGTH, upper = Constants.STARTING_UPPER_WAVELENGTH } } background = BackGround() blueBucket = Bucket(250, 40) cannon = Cannon(pegs) hud = Hud() ball = nil ballsRemaining = Constants.NUM_STARTING_BALLS trailParticles = {} lastTrailParticleTime = 0 pegsCollected = 0 Sound.playGameMusic() end function Play:update(dt) -- Slow the whole game down a bit -- Making the ball travel a little slower makes the game more suspenseful and fun dt = dt * 0.8 --Flash reset flash = false -- Slow motion. if love.keyboard.isDown("space") then dt = dt / 5 end background:update(dt) blueBucket:update(dt) --TODO: Test bucket. ok to remove and do something better for i, particle in ipairs(trailParticles) do if particle:isDead(time) then table.remove(trailParticles, i) end end if ball then ball:update(dt) time = love.timer.getTime() if (time - lastTrailParticleTime)*1000 > Constants.BALL_PARTICLES_QUANTUM_IN_MS then lastTrailParticleTime = time table.insert(trailParticles, BallParticle(ball.position, time, ball:getRadius())) end ballAndPegSize = ball:getRadius() + Constants.PEG_RADIUS for i, peg in ipairs(pegs) do normal = ball.position - peg.position if normal:len() < ballAndPegSize then local section = Utils.getSection(peg.wavelength, availableSpectrum) if section then ball:attachPeg(peg) pegsCollectedThisBall = pegsCollectedThisBall + 1; Sound.playPeg(math.min(pegsCollectedThisBall, 14)) pegsCollected = pegsCollected + 1 -- Increase the spectrum in the section of the collected peg's wavelength Utils.increaseSpectrumSection(section, availableSpectrum) table.remove(pegs, i) score = score + 100 + (25 * pegsCollectedThisBall) -- Give another powerup charge for every 10th peg collected powerupCharges = powerupCharges + 0.1 end ball:bounce(normal, dt) break end end local len = ball.position - blueBucket:getCollisionLocation() -- Collision between ball and bucket. if len:len() < ball:getRadius() + Constants.BUCKET_RADIUS then score = score + Constants.BUCKET_SCORE ballsRemaining = ballsRemaining + 1 ball = nil flash = true elseif ball and ball.position.y > Constants.SCREEN_HEIGHT + ball:getRadius() then -- Take the ball out of play because it hit the bottom. ball = nil if ballsRemaining <= 0 then Sound.stopMusic() Gamestate.switch(States.credits, pegsCollected, score) end end if not ball then cannon = Cannon(pegs) end end if cannon then cannon:update(dt) end hud:update(dt) end function Play:draw() love.graphics.setColor(255, 255, 255) background:draw() blueBucket:draw() time = love.timer.getTime() for i, particle in ipairs(trailParticles) do particle:draw(time) end if ball then ball:draw() end if cannon then cannon:draw() end if flash then love.graphics.setColor(255,255,255) love.graphics.rectangle("fill", 0,0,Constants.SCREEN_WIDTH,Constants.SCREEN_HEIGHT) end for _, peg in pairs(pegs) do peg:draw(Utils.getSection(peg.wavelength, availableSpectrum)) end hud:draw(score, ballsRemaining, powerupCharges, availableSpectrum) end function Play:keypressed(key, unicode) -- Reset the game if key == 'r' then Sound.stopMusic() Play.enter() end -- Go to the credits after this ball if key == 'c' then ballsRemaining = 0 end -- Cheat to add a powerup charge if key == 'p' then powerupCharges = powerupCharges + 1 end if not ball then return end -- Cheats to speed the ball up or slow it down if key == 'j' then ball.velocity = ball.velocity * 1.1 end if key == 'k' then ball.velocity = ball.velocity * 0.8 end end function Play:mousepressed(x, y, button) -- If a ball is already in play if ball then if powerupCharges >= 1 then powerupCharges = powerupCharges - 1 ball:propelTowards(Vector(x, y), Constants.POWERUP_STRENGTH) end -- Otherwise, fire a ball else ballsRemaining = ballsRemaining - 1 pegsCollectedThisBall = 0; if (cannon) then ball = Ball(cannon.position, cannon.power) cannon = nil end end end return Play
apache-2.0
paulosalvatore/maruim_server
data/creaturescripts/scripts/tutorial.lua
1
2950
function onLogin(player) local passoTutorial = player:pegarPassoTutorial() if habilitarTutorial and passoTutorial == 1 then local posicaoInicioTutorial = Position({x = 315, y = 2415, z = 7}) player:teleportarJogador(posicaoInicioTutorial, true) end addEvent(function(playerId) local player = Player(playerId) if not player then return end player:registerEvent("TutorialModal") if habilitarTutorial and player:checarSemVocacao() then player:enviarModalSemVocacao() elseif habilitarTutorial and passoTutorial ~= tutorialFinalizado then player:enviarModalTutorial(passoTutorial) else player:unregisterEvent("TutorialModal") end end, 0, player:getId()) return true end function onModalWindow(player, modalWindowId, buttonId, choiceId) if modalWindowId < tutorialId or modalWindowId > tutorialId+tutorialIntervaloMaximo then return false elseif modalWindowId == tutorialId then if buttonId == 1 then player:sairTutorial() else player:enviarModalTutorial(player:pegarPassoTutorial()) end else if modalWindowId >= tutorialId+1 and modalWindowId < tutorialId+tutorialFinalizado then if buttonId == 1 then if modalWindowId == tutorialId+1 and choiceId == 1 then player:iniciarTutorial() elseif modalWindowId == tutorialId+2 then player:enviarModalTutorial(3) elseif modalWindowId == tutorialId+3 then player:teleportarJogador(Town(1):getTemplePosition()) player:enviarModalTutorial(4) player:adicionarMarcasMapa(1) elseif modalWindowId == tutorialId+4 then player:enviarModalTutorial(5) elseif modalWindowId == tutorialId+5 then player:enviarModalTutorial(6) elseif modalWindowId == tutorialId+6 then player:enviarModalTutorial(7) elseif modalWindowId == tutorialId+7 then player:enviarModalTutorial(8) elseif modalWindowId == tutorialId+8 then player:enviarModalTutorial(9) elseif modalWindowId == tutorialId+9 then player:enviarModalTutorial(10) elseif modalWindowId == tutorialId+10 then player:enviarModalTutorial(11) elseif modalWindowId == tutorialId+11 then player:teleportarParaGuilda() player:enviarModalTutorial(12) elseif modalWindowId == tutorialId+12 then player:tutorialMestreGuilda() else player:confirmarSairTutorial() end else player:confirmarSairTutorial() end elseif modalWindowId == tutorialId+tutorialFinalizado+1 then if buttonId == 1 then player:setVocation(choiceId) player:sendTextMessage(MESSAGE_INFO_DESCR, "Parabéns! Você se tornou um " .. Vocation(choiceId):getName() .. ".") player:getPosition():sendMagicEffect(efeitos["green"]) else player:enviarModalAindaSemVocacao() end elseif modalWindowId == tutorialId+tutorialFinalizado+2 then if buttonId == 1 then player:enviarModalSemVocacao() else player:remove() end else player:confirmarSairTutorial() end end end
gpl-2.0
kitala1/darkstar
scripts/zones/Dynamis-Buburimu/bcnms/dynamis_Buburimu.lua
10
1142
----------------------------------- -- Area: dynamis_Buburimu -- Name: dynamis_Buburimu ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaBuburimu]UniqueID",player:getDynamisUniqueID(1287)); SetServerVariable("[DynaBuburimu]Boss_Trigger",0); SetServerVariable("[DynaBuburimu]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaBuburimu]UniqueID")); local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if(leavecode == 4) then SetServerVariable("[DynaBuburimu]UniqueID",0); end end;
gpl-3.0
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/PageView.lua
3
2677
-------------------------------- -- @module PageView -- @extend Layout,UIScrollInterface -------------------------------- -- @function [parent=#PageView] getCurPageIndex -- @param self -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#PageView] addWidgetToPage -- @param self -- @param #ccui.Widget widget -- @param #long long -- @param #bool bool -------------------------------- -- @function [parent=#PageView] getPage -- @param self -- @param #long long -- @return Layout#Layout ret (return value: ccui.Layout) -------------------------------- -- @function [parent=#PageView] removePage -- @param self -- @param #ccui.Layout layout -------------------------------- -- @function [parent=#PageView] addEventListener -- @param self -- @param #function func -------------------------------- -- @function [parent=#PageView] insertPage -- @param self -- @param #ccui.Layout layout -- @param #int int -------------------------------- -- @function [parent=#PageView] scrollToPage -- @param self -- @param #long long -------------------------------- -- @function [parent=#PageView] removePageAtIndex -- @param self -- @param #long long -------------------------------- -- @function [parent=#PageView] getPages -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#PageView] removeAllPages -- @param self -------------------------------- -- @function [parent=#PageView] addPage -- @param self -- @param #ccui.Layout layout -------------------------------- -- @function [parent=#PageView] create -- @param self -- @return PageView#PageView ret (return value: ccui.PageView) -------------------------------- -- @function [parent=#PageView] createInstance -- @param self -- @return Ref#Ref ret (return value: cc.Ref) -------------------------------- -- @function [parent=#PageView] getLayoutType -- @param self -- @return Layout::Type#Layout::Type ret (return value: ccui.Layout::Type) -------------------------------- -- @function [parent=#PageView] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#PageView] update -- @param self -- @param #float float -------------------------------- -- @function [parent=#PageView] setLayoutType -- @param self -- @param #ccui.Layout::Type type -------------------------------- -- @function [parent=#PageView] PageView -- @param self return nil
mit
kitala1/darkstar
scripts/globals/items/simit_+1.lua
35
1337
----------------------------------------- -- ID: 5597 -- Item: simit_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 18 -- Vitality 4 -- Defense 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5597); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 18); target:addMod(MOD_VIT, 4); target:addMod(MOD_DEF, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 18); target:delMod(MOD_VIT, 4); target:delMod(MOD_DEF, 2); end;
gpl-3.0
kaustavha/rackspace-monitoring-agent
tests/code_cert.test.lua
4
1448
--[[ Copyright 2012 Rackspace 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 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local codeCert = [[ -----BEGIN PUBLIC KEY----- MIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAmmCdKFi6X1mpk5AU6EEH exou9NTRyiQVaHmTQvyPu6rd9krXB47/TgBDXcGIstkhFkGLwAh3cHDEPEF2jEcw W27S+/MvQdVgC4SJaN83pmk6ZYOvr0AX6zmPschoLxl84AT9xKHhFJuH5X1eCzP5 DY1rAvNLdB9lFC/DM8m2AySwKHc1kAPhs//j6RPcI8R37yDOEta7e/ikhbAwnOFv /rs3Aob/nYE0ql2CMpO68uU9vbDYQt2bFdiX/zau402Zi9kU1lAaeNBNM0UP9thU /SSOYuDFqy+XbRVvItLhjvo5hP46GOw9GLz9ICQQohiXjC33e4Hs8sq2XkM+jYyk DGRiPEtVwt95x9h/ReCYJowJzJWnaSvQKEPNQaMvwGCV5ZLZ0IlI8cqS3m+ns4ZK gTQDQjeRJADz0JY3jBpBhLebH2HfrYJGp3EWC7CdhhTvYXN5ZkBK6A7xkzPY0mZj RAvS5K417LkAc+G0gO6qyJtXplkL4G/Q07Vdt8zc7ZAg5rbGWY83lw8E/7h0Gpu2 JXfANZzdPKiV5P2tB6ZEwdxTABY/kHEk0u0WoPjqqgNv9I/zwLCbjefon8RcIJ5D EXXm9DibcaCpRYUkq5redFXDG8VHVzYVce2CJdrko8GvWUIOsAh0Y4CbyrXgXepV BvDtjEvMJUJ/iI33Ytzi6w0CAwEAAQ== -----END PUBLIC KEY----- ]] local exports = {} exports.codeCert = codeCert return exports
apache-2.0
kitala1/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Dagger.lua
17
1480
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Animated Dagger ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if(mob:AnimationSub() == 3) then SetDropRate(103,1572,1000); else SetDropRate(103,1572,0); end target:showText(mob,ANIMATED_DAGGER_DIALOG); SpawnMob(17330306,120):updateEnmity(target); SpawnMob(17330307,120):updateEnmity(target); SpawnMob(17330308,120):updateEnmity(target); SpawnMob(17330316,120):updateEnmity(target); SpawnMob(17330317,120):updateEnmity(target); SpawnMob(17330318,120):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_DAGGER_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:showText(mob,ANIMATED_DAGGER_DIALOG+1); DespawnMob(17330306); DespawnMob(17330307); DespawnMob(17330308); DespawnMob(17330316); DespawnMob(17330317); DespawnMob(17330318); end;
gpl-3.0
zhaoluxyz/Hugula
Client/tools/luaTools/lua/jit/dis_arm.lua
74
19364
---------------------------------------------------------------------------- -- LuaJIT ARM disassembler module. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- It disassembles most user-mode ARMv7 instructions -- NYI: Advanced SIMD and VFP instructions. ------------------------------------------------------------------------------ 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, ror, tohex = bit.band, bit.bor, bit.ror, bit.tohex local lshift, rshift, arshift = bit.lshift, bit.rshift, bit.arshift ------------------------------------------------------------------------------ -- Opcode maps ------------------------------------------------------------------------------ local map_loadc = { shift = 8, mask = 15, [10] = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "vmovFmDN", "vstmFNdr", _ = { shift = 21, mask = 1, [0] = "vstrFdl", { shift = 16, mask = 15, [13] = "vpushFdr", _ = "vstmdbFNdr", } }, }, { shift = 23, mask = 3, [0] = "vmovFDNm", { shift = 16, mask = 15, [13] = "vpopFdr", _ = "vldmFNdr", }, _ = { shift = 21, mask = 1, [0] = "vldrFdl", "vldmdbFNdr", }, }, }, [11] = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "vmovGmDN", "vstmGNdr", _ = { shift = 21, mask = 1, [0] = "vstrGdl", { shift = 16, mask = 15, [13] = "vpushGdr", _ = "vstmdbGNdr", } }, }, { shift = 23, mask = 3, [0] = "vmovGDNm", { shift = 16, mask = 15, [13] = "vpopGdr", _ = "vldmGNdr", }, _ = { shift = 21, mask = 1, [0] = "vldrGdl", "vldmdbGNdr", }, }, }, _ = { shift = 0, mask = 0 -- NYI ldc, mcrr, mrrc. }, } local map_vfps = { shift = 6, mask = 0x2c001, [0] = "vmlaF.dnm", "vmlsF.dnm", [0x04000] = "vnmlsF.dnm", [0x04001] = "vnmlaF.dnm", [0x08000] = "vmulF.dnm", [0x08001] = "vnmulF.dnm", [0x0c000] = "vaddF.dnm", [0x0c001] = "vsubF.dnm", [0x20000] = "vdivF.dnm", [0x24000] = "vfnmsF.dnm", [0x24001] = "vfnmaF.dnm", [0x28000] = "vfmaF.dnm", [0x28001] = "vfmsF.dnm", [0x2c000] = "vmovF.dY", [0x2c001] = { shift = 7, mask = 0x1e01, [0] = "vmovF.dm", "vabsF.dm", [0x0200] = "vnegF.dm", [0x0201] = "vsqrtF.dm", [0x0800] = "vcmpF.dm", [0x0801] = "vcmpeF.dm", [0x0a00] = "vcmpzF.d", [0x0a01] = "vcmpzeF.d", [0x0e01] = "vcvtG.dF.m", [0x1000] = "vcvt.f32.u32Fdm", [0x1001] = "vcvt.f32.s32Fdm", [0x1800] = "vcvtr.u32F.dm", [0x1801] = "vcvt.u32F.dm", [0x1a00] = "vcvtr.s32F.dm", [0x1a01] = "vcvt.s32F.dm", }, } local map_vfpd = { shift = 6, mask = 0x2c001, [0] = "vmlaG.dnm", "vmlsG.dnm", [0x04000] = "vnmlsG.dnm", [0x04001] = "vnmlaG.dnm", [0x08000] = "vmulG.dnm", [0x08001] = "vnmulG.dnm", [0x0c000] = "vaddG.dnm", [0x0c001] = "vsubG.dnm", [0x20000] = "vdivG.dnm", [0x24000] = "vfnmsG.dnm", [0x24001] = "vfnmaG.dnm", [0x28000] = "vfmaG.dnm", [0x28001] = "vfmsG.dnm", [0x2c000] = "vmovG.dY", [0x2c001] = { shift = 7, mask = 0x1e01, [0] = "vmovG.dm", "vabsG.dm", [0x0200] = "vnegG.dm", [0x0201] = "vsqrtG.dm", [0x0800] = "vcmpG.dm", [0x0801] = "vcmpeG.dm", [0x0a00] = "vcmpzG.d", [0x0a01] = "vcmpzeG.d", [0x0e01] = "vcvtF.dG.m", [0x1000] = "vcvt.f64.u32GdFm", [0x1001] = "vcvt.f64.s32GdFm", [0x1800] = "vcvtr.u32FdG.m", [0x1801] = "vcvt.u32FdG.m", [0x1a00] = "vcvtr.s32FdG.m", [0x1a01] = "vcvt.s32FdG.m", }, } local map_datac = { shift = 24, mask = 1, [0] = { shift = 4, mask = 1, [0] = { shift = 8, mask = 15, [10] = map_vfps, [11] = map_vfpd, -- NYI cdp, mcr, mrc. }, { shift = 8, mask = 15, [10] = { shift = 20, mask = 15, [0] = "vmovFnD", "vmovFDn", [14] = "vmsrD", [15] = { shift = 12, mask = 15, [15] = "vmrs", _ = "vmrsD", }, }, }, }, "svcT", } local map_loadcu = { shift = 0, mask = 0, -- NYI unconditional CP load/store. } local map_datacu = { shift = 0, mask = 0, -- NYI unconditional CP data. } local map_simddata = { shift = 0, mask = 0, -- NYI SIMD data. } local map_simdload = { shift = 0, mask = 0, -- NYI SIMD load/store, preload. } local map_preload = { shift = 0, mask = 0, -- NYI preload. } local map_media = { shift = 20, mask = 31, [0] = false, { --01 shift = 5, mask = 7, [0] = "sadd16DNM", "sasxDNM", "ssaxDNM", "ssub16DNM", "sadd8DNM", false, false, "ssub8DNM", }, { --02 shift = 5, mask = 7, [0] = "qadd16DNM", "qasxDNM", "qsaxDNM", "qsub16DNM", "qadd8DNM", false, false, "qsub8DNM", }, { --03 shift = 5, mask = 7, [0] = "shadd16DNM", "shasxDNM", "shsaxDNM", "shsub16DNM", "shadd8DNM", false, false, "shsub8DNM", }, false, { --05 shift = 5, mask = 7, [0] = "uadd16DNM", "uasxDNM", "usaxDNM", "usub16DNM", "uadd8DNM", false, false, "usub8DNM", }, { --06 shift = 5, mask = 7, [0] = "uqadd16DNM", "uqasxDNM", "uqsaxDNM", "uqsub16DNM", "uqadd8DNM", false, false, "uqsub8DNM", }, { --07 shift = 5, mask = 7, [0] = "uhadd16DNM", "uhasxDNM", "uhsaxDNM", "uhsub16DNM", "uhadd8DNM", false, false, "uhsub8DNM", }, { --08 shift = 5, mask = 7, [0] = "pkhbtDNMU", false, "pkhtbDNMU", { shift = 16, mask = 15, [15] = "sxtb16DMU", _ = "sxtab16DNMU", }, "pkhbtDNMU", "selDNM", "pkhtbDNMU", }, false, { --0a shift = 5, mask = 7, [0] = "ssatDxMu", "ssat16DxM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxtbDMU", _ = "sxtabDNMU", }, "ssatDxMu", false, "ssatDxMu", }, { --0b shift = 5, mask = 7, [0] = "ssatDxMu", "revDM", "ssatDxMu", { shift = 16, mask = 15, [15] = "sxthDMU", _ = "sxtahDNMU", }, "ssatDxMu", "rev16DM", "ssatDxMu", }, { --0c shift = 5, mask = 7, [3] = { shift = 16, mask = 15, [15] = "uxtb16DMU", _ = "uxtab16DNMU", }, }, false, { --0e shift = 5, mask = 7, [0] = "usatDwMu", "usat16DwM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxtbDMU", _ = "uxtabDNMU", }, "usatDwMu", false, "usatDwMu", }, { --0f shift = 5, mask = 7, [0] = "usatDwMu", "rbitDM", "usatDwMu", { shift = 16, mask = 15, [15] = "uxthDMU", _ = "uxtahDNMU", }, "usatDwMu", "revshDM", "usatDwMu", }, { --10 shift = 12, mask = 15, [15] = { shift = 5, mask = 7, "smuadNMS", "smuadxNMS", "smusdNMS", "smusdxNMS", }, _ = { shift = 5, mask = 7, [0] = "smladNMSD", "smladxNMSD", "smlsdNMSD", "smlsdxNMSD", }, }, false, false, false, { --14 shift = 5, mask = 7, [0] = "smlaldDNMS", "smlaldxDNMS", "smlsldDNMS", "smlsldxDNMS", }, { --15 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "smmulNMS", _ = "smmlaNMSD", }, { shift = 12, mask = 15, [15] = "smmulrNMS", _ = "smmlarNMSD", }, false, false, false, false, "smmlsNMSD", "smmlsrNMSD", }, false, false, { --18 shift = 5, mask = 7, [0] = { shift = 12, mask = 15, [15] = "usad8NMS", _ = "usada8NMSD", }, }, false, { --1a shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1b shift = 5, mask = 3, [2] = "sbfxDMvw", }, { --1c shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1d shift = 5, mask = 3, [0] = { shift = 0, mask = 15, [15] = "bfcDvX", _ = "bfiDMvX", }, }, { --1e shift = 5, mask = 3, [2] = "ubfxDMvw", }, { --1f shift = 5, mask = 3, [2] = "ubfxDMvw", }, } local map_load = { shift = 21, mask = 9, { shift = 20, mask = 5, [0] = "strtDL", "ldrtDL", [4] = "strbtDL", [5] = "ldrbtDL", }, _ = { shift = 20, mask = 5, [0] = "strDL", "ldrDL", [4] = "strbDL", [5] = "ldrbDL", } } local map_load1 = { shift = 4, mask = 1, [0] = map_load, map_media, } local map_loadm = { shift = 20, mask = 1, [0] = { shift = 23, mask = 3, [0] = "stmdaNR", "stmNR", { shift = 16, mask = 63, [45] = "pushR", _ = "stmdbNR", }, "stmibNR", }, { shift = 23, mask = 3, [0] = "ldmdaNR", { shift = 16, mask = 63, [61] = "popR", _ = "ldmNR", }, "ldmdbNR", "ldmibNR", }, } local map_data = { shift = 21, mask = 15, [0] = "andDNPs", "eorDNPs", "subDNPs", "rsbDNPs", "addDNPs", "adcDNPs", "sbcDNPs", "rscDNPs", "tstNP", "teqNP", "cmpNP", "cmnNP", "orrDNPs", "movDPs", "bicDNPs", "mvnDPs", } local map_mul = { shift = 21, mask = 7, [0] = "mulNMSs", "mlaNMSDs", "umaalDNMS", "mlsDNMS", "umullDNMSs", "umlalDNMSs", "smullDNMSs", "smlalDNMSs", } local map_sync = { shift = 20, mask = 15, -- NYI: brackets around N. R(D+1) for ldrexd/strexd. [0] = "swpDMN", false, false, false, "swpbDMN", false, false, false, "strexDMN", "ldrexDN", "strexdDN", "ldrexdDN", "strexbDMN", "ldrexbDN", "strexhDN", "ldrexhDN", } local map_mulh = { shift = 21, mask = 3, [0] = { shift = 5, mask = 3, [0] = "smlabbNMSD", "smlatbNMSD", "smlabtNMSD", "smlattNMSD", }, { shift = 5, mask = 3, [0] = "smlawbNMSD", "smulwbNMS", "smlawtNMSD", "smulwtNMS", }, { shift = 5, mask = 3, [0] = "smlalbbDNMS", "smlaltbDNMS", "smlalbtDNMS", "smlalttDNMS", }, { shift = 5, mask = 3, [0] = "smulbbNMS", "smultbNMS", "smulbtNMS", "smulttNMS", }, } local map_misc = { shift = 4, mask = 7, -- NYI: decode PSR bits of msr. [0] = { shift = 21, mask = 1, [0] = "mrsD", "msrM", }, { shift = 21, mask = 3, "bxM", false, "clzDM", }, { shift = 21, mask = 3, "bxjM", }, { shift = 21, mask = 3, "blxM", }, false, { shift = 21, mask = 3, [0] = "qaddDMN", "qsubDMN", "qdaddDMN", "qdsubDMN", }, false, { shift = 21, mask = 3, "bkptK", }, } local map_datar = { shift = 4, mask = 9, [9] = { shift = 5, mask = 3, [0] = { shift = 24, mask = 1, [0] = map_mul, map_sync, }, { shift = 20, mask = 1, [0] = "strhDL", "ldrhDL", }, { shift = 20, mask = 1, [0] = "ldrdDL", "ldrsbDL", }, { shift = 20, mask = 1, [0] = "strdDL", "ldrshDL", }, }, _ = { shift = 20, mask = 25, [16] = { shift = 7, mask = 1, [0] = map_misc, map_mulh, }, _ = { shift = 0, mask = 0xffffffff, [bor(0xe1a00000)] = "nop", _ = map_data, } }, } local map_datai = { shift = 20, mask = 31, -- NYI: decode PSR bits of msr. Decode imm12. [16] = "movwDW", [20] = "movtDW", [18] = { shift = 0, mask = 0xf00ff, [0] = "nopv6", _ = "msrNW", }, [22] = "msrNW", _ = map_data, } local map_branch = { shift = 24, mask = 1, [0] = "bB", "blB" } local map_condins = { [0] = map_datar, map_datai, map_load, map_load1, map_loadm, map_branch, map_loadc, map_datac } -- NYI: setend. local map_uncondins = { [0] = false, map_simddata, map_simdload, map_preload, false, "blxB", map_loadcu, map_datacu, } ------------------------------------------------------------------------------ local map_gpr = { [0] = "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7", "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc", } local map_cond = { [0] = "eq", "ne", "hs", "lo", "mi", "pl", "vs", "vc", "hi", "ls", "ge", "lt", "gt", "le", "al", } local map_shift = { [0] = "lsl", "lsr", "asr", "ror", } ------------------------------------------------------------------------------ -- 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 elseif band(ctx.op, 0x0e000000) ~= 0x0a000000 then extra = "\t; 0x"..tohex(ctx.rel) end end if ctx.hexdump > 0 then ctx.out(format("%08x %s %-5s %s%s\n", ctx.addr+pos, tohex(ctx.op), text, concat(operands, ", "), extra)) else ctx.out(format("%08x %-5s %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 -- Format operand 2 of load/store opcodes. local function fmtload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local x, ofs local ext = (band(op, 0x04000000) == 0) if not ext and band(op, 0x02000000) == 0 then ofs = band(op, 4095) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs elseif ext and band(op, 0x00400000) ~= 0 then ofs = band(op, 15) + band(rshift(op, 4), 0xf0) if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end ofs = "#"..ofs else ofs = map_gpr[band(op, 15)] if ext or band(op, 0xfe0) == 0 then elseif band(op, 0xfe0) == 0x60 then ofs = format("%s, rrx", ofs) else local sh = band(rshift(op, 7), 31) if sh == 0 then sh = 32 end ofs = format("%s, %s #%d", ofs, map_shift[band(rshift(op, 5), 3)], sh) end if band(op, 0x00800000) == 0 then ofs = "-"..ofs end end if ofs == "#0" then x = format("[%s]", base) elseif band(op, 0x01000000) == 0 then x = format("[%s], %s", base, ofs) else x = format("[%s, %s]", base, ofs) end if band(op, 0x01200000) == 0x01200000 then x = x.."!" end return x end -- Format operand 2 of vector load/store opcodes. local function fmtvload(ctx, op, pos) local base = map_gpr[band(rshift(op, 16), 15)] local ofs = band(op, 255)*4 if band(op, 0x00800000) == 0 then ofs = -ofs end if base == "pc" then ctx.rel = ctx.addr + pos + 8 + ofs end if ofs == 0 then return format("[%s]", base) else return format("[%s, #%d]", base, ofs) end end local function fmtvr(op, vr, sh0, sh1) if vr == "s" then return format("s%d", 2*band(rshift(op, sh0), 15)+band(rshift(op, sh1), 1)) else return format("d%d", band(rshift(op, sh0), 15)+band(rshift(op, sh1-4), 16)) end 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(b3, 24), lshift(b2, 16), lshift(b1, 8), b0) local operands = {} local suffix = "" local last, name, pat local vr ctx.op = op ctx.rel = nil local cond = rshift(op, 28) local opat if cond == 15 then opat = map_uncondins[band(rshift(op, 25), 7)] else if cond ~= 14 then suffix = map_cond[cond] end opat = map_condins[band(rshift(op, 25), 7)] end while type(opat) ~= "string" do if not opat then return unknown(ctx) end opat = opat[band(rshift(op, opat.shift), opat.mask)] or opat._ end name, pat = match(opat, "^([a-z0-9]*)(.*)") if sub(pat, 1, 1) == "." then local s2, p2 = match(pat, "^([a-z0-9.]*)(.*)") suffix = suffix..s2 pat = p2 end for p in gmatch(pat, ".") do local x = nil if p == "D" then x = map_gpr[band(rshift(op, 12), 15)] elseif p == "N" then x = map_gpr[band(rshift(op, 16), 15)] elseif p == "S" then x = map_gpr[band(rshift(op, 8), 15)] elseif p == "M" then x = map_gpr[band(op, 15)] elseif p == "d" then x = fmtvr(op, vr, 12, 22) elseif p == "n" then x = fmtvr(op, vr, 16, 7) elseif p == "m" then x = fmtvr(op, vr, 0, 5) elseif p == "P" then if band(op, 0x02000000) ~= 0 then x = ror(band(op, 255), 2*band(rshift(op, 8), 15)) else x = map_gpr[band(op, 15)] if band(op, 0xff0) ~= 0 then operands[#operands+1] = x local s = map_shift[band(rshift(op, 5), 3)] local r = nil if band(op, 0xf90) == 0 then if s == "ror" then s = "rrx" else r = "#32" end elseif band(op, 0x10) == 0 then r = "#"..band(rshift(op, 7), 31) else r = map_gpr[band(rshift(op, 8), 15)] end if name == "mov" then name = s; x = r elseif r then x = format("%s %s", s, r) else x = s end end end elseif p == "L" then x = fmtload(ctx, op, pos) elseif p == "l" then x = fmtvload(ctx, op, pos) elseif p == "B" then local addr = ctx.addr + pos + 8 + arshift(lshift(op, 8), 6) if cond == 15 then addr = addr + band(rshift(op, 23), 2) end ctx.rel = addr x = "0x"..tohex(addr) elseif p == "F" then vr = "s" elseif p == "G" then vr = "d" elseif p == "." then suffix = suffix..(vr == "s" and ".f32" or ".f64") elseif p == "R" then if band(op, 0x00200000) ~= 0 and #operands == 1 then operands[1] = operands[1].."!" end local t = {} for i=0,15 do if band(rshift(op, i), 1) == 1 then t[#t+1] = map_gpr[i] end end x = "{"..concat(t, ", ").."}" elseif p == "r" then if band(op, 0x00200000) ~= 0 and #operands == 2 then operands[1] = operands[1].."!" end local s = tonumber(sub(last, 2)) local n = band(op, 255) if vr == "d" then n = rshift(n, 1) end operands[#operands] = format("{%s-%s%d}", last, vr, s+n-1) elseif p == "W" then x = band(op, 0x0fff) + band(rshift(op, 4), 0xf000) elseif p == "T" then x = "#0x"..tohex(band(op, 0x00ffffff), 6) elseif p == "U" then x = band(rshift(op, 7), 31) if x == 0 then x = nil end elseif p == "u" then x = band(rshift(op, 7), 31) if band(op, 0x40) == 0 then if x == 0 then x = nil else x = "lsl #"..x end else if x == 0 then x = "asr #32" else x = "asr #"..x end end elseif p == "v" then x = band(rshift(op, 7), 31) elseif p == "w" then x = band(rshift(op, 16), 31) elseif p == "x" then x = band(rshift(op, 16), 31) + 1 elseif p == "X" then x = band(rshift(op, 16), 31) - last + 1 elseif p == "Y" then x = band(rshift(op, 12), 0xf0) + band(op, 0x0f) elseif p == "K" then x = "#0x"..tohex(band(rshift(op, 4), 0x0000fff0) + band(op, 15), 4) elseif p == "s" then if band(op, 0x00100000) ~= 0 then suffix = "s"..suffix end else assert(false) end if x then last = x if type(x) == "number" then x = "#"..x end operands[#operands+1] = x end end return putop(ctx, name..suffix, 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 ctx.pos = ofs 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 < 16 then return map_gpr[r] end return "d"..(r-16) end -- Public module functions. module(...) create = create_ disass = disass_ regname = regname_
mit
apletnev/koreader
spec/unit/uimanager_bench.lua
9
1237
require("commonrequire") local util = require("ffi/util") local UIManager = require("ui/uimanager") local noop = function() end describe("UIManager checkTasks benchmark", function() local now = { util.gettime() } local wait_until -- luacheck: no unused UIManager:quit() UIManager._task_queue = {} for i=1,1000000 do table.insert( UIManager._task_queue, { time = { now[1] + 10000+i, now[2] }, action = noop } ) end -- for i=1,1000 do wait_until, now = UIManager:_checkTasks() -- luacheck: no unused -- end end) describe("UIManager schedule benchmark", function() local now = { util.gettime() } UIManager:quit() UIManager._task_queue = {} for i=1,100000 do UIManager:schedule({ now[1] + i, now[2] }, noop) end end) describe("UIManager unschedule benchmark", function() local now = { util.gettime() } UIManager:quit() UIManager._task_queue = {} for i=1,1000 do table.insert( UIManager._task_queue, { time = { now[1] + 10000+i, now[2] }, action = 'a' } ) end for i=1,1000 do UIManager:schedule(now, noop) UIManager:unschedule(noop) end end)
agpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/Settings/Pages/ShareGame/Components/RectangleButton.lua
1
2440
local CorePackages = game:GetService("CorePackages") local UserInputService = game:GetService("UserInputService") local Roact = require(CorePackages.Roact) local BUTTON_IMAGE = "rbxasset://textures/ui/Settings/MenuBarAssets/MenuButton.png" local BUTTON_IMAGE_ACTIVE = "rbxasset://textures/ui/Settings/MenuBarAssets/MenuButtonSelected.png" local BUTTON_SLICE = Rect.new(8, 6, 46, 44) local DROPSHADOW_SIZE = { Left = 4, Right = 4, Top = 2, Bottom = 6, } local RectangleButton = Roact.PureComponent:extend("RectangleButton") function RectangleButton:init() self.state = { isHovering = false, } end function RectangleButton:render() local size = self.props.size local position = self.props.position local anchorPoint = self.props.anchorPoint local layoutOrder = self.props.layoutOrder local zIndex = self.props.zIndex local onClick = self.props.onClick local children = self.props[Roact.Children] or {} local buttonImage = self.state.isHovering and BUTTON_IMAGE_ACTIVE or BUTTON_IMAGE -- Insert padding so that child elements of this component are positioned -- inside the button as expected. This is to offset the dropshadow -- extending outside the button bounds. children["UIPadding"] = Roact.createElement("UIPadding", { PaddingLeft = UDim.new(0, DROPSHADOW_SIZE.Left), PaddingRight = UDim.new(0, DROPSHADOW_SIZE.Right), PaddingTop = UDim.new(0, DROPSHADOW_SIZE.Top), PaddingBottom = UDim.new(0, DROPSHADOW_SIZE.Bottom), }) return Roact.createElement("ImageButton", { BackgroundTransparency = 1, Image = "", Size = size, Position = position, AnchorPoint = anchorPoint, LayoutOrder = layoutOrder, ZIndex = zIndex, [Roact.Event.InputBegan] = function() self:setState({isHovering = true}) end, [Roact.Event.InputEnded] = function() self:setState({isHovering = false}) end, [Roact.Event.Activated] = function() if onClick then self:setState({isHovering = false}) onClick() end end, }, { ButtonBackground = Roact.createElement("ImageLabel", { BackgroundTransparency = 1, Position = UDim2.new( 0, -DROPSHADOW_SIZE.Left, 0, -DROPSHADOW_SIZE.Top ), Size = UDim2.new( 1, DROPSHADOW_SIZE.Left + DROPSHADOW_SIZE.Right, 1, DROPSHADOW_SIZE.Top + DROPSHADOW_SIZE.Bottom ), Image = buttonImage, ScaleType = Enum.ScaleType.Slice, SliceCenter = BUTTON_SLICE, ZIndex = zIndex, }, children), }) end return RectangleButton
apache-2.0
kitala1/darkstar
scripts/globals/items/shining_trout.lua
17
1322
----------------------------------------- -- ID: 5791 -- Item: shining_trout -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5791); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
king98tm/mohammadking98
libs/dateparser.lua
502
6212
local difftime, time, date = os.difftime, os.time, os.date local format = string.format local tremove, tinsert = table.remove, table.insert local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable local dateparser={} --we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore. local unix_timestamp do local now = time() local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now))) unix_timestamp = function(t, offset_sec) local success, improper_time = pcall(time, t) if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end return improper_time - local_UTC_offset_sec - offset_sec end end local formats = {} -- format names local format_func = setmetatable({}, {__mode='v'}) --format functions ---register a date format parsing function function dateparser.register_format(format_name, format_function) if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end local found for i, f in ipairs(format_func) do --for ordering if f==format_function then found=true break end end if not found then tinsert(format_func, format_function) end formats[format_name] = format_function return true end ---register a date format parsing function function dateparser.unregister_format(format_name) if type(format_name)~="string" then return nil, "format name must be a string" end formats[format_name]=nil end ---return the function responsible for handling format_name date strings function dateparser.get_format_function(format_name) return formats[format_name] or nil, ("format %s not registered"):format(format_name) end ---try to parse date string --@param str date string --@param date_format optional date format name, if known --@return unix timestamp if str can be parsed; nil, error otherwise. function dateparser.parse(str, date_format) local success, res, err if date_format then if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end success, res = pcall(formats[date_format], str) else for i, func in ipairs(format_func) do success, res = pcall(func, str) if success and res then return res end end end return success and res end dateparser.register_format('W3CDTF', function(rest) local year, day_of_year, month, day, week local hour, minute, second, second_fraction, offset_hours local alt_rest year, rest = rest:match("^(%d%d%d%d)%-?(.*)$") day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$") if day_of_year then rest=alt_rest end month, rest = rest:match("^(%d%d)%-?(.*)$") day, rest = rest:match("^(%d%d)(.*)$") if #rest>0 then rest = rest:match("^T(.*)$") hour, rest = rest:match("^([0-2][0-9]):?(.*)$") minute, rest = rest:match("^([0-6][0-9]):?(.*)$") second, rest = rest:match("^([0-6][0-9])(.*)$") second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$") if second_fraction then rest=alt_rest end if rest=="Z" then rest="" offset_hours=0 else local sign, offset_h, offset_m sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$") local offset_m, alt_rest = rest:match("^(%d%d)(.*)$") if offset_m then rest=alt_rest end offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 then return nil end end year = tonumber(year) local d = { year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))), month = tonumber(month) or 1, day = tonumber(day) or 1, hour = tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } local t = unix_timestamp(d, (offset_hours or 0) * 3600) if second_fraction then return t + tonumber("0."..second_fraction) else return t end end) do local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/ A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9, K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5, S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12, Z = 0, EST = -5, EDT = -4, CST = -6, CDT = -5, MST = -7, MDT = -6, PST = -8, PDT = -7, GMT = 0, UT = 0, UTC = 0 } local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12} dateparser.register_format('RFC2822', function(rest) local year, month, day, day_of_year, week_of_year, weekday local hour, minute, second, second_fraction, offset_hours local alt_rest weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$") if weekday then rest=alt_rest end day, rest=rest:match("^(%d%d?)%s+(.*)$") month, rest=rest:match("^(%w%w%w)%s+(.*)$") month = month_val[month] year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$") hour, rest = rest:match("^(%d%d?):(.*)$") minute, rest = rest:match("^(%d%d?)(.*)$") second, alt_rest = rest:match("^:(%d%d)(.*)$") if second then rest = alt_rest end local tz, offset_sign, offset_h, offset_m tz, alt_rest = rest:match("^%s+(%u+)(.*)$") if tz then rest = alt_rest offset_hours = tz_table[tz] else offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$") offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60 end if #rest>0 or not (year and day and month and hour and minute) then return nil end year = tonumber(year) local d = { year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))), month = month, day = tonumber(day), hour= tonumber(hour) or 0, min = tonumber(minute) or 0, sec = tonumber(second) or 0, isdst = false } return unix_timestamp(d, offset_hours * 3600) end) end dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF return dateparser
gpl-3.0
kitala1/darkstar
scripts/zones/Windurst_Woods/npcs/Wije_Tiren.lua
36
1496
----------------------------------- -- Area: Windurst Woods -- NPC: Wije Tiren -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,WIJETIREN_SHOP_DIALOG); stock = { 0x1034, 290, --Antidote 0x119d, 10, --Distilled Water 0x1037, 728, --Echo Drops 0x1020, 4445, --Ether 0x1036, 2387, --Eye Drops 0x1010, 837, --Potion 0x1396, 98, --Scroll of Herb Pastoral 0x0b30, 9200 --Federation Waystone } showShop(player, WINDURST, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Palborough_Mines/npcs/_3z2.lua
19
1192
----------------------------------- -- Area: Palborough Mines -- NPC: Old Toolbox -- Continues Quest: The Eleventh's Hour (100%) ----------------------------------- package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Palborough_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0e); 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 == 0x0e) then player:setPos(-73, 0, 60, 1, 0xac); end end;
gpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/DevConsole/Components/DataProvider.lua
1
1761
local CorePackages = game:GetService("CorePackages") local Roact = require(CorePackages.Roact) local Components = script.Parent.Parent.Components local LogData = require(Components.Log.LogData) local ClientMemoryData = require(Components.Memory.ClientMemoryData) local ServerMemoryData = require(Components.Memory.ServerMemoryData) local NetworkData = require(Components.Network.NetworkData) local ServerScriptsData = require(Components.Scripts.ServerScriptsData) local DataStoresData = require(Components.DataStores.DataStoresData) local ServerStatsData = require(Components.ServerStats.ServerStatsData) local ActionBindingsData = require(Components.ActionBindings.ActionBindingsData) local ServerJobsData = require(Components.ServerJobs.ServerJobsData) local DataProvider = Roact.Component:extend("DataProvider") function DataProvider:init() self._context.DevConsoleData = { ClientLogData = LogData.new(true), ServerLogData = LogData.new(false), ClientMemoryData = ClientMemoryData.new(), ServerMemoryData = ServerMemoryData.new(), ClientNetworkData = NetworkData.new(true), ServerNetworkData = NetworkData.new(false), ServerScriptsData = ServerScriptsData.new(), DataStoresData = DataStoresData.new(), ServerStatsData = ServerStatsData.new(), ActionBindingsData = ActionBindingsData.new(), ServerJobsData = ServerJobsData.new(), } end function DataProvider:didMount() if self.props.isDeveloperView then for _, dataProvider in pairs(self._context.DevConsoleData) do dataProvider:start() end else self._context.DevConsoleData.ClientLogData:start() self._context.DevConsoleData.ClientMemoryData:start() end end function DataProvider:render() return Roact.oneChild(self.props[Roact.Children]) end return DataProvider
apache-2.0
kitala1/darkstar
scripts/zones/North_Gustaberg/npcs/Cavernous_Maw.lua
29
1494
----------------------------------- -- Area: North Gustaberg -- NPC: Cavernous Maw -- @pos 466 0 479 106 -- Teleports Players to North Gustaberg [S] ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/North_Gustaberg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,7)) then player:startEvent(0x0387); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID:",csid); -- printf("RESULT:",option); if (csid == 0x0387 and option == 1) then toMaw(player,11); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Rabao/npcs/Edigey.lua
19
2494
----------------------------------- -- Area: Rabao -- NPC: Edigey -- Starts and Ends Quest: Don't Forget the Antidote ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ForgetTheAntidote = player:getQuestStatus(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); if((ForgetTheAntidote == QUEST_ACCEPTED or ForgetTheAntidote == QUEST_COMPLETED) and trade:hasItemQty(1209,1) and trade:getItemCount() == 1) then player:startEvent(0x0004,0,1209); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) ForgetTheAntidote = player:getQuestStatus(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); if(ForgetTheAntidote == QUEST_AVAILABLE and player:getFameLevel(RABAO) >= 4) then player:startEvent(0x0002,0,1209); elseif(ForgetTheAntidote == QUEST_ACCEPTED) then player:startEvent(0x0003,0,1209); elseif(ForgetTheAntidote == QUEST_COMPLETED) then player:startEvent(0x0005,0,1209); else player:startEvent(0x0032); 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 == 0x0002 and option == 1) then player:addQuest(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); player:setVar("DontForgetAntidoteVar",1); elseif(csid == 0x0004 and player:getVar("DontForgetAntidoteVar") == 1) then --If completing for the first time player:setVar("DontForgetAntidoteVar",0); player:tradeComplete(); player:addTitle(262); player:addItem(16974); -- Dotanuki player:messageSpecial(ITEM_OBTAINED, 16974); player:completeQuest(OUTLANDS,DONT_FORGET_THE_ANTIDOTE); player:addFame(OUTLANDS,60); elseif(csid == 0x0004) then --Subsequent completions player:tradeComplete(); player:addGil(GIL_RATE*1800); player:messageSpecial(GIL_OBTAINED, 1800); player:addFame(OUTLANDS,30); end end;
gpl-3.0
Roblox/Core-Scripts
PlayerScripts/StarterPlayerScripts/CameraScript/RootCamera/ClassicCamera.lua
2
6597
local PlayersService = game:GetService('Players') local VRService = game:GetService("VRService") local RootCameraCreator = require(script.Parent) local UP_VECTOR = Vector3.new(0, 1, 0) local XZ_VECTOR = Vector3.new(1, 0, 1) local ZERO_VECTOR2 = Vector2.new(0, 0) local VR_PITCH_FRACTION = 0.25 local Vector3_new = Vector3.new local CFrame_new = CFrame.new local math_min = math.min local math_max = math.max local math_atan2 = math.atan2 local math_rad = math.rad local math_abs = math.abs local function clamp(low, high, num) return (num > high and high or num < low and low or num) end local function IsFinite(num) return num == num and num ~= 1/0 and num ~= -1/0 end local function IsFiniteVector3(vec3) return IsFinite(vec3.x) and IsFinite(vec3.y) and IsFinite(vec3.z) end -- May return NaN or inf or -inf -- This is a way of finding the angle between the two vectors: local function findAngleBetweenXZVectors(vec2, vec1) return math_atan2(vec1.X*vec2.Z-vec1.Z*vec2.X, vec1.X*vec2.X + vec1.Z*vec2.Z) end local function CreateClassicCamera() local module = RootCameraCreator() local tweenAcceleration = math_rad(220) local tweenSpeed = math_rad(0) local tweenMaxSpeed = math_rad(250) local timeBeforeAutoRotate = 2 local lastUpdate = tick() module.LastUserPanCamera = tick() function module:Update() module:ProcessTweens() local now = tick() local timeDelta = (now - lastUpdate) local userPanningTheCamera = (self.UserPanningTheCamera == true) local camera = workspace.CurrentCamera local player = PlayersService.LocalPlayer local humanoid = self:GetHumanoid() local cameraSubject = camera and camera.CameraSubject local isInVehicle = cameraSubject and cameraSubject:IsA('VehicleSeat') local isOnASkateboard = cameraSubject and cameraSubject:IsA('SkateboardPlatform') if lastUpdate == nil or now - lastUpdate > 1 then module:ResetCameraLook() self.LastCameraTransform = nil end if lastUpdate then local gamepadRotation = self:UpdateGamepad() if self:ShouldUseVRRotation() then self.RotateInput = self.RotateInput + self:GetVRRotationInput() else -- Cap out the delta to 0.1 so we don't get some crazy things when we re-resume from local delta = math_min(0.1, now - lastUpdate) if gamepadRotation ~= ZERO_VECTOR2 then userPanningTheCamera = true self.RotateInput = self.RotateInput + (gamepadRotation * delta) end local angle = 0 if not (isInVehicle or isOnASkateboard) then angle = angle + (self.TurningLeft and -120 or 0) angle = angle + (self.TurningRight and 120 or 0) end if angle ~= 0 then self.RotateInput = self.RotateInput + Vector2.new(math_rad(angle * delta), 0) userPanningTheCamera = true end end end -- Reset tween speed if user is panning if userPanningTheCamera then tweenSpeed = 0 module.LastUserPanCamera = tick() end local userRecentlyPannedCamera = now - module.LastUserPanCamera < timeBeforeAutoRotate local subjectPosition = self:GetSubjectPosition() if subjectPosition and player and camera then local zoom = self:GetCameraZoom() if zoom < 0.5 then zoom = 0.5 end if self:GetShiftLock() and not self:IsInFirstPerson() then -- We need to use the right vector of the camera after rotation, not before local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput) local offset = ((newLookVector * XZ_VECTOR):Cross(UP_VECTOR).unit * 1.75) if IsFiniteVector3(offset) then subjectPosition = subjectPosition + offset end else if not userPanningTheCamera and self.LastCameraTransform then local isInFirstPerson = self:IsInFirstPerson() if (isInVehicle or isOnASkateboard) and lastUpdate and humanoid and humanoid.Torso then if isInFirstPerson then if self.LastSubjectCFrame and (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then local y = -findAngleBetweenXZVectors(self.LastSubjectCFrame.lookVector, cameraSubject.CFrame.lookVector) if IsFinite(y) then self.RotateInput = self.RotateInput + Vector2.new(y, 0) end tweenSpeed = 0 end elseif not userRecentlyPannedCamera then local forwardVector = humanoid.Torso.CFrame.lookVector if isOnASkateboard then forwardVector = cameraSubject.CFrame.lookVector end tweenSpeed = clamp(0, tweenMaxSpeed, tweenSpeed + tweenAcceleration * timeDelta) local percent = clamp(0, 1, tweenSpeed * timeDelta) if self:IsInFirstPerson() then percent = 1 end local y = findAngleBetweenXZVectors(forwardVector, self:GetCameraLook()) if IsFinite(y) and math_abs(y) > 0.0001 then self.RotateInput = self.RotateInput + Vector2.new(y * percent, 0) end end end end end local VREnabled = VRService.VREnabled camera.Focus = VREnabled and self:GetVRFocus(subjectPosition, timeDelta) or CFrame_new(subjectPosition) local cameraFocusP = camera.Focus.p if VREnabled and not self:IsInFirstPerson() then local cameraHeight = self:GetCameraHeight() local vecToSubject = (subjectPosition - camera.CFrame.p) local distToSubject = vecToSubject.magnitude -- Only move the camera if it exceeded a maximum distance to the subject in VR if distToSubject > zoom or self.RotateInput.x ~= 0 then local desiredDist = math_min(distToSubject, zoom) vecToSubject = self:RotateCamera(vecToSubject.unit * XZ_VECTOR, Vector2.new(self.RotateInput.x, 0)) * desiredDist local newPos = cameraFocusP - vecToSubject local desiredLookDir = camera.CFrame.lookVector if self.RotateInput.x ~= 0 then desiredLookDir = vecToSubject end local lookAt = Vector3.new(newPos.x + desiredLookDir.x, newPos.y, newPos.z + desiredLookDir.z) self.RotateInput = ZERO_VECTOR2 camera.CFrame = CFrame_new(newPos, lookAt) + Vector3_new(0, cameraHeight, 0) end else local newLookVector = self:RotateCamera(self:GetCameraLook(), self.RotateInput) self.RotateInput = ZERO_VECTOR2 camera.CFrame = CFrame_new(cameraFocusP - (zoom * newLookVector), cameraFocusP) end self.LastCameraTransform = camera.CFrame self.LastCameraFocus = camera.Focus if (isInVehicle or isOnASkateboard) and cameraSubject:IsA('BasePart') then self.LastSubjectCFrame = cameraSubject.CFrame else self.LastSubjectCFrame = nil end end lastUpdate = now end return module end return CreateClassicCamera
apache-2.0
fqrouter/luci
modules/admin-mini/luasrc/model/cbi/mini/dhcp.lua
82
2998
--[[ 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 sys = require "luci.sys" local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" m = Map("dhcp", "DHCP") s = m:section(TypedSection, "dhcp", "DHCP-Server") s.anonymous = true s.addremove = false s.dynamic = false s:depends("interface", "lan") enable = s:option(ListValue, "ignore", translate("enable"), "") enable:value(0, translate("enable")) enable:value(1, translate("disable")) start = s:option(Value, "start", translate("First leased address")) start.rmempty = true start:depends("ignore", "0") limit = s:option(Value, "limit", translate("Number of leased addresses"), "") limit:depends("ignore", "0") function limit.cfgvalue(self, section) local value = Value.cfgvalue(self, section) if value then return tonumber(value) + 1 end end function limit.write(self, section, value) value = tonumber(value) - 1 return Value.write(self, section, value) end limit.rmempty = true time = s:option(Value, "leasetime") time:depends("ignore", "0") time.rmempty = true local leasefn, leasefp, leases uci:foreach("dhcp", "dnsmasq", function(section) leasefn = section.leasefile end ) local leasefp = leasefn and fs.access(leasefn) and io.lines(leasefn) if leasefp then leases = {} for lease in leasefp do table.insert(leases, luci.util.split(lease, " ")) end end if leases then v = m:section(Table, leases, translate("Active Leases")) name = v:option(DummyValue, 4, translate("Hostname")) function name.cfgvalue(self, ...) local value = DummyValue.cfgvalue(self, ...) return (value == "*") and "?" or value end ip = v:option(DummyValue, 3, translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) mac = v:option(DummyValue, 2, translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) ltime = v:option(DummyValue, 1, translate("Leasetime remaining")) function ltime.cfgvalue(self, ...) local value = DummyValue.cfgvalue(self, ...) return wa.date_format(os.difftime(tonumber(value), os.time())) end end s2 = m:section(TypedSection, "host", translate("Static Leases")) s2.addremove = true s2.anonymous = true s2.template = "cbi/tblsection" name = s2:option(Value, "name", translate("Hostname")) mac = s2:option(Value, "mac", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) ip = s2:option(Value, "ip", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) sys.net.arptable(function(entry) ip:value(entry["IP address"]) mac:value( entry["HW address"], entry["HW address"] .. " (" .. entry["IP address"] .. ")" ) end) return m
apache-2.0
kitala1/darkstar
scripts/zones/Port_Bastok/npcs/Rafaela.lua
37
1124
----------------------------------- -- Area: Port Bastok -- NPC: Rafaela -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0016); 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); PastPerfectVar = player:getVar("PastPerfectVar"); if (csid == 0x0016 and PastPerfectVar == 1) then player:setVar("PastPerfectVar",2); end end;
gpl-3.0
Teaonly/easyLearning.js
qulogo/train.lua
1
4559
require('torch') require('image') require('nn') require('optim') require('xlua') local util = require('./util') local data = require('./data') local model = require('./model') -- Checking input paramters and load config local cmd = torch.CmdLine() cmd:text('Options:') cmd:option('-d', 'sohu', 'The target dataset folder') cmd:option('-neck', 1024, 'The middle hidden vector') cmd:option('-gpu', 1, 'Defaut using GPU 1') cmd:option('-batch_size', 64, "Batch number") cmd:option('-seed', 1979, "Random seed") cmd:option('-threshold', 0.10, "Inpainting threshold") local opt = cmd:parse(arg) local config = util.loadConfig(opt) if (opt.gpu ~= 0) then require('cunn') end torch.manualSeed(opt.seed) torch.setnumthreads(1) torch.setdefaulttensortype('torch.FloatTensor') -- Checking model input and output size --[[ local x = torch.rand(5, 3, config.inputWidth, config.inputHeight) local gen = model.buildGenerator(opt, config) local enc = model.buildEncoder(opt, config) local disc = model.buildDiscriminator(opt, config) local z = enc:forward(x) local y = gen:forward(z) local v = disc:forward(y) print(z:size(), y:size(), v:size()) --]] ------------------------------- -- Global info ------------------------------ local netG = nn.Sequential() local netD = model.buildDiscriminator(opt, config) netG:add( model.buildEncoder(opt, config) ) netG:add( model.buildGenerator(opt, config) ) local parametersD, gradParametersD = netD:getParameters() local parametersG, gradParametersG = netG:getParameters() -- optim local optimG = optim.adam local optimD = optim.adam local optimStateG = { learningRate = 0.001, } local optimStateD = { learningRate = 0.0001, } -- loss local criterionD = nn.BCECriterion() local criterionG = nn.MSECriterion() -- input and output local label = torch.Tensor(opt.batch_size) local inputBatch, maskBatch = nil, nil local outG, outD = nil, nil -------------------------------- -- Training discriminator -------------------------------- local fDx = function(x) --netD:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) --netG:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) gradParametersD:zero() -- training with true label:fill(1) outD = netD:forward(maskBatch) local terror = criterionD:forward(outD, label) local dfd = criterionD:backward(outD, label) netD:backward(maskBatch, dfd) -- training with false label:fill(0) outG = netG:forward(inputBatch) outD = netD:forward(outG) local ferror = criterionD:forward(outD, label) dfd = criterionD:backward(outD, label) netD:backward(outG, dfd) print("D error = " .. (terror + ferror) ) return terror+ferror, gradParametersD end -------------------------------- -- Traning genrator -------------------------------- local fGx = function(x) --netD:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) --netG:apply(function(m) if torch.type(m):find('Convolution') then m.bias:zero() end end) gradParametersG:zero() -- traninging with fake true label:fill(1) local ferror = criterionD:forward(outD, label) local dfd = criterionD:backward(outD, label) local dOutG = netD:updateGradInput(outG, dfd) local l2error = criterionG:forward(outG, maskBatch) local dfg = criterionG:backward(outG, maskBatch) dOutG:add(0.1, dfg) netG:backward(inputBatch, dOutG) print("L2 error:" .. l2error .. " FG error:" .. ferror) return ferror + l2error, gradParametersG end local doTrain = function() if ( opt.gpu ~= 0) then netG:cuda() netD:cuda() criterionD:cuda() criterionG:cuda() label = label:cuda() parametersD, gradParametersD = netD:getParameters() parametersG, gradParametersG = netG:getParameters() end netG:training() netD:training() pageIndex = 1 for i = 1, config.totalNumber do inputBatch, maskBatch = data.randomBatch(opt, config, pageIndex) if ( opt.gpu ~= 0) then inputBatch = inputBatch:cuda() maskBatch = maskBatch:cuda() end -- (1) Update D network: maximize log(D(x)) + log(1 - D(G(z))) optimD(fDx, parametersD, optimStateD) -- (2) Update G network: maximize log(D(G(z))) optimG(fGx, parametersG, optimStateG) collectgarbage() print("..................") --xlua.progress(i, opt.total_iterator) end end doTrain()
mit
kitala1/darkstar
scripts/zones/Mhaura/npcs/Runito-Monito.lua
34
1472
----------------------------------- -- Area: Mhaura -- NPC: Runito-Monito -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,RUNITOMONITO_SHOP_DIALOG); stock = {0x4015,106, --Cat Bagnakhs 0x4017,1554, --Brass Bagnakhs 0x4041,855, --Brass Dagger 0x42a3,92, --Bronze Rod 0x42b9,634, --Brass Rod 0x4093,3601, --Brass Xiphos 0x40c7,2502, --Claymore 0x4140,618, --Butterfly Axe 0x439b,9, --Dart 0x43a6,3, --Wooden Arrow 0x43a7,4, --Bone Arrow 0x43b8,5} --Crossbow Bolts 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
AliKhodadad/wildman
plugins/all.lua
37
4653
do data = load_data(_config.moderation.data) local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.' end return group_type end local function show_group_settings(target) local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local settings = data[tostring(target)]['settings'] local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX return text end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(target, receiver) local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type local settings = show_group_settings(target) text = text.."\n\nGroup settings: \n"..settings local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/"..target.."all.txt", ok_cb, false) return end function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(target, receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) if not is_owner(msg) then return end return all(msg.to.id, receiver) end end return { patterns = { "^[!/](all)$", "^[!/](all) (%d+)$" }, run = run } end
gpl-2.0
raingloom/thranduil
examples/chatbox/ui/Container.lua
9
11972
local ui_path = (...):match('(.-)[^%.]+$') .. '.' local Object = require(ui_path .. 'classic.classic') local Container = Object:extend('Container') function Container:containerNew(settings) local settings = settings or {} self:bind('tab', 'focus-next') self:bind('lshift', 'previous-modifier') self:bind('escape', 'unselect') self:bind('left', 'focus-left') self:bind('right', 'focus-right') self:bind('up', 'focus-up') self:bind('down', 'focus-down') self:bind('dpleft', 'focus-left') self:bind('dpright', 'focus-right') self:bind('dpup', 'focus-up') self:bind('dpdown', 'focus-down') self.elements = {} self.currently_focused_element = nil self.any_selected = false self.disable_directional_selection = settings.disable_directional_selection self.disable_tab_selection = settings.disable_tab_selection if self.auto_align then self.auto_spacing = settings.auto_spacing or 5 self.auto_margin = settings.auto_margin or 5 self.align_positions = {} table.insert(self.align_positions, {x = self.auto_margin, y = self.auto_margin}) end end function Container:containerUpdate(dt, parent) -- Focus on elements if not self.disable_tab_selection then if self.selected and not self.input:down('previous-modifier') and self.input:pressed('focus-next') then self:focusNext() end if self.selected and self.input:down('previous-modifier') and self.input:pressed('focus-next') then self:focusPrevious() end end if not self.disable_directional_selection then if self.selected and self.input:pressed('focus-left') then self:focusDirection('left') end if self.selected and self.input:pressed('focus-right') then self:focusDirection('right') end if self.selected and self.input:pressed('focus-up') then self:focusDirection('up') end if self.selected and self.input:pressed('focus-down') then self:focusDirection('down') end end for i, element in ipairs(self.elements) do if not element.selected or not i == self.currently_focused_element then element.selected = false end if i == self.currently_focused_element then element.selected = true end end -- Unfocus all elements if the frame isn't being interacted with if not self.selected then for _, element in ipairs(self.elements) do element.selected = false end end -- Unselect on escape self.any_selected = false if self.selected then for _, element in ipairs(self.elements) do if element.selected then self.any_selected = true end end if self.input:pressed('unselect') then self:unselect() end end if self.dont_update_draw then return end -- Update children if self.type == 'Scrollarea' then for _, element in ipairs(self.elements) do if element.inside_scroll_area then element.inside_scroll_area = nil element:update(dt, self) end end else for _, element in ipairs(self.elements) do element:update(dt, self) end end end function Container:containerDraw() if self.dont_update_draw then return end for _, element in ipairs(self.elements) do element:draw() end end function Container:containerAddElement(element) if self.auto_align then local element = self:addAlignedElement(element) if element then return element end else element.parent = self table.insert(self.elements, element) element:update(0, self) return element end end function Container:containerRemoveElement(id) for i, element in ipairs(self.elements) do if element.id == id then if self.auto_align then local ap = {x = element.ix, y = element.iy} table.insert(self.align_positions, 1, ap) end table.remove(self.elements, i) return end end end function Container:addAlignedElement(element) local pointInRectangle = function(x, y, bx, by, bw, bh) if x >= bx and x <= bx + bw and y >= by and y <= by + bh then return true end end local rectangleInRectangle = function(ax, ay, aw, ah, bx, by, bw, bh) return ax <= bx + bw and bx <= ax + aw and ay <= by + bh and by <= ay + ah end local elementCollidingWithElement = function(ex, ey, ew, eh, id) for i, e in ipairs(self.elements) do if rectangleInRectangle(ex, ey, ew, eh, e.ix, e.iy, e.w, e.h) then return true end end end local alignContains = function(ap) for i, p in ipairs(self.align_positions) do local dx, dy = math.abs(p.x - ap.x), math.abs(p.y - ap.y) if dx < 0.05 and dy < 0.05 then return i end end end for i, p in ipairs(self.align_positions) do if p.x + element.w <= self.w - self.auto_margin and p.y + element.h <= self.h - self.auto_margin and not elementCollidingWithElement(p.x, p.y, element.w, element.h) then element.x, element.y = p.x, p.y element.ix, element.iy = p.x, p.y local x, y = p.x, p.y table.remove(self.align_positions, i) -- Remove element colliding anchors if #self.align_positions > 0 then for j = #self.align_positions, 1 do if pointInRectangle(self.align_positions[j].x, self.align_positions[j].y, element.x, element.y, element.w + self.auto_spacing, element.h + self.auto_spacing) then table.remove(self.align_positions, j) end end end -- Add right anchor if x + element.w + self.auto_spacing < self.w - self.auto_margin then local ap = {x = x + element.w + self.auto_spacing, y = y} if not alignContains(ap) then table.insert(self.align_positions, 1, ap) end end -- Add down anchor if y + element.h + self.auto_spacing < self.h - self.auto_margin then local ap = {x = x, y = y + element.h + self.auto_spacing} if not alignContains(ap) then table.insert(self.align_positions, ap) end end element.parent = self table.insert(self.elements, element) element:update(0, self) return element end end end function Container:focusNext() for _, element in ipairs(self.elements) do if element.any_selected then return end end for i, element in ipairs(self.elements) do if element.selected then self.currently_focused_element = i end element.selected = false end if self.currently_focused_element then self.currently_focused_element = self.currently_focused_element + 1 if self.currently_focused_element > #self.elements then self.currently_focused_element = 1 end else self.currently_focused_element = 1 end end function Container:focusPrevious() for _, element in ipairs(self.elements) do if element.any_selected then return end end for i, element in ipairs(self.elements) do if element.selected then self.currently_focused_element = i end element.selected = false end if self.currently_focused_element then self.currently_focused_element = self.currently_focused_element - 1 if self.currently_focused_element < 1 then self.currently_focused_element = #self.elements end else self.currently_focused_element = #self.elements end end function Container:focusElement(n) if not n then return end if not self.currently_focused_element then self.currently_focused_element = n; return end for _, element in ipairs(self.elements) do element.selected = false end if #self.elements >= n then self.currently_focused_element = n end end function Container:focusDirection(direction) for _, element in ipairs(self.elements) do if element.any_selected then return end end for i, element in ipairs(self.elements) do if element.selected then self.currently_focused_element = i end element.selected = false end if self.currently_focused_element then local angled = function(a, b) local d = math.abs(a - b) % 360; if d > 180 then return 360 - d else return d end end local angles = {right = 0, left = -180, up = -90, down = 90} local min, j, n = 10000, nil, 0 local selected_element = self.elements[self.currently_focused_element] if not selected_element then return end for i, element in ipairs(self.elements) do if i ~= self.currently_focused_element then local d = math.sqrt(math.pow(selected_element.x - element.x, 2) + math.pow(selected_element.y - element.y, 2)) local v = math.max(angled(math.deg(math.atan2(element.y - selected_element.y, element.x - selected_element.x)), angles[direction]), 20)*d if direction == 'right' then if element.x > selected_element.x then n = n + 1 end end if direction == 'left' then if element.x < selected_element.x then n = n + 1 end end if direction == 'up' then if element.y < selected_element.y then n = n + 1 end end if direction == 'down' then if element.y > selected_element.y then n = n + 1 end end if v <= min then min = v; j = i end end end -- Loop over if n == 0 then if direction == 'left' or direction == 'right' then max_dx, min_dy, j = -10000, 10000, nil for i, element in ipairs(self.elements) do if i ~= self.currently_focused_element then local dx, dy = math.abs(selected_element.x - element.x), math.abs(selected_element.y - element.y) if dx > max_dx or dy < min_dy then max_dx = dx min_dy = dy j = i end end end if j then self.currently_focused_element = j end elseif direction == 'up' or direction == 'down' then min_dx, max_dy, j = 10000, -10000, nil for i, element in ipairs(self.elements) do if i ~= self.currently_focused_element then local dx, dy = math.abs(selected_element.x - element.x), math.abs(selected_element.y - element.y) if dx < min_dx or dy > max_dy then min_dx = dx max_dy = dy j = i end end end if j then self.currently_focused_element = j end end -- Normal behavior elseif n > 0 and j then self.currently_focused_element = j end else self.currently_focused_element = 1 end end function Container:unselect() for _, element in ipairs(self.elements) do if element.any_selected then return end end if self.any_selected then for _, element in ipairs(self.elements) do element.selected = false self.currently_focused_element = nil end else self.selected = false end end function Container:forceUnselect() for _, element in ipairs(self.elements) do element.selected = false self.currently_focused_element = nil end end function Container:destroy() local ids = {} for _, element in ipairs(self.elements) do table.insert(ids, element.id) end for _, id in ipairs(ids) do self:removeElement(id) end for _, id in ipairs(ids) do self.ui.removeFromElementsList(id) end self.ui.removeFromElementsList(self.id) end return Container
mit
fqrouter/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/csv.lua
80
1198
--[[ Luci configuration model for statistics - collectd csv plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("CSV Plugin Configuration"), translate( "The csv plugin stores collected data in csv file format " .. "for further processing by external programs." )) -- collectd_csv config section s = m:section( NamedSection, "collectd_csv", "luci_statistics" ) -- collectd_csv.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_csv.datadir (DataDir) datadir = s:option( Value, "DataDir", translate("Storage directory for the csv files") ) datadir.default = "127.0.0.1" datadir:depends( "enable", 1 ) -- collectd_csv.storerates (StoreRates) storerates = s:option( Flag, "StoreRates", translate("Store data values as rates instead of absolute values") ) storerates.default = 0 storerates:depends( "enable", 1 ) return m
apache-2.0
kitala1/darkstar
scripts/zones/Upper_Delkfutts_Tower/npcs/Grounds_Tome.lua
34
1149
----------------------------------- -- Area: Upper Delkfutt's Tower -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_UPPER_DELKFUTTS_TOWER,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,785,786,787,788,789,0,0,0,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,785,786,787,788,789,0,0,0,0,0,GOV_MSG_UPPER_DELKFUTTS_TOWER); end;
gpl-3.0
kitala1/darkstar
scripts/zones/FeiYin/npcs/_no4.lua
6
2211
----------------------------------- -- Area: Fei'Yin -- NPC: Cermet Door (triggers Rukususu dialog) -- Type: Quest NPC -- @pos -183 0 190 204 -- Involved in Quests: Curses, Foiled A-Golem!?,SMN AF2: Class Reunion, SMN AF3: Carbuncle Debacle -- Involved in Missions: Windurst 5-1/7-2/8-2 ----------------------------------- package.loaded["scripts/zones/FeiYin/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/FeiYin/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Windurst 8-2 if(player:getCurrentMission(WINDURST) == THE_JESTER_WHO_D_BE_KING and player:getVar("MissionStatus") == 1) then player:startEvent(0x0016); -- Curses, Foiled A_Golem!? if(player:hasKeyItem(SHANTOTTOS_NEW_SPELL)) then player:startEvent(0x000E); -- deliver spell elseif(player:hasKeyItem(SHANTOTTOS_EXSPELL)) then player:startEvent(0x000D); -- spell erased, try again! -- standard dialog else player:startEvent(0x000f); end end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); -- Curses, Foiled A_Golem!? if(csid == 0x000E) then player:setVar("foiledagolemdeliverycomplete",1); player:delKeyItem(SHANTOTTOS_NEW_SPELL); -- remove key item elseif(csid == 0x0016) then player:addKeyItem(RHINOSTERY_RING); player:messageSpecial(KEYITEM_OBTAINED,RHINOSTERY_RING); if(player:hasKeyItem(AURASTERY_RING) and player:hasKeyItem(OPTISTERY_RING)) then player:setVar("MissionStatus",2) end end end;
gpl-3.0
kitala1/darkstar
scripts/globals/mobskills/PW_Bilgestorm.lua
13
1392
--------------------------------------------- -- Bilgestorm -- -- Description: Deals damage in an area of effect. Additional effect: Lowers attack, accuracy, and defense -- Type: Physical -- Utsusemi/Blink absorb: Wipes shadows -- Range: Unknown -- Notes: Only used at low health.*Experienced the use at 75%* --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 1839) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,MOBPARAM_WIPE_SHADOWS); local power = math.random(20,25); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_ACCURACY_DOWN, power, 0, 60); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_ATTACK_DOWN, power, 0, 60); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_DEFENSE_DOWN, power, 0, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
frissdiegurke/dotfiles
.config/awesome/wiboxes/wibox-right.lua
1
7573
require("awful.autofocus") local wibox = require("wibox") local gears = require("gears") local vicious = require("vicious") separator = wibox.widget.imagebox() separator:set_image(beautiful.widget_sep) -- Menu launcher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = menu }) -- CPU temperature if thermal then cpuicon = wibox.widget.imagebox() cpuicon:set_image(beautiful.widget_cpu) tzswidget = wibox.widget.textbox() vicious.register(tzswidget, vicious.widgets.thermal, " $1 °C", 19, thermal) end -- Battery state if battery then batwidget = wibox.widget.textbox() vicious.register(batwidget, vicious.widgets.bat, "$1$2%", 30, battery) end -- Memory usage if memory then memicon = wibox.widget.imagebox() memicon:set_image(beautiful.widget_mem) memwidget = wibox.widget.textbox() vicious.register(memwidget, vicious.widgets.mem, " $1% ( $2<small> </small>MB ) ", 15) end -- Network usage if traffic_device then dnicon = wibox.widget.imagebox() upicon = wibox.widget.imagebox() dnicon:set_image(beautiful.widget_net) upicon:set_image(beautiful.widget_netup) netwidget = wibox.widget.textbox() vicious.register( netwidget, vicious.widgets.net, '<span color="' .. beautiful.fg_netdn_widget .. '">${' .. traffic_device .. ' down_kb}</span>' .. ' ' .. '<span color="' .. beautiful.fg_netup_widget ..'">${' .. traffic_device .. ' up_kb}</span>', 3 ) end -- Volume level volicon = wibox.widget.imagebox() volicon:set_image(beautiful.widget_vol) volwidget = wibox.widget.textbox() function update_volume(widget) local stream = io.popen(volume) local status = stream:read("*all") stream:close() local vStr = string.match(status, "(%d?%d?%d)%%") local vNum = tonumber(vStr) if vNum then local volume = vNum / 100 if volume > 1 then volume = 1 end if volume < 0 then volume = 0 end status = string.match(status, "%[(o[^%]]*)%]") if string.find(status, "on", 1, true) then volume = " <span color='black' background='white'> " .. string.format("%3d", volume * 100) .. "%<small> </small></span>" else volume = " <span color='red' background='black'> Mute<small> </small></span>" end widget:set_markup(volume) end end update_volume(volwidget) mytimer = gears.timer({ timeout = 3 }) mytimer:connect_signal("timeout", function () update_volume(volwidget) end) mytimer:start() volwidget:buttons(awful.util.table.join( awful.button({}, 1, function () awful.spawn("audio m") update_volume(volwidget) end ), awful.button({}, 4, function () awful.spawn("audio +") update_volume(volwidget) end ), awful.button({}, 5, function () awful.spawn("audio -") update_volume(volwidget) end ) )) volicon:buttons(volwidget:buttons()) -- Date and time dateicon = wibox.widget.imagebox() dateicon:set_image(beautiful.widget_date) datewidget = wibox.widget.textbox() vicious.register(datewidget, vicious.widgets.date, "<small>%D %R:%S</small>", 1) -- -- Create a wibox for each screen and add it -- mywibox = {} promptbox = {} layoutbox = {} taglist = {} taglist.buttons = awful.util.table.join( awful.button({ }, 1, awful.tag.viewonly ), awful.button({ mkey }, 1, awful.client.movetotag ), awful.button({ }, 3, awful.tag.viewtoggle ), awful.button({ mkey }, 3, awful.client.toggletag ), awful.button({ }, 4, function(t) awful.tag.viewnext(awful.tag.getscreen(t)) end ), awful.button({ }, 5, function(t) awful.tag.viewprev(awful.tag.getscreen(t)) end ) ) tasklist = {} tasklist.buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else -- Without this, the following c:isvisible() makes no sense c.minimized = false if not c:isvisible() then awful.tag.viewonly(c:tags()[1]) end -- This will also un-minimize the client, if needed client.focus = c c:raise() end end ), awful.button({ }, 2, function (c) c:kill() end), awful.button({ }, 3, function (c) if instance then instance:hide() instance = nil else instance = awful.menu.clients({ width=250 }) end end ), awful.button({ }, 4, function (c) awful.client.focus.byidx(1) if client.focus then client.focus:raise() end end ), awful.button({ }, 5, function (c) awful.client.focus.byidx(-1) if client.focus then client.focus:raise() end end ) ) awful.screen.connect_for_each_screen(function(s) promptbox[s] = awful.widget.prompt() layoutbox[s] = awful.widget.layoutbox(s) layoutbox[s]:buttons(awful.util.table.join( awful.button({ }, 1, function () awful.layout.inc(layouts, 1) end), awful.button({ }, 3, function () awful.layout.inc(layouts, -1) end), awful.button({ }, 4, function () awful.layout.inc(layouts, 1) end), awful.button({ }, 5, function () awful.layout.inc(layouts, -1) end) )) taglist[s] = awful.widget.taglist(s, awful.widget.taglist.filter.all, taglist.buttons) tasklist[s] = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist.buttons) mywibox[s] = awful.wibar({ screen = s, position = "right", width = beautiful.wibox_height * 2 }) -- Create top layout local layout_top = wibox.layout.fixed.vertical() local layout_top_top = wibox.layout.flex.horizontal() layout_top_top:add(layoutbox[s]) layout_top_top:add(launcher) layout_top:add(layout_top_top) layout_top:add(datewidget) -- Create left layout local layout_tasklist = wibox.layout.align.horizontal(separator, tasklist[s], separator) -- Create right layout local layout_utils_top = wibox.layout.fixed.horizontal() local layout_utils_bot = wibox.layout.fixed.horizontal() local layout_utils = wibox.layout.align.horizontal() layout_utils_top:add(separator) layout_utils_top:add(taglist[s]) layout_utils_top:add(separator) layout_utils_top:add(promptbox[s]) if s.index == 1 then -- systray not working for multiple screens layout_utils_bot:add(wibox.widget.systray()) layout_utils_bot:add(separator) end if traffic_device then layout_utils_bot:add(dnicon) layout_utils_bot:add(netwidget) layout_utils_bot:add(upicon) layout_utils_bot:add(separator) end if memory then layout_utils_bot:add(memicon) layout_utils_bot:add(memwidget) layout_utils_bot:add(separator) end if thermal then layout_utils_bot:add(cpuicon) layout_utils_bot:add(tzswidget) layout_utils_bot:add(separator) end layout_utils:set_first(layout_utils_top) layout_utils:set_third(layout_utils_bot) -- Combine left and right layout local layout_both = wibox.layout.flex.vertical() local layout_both_rotated = wibox.container.rotate() layout_both:add(layout_utils) layout_both:add(layout_tasklist) layout_both_rotated:set_direction("west") layout_both_rotated:set_widget(layout_both) -- Create bottom layout local layout_bot = wibox.layout.fixed.vertical() if battery then layout_bot:add(batwidget) end layout_bot:add(volwidget) -- Combine all layouts local layout = wibox.layout.align.vertical() layout:set_first(layout_top) layout:set_second(layout_both_rotated) layout:set_third(layout_bot) -- Apply layout mywibox[s]:set_widget(layout) end)
apache-2.0
apletnev/koreader
spec/unit/document_spec.lua
8
2924
describe("PDF document module", function() local DocumentRegistry setup(function() require("commonrequire") DocumentRegistry = require("document/documentregistry") end) local doc it("should open document", function() local sample_pdf = "spec/front/unit/data/tall.pdf" doc = DocumentRegistry:openDocument(sample_pdf) assert.truthy(doc) end) it("should get page dimensions", function() local dimen = doc:getPageDimensions(1, 1, 0) assert.are.same(dimen.w, 567) assert.are.same(dimen.h, 1418) end) it("should get cover image", function() local image = doc:getCoverPageImage() assert.truthy(image) assert.are.same(320, image:getWidth()) assert.are.same(800, image:getHeight()) end) local pos0 = {page = 1, x = 0, y = 20} local pos1 = {page = 1, x = 300, y = 120} local pboxes = { {x = 26, y = 42, w = 240, h = 22}, {x = 48, y = 82, w = 185, h = 22}, } it("should clip page rect to PNG file", function() doc:clipPagePNGFile(pos0, pos1, nil, nil, "/tmp/clip0.png") doc:clipPagePNGFile(pos0, pos1, pboxes, "lighten", "/tmp/clip1.png") end) it("should clip page rect to PNG string", function() local clip0 = doc:clipPagePNGString(pos0, pos1, nil, nil) assert.truthy(clip0) local clip1 = doc:clipPagePNGString(pos0, pos1, pboxes, "lighten") assert.truthy(clip1) end) it("should calculate fast digest", function() assert.is_equal(doc:fastDigest(), "41cce710f34e5ec21315e19c99821415") end) it("should close document", function() doc:close() end) end) describe("EPUB document module", function() local DocumentRegistry setup(function() require("commonrequire") DocumentRegistry = require("document/documentregistry") end) local doc it("should open document", function() local sample_epub = "spec/front/unit/data/leaves.epub" doc = DocumentRegistry:openDocument(sample_epub) assert.truthy(doc) end) it("should get cover image", function() local image = doc:getCoverPageImage() assert.truthy(image) assert.are.same(image:getWidth(), 442) assert.are.same(image:getHeight(), 616) end) it("should calculate fast digest", function() assert.is_equal(doc:fastDigest(), "59d481d168cca6267322f150c5f6a2a3") end) it("should register droid sans fallback", function() local fonts_registry = { "Droid Sans Mono", "FreeSans", "FreeSerif", "Noto Sans", "Noto Sans CJK SC", "Noto Serif", } local face_list = cre.getFontFaces() assert.are.same(fonts_registry, face_list) end) it("should close document", function() doc:close() end) end)
agpl-3.0
kitala1/darkstar
scripts/zones/Caedarva_Mire/npcs/qm12.lua
8
1934
----------------------------------- -- Area: Caedarva Mire -- NPC: ??? -- @pos 456.993 -7.000 -270.815 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local notMeantToBeProg = player:getVar("notmeanttobeCS"); if(notMeantToBeProg == 1) then player:startEvent(0x0010); elseif(player:getQuestStatus(AHT_URHGAN,NOT_MEANT_TO_BE) == QUEST_ACCEPTED and notMeantToBeProg == 3) then player:startEvent(0x0011); elseif(player:getVar("notmeanttobeMoshdahnKilled") == 1 and player:getVar("notmeanttobeLamia27Killed") == 1) then player:startEvent(0x0012); else player:messageSpecial(NOTHING_HAPPENS); 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 == 0x0010) then player:setVar("notmeanttobeCS",2); elseif(csid == 0x0011) then if(GetMobAction(17101149) == 0 and GetMobAction(17101148) == 0) then SpawnMob(17101149):updateClaim(player); SpawnMob(17101148):updateClaim(player); end elseif(csid == 0x0012) then player:setVar("notmeanttobeMoshdahnKilled",0); player:setVar("notmeanttobeLamia27Killed",0); player:setVar("notmeanttobeCS",5); end end;
gpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/Stats/StatsAggregator.lua
1
4057
--[[ Filename: StatsAggregator.lua Written by: dbanks Description: Gather and store stats on regular heartbeat. --]] --[[ Services ]]-- local CoreGuiService = game:GetService('CoreGui') --[[ Modules ]]-- local StatsUtils = require(CoreGuiService.RobloxGui.Modules.Stats.StatsUtils) --[[ Classes ]]-- local StatsAggregatorClass = {} StatsAggregatorClass.__index = StatsAggregatorClass function StatsAggregatorClass.new(statType, numSamples, pauseBetweenSamples) local self = {} setmetatable(self, StatsAggregatorClass) self._statType = statType self._numSamples = numSamples self._pauseBetweenSamples = pauseBetweenSamples self._statName = StatsUtils.StatNames[self._statType] self._statMaxName = StatsUtils.StatMaxNames[self._statType] -- init our circular buffer. self._samples = {} for i = 0, numSamples-1, 1 do self._samples[i] = 0 end self._oldestIndex = 0 self._listeners = {} -- FIXME(dbanks) -- Just want to be real clear this is a key, not an array index. self._nextListenerId = 1001 return self end function StatsAggregatorClass:AddListener(callbackFunction) local id = self._nextListenerId self._nextListenerId = self._nextListenerId+1 self._listeners[id] = callbackFunction return id end function StatsAggregatorClass:RemoveListener(listenerId) self._listeners[listenerId] = nil end function StatsAggregatorClass:_notifyAllListeners() for listenerId, listenerCallback in pairs(self._listeners) do listenerCallback() end end function StatsAggregatorClass:StartListening() -- On a regular heartbeat, wake up and read the latest -- value into circular buffer. -- Don't bother if we're already listening. if (self._listening == true) then return end spawn(function() self._listening = true while(self._listening) do local statValue = self:_getStatValue() self:_storeStatValue(statValue) self:_notifyAllListeners() wait(self._pauseBetweenSamples) end end) end function StatsAggregatorClass:StopListening() self._listening = false end function StatsAggregatorClass:GetValues() -- Get the past N values, from oldest to newest. local retval = {} local actualIndex for i = 0, self._numSamples-1, 1 do actualIndex = (self._oldestIndex + i) % self._numSamples retval[i+1] = self._samples[actualIndex] end return retval end function StatsAggregatorClass:GetAverage() -- Get average of past N values. local retval = 0.0 for i = 0, self._numSamples-1, 1 do retval = retval + self._samples[i] end return retval / self._numSamples end function StatsAggregatorClass:GetLatestValue() -- Get latest value. local index = (self._oldestIndex + self._numSamples -1) % self._numSamples return self._samples[index] end function StatsAggregatorClass:_storeStatValue(value) -- Store this as the latest value in our circular buffer. self._samples[self._oldestIndex] = value self._oldestIndex = (self._oldestIndex + 1) % self._numSamples end function StatsAggregatorClass:_getStatValue() -- Look up and return the statistic we care about. local statsService = game:GetService("Stats") if statsService == nil then return 0 end local performanceStats = statsService:FindFirstChild("PerformanceStats") if performanceStats == nil then return 0 end local itemStats = performanceStats:FindFirstChild(self._statName) if itemStats == nil then return 0 end return itemStats:GetValue() end function StatsAggregatorClass:GetTarget() -- Look up and return the statistic we care about. local statsService = game:GetService("Stats") if statsService == nil then return 0 end local performanceStats = statsService:FindFirstChild("PerformanceStats") if performanceStats == nil then return 0 end local itemStats = performanceStats:FindFirstChild(self._statMaxName) if itemStats == nil then return 0 end return itemStats:GetValue() end return StatsAggregatorClass
apache-2.0
kitala1/darkstar
scripts/globals/items/hobgoblin_pie.lua
35
1624
----------------------------------------- -- ID: 4325 -- Item: hobgoblin_pie -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 15 -- Magic 15 -- Agility 4 -- Charisma -7 -- Health Regen While Healing 2 -- Defense % 11 -- Defense Cap 60 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4325); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 15); target:addMod(MOD_MP, 15); target:addMod(MOD_AGI, 4); target:addMod(MOD_CHR, -7); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_FOOD_DEFP, 11); target:addMod(MOD_FOOD_DEF_CAP, 60); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 15); target:delMod(MOD_MP, 15); target:delMod(MOD_AGI, 4); target:delMod(MOD_CHR, -7); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_FOOD_DEFP, 11); target:delMod(MOD_FOOD_DEF_CAP, 60); end;
gpl-3.0
n1tehawk/luaext
tests/test_table.lua
1
3085
-- test luaext table functions using LuaUnit framework local lu = require("tests.luaunit") local luaext = require("luaext") require("table") -- (for checking namespace) TestTable = {} function TestTable:test_namespace() -- check namespace compliance for _, func in ipairs({"keyof", "keys", "map"}) do if luaext._config.USE_LUA_NAMESPACES then lu.assertEquals(table[func], luaext.table[func]) else lu.assertNil(table[func]) end end end function TestTable:test_keyof() local t = {"foo", nil, 42, "bar"} lu.assertEquals(luaext.table.keyof(t, "bar"), 4) lu.assertEquals(luaext.table.keyof(t, "foo"), 1) lu.assertNil(luaext.table.keyof(t, "foobar")) lu.assertEquals(luaext.table.keyof(t, 42), 3) end function TestTable:test_keys() local function assertTableContent(actual, expected) lu.assertEquals(#actual, #expected) for k, v in pairs(expected) do lu.assertNotNil(luaext.table.keyof(actual, v)) -- "v is in actual" end end local t = {XoXo=5, foo=2, bar=1, xfoo=3, barX=4, xXx=6} -- all keys from t (unsorted) local keys, count = luaext.table.keys(t) assertTableContent(keys, {"barX", "foo", "XoXo", "xfoo", "xXx", "bar"}) lu.assertEquals(count, 6) -- all keys from t (sorted in standard table.sort() order) keys, count = luaext.table.keys(t, true) lu.assertEquals(keys, {"XoXo", "bar", "barX", "foo", "xXx", "xfoo"}) lu.assertEquals(count, 6) -- custom sort on keys keys, count = luaext.table.keys({6, 4, 5}, function(a, b) return b < a; end) lu.assertEquals(keys, {3, 2, 1}) lu.assertEquals(count, 3) -- return keys of t containing an 'x', unsorted keys, count = luaext.table.keys(t, nil, string.match, "[xX]") assertTableContent(keys, {"barX", "XoXo", "xfoo", "xXx"}) lu.assertEquals(count, 4) -- return keys of t containing an 'x', sorted in standard table.sort() order keys, count = luaext.table.keys(t, true, string.match, "[xX]") lu.assertEquals(keys, {"XoXo", "barX", "xXx", "xfoo"}) lu.assertEquals(count, 4) t = {xoxo=5, foo=2, bar=1, xfoo=3, barx=4, xxx=6} -- return keys of t containing an 'x', sorted by custom function (descending order) keys, count = luaext.table.keys(t, function(a, b) return a > b; end, string.find, "x", 1, true) lu.assertEquals(keys, {"xxx", "xoxo", "xfoo", "barx"}) lu.assertEquals(count, 4) keys, count = luaext.table.keys(t, true, string.find, "^ba") lu.assertEquals(keys, {"bar", "barx"}) lu.assertEquals(count, 2) -- luaext.table.keys() with a filter function (and sorting) t = luaext.table.map({"foo", "bar", "foobar", "fubar", "bart"}, "don't care") keys, count = luaext.table.keys(t, true, string.find, "^f") lu.assertEquals(keys, {"foo", "foobar", "fubar"}) lu.assertEquals(count, 3) end function TestTable:test_map() local t = luaext.table.map( {"foo", "baar", "rubberducky", "yo"}, function(word, result_t, result_f) return (#word == 3 or #word == 4) and result_t or result_f end, "funny", "not funny") lu.assertEquals(t.yo, "not funny") lu.assertEquals(t.foo, "funny") lu.assertEquals(t.baar, "funny") lu.assertEquals(t.rubberducky, "not funny") end
mit
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/CCBAnimationManager.lua
6
6456
-------------------------------- -- @module CCBAnimationManager -- @extend Ref -------------------------------- -- @function [parent=#CCBAnimationManager] moveAnimationsFromNode -- @param self -- @param #cc.Node node -- @param #cc.Node node -------------------------------- -- @function [parent=#CCBAnimationManager] setAutoPlaySequenceId -- @param self -- @param #int int -------------------------------- -- @function [parent=#CCBAnimationManager] getDocumentCallbackNames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] actionForSoundChannel -- @param self -- @param #cc.CCBSequenceProperty ccbsequenceproperty -- @return Sequence#Sequence ret (return value: cc.Sequence) -------------------------------- -- @function [parent=#CCBAnimationManager] setBaseValue -- @param self -- @param #cc.Value value -- @param #cc.Node node -- @param #string str -------------------------------- -- @function [parent=#CCBAnimationManager] getDocumentOutletNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] getLastCompletedSequenceName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#CCBAnimationManager] setRootNode -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#CCBAnimationManager] runAnimationsForSequenceNamedTweenDuration -- @param self -- @param #char char -- @param #float float -------------------------------- -- @function [parent=#CCBAnimationManager] addDocumentOutletName -- @param self -- @param #string str -------------------------------- -- @function [parent=#CCBAnimationManager] getSequences -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] getRootContainerSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#CCBAnimationManager] setDocumentControllerName -- @param self -- @param #string str -------------------------------- -- @function [parent=#CCBAnimationManager] setObject -- @param self -- @param #cc.Ref ref -- @param #cc.Node node -- @param #string str -------------------------------- -- @function [parent=#CCBAnimationManager] getContainerSize -- @param self -- @param #cc.Node node -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#CCBAnimationManager] actionForCallbackChannel -- @param self -- @param #cc.CCBSequenceProperty ccbsequenceproperty -- @return Sequence#Sequence ret (return value: cc.Sequence) -------------------------------- -- @function [parent=#CCBAnimationManager] getDocumentOutletNames -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] addDocumentCallbackControlEvents -- @param self -- @param #cc.Control::EventType eventtype -------------------------------- -- @function [parent=#CCBAnimationManager] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#CCBAnimationManager] getKeyframeCallbacks -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] getDocumentCallbackControlEvents -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] setRootContainerSize -- @param self -- @param #size_table size -------------------------------- -- @function [parent=#CCBAnimationManager] runAnimationsForSequenceIdTweenDuration -- @param self -- @param #int int -- @param #float float -------------------------------- -- @function [parent=#CCBAnimationManager] getRunningSequenceName -- @param self -- @return char#char ret (return value: char) -------------------------------- -- @function [parent=#CCBAnimationManager] getAutoPlaySequenceId -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#CCBAnimationManager] addDocumentCallbackName -- @param self -- @param #string str -------------------------------- -- @function [parent=#CCBAnimationManager] getRootNode -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- @function [parent=#CCBAnimationManager] addDocumentOutletNode -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#CCBAnimationManager] getSequenceDuration -- @param self -- @param #char char -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#CCBAnimationManager] addDocumentCallbackNode -- @param self -- @param #cc.Node node -------------------------------- -- @function [parent=#CCBAnimationManager] runAnimationsForSequenceNamed -- @param self -- @param #char char -------------------------------- -- @function [parent=#CCBAnimationManager] getSequenceId -- @param self -- @param #char char -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#CCBAnimationManager] getDocumentCallbackNodes -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#CCBAnimationManager] setSequences -- @param self -- @param #array_table array -------------------------------- -- @function [parent=#CCBAnimationManager] debug -- @param self -------------------------------- -- @function [parent=#CCBAnimationManager] getDocumentControllerName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#CCBAnimationManager] CCBAnimationManager -- @param self return nil
mit
kitala1/darkstar
scripts/zones/Gusgen_Mines/npcs/_5gb.lua
34
1345
----------------------------------- -- Area: Gusgen Mines -- NPC: _5gb (Lever B) -- @pos 19.999 -40.561 -54.198 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --local nID = npc:getID(); --printf("id: %u", nID); local Lever = npc:getID(); npc:openDoor(2); -- Lever animation if (GetNPCByID(Lever-6):getAnimation() == 9) then GetNPCByID(Lever-7):setAnimation(9);--close door C GetNPCByID(Lever-6):setAnimation(8);--open door B GetNPCByID(Lever-5):setAnimation(9);--close door A end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
fqrouter/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-func.lua
80
1208
--[[ 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$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true func_callerid = module:option(ListValue, "func_callerid", "Caller ID related dialplan functions", "") func_callerid:value("yes", "Load") func_callerid:value("no", "Do Not Load") func_callerid:value("auto", "Load as Required") func_callerid.rmempty = true func_enum = module:option(ListValue, "func_enum", "ENUM Functions", "") func_enum:value("yes", "Load") func_enum:value("no", "Do Not Load") func_enum:value("auto", "Load as Required") func_enum.rmempty = true func_uri = module:option(ListValue, "func_uri", "URI encoding / decoding functions", "") func_uri:value("yes", "Load") func_uri:value("no", "Do Not Load") func_uri:value("auto", "Load as Required") func_uri.rmempty = true return cbimap
apache-2.0
darrenatdesignory/CG
scripts/grid.lua
1
7615
local grid = {} -- Set initial variables to 0 grid.playerPosX = 0; grid.playerPosY = 0; grid.fieldCells = {} grid.group = nil -- width and height of the grid square (use 60 for 1024/768 field size) grid.gridSize = 48 MultiTouch = require("scripts.dmc_multitouch") XML = require("scripts.xml") local xml = require( "scripts.xml" ).newParser() grid.showBackground = function(game) -- this will vary depending on the sport local background = display.newImageRect(grid.group, "images/" .. game .. ".png", 480, 360) background.x = display.contentCenterX background.y = display.contentCenterY end local strokeWidth -- Display outlines for all positions grid.buildGrid = function(game) -- display the background for the grid grid.showBackground(game) local gameParams = xml:loadFile("xml/" .. game .. ".xml") local xCount, yCount, lineColor, bgColor, layout, orientation, itemType -- create an 8 by 6 grid -- rows print( "#gameParams = " .. #gameParams.child ) for elementCount = 1, #gameParams.child, 1 do if ( gameParams.child[elementCount].name == "grid" ) then xCount = gameParams.child[elementCount].properties.cols --.value -- columns yCount = gameParams.child[elementCount].properties.rows --.value -- grid line color lineColor = gameParams.child[elementCount].properties.lineColor --grid line size strokeWidth = gameParams.child[elementCount].properties.strokeWidth -- grid background color bgColor = gameParams.child[elementCount].properties.bgColor elseif ( gameParams.child[elementCount].name == "items" ) then grid.createItemList( gameParams.child[elementCount].properties ) end end local lineColorTbl = explode(',', lineColor) local bgColorTbl = explode(',', bgColor) -- grid offset print( "content height = " .. display.contentHeight ) print( "content width = " .. display.contentWidth ) -- possibly make these xml props later local xOffset = 26 local yOffset = 40 -- create a 10-square grid for countHorizontal = 0, xCount, 1 do x = countHorizontal * grid.gridSize for countVertical = 0, yCount, 1 do local sqLine = display.newRect(grid.group, grid.gridSize * countHorizontal + xOffset, grid.gridSize * (countVertical-1) + yOffset, grid.gridSize, grid.gridSize) sqLine.strokeWidth = strokeWidth sqLine:setStrokeColor(lineColorTbl[1], lineColorTbl[2], lineColorTbl[3]) sqLine:setFillColor(bgColorTbl[1], bgColorTbl[2], bgColorTbl[3], bgColorTbl[4]) grid.fieldCells[#grid.fieldCells + 1] = sqLine --countVertical .. '-' .. countHorizontal] = sqLine; --grid:setFillColor(0.2, 50, 0, 0) if ( countHorizontal == 0 or countHorizontal == xCount ) then sqLine:setStrokeColor(0, 0, 0, 0) sqLine:setFillColor(0, 0, 0, 0 ) end if ( countVertical == 0 or countVertical == yCount ) then sqLine:setStrokeColor(0, 0, 0, 0) sqLine:setFillColor(0, 0, 0, 0 ) end end end -- execute dragging functions end grid.gridItemDrag = function(event) if ( event == nil ) then return end local t = event.target -- check to see where they released the person if ( event.phase == "ended" or event.phase == "moved" or event.phase == "began" ) then local playerx = t.x local playery = t.y local halfCell = grid.gridSize/2 local fullCell = grid.gridSize local cellx, celly, cell for tblItem = 1, #grid.fieldCells, 1 do cellx = grid.fieldCells[tblItem].x celly = grid.fieldCells[tblItem].y cell = grid.fieldCells[tblItem] -- when I start moving the item again, unhighlight this cell if ( t == cell.item and cell.item ~= nil) then --cell:setFillColor(0.5, 0.1, 0.1, 0) cell.strokeWidth = strokeWidth end -- determine if we are close to the middle of a cell if ( cellx - playerx < halfCell and celly - playery < halfCell ) then t.x = cellx t.y = celly --print( "cellx = " .. cellx .. " / celly = " .. celly ) --print( "playerx = " .. playerx .. " / playery = " .. playery ) if ( event.phase == "ended" ) then if ( cellx + halfCell > playerx and celly + halfCell > playery ) then -- check the bounds if ( celly > 0 and playery > 0 and cellx > fullCell and playerx > fullCell ) then -- gray the cell background when the item is set --cell:setFillColor( 1, 0.2, 0.2 ) cell.strokeWidth = strokeWidth + 2 --cell:setFillColor(0.5, 0.5, 0.5, 0.9) cell.item = t -- associated this item with this cell end end end -- allow users to re-position items --MultiTouch.deactivate(t) end end end end grid.createItemList = function( props ) -- horizontal or vertical item layout local layout = props.layout -- top/bottom/top/bottom item orientation local orientation = props.orientation -- type of object to display (person, letter, number, etc.) local itemType = props.itemType -- maximum number of items to show local maxItems = props.maxItems local playerTable = {} local x = 1 local player local dim = grid.gridSize local pad = 0 -- space between items local xOffset = 40 local yOffset = 20 for countHorizontal = 1, tonumber(maxItems), 1 do if ( itemType == "person" ) then player = display.newImageRect(grid.group, "images/person.png", dim, dim) elseif ( itemType == "letter" ) then player = display.newImageRect(grid.group, "images/letter.png", dim, dim) elseif ( itemType == "number" ) then player = display.newImageRect(grid.group, "images/number.png", dim, dim) end if ( layout == "vertical" ) then if ( orientation == "left" ) then player.x = dim/2 else player.x = display.contentWidth - dim/2 end player.y = (pad+dim) * countHorizontal + yOffset + (-1*dim/2) elseif ( layout == "horizontal" ) then if ( orientation == "bottom" ) then player.y = display.contentHeight - dim/2 else player.y = dim/2; end player.x = (pad+dim) * countHorizontal + xOffset end player:addEventListener(MultiTouch.MULTITOUCH_EVENT, grid.gridItemDrag); MultiTouch.activate(player, "move", "single") playerTable[x] = player x = x + 1 end end return grid
mit
kitala1/darkstar
scripts/zones/Southern_San_dOria/TextIDs.lua
3
7112
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6415; -- Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6417; -- Try trading again after sorting your inventory. ITEM_OBTAINED = 6418; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>> GIL_OBTAINED = 6419; -- Obtained <<<Numeric Parameter 0>>> gil. KEYITEM_OBTAINED = 6421; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>> KEYITEM_LOST = 6422; -- Lost key item: HOMEPOINT_SET = 24; -- Home point set! NOT_HAVE_ENOUGH_GIL = 6423; -- You do not have enough gil. LEATHER_SUPPORT = 6751; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ?Multiple Choice (Parameter 2)?[a little/ever so slightly/ever so slightly].?Prompt? GUILD_TERMINATE_CONTRACT = 6765; -- You have terminated your trading contract with the ?Multiple Choice (Parameter 1)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild and formed a new one with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt? GUILD_NEW_CONTRACT = 6773; -- You have formed a new trading contract with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt? NO_MORE_GP_ELIGIBLE = 6780; -- You are not eligible to receive guild points at this time GP_OBTAINED = 6769; -- Obtained <<<Numeric Parameter 0>>> guild points. NOT_HAVE_ENOUGH_GP = 6786; -- You do not have enough guild points. NOTHING_OUT_OF_ORDINARY = 6432; -- There is nothing out of the ordinary here.<Prompt> -- Tutorial NPC TUTORIAL_NPC = 13475; -- Greetings and well met! Guardian of the Kingdom, Alaune, at your most humble service. -- Conquest System CONQUEST = 8457; -- You've earned conquest points! -- Mission Dialogs YOU_ACCEPT_THE_MISSION = 7170; -- You accept the mission. ORIGINAL_MISSION_OFFSET = 7181; -- Bring me one of those axes, and your mission will be a success. No running away now; we've a proud country to defend! -- Dynamis dialogs YOU_CANNOT_ENTER_DYNAMIS = 7387; -- You cannot enter Dynamis PLAYERS_HAVE_NOT_REACHED_LEVEL = 7389; -- Players who have not reached level <<<Numeric Parameter 0>>> are prohibited from entering Dynamis. UNUSUAL_ARRANGEMENT_BRANCHES = 7399; -- There is an unusual arrangement of branches here. -- Quest Dialogs UNLOCK_PALADIN = 7982; -- You can now become a paladin! FLYER_REFUSED = 8153; -- Your flyer is refused. FLYER_ACCEPTED = 8802; -- The flyer is accepted. FLYER_ALREADY = 8803; -- This person already has a flyer. -- Harvest Festival TRICK_OR_TREAT = 7329; -- Trick or treat... THANK_YOU_TREAT = 7330; -- And now for your treat... HERE_TAKE_THIS = 7331; -- Here, take this... IF_YOU_WEAR_THIS = 7332; -- If you put this on and walk around, something...unexpected might happen... THANK_YOU = 7330; -- Thank you...<<<Prompt>>> -- Other dialog ITEM_DELIVERY_DIALOG = 8382; -- Parcels delivered to rooms anywhere in Vana'diel! ROSEL_DIALOG = 7759; -- Hrmm... Now, this is interesting! It pays to keep an eye on the competition. Thanks for letting me know! BLENDARE_DIALOG = 8066; -- Wait! If I had magic, maybe I could keep my brother's hands off my sweets... BLENDARE_MESSAGE = 8804; -- Blendare looks over curiously for a moment. ROSEL_MESSAGE = 8805; -- Rosel looks over curiously for a moment. MAUGIE_DIALOG = 8806; -- A magic shop, eh? Hmm... A little magic could go a long way for making a leisurely retirement! Ho ho ho! MAUGIE_MESSAGE = 8807; -- Maugie looks over curiously for a moment. ADAUNEL_DIALOG = 8808; -- A magic shop? Maybe I'll check it out one of these days. Could help with my work, even... ADAUNEL_MESSAGE = 8809; -- Adaunel looks over curiously for a moment. LEUVERET_DIALOG = 8810; -- A magic shop? That'd be a fine place to peddle my wares. I smell a profit! I'll be up to my gills in gil, I will! LEUVERET_MESSAGE = 8811; -- Leuveret looks over curiously for a moment. PAUNELIE_DIALOG = 8282; -- I'm sorry, can I help you? -- Shop Texts LUSIANE_SHOP_DIALOG = 7933; -- Hello! Let Taumila's handle all your sundry needs! OSTALIE_SHOP_DIALOG = 7934; -- Welcome, customer. Please have a look. ASH_THADI_ENE_SHOP_DIALOG = 7955; -- Welcome to Helbort's Blades! SHILAH_SHOP_DIALOG = 8087; -- Welcome, weary traveler. Make yourself at home! CLETAE_DIALOG = 8173; -- Why, hello. All our skins are guild-approved. KUEH_IGUNAHMORI_DIALOG = 8174; -- Good day! We have lots in stock today. FERDOULEMIONT_SHOP_DIALOG = 7933; -- Hello! AVELINE_SHOP_DIALOG = 8392; -- Welcome to Raimbroy's Grocery! BENAIGE_SHOP_DIALOG = 8393; -- Looking for something in particular? MACHIELLE_OPEN_DIALOG = 8388; -- Might I interest you in produce from Norvallen? CORUA_OPEN_DIALOG = 8389; -- Ronfaure produce for sale! PHAMELISE_OPEN_DIALOG = 8390; -- I've got fresh produce from Zulkheim! APAIREMANT_OPEN_DIALOG = 8391; -- Might you be interested in produce from Gustaberg PAUNELIE_SHOP_DIALOG = 8287; -- These magic shells are full of mysteries... MACHIELLE_CLOSED_DIALOG = 8395; -- We want to sell produce from Norvallen, but the entire region is under foreign control! CORUA_CLOSED_DIALOG = 8396; -- We specialize in Ronfaure produce, but we cannot import from that region without a strong San d'Orian presence there. PHAMELISE_CLOSED_DIALOG = 8397; -- I'd be making a killing selling produce from Zulkheim, but the region's under foreign control! APAIREMANT_CLOSED_DIALOG = 8398; -- I'd love to import produce from Gustaberg, but the foreign powers in control there make me feel unsafe! POURETTE_OPEN_DIALOG = 8399; -- Derfland produce for sale! POURETTE_CLOSED_DIALOG = 8400; -- Listen, adventurer... I can't import from Derfland until the region knows San d'Orian power! MIOGIQUE_SHOP_DIALOG = 8393; -- Looking for something in particular? CARAUTIA_SHOP_DIALOG = 8394; -- Well, what sort of armor would you like? VALERIANO_SHOP_DIALOG = 8105; -- Oh, a fellow outsider! We are Troupe Valeriano. I am Valeriano, at your service! RAMINEL_DELIVERY = 8070; -- Here's your delivery! LUSIANE_THANK = 8071; -- Thank you!?Prompt? RAMINEL_DELIVERIES = 8072; -- Sorry, I have deliveries to make! -- conquest Base CONQUEST_BASE = 7006; -- Tallying conquest results...
gpl-3.0
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Altiret.lua
36
2942
----------------------------------- -- Area: Port San d'Oria -- NPC: Altiret -- NPC for Quest "The Pickpocket" ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); -- "The Pickpocket" Quest status thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET); -- "The Pickpocket" Quest, trading for light axe if (thePickpocket == 1) then count = trade:getItemCount(); freeSlot = player:getFreeSlotsCount(); giltGlasses = trade:hasItemQty(579, 1); if (count == 1 and freeSlot > 0 and giltGlasses == true) then player:tradeComplete(); player:addFame(SANDORIA,SAN_FAME*30); player:addTitle(PICKPOCKET_PINCHER); player:completeQuest(SANDORIA,THE_PICKPOCKET); player:startEvent(0x0226); elseif (giltGlasses == false) then player:startEvent(0x0227); else player:messageSpecial(6402, 579); -- CANNOT_OBTAIN_ITEM end; -- "Flyers for Regine" elseif (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); elseif (MagicFlyer == false) then player:startEvent(0x0227); end; else player:startEvent(0x0227); end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Vars for the Quest "The Pickpocket" thePickpocket = player:getQuestStatus(SANDORIA, THE_PICKPOCKET); openingCS = player:getVar("thePickpocket"); -- "The Pickpocket" Quest dialog if (thePickpocket == 0 and openingCS == 1) then player:startEvent(0x0223); player:addQuest(SANDORIA,THE_PICKPOCKET); elseif (thePickpocket == 1) then player:startEvent(0x0223); elseif (thePickpocket == 2) then player:startEvent(0x0244); else player:startEvent(0x022f); 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); -- "The Pickpocket" reward with light axe, done with quest if (csid == 0x0226) then player:addItem(16667); player:messageSpecial(6403, 16667); end; end;
gpl-3.0
ominux/torch7
test/timeSort.lua
68
5063
-- gnuplot.figure(2) -- Test torch sort, show it suffers from the problems of quicksort -- i.e. complexity O(N^2) in worst-case of sorted list require 'gnuplot' local cmd = torch.CmdLine() cmd:option('-N', 10^7, 'Maximum array size') cmd:option('-p', 50, 'Number of points in logspace') cmd:option('-r', 20, 'Number of repetitions') local options = cmd:parse(arg or {}) function main() local log10 = math.log10 or function(x) return math.log(x, 10) end local pow10 = torch.linspace(1,log10(options.N), options.p) local num_sizes = options.p local num_reps = options.r local old_rnd = torch.zeros(num_sizes, num_reps) local old_srt = torch.zeros(num_sizes, num_reps) local old_cst = torch.zeros(num_sizes, num_reps) local new_rnd = torch.zeros(num_sizes, num_reps) local new_srt = torch.zeros(num_sizes, num_reps) local new_cst = torch.zeros(num_sizes, num_reps) local ratio_rnd = torch.zeros(num_sizes, num_reps) local ratio_srt = torch.zeros(num_sizes, num_reps) local ratio_cst = torch.zeros(num_sizes, num_reps) -- Ascending sort uses new sort local function time_sort(x) collectgarbage() local start = os.clock() torch.sort(x,false) return (os.clock()-start) end -- Descending sort uses old sort local function time_old_sort(x) collectgarbage() local start = os.clock() torch.sort(x,true) return (os.clock()-start) end local benches = { function(i,j,n) -- on random local input = torch.rand(n) new_rnd[i][j] = time_sort(input:clone()) old_rnd[i][j] = time_old_sort(input:clone()) end, function(i,j,n) -- on sorted new_srt[i][j] = time_sort(torch.linspace(0,1,n)) old_srt[i][j] = time_old_sort(torch.linspace(0,1,n):add(-1):mul(-1)) -- old_time is called on descending sort, hence the reversed input end, function(i,j,n) -- on constant new_cst[i][j] = time_sort(torch.zeros(n)) old_cst[i][j] = time_old_sort(torch.zeros(n)) end } local num_benches = #benches local num_exps = num_sizes * num_benches * num_reps -- Full randomization local perm = torch.randperm(num_exps):long() local perm_benches = torch.Tensor(num_exps) local perm_reps = torch.Tensor(num_exps) local perm_sizes = torch.Tensor(num_exps) local l = 1 for i=1, num_sizes do for j=1, num_reps do for k=1, num_benches do perm_benches[ perm[l] ] = k perm_reps[ perm[l] ] = j perm_sizes[ perm[l] ] = i l = l+1 end end end local pc = 0 for j = 1, num_exps do local n = 10^pow10[perm_sizes[j]] -- print(string.format('rep %d / %d, bench %d, size %d, rep %d\n', j, num_exps, perm_benches[j], n, perm_reps[j])) if math.floor(100*j/num_exps) > pc then pc = math.floor(100*j/num_exps) io.write('.') if pc % 10 == 0 then io.write(' ' .. pc .. '%\n') end io.flush() end benches[perm_benches[j]](perm_sizes[j], perm_reps[j], n) end ratio_rnd = torch.cdiv(old_rnd:mean(2), new_rnd:mean(2)) ratio_srt = torch.cdiv(old_srt:mean(2), new_srt:mean(2)) ratio_cst = torch.cdiv(old_cst:mean(2), new_cst:mean(2)) local N = pow10:clone():apply(function(x) return 10^x end) gnuplot.setterm('x11') gnuplot.figure(1) gnuplot.raw('set log x; set mxtics 10') gnuplot.raw('set grid mxtics mytics xtics ytics') gnuplot.raw('set xrange [' .. N:min() .. ':' .. N:max() .. ']' ) gnuplot.plot({'Random - new', N, new_rnd:mean(2)}, {'Sorted - new', N, new_srt:mean(2)}, {'Constant - new', N, new_cst:mean(2)}, {'Random - old', N, old_rnd:mean(2)}, {'Sorted - old', N, old_srt:mean(2)}, {'Constant - old', N, old_cst:mean(2)}) gnuplot.xlabel('N') gnuplot.ylabel('Time (s)') gnuplot.figprint('benchmarkTime.png') gnuplot.figure(2) gnuplot.raw('set log x; set mxtics 10') gnuplot.raw('set grid mxtics mytics xtics ytics') gnuplot.raw('set xrange [' .. N:min() .. ':' .. N:max() .. ']' ) gnuplot.plot({'Random', N, ratio_rnd:mean(2)}, {'Sorted', N, ratio_srt:mean(2)}, {'Constant', N, ratio_cst:mean(2)}) gnuplot.xlabel('N') gnuplot.ylabel('Speed-up Factor (s)') gnuplot.figprint('benchmarkRatio.png') torch.save('benchmark.t7', { new_rnd=new_rnd, new_srt=new_srt, new_cst=new_cst, old_rnd=old_rnd, old_srt=old_srt, old_cst=old_cst, ratio_rnd=ratio_rnd, ratio_srt=ratio_srt, ratio_cst=ratio_cst, pow10 = pow10, num_reps = num_reps }) end main()
bsd-3-clause
kitala1/darkstar
scripts/globals/mobskills/Barbed_Crescent.lua
43
1031
--------------------------------------------------- -- Barbed Crescent -- Damage. Additional Effect: Accuracy Down. -- Area of Effect is centered around caster. -- The Additional Effect: Accuracy Down may not always process. -- Duration: Three minutes ? --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.7; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); local typeEffect = EFFECT_ACCURACY_DOWN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 50, 0, 120); target:delHP(dmg); return dmg; end;
gpl-3.0
zhaoluxyz/Hugula
Client/tools/luaTools/lua/jit/dis_x86.lua
74
29330
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2014 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = format("0x%08x", imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") 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 ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(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) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64_(code, addr, out) local ctx = create_(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q 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 local function disass64_(code, addr, out) create64_(code, addr, out):disass() end -- Return register name for RID. local function regname_(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64_(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. module(...) create = create_ create64 = create64_ disass = disass_ disass64 = disass64_ regname = regname_ regname64 = regname64_
mit
kitala1/darkstar
scripts/zones/Davoi/TextIDs.lua
5
1657
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6382; -- Obtained: <item>. GIL_OBTAINED = 6383; -- Obtained <number> gil. KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6388; -- You obtain FISHING_MESSAGE_OFFSET = 7195; -- You can't fish here. CAVE_HAS_BEEN_SEALED_OFF = 7333; -- The cave has been sealed off by some sort of barrier. MAY_BE_SOME_WAY_TO_BREAK = 7334; -- There may be some way to break through. POWER_OF_THE_ORB_ALLOW_PASS = 7336; -- The disruptive power of the orb allows passage through the barrier. QUEMARICOND_DIALOG = 7355; -- I can't believe I've lost my way! YOU_SEE_NOTHING = 7389; -- There is nothing here. AN_ORCISH_STORAGE_HOLE = 7431; -- An Orcish storage hole. There is something inside, but you cannot open it without a key. A_WELL = 7433; -- A well, presumably dug by Orcs. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7451; -- You unlock the chest! CHEST_FAIL = 7452; -- Fails to open the chest. CHEST_TRAP = 7453; -- The chest was trapped! CHEST_WEAK = 7454; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7455; -- The chest was a mimic! CHEST_MOOGLE = 7456; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7457; -- The chest was but an illusion... CHEST_LOCKED = 7458; -- The chest appears to be locked. -- conquest Base CONQUEST_BASE = 7036; -- Tallying conquest results...
gpl-3.0
sylvanaar/IDLua
testdata/non-test-system-files/lua5.1-tests/api.lua
3
19010
if T==nil then (Message or print)('\a\n >>> testC not active: skipping API tests <<<\n\a') return end function tcheck (t1, t2) table.remove(t1, 1) -- remove code assert(table.getn(t1) == table.getn(t2)) for i=1,table.getn(t1) do assert(t1[i] == t2[i]) end end function pack(...) return arg end print('testing C API') -- testing allignment a = T.d2s(12458954321123) assert(string.len(a) == 8) -- sizeof(double) assert(T.s2d(a) == 12458954321123) a,b, c = T.testC("pushnum 1; pushnum 2; pushnum 3; return 2") assert(a == 2 and b == 3 and not c) -- test that all trues are equal a,b,c = T.testC("pushbool 1; pushbool 2; pushbool 0; return 3") assert(a == b and a == true and c == false) a,b,c = T.testC"pushbool 0; pushbool 10; pushnil;\ tobool -3; tobool -3; tobool -3; return 3" assert(a==0 and b==1 and c==0) a,b,c = T.testC("gettop; return 2", 10, 20, 30, 40) assert(a == 40 and b == 5 and not c) t = pack(T.testC("settop 5; gettop; return .", 2, 3)) tcheck(t, {n=4,2,3}) t = pack(T.testC("settop 0; settop 15; return 10", 3, 1, 23)) assert(t.n == 10 and t[1] == nil and t[10] == nil) t = pack(T.testC("remove -2; gettop; return .", 2, 3, 4)) tcheck(t, {n=2,2,4}) t = pack(T.testC("insert -1; gettop; return .", 2, 3)) tcheck(t, {n=2,2,3}) t = pack(T.testC("insert 3; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=4,2,5,3,4}) t = pack(T.testC("replace 2; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=3,5,3,4}) t = pack(T.testC("replace -2; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=3,2,3,5}) t = pack(T.testC("remove 3; gettop; return .", 2, 3, 4, 5)) tcheck(t, {n=3,2,4,5}) t = pack(T.testC("insert 3; pushvalue 3; remove 3; pushvalue 2; remove 2; \ insert 2; pushvalue 1; remove 1; insert 1; \ insert -2; pushvalue -2; remove -3; gettop; return .", 2, 3, 4, 5, 10, 40, 90)) tcheck(t, {n=7,2,3,4,5,10,40,90}) t = pack(T.testC("concat 5; gettop; return .", "alo", 2, 3, "joao", 12)) tcheck(t, {n=1,"alo23joao12"}) -- testing MULTRET t = pack(T.testC("rawcall 2,-1; gettop; return .", function (a,b) return 1,2,3,4,a,b end, "alo", "joao")) tcheck(t, {n=6,1,2,3,4,"alo", "joao"}) do -- test returning more results than fit in the caller stack local a = {} for i=1,1000 do a[i] = true end; a[999] = 10 local b = T.testC([[call 1 -1; pop 1; tostring -1; return 1]], unpack, a) assert(b == "10") end -- testing lessthan assert(T.testC("lessthan 2 5, return 1", 3, 2, 2, 4, 2, 2)) assert(T.testC("lessthan 5 2, return 1", 4, 2, 2, 3, 2, 2)) assert(not T.testC("lessthan 2 -3, return 1", "4", "2", "2", "3", "2", "2")) assert(not T.testC("lessthan -3 2, return 1", "3", "2", "2", "4", "2", "2")) local b = {__lt = function (a,b) return a[1] < b[1] end} local a1,a3,a4 = setmetatable({1}, b), setmetatable({3}, b), setmetatable({4}, b) assert(T.testC("lessthan 2 5, return 1", a3, 2, 2, a4, 2, 2)) assert(T.testC("lessthan 5 -6, return 1", a4, 2, 2, a3, 2, 2)) a,b = T.testC("lessthan 5 -6, return 2", a1, 2, 2, a3, 2, 20) assert(a == 20 and b == false) -- testing lua_is function count (x, n) n = n or 2 local prog = [[ isnumber %d; isstring %d; isfunction %d; iscfunction %d; istable %d; isuserdata %d; isnil %d; isnull %d; return 8 ]] prog = string.format(prog, n, n, n, n, n, n, n, n) local a,b,c,d,e,f,g,h = T.testC(prog, x) return a+b+c+d+e+f+g+(100*h) end assert(count(3) == 2) assert(count('alo') == 1) assert(count('32') == 2) assert(count({}) == 1) assert(count(print) == 2) assert(count(function () end) == 1) assert(count(nil) == 1) assert(count(io.stdin) == 1) assert(count(nil, 15) == 100) -- testing lua_to... function to (s, x, n) n = n or 2 return T.testC(string.format("%s %d; return 1", s, n), x) end assert(to("tostring", {}) == nil) assert(to("tostring", "alo") == "alo") assert(to("tostring", 12) == "12") assert(to("tostring", 12, 3) == nil) assert(to("objsize", {}) == 0) assert(to("objsize", "alo\0\0a") == 6) assert(to("objsize", T.newuserdata(0)) == 0) assert(to("objsize", T.newuserdata(101)) == 101) assert(to("objsize", 12) == 2) assert(to("objsize", 12, 3) == 0) assert(to("tonumber", {}) == 0) assert(to("tonumber", "12") == 12) assert(to("tonumber", "s2") == 0) assert(to("tonumber", 1, 20) == 0) a = to("tocfunction", math.deg) assert(a(3) == math.deg(3) and a ~= math.deg) -- testing errors a = T.testC([[ loadstring 2; call 0,1; pushvalue 3; insert -2; call 1, 1; call 0, 0; return 1 ]], "x=150", function (a) assert(a==nil); return 3 end) assert(type(a) == 'string' and x == 150) function check3(p, ...) assert(arg.n == 3) assert(string.find(arg[3], p)) end check3(":1:", T.testC("loadstring 2; gettop; return .", "x=")) check3("cannot read", T.testC("loadfile 2; gettop; return .", ".")) check3("cannot open xxxx", T.testC("loadfile 2; gettop; return .", "xxxx")) -- testing table access a = {x=0, y=12} x, y = T.testC("gettable 2; pushvalue 4; gettable 2; return 2", a, 3, "y", 4, "x") assert(x == 0 and y == 12) T.testC("settable -5", a, 3, 4, "x", 15) assert(a.x == 15) a[a] = print x = T.testC("gettable 2; return 1", a) -- table and key are the same object! assert(x == print) T.testC("settable 2", a, "x") -- table and key are the same object! assert(a[a] == "x") b = setmetatable({p = a}, {}) getmetatable(b).__index = function (t, i) return t.p[i] end k, x = T.testC("gettable 3, return 2", 4, b, 20, 35, "x") assert(x == 15 and k == 35) getmetatable(b).__index = function (t, i) return a[i] end getmetatable(b).__newindex = function (t, i,v ) a[i] = v end y = T.testC("insert 2; gettable -5; return 1", 2, 3, 4, "y", b) assert(y == 12) k = T.testC("settable -5, return 1", b, 3, 4, "x", 16) assert(a.x == 16 and k == 4) a[b] = 'xuxu' y = T.testC("gettable 2, return 1", b) assert(y == 'xuxu') T.testC("settable 2", b, 19) assert(a[b] == 19) -- testing next a = {} t = pack(T.testC("next; gettop; return .", a, nil)) tcheck(t, {n=1,a}) a = {a=3} t = pack(T.testC("next; gettop; return .", a, nil)) tcheck(t, {n=3,a,'a',3}) t = pack(T.testC("next; pop 1; next; gettop; return .", a, nil)) tcheck(t, {n=1,a}) -- testing upvalues do local A = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]] t, b, c = A([[pushvalue U0; pushvalue U1; pushvalue U2; return 3]]) assert(b == 10 and c == 20 and type(t) == 'table') a, b = A([[tostring U3; tonumber U4; return 2]]) assert(a == nil and b == 0) A([[pushnum 100; pushnum 200; replace U2; replace U1]]) b, c = A([[pushvalue U1; pushvalue U2; return 2]]) assert(b == 100 and c == 200) A([[replace U2; replace U1]], {x=1}, {x=2}) b, c = A([[pushvalue U1; pushvalue U2; return 2]]) assert(b.x == 1 and c.x == 2) T.checkmemory() end local f = T.testC[[ pushnum 10; pushnum 20; pushcclosure 2; return 1]] assert(T.upvalue(f, 1) == 10 and T.upvalue(f, 2) == 20 and T.upvalue(f, 3) == nil) T.upvalue(f, 2, "xuxu") assert(T.upvalue(f, 2) == "xuxu") -- testing environments assert(T.testC"pushvalue G; return 1" == _G) assert(T.testC"pushvalue E; return 1" == _G) local a = {} T.testC("replace E; return 1", a) assert(T.testC"pushvalue G; return 1" == _G) assert(T.testC"pushvalue E; return 1" == a) assert(debug.getfenv(T.testC) == a) assert(debug.getfenv(T.upvalue) == _G) -- userdata inherit environment local u = T.testC"newuserdata 0; return 1" assert(debug.getfenv(u) == a) -- functions inherit environment u = T.testC"pushcclosure 0; return 1" assert(debug.getfenv(u) == a) debug.setfenv(T.testC, _G) assert(T.testC"pushvalue E; return 1" == _G) local b = newproxy() assert(debug.getfenv(b) == _G) assert(debug.setfenv(b, a)) assert(debug.getfenv(b) == a) -- testing locks (refs) -- reuse of references local i = T.ref{} T.unref(i) assert(T.ref{} == i) Arr = {} Lim = 100 for i=1,Lim do -- lock many objects Arr[i] = T.ref({}) end assert(T.ref(nil) == -1 and T.getref(-1) == nil) T.unref(-1); T.unref(-1) for i=1,Lim do -- unlock all them T.unref(Arr[i]) end function printlocks () local n = T.testC("gettable R; return 1", "n") print("n", n) for i=0,n do print(i, T.testC("gettable R; return 1", i)) end end for i=1,Lim do -- lock many objects Arr[i] = T.ref({}) end for i=1,Lim,2 do -- unlock half of them T.unref(Arr[i]) end assert(type(T.getref(Arr[2])) == 'table') assert(T.getref(-1) == nil) a = T.ref({}) collectgarbage() assert(type(T.getref(a)) == 'table') -- colect in cl the `val' of all collected userdata tt = {} cl = {n=0} A = nil; B = nil local F F = function (x) local udval = T.udataval(x) table.insert(cl, udval) local d = T.newuserdata(100) -- cria lixo d = nil assert(debug.getmetatable(x).__gc == F) loadstring("table.insert({}, {})")() -- cria mais lixo collectgarbage() -- forca coleta de lixo durante coleta! assert(debug.getmetatable(x).__gc == F) -- coleta anterior nao melou isso? local dummy = {} -- cria lixo durante coleta if A ~= nil then assert(type(A) == "userdata") assert(T.udataval(A) == B) debug.getmetatable(A) -- just acess it end A = x -- ressucita userdata B = udval return 1,2,3 end tt.__gc = F -- test whether udate collection frees memory in the right time do collectgarbage(); collectgarbage(); local x = collectgarbage("count"); local a = T.newuserdata(5001) assert(T.testC("objsize 2; return 1", a) == 5001) assert(collectgarbage("count") >= x+4) a = nil collectgarbage(); assert(collectgarbage("count") <= x+1) -- udata without finalizer x = collectgarbage("count") collectgarbage("stop") for i=1,1000 do newproxy(false) end assert(collectgarbage("count") > x+10) collectgarbage() assert(collectgarbage("count") <= x+1) -- udata with finalizer x = collectgarbage("count") collectgarbage() collectgarbage("stop") a = newproxy(true) getmetatable(a).__gc = function () end for i=1,1000 do newproxy(a) end assert(collectgarbage("count") >= x+10) collectgarbage() -- this collection only calls TM, without freeing memory assert(collectgarbage("count") >= x+10) collectgarbage() -- now frees memory assert(collectgarbage("count") <= x+1) end collectgarbage("stop") -- create 3 userdatas with tag `tt' a = T.newuserdata(0); debug.setmetatable(a, tt); na = T.udataval(a) b = T.newuserdata(0); debug.setmetatable(b, tt); nb = T.udataval(b) c = T.newuserdata(0); debug.setmetatable(c, tt); nc = T.udataval(c) -- create userdata without meta table x = T.newuserdata(4) y = T.newuserdata(0) assert(debug.getmetatable(x) == nil and debug.getmetatable(y) == nil) d=T.ref(a); e=T.ref(b); f=T.ref(c); t = {T.getref(d), T.getref(e), T.getref(f)} assert(t[1] == a and t[2] == b and t[3] == c) t=nil; a=nil; c=nil; T.unref(e); T.unref(f) collectgarbage() -- check that unref objects have been collected assert(table.getn(cl) == 1 and cl[1] == nc) x = T.getref(d) assert(type(x) == 'userdata' and debug.getmetatable(x) == tt) x =nil tt.b = b -- create cycle tt=nil -- frees tt for GC A = nil b = nil T.unref(d); n5 = T.newuserdata(0) debug.setmetatable(n5, {__gc=F}) n5 = T.udataval(n5) collectgarbage() assert(table.getn(cl) == 4) -- check order of collection assert(cl[2] == n5 and cl[3] == nb and cl[4] == na) a, na = {}, {} for i=30,1,-1 do a[i] = T.newuserdata(0) debug.setmetatable(a[i], {__gc=F}) na[i] = T.udataval(a[i]) end cl = {} a = nil; collectgarbage() assert(table.getn(cl) == 30) for i=1,30 do assert(cl[i] == na[i]) end na = nil for i=2,Lim,2 do -- unlock the other half T.unref(Arr[i]) end x = T.newuserdata(41); debug.setmetatable(x, {__gc=F}) assert(T.testC("objsize 2; return 1", x) == 41) cl = {} a = {[x] = 1} x = T.udataval(x) collectgarbage() -- old `x' cannot be collected (`a' still uses it) assert(table.getn(cl) == 0) for n in pairs(a) do a[n] = nil end collectgarbage() assert(table.getn(cl) == 1 and cl[1] == x) -- old `x' must be collected -- testing lua_equal assert(T.testC("equal 2 4; return 1", print, 1, print, 20)) assert(T.testC("equal 3 2; return 1", 'alo', "alo")) assert(T.testC("equal 2 3; return 1", nil, nil)) assert(not T.testC("equal 2 3; return 1", {}, {})) assert(not T.testC("equal 2 3; return 1")) assert(not T.testC("equal 2 3; return 1", 3)) -- testing lua_equal with fallbacks do local map = {} local t = {__eq = function (a,b) return map[a] == map[b] end} local function f(x) local u = T.newuserdata(0) debug.setmetatable(u, t) map[u] = x return u end assert(f(10) == f(10)) assert(f(10) ~= f(11)) assert(T.testC("equal 2 3; return 1", f(10), f(10))) assert(not T.testC("equal 2 3; return 1", f(10), f(20))) t.__eq = nil assert(f(10) ~= f(10)) end print'+' ------------------------------------------------------------------------- do -- testing errors during GC local a = {} for i=1,20 do a[i] = T.newuserdata(i) -- creates several udata end for i=1,20,2 do -- mark half of them to raise error during GC debug.setmetatable(a[i], {__gc = function (x) error("error inside gc") end}) end for i=2,20,2 do -- mark the other half to count and to create more garbage debug.setmetatable(a[i], {__gc = function (x) loadstring("A=A+1")() end}) end _G.A = 0 a = 0 while 1 do if xpcall(collectgarbage, function (s) a=a+1 end) then break -- stop if no more errors end end assert(a == 10) -- number of errors assert(A == 10) -- number of normal collections end ------------------------------------------------------------------------- -- test for userdata vals do local a = {}; local lim = 30 for i=0,lim do a[i] = T.pushuserdata(i) end for i=0,lim do assert(T.udataval(a[i]) == i) end for i=0,lim do assert(T.pushuserdata(i) == a[i]) end for i=0,lim do a[a[i]] = i end for i=0,lim do a[T.pushuserdata(i)] = i end assert(type(tostring(a[1])) == "string") end ------------------------------------------------------------------------- -- testing multiple states T.closestate(T.newstate()); L1 = T.newstate() assert(L1) assert(pack(T.doremote(L1, "function f () return 'alo', 3 end; f()")).n == 0) a, b = T.doremote(L1, "return f()") assert(a == 'alo' and b == '3') T.doremote(L1, "_ERRORMESSAGE = nil") -- error: `sin' is not defined a, b = T.doremote(L1, "return sin(1)") assert(a == nil and b == 2) -- 2 == run-time error -- error: syntax error a, b, c = T.doremote(L1, "return a+") assert(a == nil and b == 3 and type(c) == "string") -- 3 == syntax error T.loadlib(L1) a, b = T.doremote(L1, [[ a = strlibopen() a = packageopen() a = baselibopen(); assert(a == _G and require("_G") == a) a = iolibopen(); assert(type(a.read) == "function") assert(require("io") == a) a = tablibopen(); assert(type(a.insert) == "function") a = dblibopen(); assert(type(a.getlocal) == "function") a = mathlibopen(); assert(type(a.sin) == "function") return string.sub('okinama', 1, 2) ]]) assert(a == "ok") T.closestate(L1); L1 = T.newstate() T.loadlib(L1) T.doremote(L1, "a = {}") T.testC(L1, [[pushstring a; gettable G; pushstring x; pushnum 1; settable -3]]) assert(T.doremote(L1, "return a.x") == "1") T.closestate(L1) L1 = nil print('+') ------------------------------------------------------------------------- -- testing memory limits ------------------------------------------------------------------------- collectgarbage() T.totalmem(T.totalmem()+5000) -- set low memory limit (+5k) assert(not pcall(loadstring"local a={}; for i=1,100000 do a[i]=i end")) T.totalmem(1000000000) -- restore high limit local function stack(x) if x>0 then stack(x-1) end end -- test memory errors; increase memory limit in small steps, so that -- we get memory errors in different parts of a given task, up to there -- is enough memory to complete the task without errors function testamem (s, f) collectgarbage() stack(10) -- ensure minimum stack size local M = T.totalmem() local oldM = M local a,b = nil while 1 do M = M+3 -- increase memory limit in small steps T.totalmem(M) a, b = pcall(f) if a and b then break end -- stop when no more errors collectgarbage() if not a and not string.find(b, "memory") then -- `real' error? T.totalmem(1000000000) -- restore high limit error(b, 0) end end T.totalmem(1000000000) -- restore high limit print("\nlimit for " .. s .. ": " .. M-oldM) return b end -- testing memory errors when creating a new state b = testamem("state creation", T.newstate) T.closestate(b); -- close new state -- testing threads function expand (n,s) if n==0 then return "" end local e = string.rep("=", n) return string.format("T.doonnewstack([%s[ %s;\n collectgarbage(); %s]%s])\n", e, s, expand(n-1,s), e) end G=0; collectgarbage(); a =collectgarbage("count") loadstring(expand(20,"G=G+1"))() assert(G==20); collectgarbage(); -- assert(gcinfo() <= a+1) testamem("thread creation", function () return T.doonnewstack("x=1") == 0 -- try to create thread end) -- testing memory x compiler testamem("loadstring", function () return loadstring("x=1") -- try to do a loadstring end) local testprog = [[ local function foo () return end local t = {"x"} a = "aaa" for _, v in ipairs(t) do a=a..v end return true ]] -- testing memory x dofile _G.a = nil local t =os.tmpname() local f = assert(io.open(t, "w")) f:write(testprog) f:close() testamem("dofile", function () local a = loadfile(t) return a and a() end) assert(os.remove(t)) assert(_G.a == "aaax") -- other generic tests testamem("string creation", function () local a, b = string.gsub("alo alo", "(a)", function (x) return x..'b' end) return (a == 'ablo ablo') end) testamem("dump/undump", function () local a = loadstring(testprog) local b = a and string.dump(a) a = b and loadstring(b) return a and a() end) local t = os.tmpname() testamem("file creation", function () local f = assert(io.open(t, 'w')) assert (not io.open"nomenaoexistente") io.close(f); return not loadfile'nomenaoexistente' end) assert(os.remove(t)) testamem("table creation", function () local a, lim = {}, 10 for i=1,lim do a[i] = i; a[i..'a'] = {} end return (type(a[lim..'a']) == 'table' and a[lim] == lim) end) local a = 1 close = nil testamem("closure creation", function () function close (b,c) return function (x) return a+b+c+x end end return (close(2,3)(4) == 10) end) testamem("coroutines", function () local a = coroutine.wrap(function () coroutine.yield(string.rep("a", 10)) return {} end) assert(string.len(a()) == 10) return a() end) print'+' -- testing some auxlib functions assert(T.gsub("alo.alo.uhuh.", ".", "//") == "alo//alo//uhuh//") assert(T.gsub("alo.alo.uhuh.", "alo", "//") == "//.//.uhuh.") assert(T.gsub("", "alo", "//") == "") assert(T.gsub("...", ".", "/.") == "/././.") assert(T.gsub("...", "...", "") == "") print'OK'
apache-2.0
NiFiLocal/nifi-minifi-cpp
thirdparty/civetweb-1.10/test/HugeText.lua
12
4022
-- (c) bel2125, 2010 -- MIT public licence local letterCode = { [' '] = {0,0,0,0,0}, ['!'] = {0,0,95,0,0}, ['"'] = {0,3,4,3,0}, ['#'] = {34,127,34,127,34}, ['$'] = {36,42,127,42,18}, ['%'] = {35,19,8,100,98}, ['&'] = {54,73,85,34,80}, ["'"] = {0,11,7,0,0}, ['('] = {0,28,34,65,0}, [')'] = {0,65,34,28,0}, ['*'] = {20,8,62,8,20}, ['+'] = {8,8,62,8,8}, [','] = {0,88,56,0,0}, ['-'] = {8,8,8,8,8}, ['.'] = {0,96,96,0,0}, ['/'] = {32,16,8,4,2}, ['0'] = {62,81,73,69,62}, ['1'] = {0,66,127,64,0}, ['2'] = {66,97,81,73,70}, ['3'] = {65,73,77,75,49}, ['4'] = {24,20,18,127,16}, ['5'] = {39,69,69,69,57}, ['6'] = {60,74,73,73,48}, ['7'] = {1,1,121,5,3}, ['8'] = {54,73,73,73,54}, ['9'] = {6,73,73,41,30}, [':'] = {0,54,54,0,0}, [';'] = {0,91,59,0,0}, ['<'] = {8,20,34,65,0}, ['='] = {20,20,20,20,20}, ['>'] = {0,65,34,20,8}, ['?'] = {2,1,81,9,6}, ['@'] = {50,73,121,65,62}, ['A'] = {124,18,17,18,124}, ['B'] = {65,127,73,73,54}, ['C'] = {62,65,65,65,34}, ['D'] = {65,127,65,65,62}, ['E'] = {127,73,73,73,65}, ['F'] = {127,9,9,9,1}, ['G'] = {62,65,65,73,57}, ['H'] = {127,8,8,8,127}, ['I'] = {0,65,127,65,0}, ['J'] = {32,64,65,63,1}, ['K'] = {127,8,20,34,65}, ['L'] = {127,64,64,64,64}, ['M'] = {127,2,12,2,127}, ['N'] = {127,4,8,16,127}, ['O'] = {62,65,65,65,62}, ['P'] = {127,9,9,9,6}, ['Q'] = {62,65,81,33,94}, ['R'] = {127,9,25,41,70}, ['S'] = {38,73,73,73,50}, ['T'] = {1,1,127,1,1}, ['U'] = {63,64,64,64,63}, ['V'] = {7,24,96,24,7}, ['W'] = {127,32,24,32,127}, ['X'] = {99,20,8,20,99}, ['Y'] = {3,4,120,4,3}, ['Z'] = {97,81,73,69,67}, ['['] = {0,127,65,65,0}, ['\\'] = {2,4,8,16,32}, [']'] = {0,65,65,127,0}, ['^'] = {24,4,2,4,24}, ['_'] = {64,64,64,64,64}, ['`'] = {0,0,7,11,0}, ['a'] = {56,68,68,60,64}, ['b'] = {127,72,68,68,56}, ['c'] = {56,68,68,68,32}, ['d'] = {56,68,68,72,127}, ['e'] = {56,84,84,84,24}, ['f'] = {0,8,126,9,2}, ['g'] = {8,84,84,60,0}, ['h'] = {127,4,4,120,0}, ['i'] = {0,0,125,0,0}, ['j'] = {32,64,68,61,0}, ['k'] = {127,16,40,68,0}, ['l'] = {0,0,127,0,0}, ['m'] = {120,4,120,4,120}, ['n'] = {124,8,4,4,120}, ['o'] = {56,68,68,68,56}, ['p'] = {124,20,20,20,8}, ['q'] = {24,36,20,124,64}, ['r'] = {124,8,4,4,0}, ['s'] = {72,84,84,84,32}, ['t'] = {4,62,68,32,0}, ['u'] = {60,64,64,32,124}, ['v'] = {28,32,64,32,28}, ['w'] = {60,64,48,64,60}, ['x'] = {68,36,124,72,68}, ['y'] = {12,80,80,60,0}, ['z'] = {68,100,84,76,68}, ['{'] = {0,8,54,65,0}, ['|'] = {0,0,119,0,0}, ['}'] = {0,65,54,8,0}, ['~'] = {8,4,8,16,8}, }; letterCode['('] = {0,60,66,129,0} letterCode[')'] = {0,129,66,60,0} letterCode[','] = {0,176,112,0,0} letterCode[';'] = {0,182,118,0,0} letterCode['['] = {0,255,129,129,0} letterCode[']'] = {0,129,129,255,0} letterCode['_'] = {128,128,128,128,128} letterCode['g'] = {24,164,164,124,0} letterCode['j'] = {64,128,132,125,0} letterCode['p'] = {252,36,36,36,24} letterCode['q'] = {24,36,36,252,128} letterCode['y'] = {12,80,80,60,0} letterCode['{'] = {0,24,102,129,0} letterCode['}'] = {0,129,102,24,0} local function HugeLetter(letter) if letter==' ' then return {" ", " ", " ", " ", " ", " ", " ", " "} end local code = letterCode[letter] local str = {"", "", "", "", "", "", "", ""} for i=1,5 do local n = code[i] if n and n>0 then for b=1,8 do if bit32.btest(n, bit32.lshift(1, b-1)) then str[b] = str[b] .. letter else str[b] = str[b] .. ' ' end end end end return str end function HugeText(str) local txt = {"", "", "", "", "", "", "", ""} for i=1,string.len(str) do local s = HugeLetter(str:sub(i,i)) for b=1,8 do if i>1 then txt[b] = txt[b] .. " " .. s[b] else txt[b] = txt[b] .. s[b] end end end return txt end return HugeText
apache-2.0
kitala1/darkstar
scripts/zones/Port_Bastok/npcs/Dalba.lua
31
11049
----------------------------------- -- Area: Port Bastok -- NPC: Dalba -- Type: Past Event Watcher -- @zone: 236 -- @pos: -174.101 -7 -19.611 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Bastok Missions. local BastokMissions = 0xFFFFFFFE; if (player:hasCompletedMission(BASTOK,FETICHISM)) then BastokMissions = BastokMissions - 2; -- Fetichism. end if (player:hasCompletedMission(BASTOK,TO_THE_FORSAKEN_MINES)) then BastokMissions = BastokMissions - 4; -- To the Forsaken Mines. end -- Bastok Quests. local BastokQuests = 0xFFFFFFFE; if (player:hasCompleteQuest(BASTOK,BEAUTY_AND_THE_GALKA)) then BastokQuests = BastokQuests - 2; -- Beauty and the Galka. end if (player:hasCompleteQuest(BASTOK,WELCOME_TO_BASTOK)) then BastokQuests = BastokQuests - 4; -- Welcome to Bastok. end if (player:hasCompleteQuest(BASTOK,GUEST_OF_HAUTEUR)) then BastokQuests = BastokQuests - 8; -- Guest of Hauteur. end if (player:hasCompleteQuest(BASTOK,CID_S_SECRET)) then BastokQuests = BastokQuests - 16; -- Cid's Secret. end if (player:hasCompleteQuest(BASTOK,THE_USUAL)) then BastokQuests = BastokQuests - 32; -- The Usual. end if (player:hasCompleteQuest(BASTOK,LOVE_AND_ICE)) then BastokQuests = BastokQuests - 64; -- Love and Ice(pt.1). BastokQuests = BastokQuests - 128; -- Love and Ice(pt.2). end if (player:hasCompleteQuest(BASTOK,A_TEST_OF_TRUE_LOVE)) then BastokQuests = BastokQuests - 256; -- A Test of True Love(pt.1). BastokQuests = BastokQuests - 512; -- A Test of True Love(pt.2). BastokQuests = BastokQuests - 1024; -- A Test of True Love(pt.3). end if (player:hasCompleteQuest(BASTOK,LOVERS_IN_THE_DUSK)) then BastokQuests = BastokQuests - 2048; -- Lovers in the Dusk end if (player:hasCompleteQuest(BASTOK,GHOSTS_OF_THE_PAST)) then BastokQuests = BastokQuests - 4096; -- Ghosts of the Past(pt.1). BastokQuests = BastokQuests - 8192; -- Ghosts of the Past(pt.2). end if (player:hasCompleteQuest(BASTOK,THE_FIRST_MEETING)) then BastokQuests = BastokQuests - 16384; -- The First Meeting(pt.1). BastokQuests = BastokQuests - 32768; -- The First Meeting(pt.2). end if (player:hasCompleteQuest(BASTOK,AYAME_AND_KAEDE)) then BastokQuests = BastokQuests - 65536; -- Ayame and Kaede(pt.1). BastokQuests = BastokQuests - 131072; -- Ayame and Kaede(pt.2). BastokQuests = BastokQuests - 262144; -- Ayame and Kaede(pt.3). BastokQuests = BastokQuests - 524288; -- Ayame and Kaede(pt.4). BastokQuests = BastokQuests - 1048576; -- Ayame and Kaede(pt.5). end -- *Need to determine the correct csid/appropriate options for this cutscene --if (player:hasCompleteQuest(BASTOK,TRIAL_BY_EARTH)) then -- BastokQuests = BastokQuests - 2097152; -- Trial by Earth. --end if (player:hasCompleteQuest(BASTOK,THE_WALLS_OF_YOUR_MIND)) then BastokQuests = BastokQuests - 4194304; -- The Walls of Your Mind(pt.1). BastokQuests = BastokQuests - 8388608; -- The Walls of Your Mind(pt.2). BastokQuests = BastokQuests - 16777216; -- The Walls of Your Mind(pt.3). end if (player:hasCompleteQuest(BASTOK,FADED_PROMISES)) then BastokQuests = BastokQuests - 33554432; -- Faded Promises. end if (player:hasCompleteQuest(BASTOK,OUT_OF_THE_DEPTHS)) then BastokQuests = BastokQuests - 67108864; -- Out of the Depths(pt.1). -- *Need to determine the appropriate options for this cutscene -- BastokQuests = BastokQuests - 134217728; -- Out of the Depths(pt.2). end -- Other Quests. local OtherQuests = 0xFFFFFFFE; if (player:hasCompleteQuest(WINDURST,THE_PUPPET_MASTER)) then OtherQuests = OtherQuests - 2; -- The Puppet Master(pt.1). OtherQuests = OtherQuests - 4; -- The Puppet Master(pt.2). end if (player:hasCompleteQuest(OUTLANDS,TWENTY_IN_PIRATE_YEARS)) then OtherQuests = OtherQuests - 8; -- 20 in Pirate Years(pt.1). OtherQuests = OtherQuests - 16; -- 20 in Pirate Years(pt.2). end if (player:hasCompleteQuest(OUTLANDS,I_LL_TAKE_THE_BIG_BOX)) then OtherQuests = OtherQuests - 32; -- I'll Take the Big Box. end -- *Need the correct csids -- if (player:hasCompleteQuest(BASTOK,CHASING_DREAMS)) then -- OtherQuests = OtherQuests - 64; -- Chasing Dreams(pt.1). -- OtherQuests = OtherQuests - 128; -- Chasing Dreams(pt.2). -- end -- *This quest,as of the time this script was written,is not yet defined in the Darkstar Project. -- if (player:hasCompleteQuest(**Unknown**,MONSTROSITY)) then -- OtherQuests = OtherQuests - 256; -- Monstrosity. -- end -- Promathia Missions. local PromathiaMissions = 0xFFFFFFFE; if (player:hasCompletedMission(COP,THE_CALL_OF_THE_WYRMKING)) then PromathiaMissions = PromathiaMissions - 2; -- The Call of the Wyrmking. end if (player:hasCompletedMission(COP,THE_ENDURING_TUMULT_OF_WAR)) then PromathiaMissions = PromathiaMissions - 4; -- The Enduring Tumult of War. end -- Add-on Scenarios. local AddonScenarios = 0xFFFFFFFE; if (player:hasCompletedMission(AMK,DRENCHED_IT_BEGAN_WITH_A_RAINDROP)) then AddonScenarios = AddonScenarios - 2; -- Drenched! It Began with a Raindrop. end -- *Need the correct csid -- if (player:hasCompletedMission(AMK,HASTEN_IN_A_JAM_IN_JEUNO)) then -- AddonScenarios = AddonScenarios - 4; -- Hasten! In a Jam in Jeuno? -- end -- Determine if any cutscenes are available for the player. local gil = player:getGil(); if (BastokMissions == 0xFFFFFFFE and BastokQuests == 0xFFFFFFFE and OtherQuests == 0xFFFFFFFE and PromathiaMissions == 0xFFFFFFFE and AddonScenarios == 0xFFFFFFFE) then -- Player has no cutscenes available to be viewed. gil = 0; -- Setting gil to a value less than 10(cost) will trigger the appropriate response from this npc. end player:startEvent(0x0104,BastokMissions,BastokQuests,OtherQuests,PromathiaMissions,AddonScenarios,0xFFFFFFFE,10,gil); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (player:delGil(10) == false) then player:setLocalVar("Dalba_PlayCutscene", 2) ; -- Cancel the cutscene. player:updateEvent(0); else player:setLocalVar("Dalba_PlayCutscene", 1) end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (player:getLocalVar("Dalba_PlayCutscene") < 2) then if ( option == 1) then -- Fetichism. player:startEvent(0x03F0); elseif (option == 2) then -- To the Forsaken Mines. player:startEvent(0x03F2); elseif (option == 33) then -- Beauty and the Galka. player:startEvent(0x0002); elseif (option == 34) then -- Welcome to Bastok. player:startEvent(0x0034); elseif (option == 35) then -- Guest of Hauteur. player:startEvent(0x0037); elseif (option == 36) then -- Cid's Secret. player:startEvent(0x0085); elseif (option == 37) then -- The Usual. player:startEvent(0x0088); elseif (option == 38) then -- Love and Ice(pt.1). player:startEvent(0x00B9); elseif (option == 39) then -- Love and Ice(pt.2). player:startEvent(0x00BA); elseif (option == 40) then -- A Test of True Love(pt.1). player:startEvent(0x010E); elseif (option == 41) then -- A Test of True Love(pt.2). player:startEvent(0x0110); elseif (option == 42) then -- A Test of True Love(pt.3). player:startEvent(0x0112); elseif (option == 43) then -- Lovers in the Dusk. player:startEvent(0x0113); elseif (option == 44) then -- Ghosts of the Past(pt.1). player:startEvent(0x00E7); elseif (option == 45) then -- Ghosts of the Past(pt.2). player:startEvent(0x00E8); elseif (option == 46) then -- The First Meeting(pt.1). player:startEvent(0x00E9); elseif (option == 47) then -- The First Meeting(pt.2). player:startEvent(0x00EA); elseif (option == 48) then -- Ayame and Kaede(pt.1). player:startEvent(0x00F0); elseif (option == 49) then -- Ayame and Kaede(pt.2). player:startEvent(0x00F1); elseif (option == 50) then -- Ayame and Kaede(pt.3). player:startEvent(0x00F2); elseif (option == 51) then -- Ayame and Kaede(pt.4). player:startEvent(0x00F5); elseif (option == 52) then -- Ayame and Kaede(pt.5). player:startEvent(0x00F6); -- elseif (option == 53) then -- Trial by Earth. -- player:startEvent(0x00FA,0,TUNING_FORK_OF_EARTH,1); elseif (option == 54) then -- The Walls of Your Mind(pt.1). player:startEvent(0x011E); elseif (option == 55) then -- The Walls of Your Mind(pt.2). player:startEvent(0x0121); elseif (option == 56) then -- The Walls of Your Mind(pt.3). player:startEvent(0x0122); elseif (option == 57) then -- Faded Promises. player:startEvent(0x0128); elseif (option == 58) then -- Out of the Depths(pt.1). player:startEvent(0x0133); -- elseif (option == 59) then -- Out of the Depths(pt.2). -- player:startEvent(0x0135,0,0,0,601); -- 601 = Old Nametag elseif (option == 65) then -- The Puppet Master(pt.1). player:startEvent(0x0100,0,TUNING_FORK_OF_EARTH,0,1169,0,0,0,0); -- 1169 = Earth Pendulum elseif (option == 66) then -- The Puppet Master(pt.2). player:startEvent(0x0102); elseif (option == 67) then -- 20 in Pirate Years(pt.1). player:startEvent(0x0105); elseif (option == 68) then -- 20 in Pirate Years(pt.2). player:startEvent(0x0107); elseif (option == 69) then -- I'll Take the Big Box. player:startEvent(0x0108); -- elseif (option == 70) then -- Chasing Dreams(pt.1). -- player:startEvent(CSID); -- elseif (option == 71) then -- Chasing Dreams(pt.2). -- player:startEvent(CSID); -- elseif (option == 72) then -- Monstrosity. -- player:startEvent(CSID); elseif (option == 97) then -- The Call of the Wyrmking. player:startEvent(0x0131); elseif (option == 98) then -- The Enduring Tumult of War. player:startEvent(0x0132); elseif (option == 129) then -- Drenched! It Began with a Raindrop. player:startEvent(0x7549,0,0,0,0,0,0,236); -- elseif (option == 2) then -- Hasten! In a Jam in Jeuno? -- player:startEvent(CSID,0,0,0,0,0,0,236); end end player:setLocalVar("Dalba_PlayCutscene", 0) end;
gpl-3.0
kitala1/darkstar
scripts/globals/mobskills/PL_Wind_Shear.lua
13
1119
--------------------------------------------- -- Wind Shear -- -- Description: Deals damage to enemies within an area of effect. Additional effect: Knockback -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: 10' radial -- Notes: The knockback is rather severe. Vulpangue uses an enhanced version that inflicts Weight. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 1746) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = math.random(2,3); local accmod = 1; local dmgmod = .8; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Jugner_Forest_[S]/npcs/Roiloux_RK.lua
38
1031
----------------------------------- -- Area: Jugner Forest (S) -- NPC: Roiloux, R.K. -- Type: Campaign Arbiter -- @pos 70.493 -0.602 -9.185 82 ----------------------------------- package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Jugner_Forest_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01c2); 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
tetoali605/THETETOO_A7A
plugins/ingroup.lua
156
60323
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.peer_id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member function show_group_settingsmod(msg, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(target)] then if data[tostring(target)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(target)]['settings']['lock_bots'] then bots_protection = data[tostring(target)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(target)]['settings']['leave_ban'] then leave_ban = data[tostring(target)]['settings']['leave_ban'] end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_link'] then data[tostring(target)]['settings']['lock_link'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_sticker'] then data[tostring(target)]['settings']['lock_sticker'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection.."\nLock links : "..settings.lock_link.."\nLock RTL: "..settings.lock_rtl.."\nLock sticker: "..settings.lock_sticker.."\nPublic: "..settings.public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "Only owners can unlock flood" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function set_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_member_lock = data[tostring(target)]['settings']['public'] local long_id = data[tostring(target)]['long_id'] if not long_id then data[tostring(target)]['long_id'] = msg.to.peer_id save_data(_config.moderation.data, data) end if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return end local leave_ban = data[tostring(target)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(target)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(target)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'Link posting is already locked' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'Link posting has been locked' end end local function unlock_group_links(msg, data, target) if not is_momod(msg) then return end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'Link posting is not locked' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'Link posting has been unlocked' end end local function lock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'yes' then return 'RTL is already locked' else data[tostring(target)]['settings']['lock_rtl'] = 'yes' save_data(_config.moderation.data, data) return 'RTL has been locked' end end local function unlock_group_rtl(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_rtl'] if group_rtl_lock == 'no' then return 'RTL is already unlocked' else data[tostring(target)]['settings']['lock_rtl'] = 'no' save_data(_config.moderation.data, data) return 'RTL has been unlocked' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'yes' then return 'Sticker posting is already locked' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'Sticker posting has been locked' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return end local group_sticker_lock = data[tostring(target)]['settings']['lock_sticker'] if group_sticker_lock == 'no' then return 'Sticker posting is already unlocked' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'Sticker posting has been unlocked' end end local function lock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'yes' then return 'Contact posting is already locked' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'Contact posting has been locked' end end local function unlock_group_contacts(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['lock_contacts'] if group_contacts_lock == 'no' then return 'Contact posting is already unlocked' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'Contact posting has been unlocked' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_rtl_lock = data[tostring(target)]['settings']['strict'] if strict == 'yes' then return 'Settings are already strictly enforced' else data[tostring(target)]['settings']['strict'] = 'yes' save_data(_config.moderation.data, data) return 'Settings will be strictly enforced' end end local function disable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_contacts_lock = data[tostring(target)]['settings']['strict'] if strict == 'no' then return 'Settings are not strictly enforced' else data[tostring(target)]['settings']['strict'] = 'no' save_data(_config.moderation.data, data) return 'Settings will not be strictly enforced' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_momod(msg) then return end if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_momod(msg) then return end if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin1(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.peer_id if msg.to.peer_type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.peer_id if msg.to.peer_type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.peer_id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function mute_user_callback(extra, success, result) if result.service then local action = result.action.type if action == 'chat_add_user' or action == 'chat_del_user' or action == 'chat_rename' or action == 'chat_change_photo' then if result.action.user then user_id = result.action.user.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then mute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] removed from the muted user list") else unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to the muted user list") end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function callback_mute_res(extra, success, result) local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'chat#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] removed from muted user list") else mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] added to muted user list") end end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.peer_id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.peer_id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.peer_id) end end --[[local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.peer_id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end]] local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if msg.to.type == 'chat' then if is_admin1(msg) or not is_support(msg.from.id) then-- Admin only if matches[1] == 'add' and not matches[2] then if not is_admin1(msg) and not is_support(msg.from.id) then-- Admin only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to add group [ "..msg.to.id.." ]") return end if is_realm(msg) then return 'Error: Already a realm.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] added group [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if not is_sudo(msg) then-- Admin only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to add realm [ "..msg.to.id.." ]") return end if is_group(msg) then return 'Error: Already a group.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] added realm [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then if not is_admin1(msg) and not is_support(msg.from.id) then-- Admin only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to remove group [ "..msg.to.id.." ]") return end if not is_group(msg) then return 'Error: Not a group.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed group [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then if not is_sudo(msg) then-- Sudo only savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to remove realm [ "..msg.to.id.." ]") return end if not is_realm(msg) then return 'Error: Not a realm.' end savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed realm [ "..msg.to.id.." ]") print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end --[[Experimental if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "super_group" then local chat_id = get_receiver(msg) users = {[1]="user#id167472799",[2]="user#id170131770"} for k,v in pairs(users) do chat_add_user(chat_id, v, ok_cb, false) end --chat_upgrade(chat_id, ok_cb, false) end ]] if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return resolve_username(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return resolve_username(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end end --Begin chat settings if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked rtl chars. in names") return lock_group_rtl(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked contact posting") return lock_group_contacts(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end if matches[2] == 'links' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2]:lower() == 'rtl' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked RTL chars. in names") return unlock_group_rtl(msg, data, target) end if matches[2] == 'sticker' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contacts' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked contact posting") return unlock_group_contacts(msg, data, target) end end --End chat settings --Begin Chat mutes if matches[1] == 'mute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group "..matches[2].." has been muted" else return "Group mute "..matches[2].." is already on" end end if matches[2] == 'photo' then local msg_type = 'Photo' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group "..matches[2].." has been muted" else return "Group mute "..matches[2].." is already on" end end if matches[2] == 'video' then local msg_type = 'Video' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group "..matches[2].." has been muted" else return "Group mute "..matches[2].." is already on" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "Group mute "..msg_type.." is already on" end end if matches[2] == 'documents' then local msg_type = 'Documents' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return msg_type.." have been muted" else return "Group mute "..msg_type.." is already on" end end if matches[2] == 'text' then local msg_type = 'Text' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Group text has been muted" else return "Group mute text is already on" end end if matches[2] == 'all' then local msg_type = 'All' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: mute "..msg_type) mute(chat_id, msg_type) return "Mute "..msg_type.." has been enabled" else return "Mute "..msg_type.." is already on" end end end if matches[1] == 'unmute' and is_owner(msg) then local chat_id = msg.to.id if matches[2] == 'audio' then local msg_type = 'Audio' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Group "..msg_type.." has been unmuted" else return "Group mute "..msg_type.." is already off" end end if matches[2] == 'photo' then local msg_type = 'Photo' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Group "..msg_type.." has been unmuted" else return "Group mute "..msg_type.." is already off" end end if matches[2] == 'Video' then local msg_type = 'Video' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Group "..msg_type.." has been unmuted" else return "Group mute "..msg_type.." is already off" end end if matches[2] == 'gifs' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'documents' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return msg_type.." have been unmuted" else return "Mute "..msg_type.." is already off" end end if matches[2] == 'text' then local msg_type = 'Text' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute message") unmute(chat_id, msg_type) return "Group text has been unmuted" else return "Group mute text is already off" end end if matches[2] == 'all' then local msg_type = 'All' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: unmute "..msg_type) unmute(chat_id, msg_type) return "Mute "..msg_type.." has been disabled" else return "Mute "..msg_type.." is already disabled" end end end --Begin chat muteuser if matches[1] == "muteuser" and is_momod(msg) then local chat_id = msg.to.id local hash = "mute_user"..chat_id local user_id = "" if type(msg.reply_id) ~= "nil" then local receiver = get_receiver(msg) local get_cmd = "mute_user" get_message(msg.reply_id, mute_user_callback, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1] == "muteuser" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then mute_user(chat_id, user_id) return "["..user_id.."] removed from the muted users list" else unmute_user(chat_id, user_id) return "["..user_id.."] added to the muted user list" end elseif matches[1] == "muteuser" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local get_cmd = "mute_user" local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, callback_mute_res, {receiver = receiver, get_cmd = get_cmd}) end end --End Chat muteuser if matches[1] == "muteslist" and is_momod(msg) then local chat_id = msg.to.id if not has_mutes(chat_id) then set_mutes(chat_id) return mutes_list(chat_id) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return mutes_list(chat_id) end if matches[1] == "mutelist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") return muted_user_list(chat_id) end if matches[1] == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, target) end if matches[1] == 'public' and is_momod(msg) then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end if msg.to.type == 'chat' then if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin1(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if msg.to.type == 'chat' then if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if msg.to.type == 'chat' then if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin1(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin1(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") resolve_username(username, callbackres, cbres_extra) return end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end end local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end return { patterns = { "^[#!/](add)$", "^[#!/](add) (realm)$", "^[#!/](rem)$", "^[#!/](rem) (realm)$", "^[#!/](rules)$", "^[#!/](about)$", "^[#!/](setname) (.*)$", "^[#!/](setphoto)$", "^[#!/](promote) (.*)$", "^[#!/](promote)", "^[#!/](help)$", "^[#!/](clean) (.*)$", "^[#!/](kill) (chat)$", "^[#!/](kill) (realm)$", "^[#!/](demote) (.*)$", "^[#!/](demote)", "^[#!/](set) ([^%s]+) (.*)$", "^[#!/](lock) (.*)$", "^[#!/](setowner) (%d+)$", "^[#!/](setowner)", "^[#!/](owner)$", "^[#!/](res) (.*)$", "^[#!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[#!/](unlock) (.*)$", "^[#!/](setflood) (%d+)$", "^[#!/](settings)$", "^[#!/](public) (.*)$", "^[#!/](modlist)$", "^[#!/](newlink)$", "^[#!/](link)$", "^[#!/]([Mm]ute) ([^%s]+)$", "^[#!/]([Uu]nmute) ([^%s]+)$", "^[#!/]([Mm]uteuser)$", "^[#!/]([Mm]uteuser) (.*)$", "^[#!/]([Mm]uteslist)$", "^[#!/]([Mm]utelist)$", "^[#!/](kickinactive)$", "^[#!/](kickinactive) (%d+)$", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } end
gpl-2.0
kitala1/darkstar
scripts/zones/Valkurm_Dunes/npcs/Cavernous_Maw.lua
58
1887
----------------------------------- -- Area: Valkurm Dunes -- NPC: Cavernous Maw -- @pos 368.980, -0.443, -119.874 103 -- Teleports Players to Abyssea Misareaux ----------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/abyssea"); require("scripts/zones/Valkurm_Dunes/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_ABYSSEA == 1 and player:getMainLvl() >= 30) then local HasStone = getTravStonesTotal(player); if (HasStone >= 1 and player:getQuestStatus(ABYSSEA, DAWN_OF_DEATH) == QUEST_ACCEPTED and player:getQuestStatus(ABYSSEA, A_DELECTABLE_DEMON) == QUEST_AVAILABLE) then player:startEvent(56); else player:startEvent(55,0,1); -- No param = no entry. end else player:messageSpecial(NOTHING_HAPPENS); 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 == 56) then player:addQuest(ABYSSEA, A_DELECTABLE_DEMON); elseif (csid == 57) then -- Killed Cirein-croin elseif (csid == 55 and option == 1) then player:setPos(670,-15,318,119,216); end end;
gpl-3.0
MrUnknownGamer/pointshop
lua/pointshop/providers/json.lua
8
1744
function PROVIDER:GetData(ply, callback) if not file.IsDir('pointshop', 'DATA') then file.CreateDir('pointshop') end local points, items local filename = string.Replace(ply:SteamID(), ':', '_') if not file.Exists('pointshop/' .. filename .. '.txt', 'DATA') then file.Write('pointshop/' .. filename .. '.txt', util.TableToJSON({ Points = 0, Items = {} })) points = 0 items = {} else local data = util.JSONToTable(file.Read('pointshop/' .. filename .. '.txt', 'DATA')) points = data.Points or 0 items = data.Items or {} end return callback(points, items) end function PROVIDER:SetPoints( ply, set_points ) self:GetData(ply, function(points, items) self:SetData(ply, set_points, items) end) end function PROVIDER:GivePoints( ply, add_points ) self:GetData(ply, function(points, items) self:SetData(ply, points + add_points, items) end) end function PROVIDER:TakePoints( ply, points ) self:GivePoints(ply, -points) end function PROVIDER:SaveItem( ply, item_id, data) self:GiveItem(ply, item_id, data) end function PROVIDER:GiveItem( ply, item_id, data) self:GetData(ply, function(points, items) local tmp = table.Copy(ply.PS_Items) tmp[item_id] = data self:SetData(ply, points, tmp) end) end function PROVIDER:TakeItem( ply, item_id ) self:GetData(ply, function(points, items) local tmp = table.Copy(ply.PS_Items) tmp[item_id] = nil self:SetData(ply, points, tmp) end) end function PROVIDER:SetData(ply, points, items) if not file.IsDir('pointshop', 'DATA') then file.CreateDir('pointshop') end local filename = string.Replace(ply:SteamID(), ':', '_') file.Write('pointshop/' .. filename .. '.txt', util.TableToJSON({ Points = points, Items = items })) end
mit
crabman77/minetest-minetestforfun-server
mods/sea/seacoral/init.lua
8
19445
-- NODES -- Lightened nodes for MFF local sea_light_source = 5 minetest.register_node("seacoral:coralcyan", { description = "Cyan Coral", drawtype = "plantlike", tiles = {"seacoral_coralcyan.png"}, inventory_image = "seacoral_coralcyan.png", wield_image = "seacoral_coralcyan.png", paramtype = "light", walkable = false, climbable = true, drowning = 1, is_ground_content = true, light_source = sea_light_source, selection_box = { type = "fixed", fixed = {-0.3, -0.3, -0.3, 0.3, 0.3, 0.3} }, post_effect_color = {a=64, r=100, g=100, b=200}, groups = {snappy=3, seacoral=1, sea=1,basecolor_cyan=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:coralmagenta", { description = "Magenta Coral", drawtype = "plantlike", tiles = {"seacoral_coralmagenta.png"}, inventory_image = "seacoral_coralmagenta.png", wield_image = "seacoral_coralmagenta.png", paramtype = "light", walkable = false, light_source = sea_light_source, climbable = true, drowning = 1, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, post_effect_color = {a=64, r=100, g=100, b=200}, groups = {snappy=3, seacoral=1, sea=1,basecolor_magenta=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:coralaqua", { description = "Aqua Coral", drawtype = "plantlike", light_source = sea_light_source, tiles = {"seacoral_coralaqua.png"}, inventory_image = "seacoral_coralaqua.png", wield_image = "seacoral_coralaqua.png", paramtype = "light", walkable = false, climbable = true, drowning = 1, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.3, -0.3, 0.3, 0.3, 0.3} }, post_effect_color = {a=64, r=100, g=100, b=200}, groups = {snappy=3, seacoral=1, sea=1,excolor_aqua=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:corallime", { description = "Lime Coral", drawtype = "plantlike", tiles = {"seacoral_corallime.png"}, inventory_image = "seacoral_corallime.png", wield_image = "seacoral_corallime.png", light_source = sea_light_source, paramtype = "light", walkable = false, climbable = true, drowning = 1, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, post_effect_color = {a=64, r=100, g=100, b=200}, groups = {snappy=3, seacoral=1, sea=1,excolor_lime=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:coralskyblue", { description = "Skyblue Coral", drawtype = "plantlike", tiles = {"seacoral_coralskyblue.png"}, inventory_image = "seacoral_coralskyblue.png", wield_image = "seacoral_coralskyblue.png", paramtype = "light", walkable = false, climbable = true, light_source = sea_light_source, drowning = 1, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, post_effect_color = {a=64, r=100, g=100, b=200}, groups = {snappy=3, seacoral=1, sea=1,excolor_skyblue=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:coralredviolet", { description = "Redviolet Coral", drawtype = "plantlike", tiles = {"seacoral_coralredviolet.png"}, inventory_image = "seacoral_coralredviolet.png", wield_image = "seacoral_coralredviolet.png", paramtype = "light", walkable = false, climbable = true, drowning = 1, light_source = sea_light_source, is_ground_content = true, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, post_effect_color = {a=64, r=100, g=100, b=200}, groups = {snappy=3, seacoral=1, sea=1,excolor_redviolet=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:seacoralsandcyan", { description = "Sea coral sand cyan", tiles = {"default_sand.png"}, light_source = sea_light_source, is_ground_content = true, groups = {crumbly=3, falling_node=1, sand=1, soil=1, not_in_creative_inventory=1}, drop = 'default:sand', sounds = default.node_sound_sand_defaults(), }) minetest.register_node("seacoral:seacoraldirtcyan", { description = "Sea coral dirt cyan", tiles = {"default_dirt.png"}, light_source = sea_light_source, is_ground_content = true, groups = {crumbly=3,soil=1, not_in_creative_inventory=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:seacoralsandmagenta", { description = "Sea coral sand magenta", tiles = {"default_sand.png"}, is_ground_content = true, light_source = sea_light_source, groups = {crumbly=3, falling_node=1, sand=1, soil=1, not_in_creative_inventory=1}, drop = 'default:sand', sounds = default.node_sound_sand_defaults(), }) minetest.register_node("seacoral:seacoraldirtmagenta", { description = "Sea coral dirt magenta", light_source = sea_light_source, tiles = {"default_dirt.png"}, is_ground_content = true, groups = {crumbly=3,soil=1, not_in_creative_inventory=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:seacoralsandaqua", { description = "Sea coral sand aqua", tiles = {"default_sand.png"}, light_source = sea_light_source, is_ground_content = true, groups = {crumbly=3, falling_node=1, sand=1, soil=1, not_in_creative_inventory=1}, drop = 'default:sand', sounds = default.node_sound_sand_defaults(), }) minetest.register_node("seacoral:seacoraldirtaqua", { description = "Sea coral dirt aqua", tiles = {"default_dirt.png"}, light_source = sea_light_source, is_ground_content = true, groups = {crumbly=3,soil=1, not_in_creative_inventory=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:seacoralsandlime", { description = "Sea coral sand lime", tiles = {"default_sand.png"}, is_ground_content = true, light_source = sea_light_source, groups = {crumbly=3, falling_node=1, sand=1, soil=1, not_in_creative_inventory=1}, drop = 'default:sand', sounds = default.node_sound_sand_defaults(), }) minetest.register_node("seacoral:seacoraldirtlime", { description = "Sea coral dirt lime", tiles = {"default_dirt.png"}, is_ground_content = true, light_source = sea_light_source, groups = {crumbly=3,soil=1, not_in_creative_inventory=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:seacoralsandskyblue", { description = "Sea coral sand skyblue", tiles = {"default_sand.png"}, is_ground_content = true, light_source = sea_light_source, groups = {crumbly=3, falling_node=1, sand=1, soil=1, not_in_creative_inventory=1}, drop = 'default:sand', sounds = default.node_sound_sand_defaults(), }) minetest.register_node("seacoral:seacoraldirtskyblue", { description = "Sea coral dirt skyblue", tiles = {"default_dirt.png"}, is_ground_content = true, groups = {crumbly=3,soil=1, not_in_creative_inventory=1}, light_source = sea_light_source, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("seacoral:seacoralsandredviolet", { description = "Sea coral sand redviolet", tiles = {"default_sand.png"}, light_source = sea_light_source, is_ground_content = true, groups = {crumbly=3, falling_node=1, sand=1, soil=1, not_in_creative_inventory=1}, drop = 'default:sand', sounds = default.node_sound_sand_defaults(), }) minetest.register_node("seacoral:seacoraldirtredviolet", { description = "Sea coral dirt redviolet", tiles = {"default_dirt.png"}, light_source = sea_light_source, is_ground_content = true, groups = {crumbly=3,soil=1, not_in_creative_inventory=1}, drop = 'default:dirt', sounds = default.node_sound_dirt_defaults(), }) -- CRAFTING if( minetest.get_modpath( "colormachine") == nil ) then register_seacoral_craft = function(output,recipe) minetest.register_craft({ type = 'shapeless', output = output, recipe = recipe, }) end register_seacoral_craft('dye:cyan 4', {'seacoral:coralcyan'}) register_seacoral_craft('dye:magenta 4', {'seacoral:coralmagenta'}) register_seacoral_craft('dye:lime 4', {'seacoral:corallime'}) register_seacoral_craft('dye:aqua 4', {'seacoral:coralaqua'}) register_seacoral_craft('dye:skyblue 4', {'seacoral:coralskyblue'}) register_seacoral_craft('dye:redviolet 4', {'seacoral:coralredviolet'}) end -- SEACORAL SAND AND DIRT GENERATION minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoralsandcyan", wherein = "default:sand", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoraldirtcyan", wherein = "default:dirt", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoralsandmagenta", wherein = "default:sand", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoraldirtmagenta", wherein = "default:dirt", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoralsandaqua", wherein = "default:sand", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoraldirtaqua", wherein = "default:dirt", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoralsandlime", wherein = "default:sand", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoraldirtlime", wherein = "default:dirt", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoralsandskyblue", wherein = "default:sand", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoraldirtskyblue", wherein = "default:dirt", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoralsandredviolet", wherein = "default:sand", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) minetest.register_ore({ ore_type = "scatter", ore = "seacoral:seacoraldirtredviolet", wherein = "default:dirt", clust_scarcity = 10*10*10, clust_num_ores = 24, clust_size = 4, y_max = -4, y_min = -8, }) local function generate_ore(name, wherein, minp, maxp, seed, chunks_per_volume, chunk_size, ore_per_chunk, y_min, y_max) if maxp.y < y_min or minp.y > y_max then return end local y_min = math.max(minp.y, y_min) local y_max = math.min(maxp.y, y_max) if chunk_size >= y_max - y_min + 1 then return end local volume = (maxp.x-minp.x+1)*(y_max-y_min+1)*(maxp.z-minp.z+1) local pr = PseudoRandom(seed) local num_chunks = math.floor(chunks_per_volume * volume) local inverse_chance = math.floor(chunk_size*chunk_size*chunk_size / ore_per_chunk) for i=1,num_chunks do local y0 = pr:next(y_min, y_max-chunk_size+1) if y0 >= y_min and y0 <= y_max then local x0 = pr:next(minp.x, maxp.x-chunk_size+1) local z0 = pr:next(minp.z, maxp.z-chunk_size+1) local p0 = {x=x0, y=y0, z=z0} for x1=0,chunk_size-1 do for y1=0,chunk_size-1 do for z1=0,chunk_size-1 do if pr:next(1,inverse_chance) == 1 then local x2 = x0+x1 local y2 = y0+y1 local z2 = z0+z1 local p2 = {x=x2, y=y2, z=z2} if minetest.get_node(p2).name == wherein then minetest.set_node(p2, {name=name}) end end end end end end end end -- ABM'S minetest.register_abm({ nodenames = {"seacoral:seacoraldirtcyan"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralcyan"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoralsandcyan"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralcyan"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoraldirtmagenta"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralmagenta"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoralsandmagenta"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralmagenta"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoraldirtaqua"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralaqua"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoralsandaqua"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralaqua"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoraldirtlime"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:corallime"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoralsandlime"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:corallime"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoraldirtskyblue"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralskyblue"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoralsandskyblue"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralskyblue"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoraldirtredviolet"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralredviolet"}) else return end end }) minetest.register_abm({ nodenames = {"seacoral:seacoralsandredviolet"}, interval = 12, chance = 12, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} if (minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") then pos.y = pos.y + 1 minetest.add_node(pos, {name = "seacoral:coralredviolet"}) else return end end }) minetest.register_abm({ nodenames = {"group:seacoral"}, interval = 3, chance = 1, action = function(pos, node, active_object_count, active_object_count_wider) local yp = {x = pos.x, y = pos.y + 1, z = pos.z} local yyp = {x = pos.x, y = pos.y + 2, z = pos.z} if ((minetest.get_node(yp).name == "default:water_source" or minetest.get_node(yp).name == "noairblocks:water_sourcex") and (minetest.get_node(yyp).name == "default:water_source" or minetest.get_node(yyp).name == "noairblocks:water_sourcex")) then local objs = minetest.get_objects_inside_radius(pos, 2) for k, obj in pairs(objs) do obj:set_hp(obj:get_hp()+ 1) end else return end end }) -- OPTIONAL DEPENDENCY if( minetest.get_modpath( "colormachine") ~= nil ) then colormachine.basic_dye_sources = { "flowers:rose", "flowers:tulip", "flowers:dandelion_yellow", "seacoral:corallime", "default:cactus", "seacoral:coralaqua", "seacoral:coralcyan", "seacoral:coralskyblue", "flowers:geranium", "flowers:viola", "seacoral:coralmagenta", "seacoral:coralredviolet", "default:stone", "", "", "", "default:coal_lump" }; else return end -- ALIASES minetest.register_alias("seadye:cyan","dye:cyan") minetest.register_alias("seadye:magenta","dye:magenta") minetest.register_alias("seadye:lime","dye:lime") minetest.register_alias("seadye:aqua","dye:aqua") minetest.register_alias("seadye:skyblue","dye:skyblue") minetest.register_alias("seadye:redviolet","dye:redviolet")
unlicense
kitala1/darkstar
scripts/globals/spells/bluemagic/body_slam.lua
28
1739
----------------------------------------- -- Spell: Body Slam -- Delivers an area attack. Damage varies with TP -- Spell cost: 74 MP -- Monster Type: Dragon -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: VIT+1, MP+5 -- Level: 62 -- Casting Time: 1 seconds -- Recast Time: 27.75 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: Max HP Boost ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.5; params.tp150 = 1.5; params.tp300 = 1.5; params.azuretp = 1.5; params.duppercap = 75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Khea_Mhyyih.lua
38
1051
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Khea Mhyyih -- Type: Standard NPC -- @zone: 94 -- @pos -53.927 -4.499 56.215 -- -- 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(0x01ac); 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
kitala1/darkstar
scripts/globals/items/sis_kebabi_+1.lua
35
1659
----------------------------------------- -- ID: 5599 -- Item: sis_kebabi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Strength 6 -- Vitality -1 -- Intelligence -1 -- Attack % 20 -- Attack Cap 75 -- Ranged ATT % 20 -- Ranged ATT Cap 75 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5599); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 6); target:addMod(MOD_VIT, -1); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 75); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 75); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 6); target:delMod(MOD_VIT, -1); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 75); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 75); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Outer_Horutoto_Ruins/npcs/_ne4.lua
12
2629
----------------------------------- -- Area: Outer Horutoto Ruins -- NPC: Strange Apparatus -- @pos: -574 0 739 194 ----------------------------------- package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil; require("scripts/zones/Outer_Horutoto_Ruins/TextIDs"); require("scripts/globals/strangeapparatus"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local trade = tradeToStrApp(player, trade); if (trade ~= nil) then if ( trade == 1) then -- good trade local drop = player:getLocalVar("strAppDrop"); local dropQty = player:getLocalVar("strAppDropQty"); local docStatus = 0; -- Assistant if (hasStrAppDocStatus(player)) then docStatus = 1; -- Doctor end player:startEvent(0x0042, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0); else -- wrong chip, spawn elemental nm spawnElementalNM(player); delStrAppDocStatus(player); player:messageSpecial(SYS_OVERLOAD); player:messageSpecial(YOU_LOST_THE, trade); end else -- Invalid trade, lose doctor status delStrAppDocStatus(player); player:messageSpecial(DEVICE_NOT_WORKING); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local docStatus = 0; -- Assistant if (hasStrAppDocStatus(player)) then docStatus = 1; -- Doctor else player:setLocalVar( "strAppPass", 1); end player:startEvent(0x0040, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u", option); if (csid == 0x0040) then if (hasStrAppDocStatus(player) == false) then local docStatus = 1; -- Assistant if( option == strAppPass(player)) then -- Good password docStatus = 0; -- Doctor giveStrAppDocStatus(player); end player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0042) then local drop = player:getLocalVar("strAppDrop"); local dropQty = player:getLocalVar("strAppDropQty"); if (drop ~= 0) then if( dropQty == 0) then dropQty = 1; end player:addItem(drop, dropQty); player:setLocalVar("strAppDrop", 0); player:setLocalVar("strAppDropQty", 0); end end end;
gpl-3.0
Roblox/Core-Scripts
PlayerScripts/StarterPlayerScripts_NewStructure/RobloxPlayerScript/ControlScript/ClickToMoveController.lua
1
31276
--[[ -- Original By Kip Turner, Copyright Roblox 2014 -- Updated by Garnold to utilize the new PathfindingService API, 2017 -- 2018 PlayerScripts Update - AllYourBlox --]] --[[ Roblox Services ]]-- local UserInputService = game:GetService("UserInputService") local ContextActionService = game:GetService("ContextActionService") local PathfindingService = game:GetService("PathfindingService") local Players = game:GetService("Players") local RunService = game:GetService("RunService") local DebrisService = game:GetService('Debris') local ReplicatedStorage = game:GetService('ReplicatedStorage') local TweenService = game:GetService("TweenService") --[[ Constants ]]-- local ZERO_VECTOR3 = Vector3.new(0,0,0) local movementKeys = { [Enum.KeyCode.W] = true; [Enum.KeyCode.A] = true; [Enum.KeyCode.S] = true; [Enum.KeyCode.D] = true; [Enum.KeyCode.Up] = true; [Enum.KeyCode.Down] = true; } local FFlagUserNavigationFixClickToMoveInterruptionSuccess, FFlagUserNavigationFixClickToMoveInterruptionResult = pcall(function() return UserSettings():IsUserFeatureEnabled("UserNavigationFixClickToMoveInterruption") end) local FFlagUserNavigationFixClickToMoveInterruption = FFlagUserNavigationFixClickToMoveInterruptionSuccess and FFlagUserNavigationFixClickToMoveInterruptionResult local Player = Players.LocalPlayer local PlayerScripts = Player.PlayerScripts local TouchJump = nil local SHOW_PATH = true local RayCastIgnoreList = workspace.FindPartOnRayWithIgnoreList local CurrentSeatPart = nil local DrivingTo = nil local XZ_VECTOR3 = Vector3.new(1,0,1) local ZERO_VECTOR3 = Vector3.new(0,0,0) local ZERO_VECTOR2 = Vector2.new(0,0) local BindableEvent_OnFailStateChanged = nil if UserInputService.TouchEnabled then -- BindableEvent_OnFailStateChanged = MasterControl:GetClickToMoveFailStateChanged() end --------------------------UTIL LIBRARY------------------------------- local Utility = {} do local function ViewSizeX() local camera = workspace.CurrentCamera local x = camera and camera.ViewportSize.X or 0 local y = camera and camera.ViewportSize.Y or 0 if x == 0 then return 1024 else if x > y then return x else return y end end end Utility.ViewSizeX = ViewSizeX local function ViewSizeY() local camera = workspace.CurrentCamera local x = camera and camera.ViewportSize.X or 0 local y = camera and camera.ViewportSize.Y or 0 if y == 0 then return 768 else if x > y then return y else return x end end end Utility.ViewSizeY = ViewSizeY local function FindCharacterAncestor(part) if part then local humanoid = part:FindFirstChild("Humanoid") if humanoid then return part, humanoid else return FindCharacterAncestor(part.Parent) end end end Utility.FindCharacterAncestor = FindCharacterAncestor local function Raycast(ray, ignoreNonCollidable, ignoreList) local ignoreList = ignoreList or {} local hitPart, hitPos, hitNorm, hitMat = RayCastIgnoreList(workspace, ray, ignoreList) if hitPart then if ignoreNonCollidable and hitPart.CanCollide == false then table.insert(ignoreList, hitPart) return Raycast(ray, ignoreNonCollidable, ignoreList) end return hitPart, hitPos, hitNorm, hitMat end return nil, nil end Utility.Raycast = Raycast local function AveragePoints(positions) local avgPos = ZERO_VECTOR2 if #positions > 0 then for i = 1, #positions do avgPos = avgPos + positions[i] end avgPos = avgPos / #positions end return avgPos end Utility.AveragePoints = AveragePoints end local humanoidCache = {} local function findPlayerHumanoid(player) local character = player and player.Character if character then local resultHumanoid = humanoidCache[player] if resultHumanoid and resultHumanoid.Parent == character then return resultHumanoid else humanoidCache[player] = nil -- Bust Old Cache local humanoid = character:FindFirstChildOfClass("Humanoid") if humanoid then humanoidCache[player] = humanoid end return humanoid end end end --------------------------CHARACTER CONTROL------------------------------- local CurrentIgnoreList local function GetCharacter() return Player and Player.Character end local function GetTorso() local humanoid = findPlayerHumanoid(Player) return humanoid and humanoid.RootPart end local function getIgnoreList() if CurrentIgnoreList then return CurrentIgnoreList end CurrentIgnoreList = {} table.insert(CurrentIgnoreList, GetCharacter()) return CurrentIgnoreList end -----------------------------------PATHER-------------------------------------- local popupAdornee local function getPopupAdorneePart() --Handle the case of the adornee part getting deleted (camera changed, maybe) if popupAdornee and not popupAdornee.Parent then popupAdornee = nil end --If the adornee doesn't exist yet, create it if not popupAdornee then popupAdornee = Instance.new("Part") popupAdornee.Name = "ClickToMovePopupAdornee" popupAdornee.Transparency = 1 popupAdornee.CanCollide = false popupAdornee.Anchored = true popupAdornee.Size = Vector3.new(2, 2, 2) popupAdornee.CFrame = CFrame.new() popupAdornee.Parent = workspace.CurrentCamera end return popupAdornee end local activePopups = {} local function createNewPopup(popupType) local newModel = Instance.new("ImageHandleAdornment") newModel.AlwaysOnTop = false newModel.Transparency = 1 newModel.Size = ZERO_VECTOR2 newModel.SizeRelativeOffset = ZERO_VECTOR3 newModel.Image = "rbxasset://textures/ui/move.png" newModel.ZIndex = 20 local radius = 0 if popupType == "DestinationPopup" then newModel.Color3 = Color3.fromRGB(0, 175, 255) radius = 1.25 elseif popupType == "DirectWalkPopup" then newModel.Color3 = Color3.fromRGB(0, 175, 255) radius = 1.25 elseif popupType == "FailurePopup" then newModel.Color3 = Color3.fromRGB(255, 100, 100) radius = 1.25 elseif popupType == "PatherPopup" then newModel.Color3 = Color3.fromRGB(255, 255, 255) radius = 1 newModel.ZIndex = 10 end newModel.Size = Vector2.new(5, 0.1) * radius local dataStructure = {} dataStructure.Model = newModel activePopups[#activePopups + 1] = newModel function dataStructure:TweenIn() local tweenInfo = TweenInfo.new(1.5, Enum.EasingStyle.Elastic, Enum.EasingDirection.Out) local tween1 = TweenService:Create(newModel, tweenInfo, { Size = Vector2.new(2,2) * radius }) tween1:Play() TweenService:Create(newModel, TweenInfo.new(0.25, Enum.EasingStyle.Sine, Enum.EasingDirection.InOut, 0, false, 0.1), { Transparency = 0, SizeRelativeOffset = Vector3.new(0, radius * 1.5, 0) }):Play() return tween1 end function dataStructure:TweenOut() local tweenInfo = TweenInfo.new(0.25, Enum.EasingStyle.Quad, Enum.EasingDirection.In) local tween1 = TweenService:Create(newModel, tweenInfo, { Size = ZERO_VECTOR2 }) tween1:Play() coroutine.wrap(function() tween1.Completed:Wait() for i = 1, #activePopups do if activePopups[i] == newModel then table.remove(activePopups, i) break end end end)() return tween1 end function dataStructure:Place(position, dest) -- place the model at position if not self.Model.Parent then local popupAdorneePart = getPopupAdorneePart() self.Model.Parent = popupAdorneePart self.Model.Adornee = popupAdorneePart --Start the 10-stud long ray 2.5 studs above where the tap happened and point straight down to try to find --the actual ground position. local ray = Ray.new(position + Vector3.new(0, 2.5, 0), Vector3.new(0, -10, 0)) local hitPart, hitPoint, hitNormal = workspace:FindPartOnRayWithIgnoreList(ray, { workspace.CurrentCamera, Player.Character }) self.Model.CFrame = CFrame.new(hitPoint) + Vector3.new(0, -radius,0) end end return dataStructure end local function createPopupPath(points, numCircles) -- creates a path with the provided points, using the path and number of circles provided local popups = {} local stopTraversing = false local function killPopup(i) -- kill all popups before and at i for iter, v in pairs(popups) do if iter <= i then local tween = v:TweenOut() spawn(function() tween.Completed:Wait() v.Model:Destroy() end) popups[iter] = nil end end end local function stopFunction() stopTraversing = true killPopup(#points) end spawn(function() for i = 1, #points do if stopTraversing then break end local includeWaypoint = i % numCircles == 0 and i < #points and (points[#points].Position - points[i].Position).magnitude > 4 if includeWaypoint then local popup = createNewPopup("PatherPopup") popups[i] = popup local nextPopup = points[i+1] popup:Place(points[i].Position, nextPopup and nextPopup.Position or points[#points].Position) local tween = popup:TweenIn() wait(0.2) end end end) return stopFunction, killPopup end local function Pather(character, endPoint, surfaceNormal) local this = {} this.Cancelled = false this.Started = false this.Finished = Instance.new("BindableEvent") this.PathFailed = Instance.new("BindableEvent") this.PathComputing = false this.PathComputed = false this.TargetPoint = endPoint this.TargetSurfaceNormal = surfaceNormal this.DiedConn = nil this.SeatedConn = nil this.MoveToConn = nil this.CurrentPoint = 0 function this:Cleanup() if this.stopTraverseFunc then this.stopTraverseFunc() end if this.MoveToConn then this.MoveToConn:Disconnect() this.MoveToConn = nil end if this.DiedConn then this.DiedConn:Disconnect() this.DiedConn = nil end if this.SeatedConn then this.SeatedConn:Disconnect() this.SeatedConn = nil end this.humanoid = nil end function this:Cancel() this.Cancelled = true this:Cleanup() end function this:OnPathInterrupted() -- Stop moving this.Cancelled = true this:OnPointReached(false) end function this:ComputePath() local humanoid = findPlayerHumanoid(Player) local torso = humanoid and humanoid.Torso local success = false if torso then if this.PathComputed or this.PathComputing then return end this.PathComputing = true success = pcall(function() this.pathResult = PathfindingService:FindPathAsync(torso.CFrame.p, this.TargetPoint) end) this.pointList = this.pathResult and this.pathResult:GetWaypoints() this.PathComputing = false this.PathComputed = this.pathResult and this.pathResult.Status == Enum.PathStatus.Success or false end return true end function this:IsValidPath() if not this.pathResult then this:ComputePath() end return this.pathResult.Status == Enum.PathStatus.Success end function this:OnPointReached(reached) if reached and not this.Cancelled then this.CurrentPoint = this.CurrentPoint + 1 if this.CurrentPoint > #this.pointList then -- End of path reached if this.stopTraverseFunc then this.stopTraverseFunc() end this.Finished:Fire() this:Cleanup() else -- If next action == Jump, but the humanoid -- is still jumping from a previous action -- wait until it gets to the ground if this.CurrentPoint + 1 <= #this.pointList then local nextAction = this.pointList[this.CurrentPoint + 1].Action if nextAction == Enum.PathWaypointAction.Jump then local currentState = this.humanoid:GetState() if currentState == Enum.HumanoidStateType.FallingDown or currentState == Enum.HumanoidStateType.Freefall or currentState == Enum.HumanoidStateType.Jumping then this.humanoid.FreeFalling:Wait() -- Give time to the humanoid's state to change -- Otherwise, the jump flag in Humanoid -- will be reset by the state change wait(0.1) end end end -- Move to the next point if this.setPointFunc then this.setPointFunc(this.CurrentPoint) end local nextWaypoint = this.pointList[this.CurrentPoint] if nextWaypoint.Action == Enum.PathWaypointAction.Jump then this.humanoid.Jump = true end this.humanoid:MoveTo(nextWaypoint.Position) end else this.PathFailed:Fire() this:Cleanup() end end function this:Start() if CurrentSeatPart then return end this.humanoid = findPlayerHumanoid(Player) if FFlagUserNavigationFixClickToMoveInterruption and not this.humanoid then this.PathFailed:Fire() return end if this.Started then return end this.Started = true if SHOW_PATH then -- choose whichever one Mike likes best this.stopTraverseFunc, this.setPointFunc = createPopupPath(this.pointList, 4) end if #this.pointList > 0 then if FFlagUserNavigationFixClickToMoveInterruption then this.SeatedConn = this.humanoid.Seated:Connect(function(reached) this:OnPathInterrupted() end) this.DiedConn = this.humanoid.Died:Connect(function(reached) this:OnPathInterrupted() end) end this.MoveToConn = this.humanoid.MoveToFinished:Connect(function(reached) this:OnPointReached(reached) end) this.CurrentPoint = 1 -- The first waypoint is always the start location. Skip it. this:OnPointReached(true) -- Move to first point else this.PathFailed:Fire() if this.stopTraverseFunc then this.stopTraverseFunc() end end end this:ComputePath() if not this.PathComputed then -- set the end point towards the camera and raycasted towards the ground in case we hit a wall local offsetPoint = this.TargetPoint + this.TargetSurfaceNormal*1.5 local ray = Ray.new(offsetPoint, Vector3.new(0,-1,0)*50) local newHitPart, newHitPos = RayCastIgnoreList(workspace, ray, getIgnoreList()) if newHitPart then this.TargetPoint = newHitPos end -- try again this:ComputePath() end return this end ------------------------------------------------------------------------- local function IsInBottomLeft(pt) local joystickHeight = math.min(Utility.ViewSizeY() * 0.33, 250) local joystickWidth = joystickHeight return pt.X <= joystickWidth and pt.Y > Utility.ViewSizeY() - joystickHeight end local function IsInBottomRight(pt) local joystickHeight = math.min(Utility.ViewSizeY() * 0.33, 250) local joystickWidth = joystickHeight return pt.X >= Utility.ViewSizeX() - joystickWidth and pt.Y > Utility.ViewSizeY() - joystickHeight end local function CheckAlive(character) local humanoid = findPlayerHumanoid(Player) return humanoid ~= nil and humanoid.Health > 0 end local function GetEquippedTool(character) if character ~= nil then for _, child in pairs(character:GetChildren()) do if child:IsA('Tool') then return child end end end end local ExistingPather = nil local ExistingIndicator = nil local PathCompleteListener = nil local PathFailedListener = nil local function CleanupPath() DrivingTo = nil if ExistingPather then ExistingPather:Cancel() end if PathCompleteListener then PathCompleteListener:Disconnect() PathCompleteListener = nil end if PathFailedListener then PathFailedListener:Disconnect() PathFailedListener = nil end if ExistingIndicator then local obj = ExistingIndicator local tween = obj:TweenOut() local tweenCompleteEvent = nil tweenCompleteEvent = tween.Completed:connect(function() tweenCompleteEvent:Disconnect() obj.Model:Destroy() end) ExistingIndicator = nil end end local function getExtentsSize(Parts) local maxX,maxY,maxZ = -math.huge,-math.huge,-math.huge local minX,minY,minZ = math.huge,math.huge,math.huge for i = 1, #Parts do maxX,maxY,maxZ = math.max(maxX, Parts[i].Position.X), math.max(maxY, Parts[i].Position.Y), math.max(maxZ, Parts[i].Position.Z) minX,minY,minZ = math.min(minX, Parts[i].Position.X), math.min(minY, Parts[i].Position.Y), math.min(minZ, Parts[i].Position.Z) end return Region3.new(Vector3.new(minX, minY, minZ), Vector3.new(maxX, maxY, maxZ)) end local function inExtents(Extents, Position) if Position.X < (Extents.CFrame.p.X - Extents.Size.X/2) or Position.X > (Extents.CFrame.p.X + Extents.Size.X/2) then return false end if Position.Z < (Extents.CFrame.p.Z - Extents.Size.Z/2) or Position.Z > (Extents.CFrame.p.Z + Extents.Size.Z/2) then return false end --ignoring Y for now return true end local function showQuickPopupAsync(position, popupType) local popup = createNewPopup(popupType) popup:Place(position, Vector3.new(0,position.y,0)) local tweenIn = popup:TweenIn() tweenIn.Completed:Wait() local tweenOut = popup:TweenOut() tweenOut.Completed:Wait() popup.Model:Destroy() popup = nil end local FailCount = 0 local function OnTap(tapPositions, goToPoint) -- Good to remember if this is the latest tap event local camera = workspace.CurrentCamera local character = Player.Character if not CheckAlive(character) then return end -- This is a path tap position if #tapPositions == 1 or goToPoint then if camera then local unitRay = camera:ScreenPointToRay(tapPositions[1].x, tapPositions[1].y) local ray = Ray.new(unitRay.Origin, unitRay.Direction*1000) -- inivisicam stuff local initIgnore = getIgnoreList() local invisicamParts = {} --InvisicamModule and InvisicamModule:GetObscuredParts() or {} local ignoreTab = {} -- add to the ignore list for i, v in pairs(invisicamParts) do ignoreTab[#ignoreTab+1] = i end for i = 1, #initIgnore do ignoreTab[#ignoreTab+1] = initIgnore[i] end -- local myHumanoid = findPlayerHumanoid(Player) local hitPart, hitPt, hitNormal, hitMat = Utility.Raycast(ray, true, ignoreTab) local hitChar, hitHumanoid = Utility.FindCharacterAncestor(hitPart) local torso = GetTorso() local startPos = torso.CFrame.p if goToPoint then hitPt = goToPoint hitChar = nil end if hitChar and hitHumanoid and hitHumanoid.RootPart and (hitHumanoid.Torso.CFrame.p - torso.CFrame.p).magnitude < 7 then CleanupPath() if myHumanoid then myHumanoid:MoveTo(hitPt) end -- Do shoot local currentWeapon = GetEquippedTool(character) if currentWeapon then currentWeapon:Activate() LastFired = tick() end elseif hitPt and character and not CurrentSeatPart then local thisPather = Pather(character, hitPt, hitNormal) if thisPather:IsValidPath() then FailCount = 0 thisPather:Start() if BindableEvent_OnFailStateChanged then BindableEvent_OnFailStateChanged:Fire(false) end CleanupPath() local destinationPopup = createNewPopup("DestinationPopup") destinationPopup:Place(hitPt, Vector3.new(0,hitPt.y,0)) local failurePopup = createNewPopup("FailurePopup") local currentTween = destinationPopup:TweenIn() ExistingPather = thisPather ExistingIndicator = destinationPopup PathCompleteListener = thisPather.Finished.Event:Connect(function() if destinationPopup then if ExistingIndicator == destinationPopup then ExistingIndicator = nil end local tween = destinationPopup:TweenOut() local tweenCompleteEvent = nil tweenCompleteEvent = tween.Completed:Connect(function() tweenCompleteEvent:Disconnect() destinationPopup.Model:Destroy() destinationPopup = nil end) end if hitChar then local humanoid = findPlayerHumanoid(Player) local currentWeapon = GetEquippedTool(character) if currentWeapon then currentWeapon:Activate() LastFired = tick() end if humanoid then humanoid:MoveTo(hitPt) end end end) PathFailedListener = thisPather.PathFailed.Event:Connect(function() if FFlagUserNavigationFixClickToMoveInterruption then CleanupPath() end if failurePopup then failurePopup:Place(hitPt, Vector3.new(0,hitPt.y,0)) local failTweenIn = failurePopup:TweenIn() failTweenIn.Completed:Wait() local failTweenOut = failurePopup:TweenOut() failTweenOut.Completed:Wait() failurePopup.Model:Destroy() failurePopup = nil end end) else if hitPt then -- Feedback here for when we don't have a good path local foundDirectPath = false if (hitPt-startPos).Magnitude < 25 and (startPos.y-hitPt.y > -3) then -- move directly here if myHumanoid then if myHumanoid.Sit then myHumanoid.Jump = true end myHumanoid:MoveTo(hitPt) foundDirectPath = true end end coroutine.wrap(showQuickPopupAsync)(hitPt, foundDirectPath and "DirectWalkPopup" or "FailurePopup") end end elseif hitPt and character and CurrentSeatPart then local destinationPopup = createNewPopup("DestinationPopup") ExistingIndicator = destinationPopup destinationPopup:Place(hitPt, Vector3.new(0,hitPt.y,0)) destinationPopup:TweenIn() DrivingTo = hitPt local ConnectedParts = CurrentSeatPart:GetConnectedParts(true) while wait() do if CurrentSeatPart and ExistingIndicator == destinationPopup then local ExtentsSize = getExtentsSize(ConnectedParts) if inExtents(ExtentsSize, hitPt) then local popup = destinationPopup spawn(function() local tweenOut = popup:TweenOut() tweenOut.Completed:Wait() popup.Model:Destroy() end) destinationPopup = nil DrivingTo = nil break end else if CurrentSeatPart == nil and destinationPopup == ExistingIndicator then DrivingTo = nil OnTap(tapPositions, hitPt) end local popup = destinationPopup spawn(function() local tweenOut = popup:TweenOut() tweenOut.Completed:Wait() popup.Model:Destroy() end) destinationPopup = nil break end end end end elseif #tapPositions >= 2 then if camera then -- Do shoot local avgPoint = Utility.AveragePoints(tapPositions) local unitRay = camera:ScreenPointToRay(avgPoint.x, avgPoint.y) local currentWeapon = GetEquippedTool(character) if currentWeapon then currentWeapon:Activate() LastFired = tick() end end end end local function IsFinite(num) return num == num and num ~= 1/0 and num ~= -1/0 end local function findAngleBetweenXZVectors(vec2, vec1) return math.atan2(vec1.X*vec2.Z-vec1.Z*vec2.X, vec1.X*vec2.X + vec1.Z*vec2.Z) end local function DisconnectEvent(event) if event then event:Disconnect() end end --[[ The ClickToMove Controller Class ]]-- local BaseCharacterController = require(script.Parent:WaitForChild("BaseCharacterController")) local ClickToMove = setmetatable({}, BaseCharacterController) ClickToMove.__index = ClickToMove function ClickToMove.new() print("Instantiating Keyboard Controller") local self = setmetatable(BaseCharacterController.new(), ClickToMove) self.fingerTouches = {} self.numUnsunkTouches = 0 -- PC simulation self.mouse1Down = tick() self.mouse1DownPos = Vector2.new() self.mouse2DownTime = tick() self.mouse2DownPos = Vector2.new() self.mouse2UpTime = tick() self.tapConn = nil self.inputBeganConn = nil self.inputChangedConn = nil self.inputEndedConn = nil self.humanoidDiedConn = nil self.characterChildAddedConn = nil self.onCharacterAddedConn = nil self.characterChildRemovedConn = nil self.renderSteppedConn = nil self.humanoidSeatedConn = nil self.running = false return self end function ClickToMove:DisconnectEvents() DisconnectEvent(self.tapConn) DisconnectEvent(self.inputBeganConn) DisconnectEvent(self.inputChangedConn) DisconnectEvent(self.inputEndedConn) DisconnectEvent(self.humanoidDiedConn) DisconnectEvent(self.characterChildAddedConn) DisconnectEvent(self.onCharacterAddedConn) DisconnectEvent(self.renderSteppedConn) DisconnectEvent(self.characterChildRemovedConn) -- TODO: Resolve with ControlScript handling of seating for vehicles DisconnectEvent(self.humanoidSeatedConn) pcall(function() RunService:UnbindFromRenderStep("ClickToMoveRenderUpdate") end) end function ClickToMove:OnTouchBegan(input, processed) if self.fingerTouches[input] == nil and not processed then self.numUnsunkTouches = self.numUnsunkTouches + 1 end self.fingerTouches[input] = processed end function ClickToMove:OnTouchChanged(input, processed) if self.fingerTouches[input] == nil then self.fingerTouches[input] = processed if not processed then self.numUnsunkTouches = self.numUnsunkTouches + 1 end end end function ClickToMove:OnTouchEnded(input, processed) if self.fingerTouches[input] ~= nil and self.fingerTouches[input] == false then self.numUnsunkTouches = self.numUnsunkTouches - 1 end self.fingerTouches[input] = nil end function ClickToMove:OnCharacterAdded(character) self:DisconnectEvents() self.inputBeganConn = UserInputService.InputBegan:Connect(function(input, processed) if input.UserInputType == Enum.UserInputType.Touch then self:OnTouchBegan(input, processed) -- Give back controls when they tap both sticks local wasInBottomLeft = IsInBottomLeft(input.Position) local wasInBottomRight = IsInBottomRight(input.Position) if wasInBottomRight or wasInBottomLeft then for otherInput, _ in pairs(self.fingerTouches) do if otherInput ~= input then local otherInputInLeft = IsInBottomLeft(otherInput.Position) local otherInputInRight = IsInBottomRight(otherInput.Position) if otherInput.UserInputState ~= Enum.UserInputState.End and ((wasInBottomLeft and otherInputInRight) or (wasInBottomRight and otherInputInLeft)) then if BindableEvent_OnFailStateChanged then BindableEvent_OnFailStateChanged:Fire(true) end return end end end end end -- Cancel path when you use the keyboard controls. if processed == false and input.UserInputType == Enum.UserInputType.Keyboard and movementKeys[input.KeyCode] then CleanupPath() end if input.UserInputType == Enum.UserInputType.MouseButton1 then self.mouse1DownTime = tick() self.mouse1DownPos = input.Position end if input.UserInputType == Enum.UserInputType.MouseButton2 then self.mouse2DownTime = tick() self.mouse2DownPos = input.Position end end) self.inputChangedConn = UserInputService.InputChanged:Connect(function(input, processed) if input.UserInputType == Enum.UserInputType.Touch then self:OnTouchChanged(input, processed) end end) self.inputEndedConn = UserInputService.InputEnded:Connect(function(input, processed) if input.UserInputType == Enum.UserInputType.Touch then self:OnTouchEnded(input, processed) end if input.UserInputType == Enum.UserInputType.MouseButton2 then self.mouse2UpTime = tick() local currPos = input.Position if self.mouse2UpTime - self.mouse2DownTime < 0.25 and (currPos - self.mouse2DownPos).magnitude < 5 then local positions = {currPos} OnTap(positions) end end end) self.tapConn = UserInputService.TouchTap:Connect(function(touchPositions, processed) if not processed then OnTap(touchPositions) end end) local function computeThrottle(dist) if dist > .2 then return 0.5+(dist^2)/2 else return 0 end end local lastSteer = 0 --kP = how much the steering corrects for the current error in driving angle --kD = how much the steering corrects for how quickly the error in driving angle is changing local kP = 1 local kD = 0.5 local function getThrottleAndSteer(object, point) local throttle, steer = 0, 0 local oCF = object.CFrame local relativePosition = oCF:pointToObjectSpace(point) local relativeZDirection = -relativePosition.z local relativeDistance = relativePosition.magnitude -- throttle quadratically increases from 0-1 as distance from the selected point goes from 0-50, after 50, throttle is 1. -- this allows shorter distance travel to have more fine-tuned control. throttle = computeThrottle(math.min(1,relativeDistance/50))*math.sign(relativeZDirection) local steerAngle = -math.atan2(-relativePosition.x, -relativePosition.z) steer = steerAngle/(math.pi/4) local steerDelta = steer - lastSteer lastSteer = steer local pdSteer = kP * steer + kD * steer return throttle, pdSteer end local function Update() if CurrentSeatPart then if DrivingTo then local throttle, steer = getThrottleAndSteer(CurrentSeatPart, DrivingTo) CurrentSeatPart.ThrottleFloat = throttle CurrentSeatPart.SteerFloat = steer else CurrentSeatPart.ThrottleFloat = 0 CurrentSeatPart.SteerFloat = 0 end end local cameraPos = workspace.CurrentCamera.CFrame.p for i = 1, #activePopups do local popup = activePopups[i] popup.CFrame = CFrame.new(popup.CFrame.p, cameraPos) end end RunService:BindToRenderStep("ClickToMoveRenderUpdate",Enum.RenderPriority.Camera.Value - 1,Update) -- TODO: Resolve with control script seating functionality -- local function onSeated(child, active, currentSeatPart) -- if active then -- if TouchJump and UserInputService.TouchEnabled then -- TouchJump:Enable() -- end -- if currentSeatPart and currentSeatPart.ClassName == "VehicleSeat" then -- CurrentSeatPart = currentSeatPart -- end -- else -- CurrentSeatPart = nil -- if TouchJump and UserInputService.TouchEnabled then -- TouchJump:Disable() -- end -- end -- end local function OnCharacterChildAdded(child) if UserInputService.TouchEnabled then if child:IsA('Tool') then child.ManualActivationOnly = true end end if child:IsA('Humanoid') then DisconnectEvent(self.humanoidDiedConn) self.humanoidDiedConn = child.Died:Connect(function() if ExistingIndicator then DebrisService:AddItem(ExistingIndicator.Model, 1) end end) -- self.humanoidSeatedConn = child.Seated:Connect(function(active, seat) onSeated(child, active, seat) end) -- if child.SeatPart then -- onSeated(child, true, child.SeatPart) -- end end end self.characterChildAddedConn = character.ChildAdded:Connect(function(child) OnCharacterChildAdded(child) end) self.characterChildRemovedConn = character.ChildRemoved:Connect(function(child) if UserInputService.TouchEnabled then if child:IsA('Tool') then child.ManualActivationOnly = false end end end) for _, child in pairs(character:GetChildren()) do OnCharacterChildAdded(child) end end function ClickToMove:Start() self:Enable(true) end function ClickToMove:Stop() self:Enable(false) end function ClickToMove:Enable(enable) if enable then if not self.running then if Player.Character then -- retro-listen self:OnCharacterAdded(Player.Character) end self.onCharacterAddedConn = Player.CharacterAdded:Connect(function(char) self:OnCharacterAdded(char) end) self.running = true end else if self.running then self:DisconnectEvents() CleanupPath() -- Restore tool activation on shutdown if UserInputService.TouchEnabled then local character = Player.Character if character then for _, child in pairs(character:GetChildren()) do if child:IsA('Tool') then child.ManualActivationOnly = false end end end end DrivingTo = nil self.running = false end end self.enabled = enable end return ClickToMove
apache-2.0
xsolinsx/AISashaAPI
plugins/getsetunset.lua
1
27827
-- tables that contains 'group_id' = message_id to delete old commands responses local oldResponses = { lastGet = { }, lastGetGlobal = { }, } local function get_variables_hash(chat_id, chat_type, global) if global then if not redis_get_something(chat_id .. ':gvariables') then return 'gvariables' end return false else if chat_type == 'private' then return 'user:' .. chat_id .. ':variables' end if chat_type == 'group' then return 'group:' .. chat_id .. ':variables' end if chat_type == 'supergroup' then return 'supergroup:' .. chat_id .. ':variables' end if chat_type == 'channel' then return 'channel:' .. chat_id .. ':variables' end return false end end local function list_variables(msg, global) local hash = get_variables_hash(msg.chat.id, msg.chat.type, global) local text = '' if global then text = langs[msg.lang].getGlobalStart else text = langs[msg.lang].getStart:gsub('X', msg.chat.print_name or msg.chat.title or(msg.chat.first_name ..(msg.chat.last_name or ''))) end if hash then local names = redis_get_something(hash) if names then for key, value in pairs(names) do text = text .. '\n' .. key:gsub('_', ' ') end end return text end end local function get_value(chat_id, chat_type, var_name) var_name = var_name:gsub(' ', '_') if not redis_get_something(chat_id .. ':gvariables') then local hash = get_variables_hash(chat_id, chat_type, true) if hash then local value = redis_hget_something(hash, var_name) if value then return value end end end local hash = get_variables_hash(chat_id, chat_type, false) if hash then local value = redis_hget_something(hash, var_name) if value then return value end end end local function get_rules(chat_id) local lang = get_lang(chat_id) if not data[tostring(chat_id)].rules then return langs[lang].noRules end local rules = data[tostring(chat_id)].rules return rules end local function adjust_value(value, msg, parse_mode) -- chat local chat = msg.chat if string.find(value, '$chatid') then value = value:gsub('$chatid', chat.id) end if string.find(value, '$chatname') then value = value:gsub('$chatname', chat.title) end if string.find(value, '$chatusername') then if chat.username then value = value:gsub('$chatusername', '@' .. chat.username) else value = value:gsub('$chatusername', 'NO CHAT USERNAME') end end if string.find(value, '$rules') then value = value:gsub('$rules', get_rules(chat.id)) end if string.find(value, '$grouplink') then value = value:gsub('$grouplink', data[tostring(chat.id)].link or 'NO GROUP LINK SET') end -- user local user = msg.from if string.find(value, '$userid') then value = value:gsub('$userid', user.id) end if string.find(value, '$firstname') then value = value:gsub('$firstname', user.first_name) end if string.find(value, '$lastname') then value = value:gsub('$lastname', user.last_name or '') end if string.find(value, '$printname') then value = value:gsub('$printname', user.first_name .. ' ' ..(user.last_name or '')) end if string.find(value, '$username') then if user.username then value = value:gsub('$username', '@' .. user.username) else value = value:gsub('$username', 'NO USERNAME') end end if string.find(value, '$mention') then if not parse_mode then value = value:gsub('$mention', '[' .. user.first_name .. '](tg://user?id=' .. user.id .. ')') else if parse_mode == 'html' then value = value:gsub('$mention', '<a href="tg://user?id=' .. user.id .. '">' .. html_escape(user.first_name) .. '</a>') elseif parse_mode == 'markdown' then value = value:gsub('$mention', '[' .. user.first_name:mEscape_hard() .. '](tg://user?id=' .. user.id .. ')') end end end -- replyuser local replyuser = user if msg.reply then replyuser = msg.reply_to_message.from end if string.find(value, '$replyuserid') then value = value:gsub('$replyuserid', replyuser.id) end if string.find(value, '$replyfirstname') then value = value:gsub('$replyfirstname', replyuser.first_name) end if string.find(value, '$replylastname') then value = value:gsub('$replylastname', replyuser.last_name or '') end if string.find(value, '$replyprintname') then value = value:gsub('$replyprintname', replyuser.first_name .. ' ' ..(replyuser.last_name or '')) end if string.find(value, '$replyusername') then if replyuser.username then value = value:gsub('$replyusername', '@' .. replyuser.username) else value = value:gsub('$replyusername', 'NO USERNAME') end end if string.find(value, '$replymention') then if not parse_mode then value = value:gsub('$replymention', '[' .. replyuser.first_name .. '](tg://user?id=' .. replyuser.id .. ')') else if parse_mode == 'html' then value = value:gsub('$replymention', '<a href="tg://user?id=' .. replyuser.id .. '">' .. html_escape(replyuser.first_name) .. '</a>') elseif parse_mode == 'markdown' then value = value:gsub('$replymention', '[' .. replyuser.first_name:mEscape_hard() .. '](tg://user?id=' .. replyuser.id .. ')') end end end -- forward chat local fwd_chat = chat if msg.forward and msg.forward_from_chat then fwd_chat = msg.forward_from_chat end if string.find(value, '$forwardchatid') then value = value:gsub('$forwardchatid', fwd_chat.id) end if string.find(value, '$forwardchatname') then value = value:gsub('$forwardchatname', fwd_chat.title) end if string.find(value, '$forwardchatusername') then if fwd_chat.username then value = value:gsub('$forwardchatusername', '@' .. fwd_chat.username) else value = value:gsub('$forwardchatusername', 'NO CHAT USERNAME') end end -- forward user local fwd_user = user if msg.forward and msg.forward_from then fwd_user = msg.forward_from end if string.find(value, '$forwarduserid') then value = value:gsub('$forwarduserid', fwd_user.id) end if string.find(value, '$forwardfirstname') then value = value:gsub('$forwardfirstname', fwd_user.first_name) end if string.find(value, '$forwardlastname') then value = value:gsub('$forwardlastname', fwd_user.last_name or '') end if string.find(value, '$forwardprintname') then value = value:gsub('$forwardprintname', fwd_user.first_name .. ' ' ..(fwd_user.last_name or '')) end if string.find(value, '$forwardusername') then if fwd_user.username then value = value:gsub('$forwardusername', '@' .. fwd_user.username) else value = value:gsub('$forwardusername', 'NO USERNAME') end end if string.find(value, '$forwardmention') then if not parse_mode then value = value:gsub('$forwardmention', '[' .. fwd_user.first_name .. '](tg://user?id=' .. fwd_user.id .. ')') else if parse_mode == 'html' then value = value:gsub('$forwardmention', '<a href="tg://user?id=' .. fwd_user.id .. '">' .. html_escape(fwd_user.first_name) .. '</a>') elseif parse_mode == 'markdown' then value = value:gsub('$forwardmention', '[' .. fwd_user.first_name:mEscape_hard() .. '](tg://user?id=' .. fwd_user.id .. ')') end end end return value end local function set_unset_variables_hash(chat_id, chat_type, global) if global then return 'gvariables' else if chat_type == 'private' then return 'user:' .. chat_id .. ':variables' end if chat_type == 'group' then return 'group:' .. chat_id .. ':variables' end if chat_type == 'supergroup' then return 'supergroup:' .. chat_id .. ':variables' end if chat_type == 'channel' then return 'channel:' .. chat_id .. ':variables' end return false end end local function set_value(chat_id, chat_type, name, value, global) if (not name or not value) then return langs[get_lang(chat_id)].errorTryAgain end local hash = set_unset_variables_hash(chat_id, chat_type, global) if hash then redis_hset_something(hash, name, value) if global then return name .. langs[get_lang(chat_id)].gSaved else return name .. langs[get_lang(chat_id)].saved end end end local function unset_var(chat_id, chat_type, name, global) if (not name) then return langs[get_lang(chat_id)].errorTryAgain end local hash = set_unset_variables_hash(chat_id, chat_type, global) if hash then redis_hdelsrem_something(hash, name:lower()) if global then return name:lower() .. langs[get_lang(chat_id)].gDeleted else return name:lower() .. langs[get_lang(chat_id)].deleted end end end local function check_word(msg, word, pre) if msg.text then if pre then if not string.match(msg.text, "^[#!/][Gg][Ee][Tt] (.*)$") and not string.match(msg.text, "^[#!/][Uu][Nn][Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll] ([^%s]+)$") and not string.match(msg.text, "^[#!/]([Ii][Mm][Pp][Oo][Rr][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ss][Ee][Tt][Ss]) (.+)$") and not string.match(msg.text, "^[#!/][Uu][Nn][Ss][Ee][Tt] ([^%s]+)$") and not string.match(msg.text, "^[#!/][Ii][Mm][Pp][Oo][Rr][Tt][Gg][Rr][Oo][Uu][Pp][Ss][Ee][Tt][Ss] (.+)$") then if string.match(msg.text:lower(), word:lower()) then local value = get_value(msg.chat.id, msg.chat.type, word:lower()) if value then print('GET FOUND') return value end end end else if string.match(msg.text:lower(), word:lower()) then local value = get_value(msg.chat.id, msg.chat.type, word:lower()) if value then print('GET FOUND') return value end end end end return false end local function run(msg, matches) if matches[1]:lower() == 'get' or matches[1]:lower() == 'getlist' then if not matches[2] then mystat('/get') if msg.from.is_mod then local tmp = oldResponses.lastGet[tostring(msg.chat.id)] oldResponses.lastGet[tostring(msg.chat.id)] = getMessageId(sendReply(msg, list_variables(msg, false))) if tmp then deleteMessage(msg.chat.id, tmp, true) end io.popen('lua timework.lua "deletemessage" "60" "' .. msg.chat.id .. '" "' .. msg.message_id .. '"') else local tmp = '' if not sendMessage(msg.from.id, list_variables(msg, false)) then tmp = getMessageId(sendKeyboard(msg.chat.id, langs[msg.lang].cantSendPvt, { inline_keyboard = { { { text = "/start", url = bot.link } } } }, false, msg.message_id)) else tmp = getMessageId(sendReply(msg, langs[msg.lang].generalSendPvt, 'html')) end io.popen('lua timework.lua "deletemessage" "60" "' .. msg.chat.id .. '" "' .. msg.message_id .. ',' .. tmp .. '"') end return else mystat('/get <var_name>') local vars = list_variables(msg, false) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local answer = check_word(msg, word:lower(), false) if answer then return langs[msg.lang].getCommand:gsub('X', word:lower()) .. answer end end end local vars = list_variables(msg, true) if vars ~= nil then local t = vars:split('\n') for i, word in pairs(t) do local answer = check_word(msg, word:lower(), false) if answer then return langs[msg.lang].getCommand:gsub('X', word:lower()) .. answer end end end return langs[msg.lang].noSetValue end end if matches[1]:lower() == 'getglobal' or matches[1]:lower() == 'getgloballist' then mystat('/getglobal') if msg.from.is_mod then local tmp = oldResponses.lastGetGlobal[tostring(msg.chat.id)] oldResponses.lastGetGlobal[tostring(msg.chat.id)] = getMessageId(sendReply(msg, list_variables(msg, true))) if tmp then deleteMessage(msg.chat.id, tmp, true) end io.popen('lua timework.lua "deletemessage" "60" "' .. msg.chat.id .. '" "' .. msg.message_id .. '"') return else local tmp = '' if not sendMessage(msg.from.id, list_variables(msg, true)) then tmp = getMessageId(sendKeyboard(msg.chat.id, langs[msg.lang].cantSendPvt, { inline_keyboard = { { { text = "/start", url = bot.link } } } }, false, msg.message_id)) else tmp = getMessageId(sendReply(msg, langs[msg.lang].generalSendPvt, 'html')) end io.popen('lua timework.lua "deletemessage" "60" "' .. msg.chat.id .. '" "' .. msg.message_id .. ',' .. tmp .. '"') end return end if matches[1]:lower() == 'exportgroupsets' then mystat('/exportgroupsets') if msg.from.is_owner then if list_variables(msg, false) then local tab = list_variables(msg, false):split('\n') local newtab = { } for i, word in pairs(tab) do newtab[word] = get_value(msg.chat.id, msg.chat.type, word:lower()) end file_name = string.random(50) local file_path = "data/tmp/" .. file_name .. ".json" save_data(file_path, newtab) return pyrogramUpload(msg.chat.id, "document", file_path, msg.message_id) end else return langs[msg.lang].require_owner end end if matches[1]:lower() == 'exportglobalsets' then mystat('/exportglobalsets') if is_admin(msg) then if list_variables(msg, true) then local tab = list_variables(msg, true):split('\n') local newtab = { } for i, word in pairs(tab) do newtab[word] = get_value(msg.chat.id, msg.chat.type, word:lower()) end local text = '' for word, answer in pairs(newtab) do text = text .. '/setglobal ' .. word:gsub(' ', '_') .. ' ' .. answer .. '\nXXXxxxXXX\n' end return text end else return langs[msg.lang].require_admin end end if matches[1]:lower() == 'enableglobal' then mystat('/enableglobal') if msg.from.is_owner then redis_del_something(msg.chat.id .. ':gvariables') return langs[msg.lang].globalEnable else return langs[msg.lang].require_owner end end if matches[1]:lower() == 'disableglobal' then mystat('/disableglobal') if msg.from.is_owner then redis_set_something(msg.chat.id .. ':gvariables', true) return langs[msg.lang].globalDisable else return langs[msg.lang].require_owner end end if matches[1]:lower() == 'setmedia' then if msg.from.is_mod then mystat('/setmedia') if not matches[2] then return langs[msg.lang].errorTryAgain end local hash = set_unset_variables_hash(msg.chat.id, msg.chat.type) if hash then local caption = matches[3] or '' local file_id, file_name, file_size, media_type if msg.reply then file_id, file_name, file_size = extractMediaDetails(msg.reply_to_message) media_type = msg.reply_to_message.media_type elseif msg.media then file_id, file_name, file_size = extractMediaDetails(msg) media_type = msg.media_type end if file_id and file_name and file_size then if file_size <= 20971520 then if caption ~= '' then caption = ' ' .. caption end if pcall( function() string.match(string.sub(matches[2]:lower(), 1, 50), string.sub(matches[2]:lower(), 1, 50)) end ) then redis_hset_something(hash, string.sub(matches[2]:lower(), 1, 50), media_type .. file_id .. caption) return langs[msg.lang].mediaSaved else return langs[msg.lang].errorTryAgain end else return langs[msg.lang].cantDownloadMoreThan20MB end else return langs[msg.lang].useCommandOnFile end end else return langs[msg.lang].require_mod end end if matches[1]:lower() == 'set' then if msg.from.is_mod then mystat('/set') if string.match(matches[3], '[Cc][Rr][Oo][Ss][Ss][Ee][Xx][Ee][Cc]') then return langs[msg.lang].crossexecDenial end if pcall( function() string.match(string.sub(matches[2]:lower(), 1, 50), string.sub(matches[2]:lower(), 1, 50)) end ) then return set_value(msg.chat.id, msg.chat.type, string.sub(matches[2]:lower(), 1, 50), string.sub(matches[3], 1, 4096), false) else return langs[msg.lang].errorTryAgain end else return langs[msg.lang].require_mod end end if matches[1]:lower() == 'setglobal' then if is_admin(msg) then mystat('/setglobal') if string.match(matches[3], '[Cc][Rr][Oo][Ss][Ss][Ee][Xx][Ee][Cc]') then return langs[msg.lang].crossexecDenial end if pcall( function() string.match(string.sub(matches[2]:lower(), 1, 50), string.sub(matches[2]:lower(), 1, 50)) end ) then return set_value(msg.chat.id, msg.chat.type, string.sub(matches[2]:lower(), 1, 50), string.sub(matches[3], 1, 4096), true) else return langs[msg.lang].errorTryAgain end else return langs[msg.lang].require_admin end end if matches[1]:lower() == 'unset' then mystat('/unset') if msg.from.is_mod then return unset_var(msg.chat.id, msg.chat.type, string.gsub(string.sub(matches[2], 1, 50), ' ', '_'):lower(), false) else return langs[msg.lang].require_mod end end if matches[1]:lower() == 'unsetglobal' then mystat('/unsetglobal') if is_admin(msg) then return unset_var(msg.chat.id, msg.chat.type, string.gsub(string.sub(matches[2], 1, 50), ' ', '_'):lower(), true) else return langs[msg.lang].require_admin end end end local function pre_process(msg) if msg then -- local local vars = redis_get_something(get_variables_hash(msg.chat.id, msg.chat.type, false)) if vars then for key, word in pairs(vars) do local answer = check_word(msg, key:gsub('_', ' '):lower(), true) if answer then if string.match(answer, '^photo') then answer = answer:gsub('^photo', '') local media_id = answer:match('^([^%s]+)') local caption = answer:match('^[^%s]+ (.*)') sendPhotoId(msg.chat.id, media_id, caption, msg.message_id) return msg elseif string.match(answer, '^video_note') then answer = answer:gsub('^video_note', '') local media_id = answer:match('^([^%s]+)') sendVideoNoteId(msg.chat.id, media_id, msg.message_id) return msg elseif string.match(answer, '^video') then answer = answer:gsub('^video', '') local media_id = answer:match('^([^%s]+)') local caption = answer:match('^[^%s]+ (.*)') sendVideoId(msg.chat.id, media_id, caption, msg.message_id) return msg elseif string.match(answer, '^audio') then answer = answer:gsub('^audio', '') local media_id = answer:match('^([^%s]+)') local caption = answer:match('^[^%s]+ (.*)') sendAudioId(msg.chat.id, media_id, caption, msg.message_id) return msg elseif string.match(answer, '^voice_note') or string.match(answer, '^voice') then answer = answer:gsub('^voice_note', '') answer = answer:gsub('^voice', '') local media_id = answer:match('^([^%s]+)') local caption = answer:match('^[^%s]+ (.*)') sendVoiceId(msg.chat.id, media_id, caption, msg.message_id) return msg elseif string.match(answer, '^gif') then answer = answer:gsub('^gif', '') local media_id = answer:match('^([^%s]+)') local caption = answer:match('^[^%s]+ (.*)') sendAnimationId(msg.chat.id, media_id, caption, msg.message_id) return msg elseif string.match(answer, '^document') then answer = answer:gsub('^document', '') local media_id = answer:match('^([^%s]+)') local caption = answer:match('^[^%s]+ (.*)') sendDocumentId(msg.chat.id, media_id, caption, msg.message_id) return msg elseif string.match(answer, '^sticker') then answer = answer:gsub('^sticker', '') local media_id = answer:match('^([^%s]+)') sendStickerId(msg.chat.id, media_id, msg.message_id) return msg else if string.find(answer, '$mention') or string.find(answer, '$replymention') or string.find(answer, '$forwardmention') then if not sendReply(msg, adjust_value(answer, msg, 'markdown'), 'markdown') then if not sendReply(msg, adjust_value(answer, msg, 'html'), 'html') then sendReply(msg, adjust_value(answer, msg)) end end else sendReply(msg, adjust_value(answer, msg)) end return msg end end end end -- global local vars = redis_get_something(get_variables_hash(msg.chat.id, msg.chat.type, true)) if vars then for key, word in pairs(vars) do local answer = check_word(msg, key:gsub('_', ' '):lower(), true) if answer then if string.find(answer, '$mention') or string.find(answer, '$replymention') or string.find(answer, '$forwardmention') then if not sendReply(msg, adjust_value(answer, msg, 'markdown'), 'markdown') then if not sendReply(msg, adjust_value(answer, msg, 'html'), 'html') then sendReply(msg, adjust_value(answer, msg)) end end else sendReply(msg, adjust_value(answer, msg)) end return msg end end end return msg end end return { description = "GETSETUNSET", patterns = { --- GET "^[#!/]([Gg][Ee][Tt]) (.*)$", "^[#!/]([Gg][Ee][Tt][Ll][Ii][Ss][Tt])$", "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ll][Ii][Ss][Tt])$", "^[#!/]([Ee][Nn][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", "^[#!/]([Dd][Ii][Ss][Aa][Bb][Ll][Ee][Gg][Ll][Oo][Bb][Aa][Ll])$", "^[#!/]([Ee][Xx][Pp][Oo][Rr][Tt][Gg][Ll][Oo][Bb][Aa][Ll][Ss][Ee][Tt][Ss])$", "^[#!/]([Ee][Xx][Pp][Oo][Rr][Tt][Gg][Rr][Oo][Uu][Pp][Ss][Ee][Tt][Ss])$", -- getlist "^[#!/]([Gg][Ee][Tt])$", -- getgloballist "^[#!/]([Gg][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll])$", --- SET "^[#!/]([Ss][Ee][Tt]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll]) ([^%s]+) (.+)$", "^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+) (.*)$", "^[#!/]([Ss][Ee][Tt][Mm][Ee][Dd][Ii][Aa]) ([^%s]+)$", --- UNSET "^[#!/]([Uu][Nn][Ss][Ee][Tt]) (.*)$", "^[#!/]([Uu][Nn][Ss][Ee][Tt][Gg][Ll][Oo][Bb][Aa][Ll]) (.*)$", }, pre_process = pre_process, run = run, min_rank = 1, syntax = { "USER", "/get {var_name}", "(/getlist|/get)", "(/getgloballist|/getglobal)", "MOD", "/set {var_name}|{pattern} {text}", "/setmedia {var_name}|{pattern} {media}|{reply_media} [{caption}]", "/unset {var_name}|{pattern}", "OWNER", "/enableglobal", "/disableglobal", "ADMIN", "/setglobal {var_name}|{pattern} {text}", "/unsetglobal {var_name}|{pattern}", }, }
gpl-2.0
daurnimator/lua-systemd
src/journal.lua
1
2191
local id128 = require "systemd.id128" local c = require "systemd.journal.core" local methods = c.JOURNAL_METHODS local function strip_field_name(str) return str:match("=(.*)$") end local function split_field(str) return str:match("^([^=]*)=(.*)$") end c.LOG = { EMERG = 0; ALERT = 1; CRIT = 2; ERR = 3; WARNING = 4; NOTICE = 5; INFO = 6; DEBUG = 7; } function c.print(priority, ...) return c.sendv { "PRIORITY=" .. priority; "MESSAGE=" .. string.format(...); } end function c.sendt(m) local t = { } for k, v in pairs(m) do t[#t+1] = k .. "=" .. v end return c.sendv(t) end function methods:get(field) local ok, res, code = self:get_data(field) if ok then return strip_field_name(res) elseif ok == false then return nil else error(res, 2); end end local function next_field(self) local ok, res = self:enumerate_data() if ok then return split_field(res) elseif ok == false then return nil else error(res, 2) end end function methods:each_data() self:restart_data() return next_field, self end local function next_unique(self) local ok, res = self:enumerate_unique() if ok then return strip_field_name(res) elseif ok == false then return nil else error(res, 2) end end function methods:each_unique(field) self:restart_unique() assert(self:query_unique(field)) return next_unique, self end -- Converts the current journal entry to a lua table -- Includes __ prefixed "Address Fields" function methods:to_table() local t = { __CURSOR = self:get_cursor(); __REALTIME_TIMESTAMP = self:get_realtime_usec(); __MONOTONIC_TIMESTAMP = self:get_monotonic_usec(); } for field, value in self:each_data() do t[field] = value end return t end function methods:get_catalog() local ok, err, errno = self:get_data "MESSAGE_ID" if ok == nil then return nil, err, errno elseif ok == false then return false else local message_id = err:match("=(.*)$") if message_id == nil then return false end local message_id = id128.from_string(message_id) local text = message_id:get_catalog() if not text then return false end local t = self:to_table() text = text:gsub("@([^@]-)@", t) return text end end return c
mit
kitala1/darkstar
scripts/globals/items/calico_comet.lua
18
1280
----------------------------------------- -- ID: 5715 -- Item: Calico Comet -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5715); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/Skeleton.lua
3
1396
-------------------------------- -- @module Skeleton -- @extend Node,BlendProtocol -------------------------------- -- @function [parent=#Skeleton] setToSetupPose -- @param self -------------------------------- -- @function [parent=#Skeleton] setBlendFunc -- @param self -- @param #cc.BlendFunc blendfunc -------------------------------- -- @function [parent=#Skeleton] onDraw -- @param self -- @param #cc.Mat4 mat4 -- @param #bool bool -------------------------------- -- @function [parent=#Skeleton] setSlotsToSetupPose -- @param self -------------------------------- -- @function [parent=#Skeleton] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- @function [parent=#Skeleton] setSkin -- @param self -- @param #char char -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Skeleton] setBonesToSetupPose -- @param self -------------------------------- -- @function [parent=#Skeleton] getBoundingBox -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- @function [parent=#Skeleton] onEnter -- @param self -------------------------------- -- @function [parent=#Skeleton] onExit -- @param self return nil
mit
kitala1/darkstar
scripts/zones/Sacrarium/npcs/qm3.lua
8
1733
----------------------------------- -- Area: Sacrarium -- NPC: qm3 (???) -- Notes: Used to spawn Old Prof. Mariselle -- @pos 62.668 -3.111 127.288 28 ----------------------------------- package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Sacrarium/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local OldProfessor = 16891970; if(GetServerVariable("Old_Prof_Spawn_Location") == 3) then if(player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0)then player:messageSpecial(EVIL_PRESENCE); SpawnMob(OldProfessor,300):updateClaim(player); GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC else player:messageSpecial(DRAWER_SHUT); end elseif(player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false)then player:addKeyItem(RELIQUIARIUM_KEY); player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY); else player:messageSpecial(DRAWER_OPEN); player:messageSpecial(DRAWER_EMPTY); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) end;
gpl-3.0
kitala1/darkstar
scripts/zones/Caedarva_Mire/npcs/Tyamah.lua
23
1334
----------------------------------- -- Area: Caedarva Mire -- NPC: Tyamah -- Type: Alzadaal Undersea Ruins -- @pos 320.003 0.124 -700.011 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver player:tradeComplete(); player:startEvent(0x00a3); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getXPos() > 320) then player:startEvent(0x00a4); else player:startEvent(0x00a2); 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 == 0x00a3) then player:setPos(-20,-4,835,64,72); end end;
gpl-3.0
fastmailops/prosody
plugins/mod_roster.lua
4
5789
-- Prosody IM -- Copyright (C) 2008-2010 Matthew Wild -- Copyright (C) 2008-2010 Waqas Hussain -- -- This project is MIT/X11 licensed. Please see the -- COPYING file in the source package for more information. -- local st = require "util.stanza" local jid_split = require "util.jid".split; local jid_prep = require "util.jid".prep; local t_concat = table.concat; local tonumber = tonumber; local pairs, ipairs = pairs, ipairs; local rm_load_roster = require "core.rostermanager".load_roster; local rm_remove_from_roster = require "core.rostermanager".remove_from_roster; local rm_add_to_roster = require "core.rostermanager".add_to_roster; local rm_roster_push = require "core.rostermanager".roster_push; local core_post_stanza = prosody.core_post_stanza; module:add_feature("jabber:iq:roster"); local rosterver_stream_feature = st.stanza("ver", {xmlns="urn:xmpp:features:rosterver"}); module:hook("stream-features", function(event) local origin, features = event.origin, event.features; if origin.username then features:add_child(rosterver_stream_feature); end end); module:hook("iq/self/jabber:iq:roster:query", function(event) local session, stanza = event.origin, event.stanza; if stanza.attr.type == "get" then local roster = st.reply(stanza); local client_ver = tonumber(stanza.tags[1].attr.ver); local server_ver = tonumber(session.roster[false].version or 1); if not (client_ver and server_ver) or client_ver ~= server_ver then roster:query("jabber:iq:roster"); -- Client does not support versioning, or has stale roster for jid, item in pairs(session.roster) do if jid ~= "pending" and jid then roster:tag("item", { jid = jid, subscription = item.subscription, ask = item.ask, name = item.name, }); for group in pairs(item.groups) do roster:tag("group"):text(group):up(); end roster:up(); -- move out from item end end roster.tags[1].attr.ver = server_ver; end session.send(roster); session.interested = true; -- resource is interested in roster updates else -- stanza.attr.type == "set" local query = stanza.tags[1]; if #query.tags == 1 and query.tags[1].name == "item" and query.tags[1].attr.xmlns == "jabber:iq:roster" and query.tags[1].attr.jid -- Protection against overwriting roster.pending, until we move it and query.tags[1].attr.jid ~= "pending" then local item = query.tags[1]; local from_node, from_host = jid_split(stanza.attr.from); local jid = jid_prep(item.attr.jid); local node, host, resource = jid_split(jid); if not resource and host then if jid ~= from_node.."@"..from_host then if item.attr.subscription == "remove" then local roster = session.roster; local r_item = roster[jid]; if r_item then local to_bare = node and (node.."@"..host) or host; -- bare JID if r_item.subscription == "both" or r_item.subscription == "from" or (roster.pending and roster.pending[jid]) then core_post_stanza(session, st.presence({type="unsubscribed", from=session.full_jid, to=to_bare})); end if r_item.subscription == "both" or r_item.subscription == "to" or r_item.ask then core_post_stanza(session, st.presence({type="unsubscribe", from=session.full_jid, to=to_bare})); end local success, err_type, err_cond, err_msg = rm_remove_from_roster(session, jid); if success then session.send(st.reply(stanza)); rm_roster_push(from_node, from_host, jid); else session.send(st.error_reply(stanza, err_type, err_cond, err_msg)); end else session.send(st.error_reply(stanza, "modify", "item-not-found")); end else local r_item = {name = item.attr.name, groups = {}}; if r_item.name == "" then r_item.name = nil; end if session.roster[jid] then r_item.subscription = session.roster[jid].subscription; r_item.ask = session.roster[jid].ask; else r_item.subscription = "none"; end for _, child in ipairs(item) do if child.name == "group" then local text = t_concat(child); if text and text ~= "" then r_item.groups[text] = true; end end end local success, err_type, err_cond, err_msg = rm_add_to_roster(session, jid, r_item); if success then -- Ok, send success session.send(st.reply(stanza)); -- and push change to all resources rm_roster_push(from_node, from_host, jid); else -- Adding to roster failed session.send(st.error_reply(stanza, err_type, err_cond, err_msg)); end end else -- Trying to add self to roster session.send(st.error_reply(stanza, "cancel", "not-allowed")); end else -- Invalid JID added to roster session.send(st.error_reply(stanza, "modify", "bad-request")); -- FIXME what's the correct error? end else -- Roster set didn't include a single item, or its name wasn't 'item' session.send(st.error_reply(stanza, "modify", "bad-request")); end end return true; end); module:hook_global("user-deleted", function(event) local username, host = event.username, event.host; if host ~= module.host then return end local bare = username .. "@" .. host; local roster = rm_load_roster(username, host); for jid, item in pairs(roster) do if jid and jid ~= "pending" then if item.subscription == "both" or item.subscription == "from" or (roster.pending and roster.pending[jid]) then module:send(st.presence({type="unsubscribed", from=bare, to=jid})); end if item.subscription == "both" or item.subscription == "to" or item.ask then module:send(st.presence({type="unsubscribe", from=bare, to=jid})); end end end end, 300);
mit
kitala1/darkstar
scripts/zones/Kazham/npcs/Ronta-Onta.lua
23
4041
----------------------------------- -- Area: Kazham -- NPC: Ronta-Onta -- Starts and Finishes Quest: Trial by Fire -- @pos 100 -15 -97 250 ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TrialByFire = player:getQuestStatus(OUTLANDS,TRIAL_BY_FIRE); WhisperOfFlames = player:hasKeyItem(WHISPER_OF_FLAMES); realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day if((TrialByFire == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 6) or (TrialByFire == QUEST_COMPLETED and realday ~= player:getVar("TrialByFire_date"))) then player:startEvent(0x010e,0,TUNING_FORK_OF_FIRE); -- Start and restart quest "Trial by Fire" elseif(TrialByFire == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_FIRE) == false and WhisperOfFlames == false) then player:startEvent(0x011d,0,TUNING_FORK_OF_FIRE); -- Defeat against Ifrit : Need new Fork elseif(TrialByFire == QUEST_ACCEPTED and WhisperOfFlames == false) then player:startEvent(0x010f,0,TUNING_FORK_OF_FIRE,0); elseif(TrialByFire == QUEST_ACCEPTED and WhisperOfFlames) then numitem = 0; if(player:hasItem(17665)) then numitem = numitem + 1; end -- Ifrits Blade if(player:hasItem(13241)) then numitem = numitem + 2; end -- Fire Belt if(player:hasItem(13560)) then numitem = numitem + 4; end -- Fire Ring if(player:hasItem(1203)) then numitem = numitem + 8; end -- Egil's Torch if(player:hasSpell(298)) then numitem = numitem + 32; end -- Ability to summon Ifrit player:startEvent(0x0111,0,TUNING_FORK_OF_FIRE,0,0,numitem); else player:startEvent(0x0112); -- 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 == 0x010e and option == 1) then if(player:getQuestStatus(OUTLANDS,TRIAL_BY_FIRE) == QUEST_COMPLETED) then player:delQuest(OUTLANDS,TRIAL_BY_FIRE); end player:addQuest(OUTLANDS,TRIAL_BY_FIRE); player:setVar("TrialByFire_date", 0); player:addKeyItem(TUNING_FORK_OF_FIRE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_FIRE); elseif(csid == 0x011d) then player:addKeyItem(TUNING_FORK_OF_FIRE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_FIRE); elseif(csid == 0x0111) then item = 0; if(option == 1) then item = 17665; -- Ifrits Blade elseif(option == 2) then item = 13241; -- Fire Belt elseif(option == 3) then item = 13560; -- Fire Ring elseif(option == 4) then item = 1203; -- Egil's Torch end if(player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if(option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif(option == 6) then player:addSpell(298); -- Ifrit Spell player:messageSpecial(IFRIT_UNLOCKED,0,0,0); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_FIRE); player:delKeyItem(WHISPER_OF_FLAMES); player:setVar("TrialByFire_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(KAZHAM,WIN_FAME*30); player:completeQuest(OUTLANDS,TRIAL_BY_FIRE); end end end;
gpl-3.0
ZenityRTS/Zenity
libs/chiliui/luaui/chili/chili/controls/object.lua
3
24043
--//============================================================================= --- Object module --- Object fields. -- @table Object -- @bool[opt=true] visible control is displayed -- @tparam {Object1,Object2,...} children table of visible children objects (default {}) -- @tparam {Object1,Object2,...} children_hidden table of invisible children objects (default {}) -- @tparam {"obj1Name"=Object1,"obj2Name"=Object2,...} childrenByName table mapping name->child -- @tparam {func1,func2,...} OnDispose function listeners for object disposal, (default {}) -- @tparam {func1,func2,...} OnClick function listeners for mouse click, (default {}) -- @tparam {func1,func2,...} OnDblClick function listeners for mouse double click, (default {}) -- @tparam {func1,func2,...} OnMouseDown function listeners for mouse press, (default {}) -- @tparam {func1,func2,...} OnMouseUp function listeners for mouse release, (default {}) -- @tparam {func1,func2,...} OnMouseMove function listeners for mouse movement, (default {}) -- @tparam {func1,func2,...} OnMouseWheel function listeners for mouse scrolling, (default {}) -- @tparam {func1,func2,...} OnMouseOver function listeners for mouse over...?, (default {}) -- @tparam {func1,func2,...} OnMouseOut function listeners for mouse leaving the object, (default {}) -- @tparam {func1,func2,...} OnKeyPress function listeners for key press, (default {}) -- @tparam {func1,func2,...} OnFocusUpdate function listeners for focus change, (default {}) -- @bool[opt=false] disableChildrenHitTest if set childrens are not clickable/draggable etc - their mouse events are not processed Object = { classname = 'object', --x = 0, --y = 0, --width = 10, --height = 10, defaultWidth = 10, --FIXME really needed? defaultHeight = 10, visible = true, --hidden = false, --// synonym for above preserveChildrenOrder = false, --// if false adding/removing children is much faster, but also the order (in the .children array) isn't reliable anymore children = {}, children_hidden = {}, childrenByName = CreateWeakTable(), OnDispose = {}, OnClick = {}, OnDblClick = {}, OnMouseDown = {}, OnMouseUp = {}, OnMouseMove = {}, OnMouseWheel = {}, OnMouseOver = {}, OnMouseOut = {}, OnKeyPress = {}, OnTextInput = {}, OnFocusUpdate = {}, OnHide = {}, OnShow = {}, disableChildrenHitTest = false, --// if set childrens are not clickable/draggable etc - their mouse events are not processed } do local __lowerkeys = {} Object.__lowerkeys = __lowerkeys for i,v in pairs(Object) do if (type(i)=="string") then __lowerkeys[i:lower()] = i end end end local this = Object local inherited = this.inherited --//============================================================================= --// used to generate unique objects names local cic = {} local function GetUniqueId(classname) local ci = cic[classname] or 0 cic[classname] = ci + 1 return ci end --//============================================================================= --- Object constructor -- @tparam Object obj the object table function Object:New(obj) obj = obj or {} --// check if the user made some lower-/uppercase failures for i,v in pairs(obj) do if (not self[i])and(isstring(i)) then local correctName = self.__lowerkeys[i:lower()] if (correctName)and(obj[correctName] == nil) then obj[correctName] = v end end end --// give name if (not obj.name) then obj.name = self.classname .. GetUniqueId(self.classname) end --// make an instance for i,v in pairs(self) do --// `self` means the class here and not the instance! if (i ~= "inherited") then local t = type(v) local ot = type(obj[i]) if (t=="table")or(t=="metatable") then if (ot == "nil") then obj[i] = {}; ot = "table"; end if (ot ~= "table")and(ot ~= "metatable") then Spring.Log("Chili", "error", obj.name .. ": Wrong param type given to " .. i .. ": got " .. ot .. " expected table.") obj[i] = {} end table.merge(obj[i],v) if (t=="metatable") then setmetatable(obj[i], getmetatable(v)) end elseif (ot == "nil") then obj[i] = v end end end setmetatable(obj,{__index = self}) --// auto dispose remaining Dlists etc. when garbage collector frees this object local hobj = MakeHardLink(obj) --// handle children & parent local parent = obj.parent if (parent) then obj.parent = nil --// note: we are using the hardlink here, --// else the link could get gc'ed and dispose our object parent:AddChild(hobj) end local cn = obj.children obj.children = {} for i=1,#cn do obj:AddChild(cn[i],true) end --// sets obj._widget DebugHandler:RegisterObject(obj) return hobj end --- Disposes of the object. -- Calling this releases unmanaged resources like display lists and disposes of the object. -- Children are disposed too. -- TODO: use scream, in case the user forgets. -- nil -> nil function Object:Dispose(_internal) if (not self.disposed) then --// check if the control is still referenced (if so it would indicate a bug in chili's gc) if _internal then if self._hlinks and next(self._hlinks) then local hlinks_cnt = table.size(self._hlinks) local i,v = next(self._hlinks) if hlinks_cnt > 1 or (v ~= self) then --// check if user called Dispose() directly Spring.Log("Chili", "error", ("Tried to dispose \"%s\"! It's still referenced %i times!"):format(self.name, hlinks_cnt)) end end end self:CallListeners(self.OnDispose) self.disposed = true TaskHandler.RemoveObject(self) --DebugHandler:UnregisterObject(self) --// not needed if (UnlinkSafe(self.parent)) then self.parent:RemoveChild(self) end self:SetParent(nil) self:ClearChildren() end end function Object:AutoDispose() self:Dispose(true) end function Object:Clone() local newinst = {} -- FIXME return newinst end function Object:Inherit(class) class.inherited = self for i,v in pairs(self) do if (class[i] == nil)and(i ~= "inherited")and(i ~= "__lowerkeys") then t = type(v) if (t == "table") --[[or(t=="metatable")--]] then class[i] = table.shallowcopy(v) else class[i] = v end end end local __lowerkeys = {} class.__lowerkeys = __lowerkeys for i,v in pairs(class) do if (type(i)=="string") then __lowerkeys[i:lower()] = i end end --setmetatable(class,{__index=self}) --// backward compability with old DrawControl gl state (change was done with v2.1) local w = DebugHandler.GetWidgetOrigin() if (w ~= widget)and(w ~= Chili) then class._hasCustomDrawControl = true end return class end --//============================================================================= --- Sets the parent object -- @tparam Object obj parent object function Object:SetParent(obj) obj = UnlinkSafe(obj) local typ = type(obj) if (typ ~= "table") then self.parent = nil return end self.parent = MakeWeakLink(obj, self.parent) self:Invalidate() end --- Adds the child object -- @tparam Object obj child object to be added function Object:AddChild(obj, dontUpdate) local objDirect = UnlinkSafe(obj) if (self.children[objDirect]) then Spring.Log("Chili", "error", ("Tried to add multiple times \"%s\" to \"%s\"!"):format(obj.name, self.name)) return end local hobj = MakeHardLink(objDirect) if (obj.name) then if (self.childrenByName[obj.name]) then error(("Chili: There is already a control with the name `%s` in `%s`!"):format(obj.name, self.name)) return end self.childrenByName[obj.name] = hobj end if UnlinkSafe(obj.parent) then obj.parent:RemoveChild(obj) end obj:SetParent(self) local children = self.children local i = #children+1 children[i] = objDirect children[hobj] = i children[objDirect] = i self:Invalidate() end --- Removes the child object -- @tparam Object child child object to be removed function Object:RemoveChild(child) if not isindexable(child) then return child end if CompareLinks(child.parent,self) then child:SetParent(nil) end local childDirect = UnlinkSafe(child) if (self.children_hidden[childDirect]) then self.children_hidden[childDirect] = nil return true end if (not self.children[childDirect]) then --Spring.Echo(("Chili: tried remove none child \"%s\" from \"%s\"!"):format(child.name, self.name)) --Spring.Echo(DebugHandler.Stacktrace()) return false end if (child.name) then self.childrenByName[child.name] = nil end for i,v in pairs(self.children) do if CompareLinks(childDirect,i) then self.children[i] = nil end end local children = self.children local cn = #children for i=1,cn do if CompareLinks(childDirect,children[i]) then if (self.preserveChildrenOrder) then --// slow table.remove(children, i) else --// fast children[i] = children[cn] children[cn] = nil end children[child] = nil --FIXME (unused/unuseful?) children[childDirect] = nil self:Invalidate() return true end end return false end --- Removes all children function Object:ClearChildren() --// make it faster local old = self.preserveChildrenOrder self.preserveChildrenOrder = false --// remove all children for i=1,#self.children_hidden do self:ShowChild(self.children_hidden[i]) end for i=#self.children,1,-1 do self:RemoveChild(self.children[i]) end --// restore old state self.preserveChildrenOrder = old end --- Specifies whether the object has any visible children -- @treturn bool function Object:IsEmpty() return (not self.children[1]) end --//============================================================================= --- Hides a specific child -- @tparam Object obj child to be hidden function Object:HideChild(obj) --FIXME cause of performance reasons it would be usefull to use the direct object, but then we need to cache the link somewhere to avoid the auto calling of dispose local objDirect = UnlinkSafe(obj) if (not self.children[objDirect]) then --if (self.debug) then Spring.Log("Chili", "error", "Tried to hide a non-child (".. (obj.name or "") ..")") --end return end if (self.children_hidden[objDirect]) then --if (self.debug) then Spring.Log("Chili", "error", "Tried to hide the same child multiple times (".. (obj.name or "") ..")") --end return end local hobj = MakeHardLink(objDirect) local pos = {hobj, 0, nil, nil} local children = self.children local cn = #children for i=1,cn+1 do if CompareLinks(objDirect,children[i]) then pos = {hobj, i, MakeWeakLink(children[i-1]), MakeWeakLink(children[i+1])} break end end self:RemoveChild(obj) self.children_hidden[objDirect] = pos obj.parent = self end --- Makes a specific child visible -- @tparam Object obj child to be made visible function Object:ShowChild(obj) --FIXME cause of performance reasons it would be usefull to use the direct object, but then we need to cache the link somewhere to avoid the auto calling of dispose local objDirect = UnlinkSafe(obj) if (not self.children_hidden[objDirect]) then --if (self.debug) then Spring.Log("Chili", "error", "Tried to show a non-child (".. (obj.name or "") ..")") --end return end if (self.children[objDirect]) then --if (self.debug) then Spring.Log("Chili", "error", "Tried to show the same child multiple times (".. (obj.name or "") ..")") --end return end local params = self.children_hidden[objDirect] self.children_hidden[objDirect] = nil local children = self.children local cn = #children if (params[3]) then for i=1,cn do if CompareLinks(params[3],children[i]) then self:AddChild(obj) self:SetChildLayer(obj,i+1) return true end end end self:AddChild(obj) self:SetChildLayer(obj,params[2]) return true end --- Sets the visibility of the object -- @bool visible visibility status function Object:SetVisibility(visible) if (visible) then self.parent:ShowChild(self) else self.parent:HideChild(self) end self.visible = visible self.hidden = not visible end --- Hides the objects function Object:Hide() local wasHidden = self.hidden self:SetVisibility(false) if not wasHidden then self:CallListeners(self.OnHide, self) end end --- Makes the object visible function Object:Show() local wasVisible = self.hidden self:SetVisibility(true) if not wasVisible then self:CallListeners(self.OnShow, self) end end --- Toggles object visibility function Object:ToggleVisibility() self:SetVisibility(not self.visible) end --//============================================================================= function Object:SetChildLayer(child,layer) child = UnlinkSafe(child) local children = self.children layer = math.min(layer, #children) --// it isn't at the same pos anymore, search it! for i=1,#children do if CompareLinks(children[i], child) then table.remove(children,i) break end end table.insert(children,layer,child) self:Invalidate() end function Object:SetLayer(layer) if (self.parent) then (self.parent):SetChildLayer(self, layer) end end function Object:BringToFront() self:SetLayer(1) end --//============================================================================= function Object:InheritsFrom(classname) if (self.classname == classname) then return true elseif not self.inherited then return false else return self.inherited.InheritsFrom(self.inherited,classname) end end --//============================================================================= --- Returns a child by name -- @string name child name -- @treturn Object child function Object:GetChildByName(name) local cn = self.children for i=1,#cn do if (name == cn[i].name) then return cn[i] end end for c in pairs(self.children_hidden) do if (name == c.name) then return MakeWeakLink(c) end end end --// Backward-Compability Object.GetChild = Object.GetChildByName --- Resursive search to find an object by its name -- @string name name of the object -- @treturn Object function Object:GetObjectByName(name) local r = self.childrenByName[name] if r then return r end for i=1,#self.children do local c = self.children[i] if (name == c.name) then return c else local result = c:GetObjectByName(name) if (result) then return result end end end for c in pairs(self.children_hidden) do if (name == c.name) then return MakeWeakLink(c) else local result = c:GetObjectByName(name) if (result) then return result end end end end --// Climbs the family tree and returns the first parent that satisfies a --// predicate function or inherites the given class. --// Returns nil if not found. function Object:FindParent(predicate) if not self.parent then return -- not parent with such class name found, return nil elseif (type(predicate) == "string" and (self.parent):InheritsFrom(predicate)) or (type(predicate) == "function" and predicate(self.parent)) then return self.parent else return self.parent:FindParent(predicate) end end function Object:IsDescendantOf(object, _already_unlinked) if (not _already_unlinked) then object = UnlinkSafe(object) end if (UnlinkSafe(self) == object) then return true end if (self.parent) then return (self.parent):IsDescendantOf(object, true) end return false end function Object:IsAncestorOf(object, _level, _already_unlinked) _level = _level or 1 if (not _already_unlinked) then object = UnlinkSafe(object) end local children = self.children for i=1,#children do if (children[i] == object) then return true, _level end end _level = _level + 1 for i=1,#children do local c = children[i] local res,lvl = c:IsAncestorOf(object, _level, true) if (res) then return true, lvl end end return false end --//============================================================================= function Object:CallListeners(listeners, ...) for i=1,#listeners do local eventListener = listeners[i] if eventListener(self, ...) then return true end end end function Object:CallListenersInverse(listeners, ...) for i=#listeners,1,-1 do local eventListener = listeners[i] if eventListener(self, ...) then return true end end end function Object:CallChildren(eventname, ...) local children = self.children for i=1,#children do local child = children[i] if (child) then local obj = child[eventname](child, ...) if (obj) then return obj end end end end function Object:CallChildrenInverse(eventname, ...) local children = self.children for i=#children,1,-1 do local child = children[i] if (child) then local obj = child[eventname](child, ...) if (obj) then return obj end end end end function Object:CallChildrenInverseCheckFunc(checkfunc,eventname, ...) local children = self.children for i=#children,1,-1 do local child = children[i] if (child)and(checkfunc(self,child)) then local obj = child[eventname](child, ...) if (obj) then return obj end end end end local function InLocalRect(cx,cy,w,h) return (cx>=0)and(cy>=0)and(cx<=w)and(cy<=h) end function Object:CallChildrenHT(eventname, x, y, ...) if self.disableChildrenHitTest then return nil end local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(x,y) if InLocalRect(cx,cy,c.width,c.height) and c:HitTest(cx,cy) then local obj = c[eventname](c, cx, cy, ...) if (obj) then return obj end end end end end function Object:CallChildrenHTWeak(eventname, x, y, ...) if self.disableChildrenHitTest then return nil end local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(x,y) if InLocalRect(cx,cy,c.width,c.height) then local obj = c[eventname](c, cx, cy, ...) if (obj) then return obj end end end end end --//============================================================================= function Object:RequestUpdate() --// we have something todo in Update --// so we register this object in the taskhandler TaskHandler.RequestUpdate(self) end function Object:Invalidate() --FIXME should be Control only end function Object:Draw() self:CallChildrenInverse('Draw') end function Object:TweakDraw() self:CallChildrenInverse('TweakDraw') end --//============================================================================= function Object:LocalToParent(x,y) return x + self.x, y + self.y end function Object:ParentToLocal(x,y) return x - self.x, y - self.y end Object.ParentToClient = Object.ParentToLocal Object.ClientToParent = Object.LocalToParent function Object:LocalToClient(x,y) return x,y end function Object:LocalToScreen(x,y) if (not self.parent) then return x,y end --Spring.Echo((not self.parent) and debug.traceback()) return (self.parent):ClientToScreen(self:LocalToParent(x,y)) end function Object:ClientToScreen(x,y) if (not self.parent) then return self:ClientToParent(x,y) end return (self.parent):ClientToScreen(self:ClientToParent(x,y)) end function Object:ScreenToLocal(x,y) if (not self.parent) then return self:ParentToLocal(x,y) end return self:ParentToLocal((self.parent):ScreenToClient(x,y)) end function Object:ScreenToClient(x,y) if (not self.parent) then return self:ParentToClient(x,y) end return self:ParentToClient((self.parent):ScreenToClient(x,y)) end function Object:LocalToObject(x, y, obj) if CompareLinks(self,obj) then return x, y end if (not self.parent) then return -1,-1 end x, y = self:LocalToParent(x, y) return self.parent:LocalToObject(x, y, obj) end --//============================================================================= function Object:_GetMaxChildConstraints(child) return 0, 0, self.width, self.height end --//============================================================================= function Object:HitTest(x,y) if not self.disableChildrenHitTest then local children = self.children for i=1,#children do local c = children[i] if (c) then local cx,cy = c:ParentToLocal(x,y) if InLocalRect(cx,cy,c.width,c.height) then local obj = c:HitTest(cx,cy) if (obj) then return obj end end end end end return false end function Object:IsAbove(x, y, ...) return self:HitTest(x,y) end function Object:MouseMove(...) if (self:CallListeners(self.OnMouseMove, ...)) then return self end return self:CallChildrenHT('MouseMove', ...) end function Object:MouseDown(...) if (self:CallListeners(self.OnMouseDown, ...)) then return self end return self:CallChildrenHT('MouseDown', ...) end function Object:MouseUp(...) if (self:CallListeners(self.OnMouseUp, ...)) then return self end return self:CallChildrenHT('MouseUp', ...) end function Object:MouseClick(...) if (self:CallListeners(self.OnClick, ...)) then return self end return self:CallChildrenHT('MouseClick', ...) end function Object:MouseDblClick(...) if (self:CallListeners(self.OnDblClick, ...)) then return self end return self:CallChildrenHT('MouseDblClick', ...) end function Object:MouseWheel(...) if (self:CallListeners(self.OnMouseWheel, ...)) then return self end return self:CallChildrenHTWeak('MouseWheel', ...) end function Object:MouseOver(...) if (self:CallListeners(self.OnMouseOver, ...)) then return self end end function Object:MouseOut(...) if (self:CallListeners(self.OnMouseOut, ...)) then return self end end function Object:KeyPress(...) if (self:CallListeners(self.OnKeyPress, ...)) then return self end return false end function Object:TextInput(...) if (self:CallListeners(self.OnTextInput, ...)) then return self end return false end function Object:FocusUpdate(...) if (self:CallListeners(self.OnFocusUpdate, ...)) then return self end return false end --//=============================================================================
gpl-2.0
EmmanuelOga/easing
examples/love/main.lua
1
1755
W = 800 H = 600 -- graphicate easing functions using love2d. local easing = require("easing") local renderFun = require("renderFun") local movingDot = require("movingDot") FONT_SIZE = 14 SEGMENTS = 500 POINT_SIZE = 2 LINE_SIZE = 2 GRAPH_SIZE = 0.6 -- percent of screen. -------------------------------------------------- CHART_W = W * GRAPH_SIZE CHART_H = H * GRAPH_SIZE * (W / H) CHART_X = ( W - CHART_W ) / 2 CHART_Y = ( H - CHART_H ) / 2 function love.load() love.graphics.setFont(love.graphics.newFont(FONT_SIZE)) love.graphics.setLineWidth(LINE_SIZE) love.graphics.setLineStyle("smooth") love.graphics.setPointSize(POINT_SIZE) -- put all easing function names inside an array for easy navigation by array index. functions = {} for funName, _ in pairs(easing) do functions[#functions + 1] = funName end table.sort(functions) selFun = 1 dot = movingDot(CHART_H * 2 / 3, functions[selFun]) end function love.draw() love.graphics.setColor(255, 0, 0, 255) love.graphics.print("Press up and down to change the easing function.", 50, CHART_Y - 50) love.graphics.print(selFun .. "/" .. #functions .. " - " .. functions[selFun], CHART_X + CHART_W - 50, CHART_Y - 50) dot.render(W - (W - CHART_X - CHART_W) / 2, CHART_Y + CHART_H * 2 / 3 / 4, functions[selFun]) renderFun(CHART_X, CHART_Y, CHART_W, CHART_H, functions[selFun]) end function love.update(dt) dot.update(dt) end function love.keypressed(key, unicode) if key == 'down' then if selFun > 1 then selFun = selFun - 1 dot = movingDot(CHART_H * 2 / 3, functions[selFun]) end elseif key == 'up' then if selFun < #functions then selFun = selFun + 1 dot = movingDot(CHART_H * 2 / 3, functions[selFun]) end end end
mit
kitala1/darkstar
scripts/globals/mobskills/PL_Chaos_Blade.lua
58
1118
--------------------------------------------- -- Chaos Blade -- -- Description: Deals Dark damage to enemies within a fan-shaped area. Additional effect: Curse -- Type: Magical -- Utsusemi/Blink absorb: Ignores Shadows -- Range: Melee -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 421) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local dmgmod = 2; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg() * 3,ELE_DARK,dmgmod,TP_MAB_BONUS,1); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); -- curse LAST so you don't die local typeEffect = EFFECT_CURSE_I; MobStatusEffectMove(mob, target, typeEffect, 25, 0, 60); return dmg; end;
gpl-3.0
kiarash14/be
plugins/yoda.lua
642
1199
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(text) local api = "https://yoda.p.mashape.com/yoda?" text = string.gsub(text, " ", "+") local parameters = "sentence="..(text or "") local url = api..parameters local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) return body end local function run(msg, matches) return request(matches[1]) end return { description = "Listen to Yoda and learn from his words!", usage = "!yoda You will learn how to speak like me someday.", patterns = { "^![y|Y]oda (.*)$" }, run = run }
gpl-2.0
kitala1/darkstar
scripts/globals/items/sakura_biscuit.lua
36
1161
----------------------------------------- -- ID: 6010 -- Item: Sakura Biscuit -- Food Effect: 30Min, All Races ----------------------------------------- -- Intelligence 3 -- Charisma 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,6010); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 3); target:addMod(MOD_CHR, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 3); target:delMod(MOD_CHR, 2); end;
gpl-3.0