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
kjmac123/metabuilder
metabuilder/metabase/ndk_android.lua
1
1400
metabase "ndk_android" import "metabase_common.lua" import "platform_android.lua" supportedplatforms { "NDK", } writer "writer_ndk.lua" option("ndkoptions", "APP_ABI", "all") option("ndkoptions", "APP_PLATFORM", "android-14") option("ndkoptions", "NDK_TOOLCHAIN_VERSION", "clang") option("ndkoptions", "APP_STL", "stlport_static") local appCFLAGSCommon = "-Wno-multichar -fno-rtti -fno-exceptions -marm -fpic -Wno-unused-variable -Wno-unused-value " config "Debug" option( "ndkoptions", "APP_OPTIM", "debug") option( "ndkoptions", "APP_CFLAGS", appCFLAGSCommon .. " -O0") config_end() config "Release" option( "ndkoptions", "APP_OPTIM", "release") option( "ndkoptions", "APP_CFLAGS", appCFLAGSCommon .. " -O3") config_end() config "Profile" option( "ndkoptions", "APP_OPTIM", "release") option( "ndkoptions", "APP_CFLAGS", appCFLAGSCommon .. " -O3") config_end() config "Master" option( "ndkoptions", "APP_ABI", "all") -- Build for all supported CPU types option( "ndkoptions", "APP_OPTIM", "release") option( "ndkoptions", "APP_CFLAGS", appCFLAGSCommon .." -O3") config_end() metabase_end() ndk = {} function ndk.setminapi(minapi) end function ndk.settargetapi(targetapi) --option("ndkoptions", "APP_PLATFORM", targetapi) end function ndk.setprojectdir(dir) option("_ndk", "ProjectDir", dir) end
mit
jshackley/darkstar
scripts/zones/Kazham/npcs/Khau_Mahiyoeloh.lua
15
1102
----------------------------------- -- Area: Kazham -- NPC: Khau Mahiyoeloh -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00A5); -- scent from Blue Rafflesias else player:startEvent(0x003C); 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
jshackley/darkstar
scripts/zones/Temenos/bcnms/Temenos_Western_Tower.lua
19
1039
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[Temenos_W_Tower]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1298),TEMENOS); HideTemenosDoor(GetInstanceRegion(1298)); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[Temenos_W_Tower]UniqueID")); player:setVar("LimbusID",1298); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
goksie/newfies-dialer
lua/libs/pythonic/optparse.lua
8
6134
--[[ LUA MODULE pythonic.optparse - Lua-based partial reimplementation of Python's optparse [2-3] command-line parsing module. SYNOPSIS local OptionParser = require "pythonic.optparse" . OptionParser local opt = OptionParser{usage="%prog [options] [gzip-file...]", version="foo 1.23", add_help_option=false} opt.add_option{"-h", "--help", action="store_true", dest="help", help="give this help"} opt.add_option{ "-f", "--force", dest="force", action="store_true", help="force overwrite of output file"} local options, args = opt.parse_args() if options.help then opt.print_help(); os.exit(1) end if options.force then print 'f' end for _, name in ipairs(args) do print(name) end DESCRIPTION This library provides a command-line parsing[1] similar to Python optparse [2-3]. Note: Python also supports getopt [4]. STATUS This module is fairly basic but could be expanded. API See source code and also compare to Python's docs [2,3] for details because the following documentation is incomplete. opt = OptionParser {usage=usage, version=version, add_help_option=add_help_option} Create command line parser. opt.add_options{shortflag, longflag, action=action, metavar=metavar, dest=dest, help=help} Add command line option specification. This may be called multiple times. opt.parse_args() --> options, args Perform argument parsing. DEPENDENCIES None (other than Lua 5.1 or 5.2) REFERENCES [1] http://lua-users.org/wiki/CommandLineParsing [2] http://docs.python.org/lib/optparse-defining-options.html [3] http://blog.doughellmann.com/2007/08/pymotw-optparse.html [4] http://docs.python.org/lib/module-getopt.html LICENSE (c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (end license) --]] local M = {_TYPE='module', _NAME='pythonic.optparse', _VERSION='0.3.20111128'} local ipairs = ipairs local unpack = unpack local io = io local table = table local os = os local arg = arg local function OptionParser(t) local usage = t.usage --local version = t.version local o = {} local option_descriptions = {} local option_of = {} function o.fail(s) -- extension io.stderr:write(s .. '\n') os.exit(1) end function o.add_option(optdesc) option_descriptions[#option_descriptions+1] = optdesc for _,v in ipairs(optdesc) do option_of[v] = optdesc end end function o.parse_args() -- expand options (e.g. "--input=file" -> "--input", "file") if not arg then arg = {} end local arg = {unpack(arg)} for i=#arg,1,-1 do local v = arg[i] local flag, val = v:match('^(%-%-%w+)=(.*)') if flag then arg[i] = flag table.insert(arg, i+1, val) end end local options = {} local args = {} local i = 1 while i <= #arg do local v = arg[i] local optdesc = option_of[v] if optdesc then local action = optdesc.action local val if action == 'store' or action == nil then i = i + 1 val = arg[i] if not val then o.fail('option requires an argument ' .. v) end elseif action == 'store_true' then val = true elseif action == 'store_false' then val = false end options[optdesc.dest] = val else if v:match('^%-') then o.fail('invalid option ' .. v) end args[#args+1] = v end i = i + 1 end if options.help then o.print_help() os.exit() end if options.version then io.stdout:write(t.version .. "\n") os.exit() end return options, args end local function flags_str(optdesc) local sflags = {} local action = optdesc.action for _,flag in ipairs(optdesc) do local sflagend if action == nil or action == 'store' then local metavar = optdesc.metavar or optdesc.dest:upper() sflagend = #flag == 2 and ' ' .. metavar or '=' .. metavar else sflagend = '' end sflags[#sflags+1] = flag .. sflagend end return table.concat(sflags, ', ') end function o.print_help() io.stdout:write("Usage: " .. usage:gsub('%%prog', arg[0]) .. "\n") io.stdout:write("\n") io.stdout:write("Options:\n") local maxwidth = 0 for _,optdesc in ipairs(option_descriptions) do maxwidth = math.max(maxwidth, #flags_str(optdesc)) end for _,optdesc in ipairs(option_descriptions) do io.stdout:write(" " .. ('%-'..maxwidth..'s '):format(flags_str(optdesc)) .. optdesc.help .. "\n") end end if t.add_help_option == nil or t.add_help_option == true then o.add_option{"--help", action="store_true", dest="help", help="show this help message and exit"} end if t.version then o.add_option{"--version", action="store_true", dest="version", help="output version info."} end return o end M.OptionParser = OptionParser return M
mpl-2.0
DipColor/mehrabon3
plugins/help.lua
290
1653
do -- Returns true if is not empty local function has_usage_data(dict) if (dict.usage == nil or dict.usage == '') then return false end return true end -- Get commands for that plugin local function plugin_help(name) local plugin = plugins[name] if not plugin then return nil end local text = "" if (type(plugin.usage) == "table") then for ku,usage in pairs(plugin.usage) do text = text..usage..'\n' end text = text..'\n' elseif has_usage_data(plugin) then -- Is not empty text = text..plugin.usage..'\n\n' end return text end -- !help command local function telegram_help() local text = "Plugin list: \n\n" -- Plugins names for name in pairs(plugins) do text = text..name..'\n' end text = text..'\n'..'Write "!help [plugin name]" for more info.' text = text..'\n'..'Or "!help all" to show all info.' return text end -- !help all command local function help_all() local ret = "" for name in pairs(plugins) do ret = ret .. plugin_help(name) end return ret end local function run(msg, matches) if matches[1] == "!help" then return telegram_help() elseif matches[1] == "!help all" then return help_all() else local text = plugin_help(matches[1]) if not text then text = telegram_help() end return text end end return { description = "Help plugin. Get info from other plugins. ", usage = { "!help: Show list of plugins.", "!help all: Show all commands for every plugin.", "!help [plugin name]: Commands for that plugin." }, patterns = { "^!help$", "^!help all", "^!help (.+)" }, run = run } end
gpl-2.0
LiberatorUSA/GUCEF
dependencies/tolua/src/bin/lua/feature.lua
14
2134
-- tolua: abstract feature class -- Written by Waldemar Celes -- TeCGraf/PUC-Rio -- Jul 1998 -- $Id: feature.lua,v 1.3 2009/11/24 16:45:14 fabraham Exp $ -- This code is free software; you can redistribute it and/or modify it. -- The software provided hereunder is on an "as is" basis, and -- the author has no obligation to provide maintenance, support, updates, -- enhancements, or modifications. -- Feature class -- Represents the base class of all mapped feature. classFeature = { } classFeature.__index = classFeature -- write support code function classFeature:supcode () end -- output tag function classFeature:decltype () end -- register feature function classFeature:register () end -- translate verbatim function classFeature:preamble () end -- check if it is a variable function classFeature:isvariable () return false end -- checi if it requires collection function classFeature:requirecollection (t) return false end -- build names function classFeature:buildnames () if self.name and self.name~='' then local n = split(self.name,'@') self.name = n[1] if not n[2] then n[2] = applyrenaming(n[1]) end self.lname = n[2] or gsub(n[1],"%[.-%]","") end self.name = getonlynamespace() .. self.name end -- check if feature is inside a container definition -- it returns the container class name or nil. function classFeature:incontainer (which) if self.parent then local parent = self.parent while parent do if parent.classtype == which then return parent.name end parent = parent.parent end end return nil end function classFeature:inclass () return self:incontainer('class') end function classFeature:inmodule () return self:incontainer('module') end function classFeature:innamespace () return self:incontainer('namespace') end -- return C binding function name based on name -- the client specifies a prefix function classFeature:cfuncname (n) if self.parent then n = self.parent:cfuncname(n) end if self.lname and strsub(self.lname,1,1)~="." -- operator are named as ".add" then return n..'_'..self.lname else return n..'_'..self.name end end
apache-2.0
LiberatorUSA/GUCEF
dependencies/tolua/src/bin/lua/clean.lua
7
1341
-- mark up comments and strings STR1 = "\001" STR2 = "\002" STR3 = "\003" STR4 = "\004" REM = "\005" ANY = "([\001-\005])" ESC1 = "\006" ESC2 = "\007" MASK = { -- the substitution order is important {ESC1, "\\'", "\\'"}, {ESC2, '\\"', '\\"'}, {STR1, "'", "'"}, {STR2, '"', '"'}, {STR3, "%[%[", "[["}, {STR4, "%]%]", "]]"}, {REM , "%-%-", "--"}, } function mask (s) for i = 1,getn(MASK) do s = gsub(s,MASK[i][2],MASK[i][1]) end return s end function unmask (s) for i = 1,getn(MASK) do s = gsub(s,MASK[i][1],MASK[i][3]) end return s end function clean (s) -- check for compilation error local code = "return function () " .. s .. " end" if not dostring(code) then return nil end local S = "" -- saved string s = mask(s) -- remove blanks and comments while 1 do local b,e,d = strfind(s,ANY) if b then S = S..strsub(s,1,b-1) s = strsub(s,b+1) if d==STR1 or d==STR2 then e = strfind(s,d) S = S ..d..strsub(s,1,e) s = strsub(s,e+1) elseif d==STR3 then e = strfind(s,STR4) S = S..d..strsub(s,1,e) s = strsub(s,e+1) elseif d==REM then s = gsub(s,"[^\n]*(\n?)","%1",1) end else S = S..s break end end -- eliminate unecessary spaces S = gsub(S,"[ \t]+"," ") S = gsub(S,"[ \t]*\n[ \t]*","\n") S = gsub(S,"\n+","\n") S = unmask(S) return S end
apache-2.0
jshackley/darkstar
scripts/zones/Yughott_Grotto/TextIDs.lua
15
1096
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6543; -- Obtained: <item>. GIL_OBTAINED = 6544; -- Obtained <number> gil. KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here. HOMEPOINT_SET = 7432; -- Home point set! -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7324; -- You unlock the chest! CHEST_FAIL = 7325; -- Fails to open the chest. CHEST_TRAP = 7326; -- The chest was trapped! CHEST_WEAK = 7327; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7328; -- The chest was a mimic! CHEST_MOOGLE = 7329; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7330; -- The chest was but an illusion... CHEST_LOCKED = 7331; -- The chest appears to be locked. -- Mining MINING_IS_POSSIBLE_HERE = 7332; -- Mining is possible here if you have -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
elbamos/nn
ClassSimplexCriterion.lua
10
3822
local ClassSimplexCriterion, parent = torch.class('nn.ClassSimplexCriterion', 'nn.MSECriterion') --[[ This file implements a criterion for multi-class classification. It learns an embedding per class, where each class' embedding is a point on an (N-1)-dimensional simplex, where N is the number of classes. For example usage of this class, look at doc/criterion.md Reference: http://arxiv.org/abs/1506.08230 ]]-- --[[ function regsplex(n): regsplex returns the coordinates of the vertices of a regular simplex centered at the origin. The Euclidean norms of the vectors specifying the vertices are all equal to 1. The input n is the dimension of the vectors; the simplex has n+1 vertices. input: n -- dimension of the vectors specifying the vertices of the simplex output: a -- tensor dimensioned (n+1,n) whose rows are vectors specifying the vertices reference: http://en.wikipedia.org/wiki/Simplex#Cartesian_coordinates_for_regular_n-dimensional_simplex_in_Rn --]] local function regsplex(n) local a = torch.zeros(n+1,n) for k = 1,n do -- determine the last nonzero entry in the vector for the k-th vertex if k==1 then a[k][k] = 1 end if k>1 then a[k][k] = math.sqrt( 1 - a[{ {k},{1,k-1} }]:norm()^2 ) end -- fill the k-th coordinates for the vectors of the remaining vertices local c = (a[k][k]^2 - 1 - 1/n) / a[k][k] a[{ {k+1,n+1},{k} }]:fill(c) end return a end function ClassSimplexCriterion:__init(nClasses) parent.__init(self) assert(nClasses and nClasses > 1 and nClasses == (nClasses -(nClasses % 1)), "Required positive integer argument nClasses > 1") self.nClasses = nClasses -- embedding the simplex in a space of dimension strictly greater than -- the minimum possible (nClasses-1) is critical for effective training. local simp = regsplex(nClasses - 1) self.simplex = torch.cat(simp, torch.zeros(simp:size(1), nClasses -simp:size(2)), 2) self._target = torch.Tensor(nClasses) end -- handle target being both 1D tensor, and -- target being 2D tensor (2D tensor means dont do anything) local function transformTarget(self, target) if torch.type(target) == 'number' then self._target:resize(self.nClasses) self._target:copy(self.simplex[target]) elseif torch.isTensor(target) then assert(target:dim() == 1, '1D tensors only!') local nSamples = target:size(1) self._target:resize(nSamples, self.nClasses) for i=1,nSamples do self._target[i]:copy(self.simplex[target[i]]) end end end function ClassSimplexCriterion:updateOutput(input, target) transformTarget(self, target) assert(input:nElement() == self._target:nElement()) self.output_tensor = self.output_tensor or input.new(1) input.THNN.MSECriterion_updateOutput( input:cdata(), self._target:cdata(), self.output_tensor:cdata(), self.sizeAverage ) self.output = self.output_tensor[1] return self.output end function ClassSimplexCriterion:updateGradInput(input, target) assert(input:nElement() == self._target:nElement()) input.THNN.MSECriterion_updateGradInput( input:cdata(), self._target:cdata(), self.gradInput:cdata(), self.sizeAverage ) return self.gradInput end function ClassSimplexCriterion:getPredictions(input) if input:dim() == 1 then input = input:view(1, -1) end return torch.mm(input, self.simplex:t()) end function ClassSimplexCriterion:getTopPrediction(input) local prod = self:getPredictions(input) local _, maxs = prod:max(prod:nDimension()) return maxs:view(-1) end
bsd-3-clause
jshackley/darkstar
scripts/globals/spells/light_carol.lua
18
1505
----------------------------------------- -- Spell: Light Carol -- Increases light resistance for party members within the area of effect. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED); local power = 20; if (sLvl+iLvl > 200) then power = power + math.floor((sLvl+iLvl-200) / 10); end if (power >= 40) then power = 40; end local iBoost = caster:getMod(MOD_CAROL_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost*5; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_CAROL,power,0,duration,caster:getID(), ELE_LIGHT, 1)) then spell:setMsg(75); end return EFFECT_CAROL; end;
gpl-3.0
jshackley/darkstar
scripts/zones/Dynamis-Valkurm/mobs/Avatar_Idol.lua
1
1131
----------------------------------- -- Area: Dynamis Valkurm -- MOB: Manifest_Idol ----------------------------------- package.loaded["scripts/zones/Dynamis-Valkurm/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Valkurm/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobID = mob:getID(); if (mobID == 16937264 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(10); --print("addtime 10min"); mob:addInBattlefieldList(); elseif (mobID == 16937262 and mob:isInBattlefieldList() == false) then ally:addTimeToDynamis(20); --print("addtime 20min"); mob:addInBattlefieldList(); end end;
gpl-3.0
Victek/wrt1900ac-aa
veriksystems/luci-0.11/applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
11
1439
--[[ Luci configuration model for statistics - collectd ping 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: ping.lua 6509 2010-11-18 18:08:23Z soma $ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
gpl-2.0
Ombridride/minetest-minetestforfun-server
mods/returnmirror/init.lua
9
4260
returnmirror = {} returnmirror.cost_teleport = 200 returnmirror.cost_set = 20 if tonumber(minetest.setting_get("returnmirror_cost_teleport")) ~= nil then returnmirror.cost_teleport = tonumber(minetest.setting_get("returnmirror_cost_teleport")) end if tonumber(minetest.setting_get("returnmirror_cost_set")) ~= nil then returnmirror.cost_set = tonumber(minetest.setting_get("returnmirror_cost_set")) end if minetest.get_modpath("mana") ~= nil then returnmirror.mana = true else returnmirror.mana = false end returnmirror.mana_check = function(player, cost) local allowed if returnmirror.mana then if mana.subtract(player:get_player_name(), cost) then allowed = true else allowed = false end else allowed = true end return allowed end minetest.register_tool("returnmirror:mirror_inactive", { description = "Mirror of Returning/Portal mirror", inventory_image = "returnmirror_mirror_inactive.png", wield_image = "returnmirror_mirror_inactive.png", tool_capabilities = {}, on_place = function(itemstack, placer, pointed_thing) if returnmirror.mana_check(placer, returnmirror.cost_set) then local pos = placer:getpos() local newitem = ItemStack("returnmirror:mirror_active") newitem:set_metadata(minetest.pos_to_string(pos)) minetest.sound_play({name="returnmirror_set", gain=0.5}, {pos=pos, max_hear_distance=12}) return newitem end end, }) minetest.register_craftitem("returnmirror:mirror_glass", { description = "Mirror glass", inventory_image = "returnmirror_mirror_glass.png", wield_image = "returnmirror_mirror_glass.png", }) minetest.register_tool("returnmirror:mirror_active", { description = "Mirror of Returning/Portal mirror", stack_max = 1, inventory_image = "returnmirror_mirror_active.png", wield_image = "returnmirror_mirror_active.png", tool_capabilities = {}, on_use = function(itemstack, user, pointed_thing) local dest_string = itemstack:get_metadata() local dest = minetest.string_to_pos(dest_string) if dest ~= nil then if returnmirror.mana_check(user, returnmirror.cost_teleport) then local src = user:getpos() minetest.sound_play( {name="returnmirror_teleport", gain=1}, {pos=src, max_hear_distance=30}) minetest.add_particlespawner({ amount = 50, time = 0.1, minpos = {x=src.x-0.4, y=src.y+0.25, z=src.z-0.4}, maxpos = {x=src.x+0.4, y=src.y+0.75, z=src.z+0.4}, minvel = {x=-0.2, y=-0.2, z=-0.2}, maxvel = {x=0.2, y=0.2, z=0.2}, minexptime=3, maxexptime=4.5, minsize=1, maxsize=1.25, texture = "returnmirror_particle_departure.png", }) user:setpos(dest) minetest.sound_play( {name="returnmirror_teleport", gain=1}, {pos=dest, max_hear_distance=30}) minetest.add_particlespawner({ amount = 100, time = 0.1, minpos = {x=dest.x-0.4, y=dest.y+0.25, z=dest.z-0.4}, maxpos = {x=dest.x+0.4, y=dest.y+0.75, z=dest.z+0.4}, minvel = {x=-0.4, y=-0.3, z=-0.4}, maxvel = {x=0.4, y=0.3, z=0.4}, minexptime=6, maxexptime=12, minsize=1, maxsize=1.25, texture = "returnmirror_particle_arrival.png", }) end end end, on_place = function(itemstack, placer, pointed_thing) if returnmirror.mana_check(placer, returnmirror.cost_set) then local pos = placer:getpos() itemstack:set_metadata(minetest.pos_to_string(pos)) minetest.sound_play( {name="returnmirror_set", gain=1}, {pos=pos, max_hear_distance=12}) return itemstack end end, groups = { not_in_creative_inventory = 1 }, }) minetest.register_alias("returnmirror:mirror_inactive", "returnmirror:returnmirror") minetest.register_craft({ output = "returnmirror:mirror_glass", recipe = { {"default:diamondblock","default:mese","default:diamondblock"}, {"default:mese","doors:door_obsidian_glass","default:mese"}, {"default:diamondblock","default:mese","default:diamondblock"}, }, }) minetest.register_craft({ output = "returnmirror:mirror_inactive", recipe = { {"default:diamondblock", "default:nyancat", "default:diamondblock"}, {"default:nyancat", "returnmirror:mirror_glass", "default:nyancat"}, {"default:diamondblock", "default:nyancat", "default:diamondblock"}, }, }) minetest.register_alias("returnmirror:portal","returnmirror:mirror_inactive")
unlicense
Victek/wrt1900ac-aa
veriksystems/luci-0.11/contrib/luadoc/lua/luadoc/doclet/formatter.lua
171
2556
------------------------------------------------------------------------------- -- Doclet to format source code according to LuaDoc standard tags. This doclet -- (re)write .lua files adding missing standard tags. Texts are formatted to -- 80 columns and function parameters are added based on code analysis. -- -- @release $Id: formatter.lua,v 1.5 2007/04/18 14:28:39 tomas Exp $ ------------------------------------------------------------------------------- local util = require "luadoc.util" local assert, ipairs, pairs, type = assert, ipairs, pairs, type local string = require"string" local table = require"table" module "luadoc.doclet.formatter" options = { output_dir = "./", } ------------------------------------------------------------------------------- -- Assembly the output filename for an input file. -- TODO: change the name of this function function out_file (filename) local h = filename h = options.output_dir..h return h end ------------------------------------------------------------------------------- -- Generate a new lua file for each input lua file. If the user does not -- specify a different output directory input files will be rewritten. -- @param doc documentation table function start (doc) local todo = "<TODO>" -- Process files for i, file_doc in ipairs(doc.files) do -- assembly the filename local filename = out_file(file_doc.name) luadoc.logger:info(string.format("generating file `%s'", filename)) -- TODO: confirm file overwrite local f = posix.open(filename, "w") assert(f, string.format("could not open `%s' for writing", filename)) for _, block in ipairs(file_doc.doc) do -- write reorganized comments f:write(string.rep("-", 80).."\n") -- description f:write(util.comment(util.wrap(block.description, 77))) f:write("\n") if block.class == "function" then -- parameters table.foreachi(block.param, function (_, param_name) f:write(util.comment(util.wrap(string.format("@param %s %s", param_name, block.param[param_name] or todo), 77))) f:write("\n") end) -- return if type(block.ret) == "table" then table.foreachi(block.ret, function (_, ret) f:write(util.comment(util.wrap(string.format("@return %s", ret), 77)).."\n") end) else f:write(util.comment(util.wrap(string.format("@return %s", block.ret or todo), 77)).."\n") end end -- TODO: usage -- TODO: see -- write code for _, line in ipairs(block.code) do f:write(line.."\n") end end f:close() end end
gpl-2.0
jshackley/darkstar
scripts/zones/Ifrits_Cauldron/npcs/qm4.lua
2
1574
----------------------------------- -- Area: Ifrit's Cauldron -- NPC: ??? -- Involved in Mission: Bastok 6-2 -- @pos 171 0 -25 205 ----------------------------------- package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Ifrits_Cauldron/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getCurrentMission(BASTOK) == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 2) then if (GetMobAction(17616897) == 0 and GetMobAction(17616898) == 0 and trade:hasItemQty(646,1) and trade:getItemCount() == 1) then player:tradeComplete(); SpawnMob(17616897):updateClaim(player); SpawnMob(17616898):updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
SpRoXx/GTW-RPG
[resources]/GTWpolice/blips.lua
2
1262
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- blips_table = { {1551,-1676,16}, -- LSPD {-1606,715,8}, -- SFPD {2340,2457,14}, -- LVPD {-214,979,19}, -- FCPD {-1392,2635,55}, -- EQPD {-2241,2293,5}, -- BMPD } -- Create blips to show nearest police department always for k,v in pairs(blips_table) do --local blip = exports.customblips:createCustomBlip(v[1], v[2], 16, 16, "police_blip.png", 200) --exports.customblips:setCustomBlipRadarScale(blip, 1.6) createBlip(v[1],v[2],v[3], 30, 2, 0,0,0,255, 5, 400) end -- Function to print code to generate blips function get_coordinates(cmd) local x,y,z = getElementPosition(localPlayer) outputChatBox(" {"..math.floor(x)..","..math.floor(y)..","..math.floor(z).."},") end addCommandHandler("mpdblip", get_coordinates)
bsd-2-clause
jshackley/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/npcs/Runic_Portal.lua
17
2025
----------------------------------- -- Area: Alzadaal Undersea Ruins -- NPC: Runic Portal -- Arrapago Reef Teleporter Back to Aht Urgan Whitegate -- @pos 206.500 -1.220 33.500 72 -- @pos 206.500 -1.220 6.500 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/globals/besieged"); require("scripts/globals/teleports"); require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Z = player:getZPos(); if (Z > 27.5 and Z > 39.5) then -- Northern Stage point. if (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,6) == 1) then player:startEvent(0x0075); else player:startEvent(0x0079); end else player:messageSpecial(RESPONSE); end else if (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,6) == 1) then player:startEvent(0x0076); else player:startEvent(0x007a); end else player:messageSpecial(RESPONSE); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("CSID: %u",csid); printf("RESULT: %u",option); if ((csid == 0x0079 or csid == 0x007a) and option == 1) then player:addNationTeleport(AHTURHGAN,64); toChamberOfPassage(player); elseif ((csid == 0x0075 or csid == 0x0076) and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
jshackley/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/_0zt.lua
17
1389
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: Luminus convergence ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==5) then player:startEvent(0x00CC); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (csid==0x00CC) then player:completeMission(COP,WHEN_ANGELS_FALL); player:addMission(COP,DAWN); player:setVar("PromathiaStatus",0); end end;
gpl-3.0
Ombridride/minetest-minetestforfun-server
mods/email/hudkit.lua
12
1044
-- HudKit, by rubenwardy -- License: Either WTFPL or CC0, you can choose. local function hudkit() return { players = {}, add = function(self, player, id, def) local name = player:get_player_name() local elements = self.players[name] if not elements then self.players[name] = {} elements = self.players[name] end elements[id] = player:hud_add(def) end, exists = function(self, player, id) local elements = self.players[player:get_player_name()] return elements and elements[id] end, change = function(self, player, id, stat, value) local elements = self.players[player:get_player_name()] if not elements or not elements[id] then return false end player:hud_change(elements[id], stat, value) return true end, remove = function(self, player, id) local elements = self.players[player:get_player_name()] if not elements or not elements[id] then return false end player:hud_remove(elements[id]) elements[id] = nil return true end } end return hudkit
unlicense
jshackley/darkstar
scripts/zones/Port_Jeuno/npcs/Purequane.lua
17
1361
----------------------------------- -- Area: Port Jeuno -- NPC: Purequane -- @zone 246 -- @pos -76 8 54 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then player:startEvent(0x0026); else player:startEvent(0x002e); 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); if (csid == 0x0026) then Z = player:getZPos(); if (Z >= 58 and Z <= 61) then player:delGil(200); end end end;
gpl-3.0
Ombridride/minetest-minetestforfun-server
mods/mesecons/mesecons_extrawires/crossover.lua
8
5068
function crossover_get_rules(node) return { {--first wire {x=-1,y=0,z=0}, {x=1,y=0,z=0}, }, {--second wire {x=0,y=0,z=-1}, {x=0,y=0,z=1}, }, } end local crossover_states = { "mesecons_extrawires:crossover_off", "mesecons_extrawires:crossover_01", "mesecons_extrawires:crossover_10", "mesecons_extrawires:crossover_on", } minetest.register_node("mesecons_extrawires:crossover_off", { description = "Insulated Crossover", drawtype = "nodebox", tiles = { "jeija_insulated_wire_crossing_tb_off.png", "jeija_insulated_wire_crossing_tb_off.png", "jeija_insulated_wire_ends_off.png" }, paramtype = "light", walkable = false, stack_max = 99, selection_box = {type="fixed", fixed={-16/32-0.0001, -18/32, -16/32-0.001, 16/32+0.001, -5/32, 16/32+0.001}}, node_box = { type = "fixed", fixed = { { -16/32-0.001, -17/32, -3/32, 16/32+0.001, -13/32, 3/32 }, { -3/32, -17/32, -16/32-0.001, 3/32, -13/32, -6/32 }, { -3/32, -13/32, -9/32, 3/32, -6/32, -6/32 }, { -3/32, -9/32, -9/32, 3/32, -6/32, 9/32 }, { -3/32, -13/32, 6/32, 3/32, -6/32, 9/32 }, { -3/32, -17/32, 6/32, 3/32, -13/32, 16/32+0.001 }, }, }, groups = {dig_immediate=2, mesecon=3}, --MFF mesecons = { conductor = { states = crossover_states, rules = crossover_get_rules(), } }, }) minetest.register_node("mesecons_extrawires:crossover_01", { description = "You hacker you!", drop = "mesecons_extrawires:crossover_off", drawtype = "nodebox", tiles = { "jeija_insulated_wire_crossing_tb_01.png", "jeija_insulated_wire_crossing_tb_01.png", "jeija_insulated_wire_ends_01x.png", "jeija_insulated_wire_ends_01x.png", "jeija_insulated_wire_ends_01z.png", "jeija_insulated_wire_ends_01z.png" }, paramtype = "light", walkable = false, stack_max = 99, selection_box = {type="fixed", fixed={-16/32-0.0001, -18/32, -16/32-0.001, 16/32+0.001, -5/32, 16/32+0.001}}, node_box = { type = "fixed", fixed = { { -16/32-0.001, -17/32, -3/32, 16/32+0.001, -13/32, 3/32 }, { -3/32, -17/32, -16/32-0.001, 3/32, -13/32, -6/32 }, { -3/32, -13/32, -9/32, 3/32, -6/32, -6/32 }, { -3/32, -9/32, -9/32, 3/32, -6/32, 9/32 }, { -3/32, -13/32, 6/32, 3/32, -6/32, 9/32 }, { -3/32, -17/32, 6/32, 3/32, -13/32, 16/32+0.001 }, }, }, groups = {dig_immediate=2, mesecon=3, not_in_creative_inventory=1}, --MFF mesecons = { conductor = { states = crossover_states, rules = crossover_get_rules(), } }, }) minetest.register_node("mesecons_extrawires:crossover_10", { description = "You hacker you!", drop = "mesecons_extrawires:crossover_off", drawtype = "nodebox", tiles = { "jeija_insulated_wire_crossing_tb_10.png", "jeija_insulated_wire_crossing_tb_10.png", "jeija_insulated_wire_ends_10x.png", "jeija_insulated_wire_ends_10x.png", "jeija_insulated_wire_ends_10z.png", "jeija_insulated_wire_ends_10z.png" }, paramtype = "light", walkable = false, stack_max = 99, selection_box = {type="fixed", fixed={-16/32-0.0001, -18/32, -16/32-0.001, 16/32+0.001, -5/32, 16/32+0.001}}, node_box = { type = "fixed", fixed = { { -16/32-0.001, -17/32, -3/32, 16/32+0.001, -13/32, 3/32 }, { -3/32, -17/32, -16/32-0.001, 3/32, -13/32, -6/32 }, { -3/32, -13/32, -9/32, 3/32, -6/32, -6/32 }, { -3/32, -9/32, -9/32, 3/32, -6/32, 9/32 }, { -3/32, -13/32, 6/32, 3/32, -6/32, 9/32 }, { -3/32, -17/32, 6/32, 3/32, -13/32, 16/32+0.001 }, }, }, groups = {dig_immediate=3, mesecon=3, not_in_creative_inventory=1}, mesecons = { conductor = { states = crossover_states, rules = crossover_get_rules(), } }, }) minetest.register_node("mesecons_extrawires:crossover_on", { description = "You hacker you!", drop = "mesecons_extrawires:crossover_off", drawtype = "nodebox", tiles = { "jeija_insulated_wire_crossing_tb_on.png", "jeija_insulated_wire_crossing_tb_on.png", "jeija_insulated_wire_ends_on.png", "jeija_insulated_wire_ends_on.png", "jeija_insulated_wire_ends_on.png", "jeija_insulated_wire_ends_on.png" }, paramtype = "light", walkable = false, stack_max = 99, selection_box = {type="fixed", fixed={-16/32-0.0001, -18/32, -16/32-0.001, 16/32+0.001, -5/32, 16/32+0.001}}, node_box = { type = "fixed", fixed = { { -16/32-0.001, -17/32, -3/32, 16/32+0.001, -13/32, 3/32 }, { -3/32, -17/32, -16/32-0.001, 3/32, -13/32, -6/32 }, { -3/32, -13/32, -9/32, 3/32, -6/32, -6/32 }, { -3/32, -9/32, -9/32, 3/32, -6/32, 9/32 }, { -3/32, -13/32, 6/32, 3/32, -6/32, 9/32 }, { -3/32, -17/32, 6/32, 3/32, -13/32, 16/32+0.001 }, }, }, groups = {dig_immediate=3, mesecon=3, not_in_creative_inventory=1}, mesecons = { conductor = { states = crossover_states, rules = crossover_get_rules(), } }, }) minetest.register_craft({ type = "shapeless", output = "mesecons_extrawires:crossover_off", recipe = { "mesecons_insulated:insulated_off", "mesecons_insulated:insulated_off", }, }) minetest.register_craft({ type = "shapeless", output = "mesecons_insulated:insulated_off 2", recipe = { "mesecons_extrawires:crossover_off", }, })
unlicense
sp3ctum/lean
tests/lua/old/hop2.lua
6
4657
import("util.lua") function pibody(e) while (e:is_pi()) do local _, _, r = e:fields() e = r end return e end function funbody(e) while (e:is_lambda()) do local _, _, r = e:fields() e = r end return e end function hoptst(rule, target, expected, perfect_match, no_env) if expected == nil then expected = true end local th = parse_lean(rule) local p = pibody(th):arg(2) local t = funbody(parse_lean(target)) local r if no_env then r = hop_match(p, t, nil) else r = hop_match(p, t) end -- print(p, t) if (r and not expected) or (not r and expected) then error("test failed: " .. tostring(rule) .. " === " .. tostring(target)) end if r then local s = p:instantiate(r):beta_reduce() print "Solution:" for i = 1, #r do print("#" .. tostring(i) .. " <--- " .. tostring(r[i])) end print "" if perfect_match then t = t:beta_reduce() if s ~= t then print("Mismatch") print(s) print(t) end assert(s == t) end end end parse_lean_cmds([[ variable f : Nat -> Nat -> Nat variable g : Nat -> Nat variable p : Nat -> Bool variable n : Nat ]]) hoptst([[forall (h : Nat -> Nat), (forall x : Nat, h 0 = h x) = true]], [[fun (ff : Nat -> Nat), forall x : Nat, ff 0 = ff x]]) hoptst([[forall (h : Nat -> Nat -> Nat) (a : Nat), (forall x : Nat, (h x a) = a) = true]], [[fun (a b c : Nat), (forall x : Nat, (f x b) = b)]]) hoptst([[forall (A : TypeU) (P Q : A -> Bool), (forall x : A, P x /\ Q x) = ((forall x : A, P x) /\ (forall x : A, Q x))]], [[forall x : Nat, p (f x 0) /\ f (f x x) 1 >= 0]]) hoptst([[forall (F G : Nat -> Nat), (forall x y : Nat, F x = x /\ G y = y) = (F = G)]], [[(forall x y : Nat, f x (g x) = x /\ g (g (g y)) = y)]]) hoptst([[forall (F G : Nat -> Nat), (forall x y : Nat, F x = x /\ G y = y) = (F = G)]], [[fun (a b c : Nat), (forall x y : Nat, f x (f (g b) c) = x /\ (f (g (g (f y c))) a) = y)]]) hoptst([[forall (a b c : Bool), ((a /\ b) /\ c) = (a /\ (b /\ c))]], [[fun (p1 p2 p3 p4 p5 : Bool), (((p1 ∧ p2) ∧ p3) ∧ (p4 ∧ p2))]]) hoptst([[forall (F G : Nat -> Bool), (forall x : Nat, F x = (F x ∧ G x)) = (F = G)]], [[forall x : Nat, p (f x x) = (p (f x x) ∧ p (f x 0))]]) hoptst([[forall (F G : Nat -> Bool), (forall x : Nat, F x = (F x ∧ G x)) = (F = G)]], [[forall x : Nat, p (f x x) = (p (f (g x) x) ∧ p (f x 0))]], false) hoptst([[forall (F G : Nat -> Nat), (forall x y : Nat, F x = x /\ G y = y) = (F = G)]], [[fun (a b c : Nat), (forall x y : Nat, f x (f (g y) c) = x /\ (f (g (g (f y c))) a) = y)]], false) hoptst([[forall (a : Bool), (a /\ true) = a]], [[fun (p1 p2 p3 : Bool), (p1 /\ p2) /\ true]]) hoptst([[forall (a : Bool), (a /\ true) = a]], [[fun (p1 p2 p3 : Bool), (p1 /\ p2) /\ false]], false) hoptst([[forall (h : Nat -> Nat) (a : Nat), (h a) = a]], [[fun (a b c : Nat), f a b]]) hoptst([[forall (a : Nat), (g a) = a]], [[fun (a b c : Nat), f a b]], false) hoptst([[forall (A : Type) (a : A), (a = a) = true]], [[fun (a b : Nat), b = b]]) hoptst([[forall (h : Nat -> Nat), (forall x : Nat, h x = h 0) = true]], [[fun (ff : Nat -> Nat), forall x : Nat, ff x = ff 0]]) hoptst([[forall (h : Nat -> Nat), (forall x : Nat, h x = h 0) = true]], [[fun (ff : Nat -> Nat) (a b c : Nat), forall x : Nat, ff x = ff 0]]) hoptst([[forall (h : Nat -> Nat -> Bool), (forall x : Nat, h x x) = true]], [[fun (a b : Nat), forall x : Nat, f x x]]) hoptst([[forall (h : Nat -> Nat -> Bool), (forall x : Nat, h x x) = true]], -- this is not a higher-order pattern [[fun (a b : Nat), forall x : Nat, f (f x) (f x)]], false) hoptst([[forall (h : Nat -> Nat -> Bool), (forall x : Nat, h n x) = true]], [[fun (ff : Nat -> Nat -> Bool) (a b : Nat), forall x : Nat, ff n x]]) hoptst([[forall (h : Nat -> Nat -> Bool), (forall x : Nat, h n x) = true]], -- this is not a higher-order pattern [[fun (ff : Nat -> Nat -> Bool) (a b : Nat), forall x : Nat, ff n (g x)]], false) hoptst([[forall (h : Nat -> Bool), (forall x y : Nat, h x) = true]], [[fun (a b : Nat), forall x y : Nat, (fun z : Nat, z + x) (fun w1 w2 : Nat, w1 + w2 + x)]]) hoptst([[forall (h : Nat -> Bool), (forall x y : Nat, h y) = true]], [[fun (a b : Nat), forall x y : Nat, (fun z : Nat, z + y) (fun w1 w2 : Nat, w1 + w2 + y)]]) parse_lean_cmds([[ definition ww := 0 ]]) hoptst('ww = 0', '0', true, false) hoptst('ww = 0', '0', false, false, true)
apache-2.0
luastoned/turbo
turbo/3rdparty/middleclass/middleclass.lua
12
5300
-- middleclass.lua - v2.0 (2011-09) -- Copyright (c) 2011 Enrique García Cota -- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: -- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -- Based on YaciCode, from Julien Patte and LuaObject, from Sebastien Rocca-Serra local _classes = setmetatable({}, {__mode = "k"}) local function _setClassDictionariesMetatables(klass) local dict = klass.__instanceDict dict.__index = dict local super = klass.super if super then local superStatic = super.static setmetatable(dict, super.__instanceDict) setmetatable(klass.static, { __index = function(_,k) return dict[k] or superStatic[k] end }) else setmetatable(klass.static, { __index = function(_,k) return dict[k] end }) end end local function _setClassMetatable(klass) setmetatable(klass, { __tostring = function() return "class " .. klass.name end, __index = klass.static, __newindex = klass.__instanceDict, __call = function(self, ...) return self:new(...) end }) end local function _createClass(name, super) local klass = { name = name, super = super, static = {}, __mixins = {}, __instanceDict={} } klass.subclasses = setmetatable({}, {__mode = "k"}) _setClassDictionariesMetatables(klass) _setClassMetatable(klass) _classes[klass] = true return klass end local function _createLookupMetamethod(klass, name) return function(...) local method = klass.super[name] assert( type(method)=='function', tostring(klass) .. " doesn't implement metamethod '" .. name .. "'" ) return method(...) end end local function _setClassMetamethods(klass) for _,m in ipairs(klass.__metamethods) do klass[m]= _createLookupMetamethod(klass, m) end end local function _setDefaultInitializeMethod(klass, super) klass.initialize = function(instance, ...) return super.initialize(instance, ...) end end local function _includeMixin(klass, mixin) assert(type(mixin)=='table', "mixin must be a table") for name,method in pairs(mixin) do if name ~= "included" and name ~= "static" then klass[name] = method end end if mixin.static then for name,method in pairs(mixin.static) do klass.static[name] = method end end if type(mixin.included)=="function" then mixin:included(klass) end klass.__mixins[mixin] = true end Object = _createClass("Object", nil) Object.static.__metamethods = { '__add', '__call', '__concat', '__div', '__le', '__lt', '__mod', '__mul', '__pow', '__sub', '__tostring', '__unm' } function Object.static:allocate() assert(_classes[self], "Make sure that you are using 'Class:allocate' instead of 'Class.allocate'") return setmetatable({ class = self }, self.__instanceDict) end function Object.static:new(...) local instance = self:allocate() instance:initialize(...) return instance end function Object.static:subclass(name) assert(_classes[self], "Make sure that you are using 'Class:subclass' instead of 'Class.subclass'") assert(type(name) == "string", "You must provide a name(string) for your class") local subclass = _createClass(name, self) _setClassMetamethods(subclass) _setDefaultInitializeMethod(subclass, self) self.subclasses[subclass] = true self:subclassed(subclass) return subclass end function Object.static:subclassed(other) end function Object.static:include( ... ) assert(_classes[self], "Make sure you that you are using 'Class:include' instead of 'Class.include'") for _,mixin in ipairs({...}) do _includeMixin(self, mixin) end return self end function Object:initialize() end function Object:__tostring() return "instance of " .. tostring(self.class) end function class(name, super, ...) super = super or Object return super:subclass(name, ...) end function instanceOf(aClass, obj) if not _classes[aClass] or type(obj) ~= 'table' or not _classes[obj.class] then return false end if obj.class == aClass then return true end return subclassOf(aClass, obj.class) end function subclassOf(other, aClass) if not _classes[aClass] or not _classes[other] or aClass.super == nil then return false end return aClass.super == other or subclassOf(other, aClass.super) end function includes(mixin, aClass) if not _classes[aClass] then return false end if aClass.__mixins[mixin] then return true end return includes(mixin, aClass.super) end
apache-2.0
jshackley/darkstar
scripts/zones/La_Theine_Plateau/Zone.lua
17
5853
----------------------------------- -- -- Zone: La_Theine_Plateau (102) -- ----------------------------------- package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/La_Theine_Plateau/TextIDs"); require("scripts/globals/zone"); require("scripts/globals/icanheararainbow"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/weather"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 688, 153, DIGREQ_NONE }, { 17396, 155, DIGREQ_NONE }, { 17296, 134, DIGREQ_NONE }, { 641, 103, DIGREQ_NONE }, { 840, 56, DIGREQ_NONE }, { 642, 49, DIGREQ_NONE }, { 696, 57, DIGREQ_NONE }, { 694, 40, DIGREQ_NONE }, { 622, 28, DIGREQ_NONE }, { 700, 3, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 4545, 34, DIGREQ_BURROW }, { 636, 20, DIGREQ_BURROW }, { 616, 8, DIGREQ_BURROW }, { 5235, 2, DIGREQ_BURROW }, { 2364, 139, DIGREQ_BORE }, { 2235, 44, DIGREQ_BORE }, { 617, 6, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 1237, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17195678,17195679}; SetFieldManual(manuals); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -272.118, 21.715, 98.859, 243); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x007b; elseif ( prevZone == 193 and player:getVar( "darkPuppetCS") == 5 and player:getFreeSlotsCount() >= 1) then cs = 0x007a; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x007d; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x007b) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x007d) then player:updateEvent(0,0,0,0,0,2); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x007b) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x007a) then player:addItem( 14096); player:messageSpecial( ITEM_OBTAINED, 14096); -- Chaos Sollerets player:setVar( "darkPuppetCS", 0); player:addFame( BASTOK, AF2_FAME); player:completeQuest( BASTOK,DARK_PUPPET); end end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) local _2u0 = GetNPCByID(17195607); local VanadielTOTD = VanadielTOTD(); local I_Can_Hear_a_Rainbow = GetServerVariable("I_Can_Hear_a_Rainbow"); if (I_Can_Hear_a_Rainbow == 1 and weather ~= WEATHER_RAIN and VanadielTOTD >= TIME_DAWN and VanadielTOTD <= TIME_EVENING and _2u0:getAnimation() == 9) then _2u0:setAnimation(8); elseif (I_Can_Hear_a_Rainbow == 1 and weather == WEATHER_RAIN and _2u0:getAnimation() == 8) then _2u0:setAnimation(9); SetServerVariable("I_Can_Hear_a_Rainbow", 0); end end; ----------------------------------- -- onTOTDChange ----------------------------------- function onTOTDChange(TOTD) local _2u0 = GetNPCByID(17195607); local I_Can_Hear_a_Rainbow = GetServerVariable("I_Can_Hear_a_Rainbow"); if (I_Can_Hear_a_Rainbow == 1 and TOTD >= TIME_DAWN and TOTD <= TIME_EVENING and _2u0:getAnimation() == 9) then _2u0:setAnimation(8); elseif (I_Can_Hear_a_Rainbow == 1 and TOTD < TIME_DAWN or TOTD > TIME_EVENING and _2u0:getAnimation() == 8) then _2u0:setAnimation(9); SetServerVariable("I_Can_Hear_a_Rainbow", 0); end end;
gpl-3.0
jshackley/darkstar
scripts/zones/Bostaunieux_Oubliette/npcs/Novalmauge.lua
17
4021
----------------------------------- -- Area: Bostaunieux Obliette -- NPC: Novalmauge -- Starts and Finishes Quest: The Rumor -- Involved in Quest: The Holy Crest, Trouble at the Sluice -- @pos 70 -24 21 167 ----------------------------------- package.loaded["scripts/zones/Bostaunieux_Oubliette/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Bostaunieux_Oubliette/TextIDs"); require("scripts/globals/pathfind"); local path = { 41.169430, -24.000000, 19.860674, 42.256676, -24.000000, 19.885197, 41.168694, -24.000000, 19.904638, 21.859211, -24.010996, 19.792259, 51.917370, -23.924366, 19.970068, 74.570229, -24.024828, 20.103880, 44.533886, -23.947662, 19.926519 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getVar("troubleAtTheSluiceVar") == 2) then if (trade:hasItemQty(959,1) and trade:getItemCount() == 1) then -- Trade Dahlia player:startEvent(0x0011); npc:wait(-1); end end if (player:getQuestStatus(SANDORIA,THE_RUMOR) == QUEST_ACCEPTED) then local count = trade:getItemCount(); local BeastBlood = trade:hasItemQty(930,1) if (BeastBlood == true and count == 1) then player:startEvent(0x000c); npc:wait(-1); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local troubleAtTheSluice = player:getQuestStatus(SANDORIA,TROUBLE_AT_THE_SLUICE); local TheHolyCrest = player:getVar("TheHolyCrest_Event"); local tatsVar = player:getVar("troubleAtTheSluiceVar"); local theRumor = player:getQuestStatus(SANDORIA,THE_RUMOR); npc:wait(-1); -- The Holy Crest Quest if (TheHolyCrest == 1) then player:startEvent(0x0006); elseif (TheHolyCrest == 2) then player:startEvent(0x0007); -- Trouble at the Sluice Quest elseif (tatsVar == 1) then player:startEvent(0x000f); player:setVar("troubleAtTheSluiceVar",2); elseif (tatsVar == 2) then player:startEvent(0x0010); -- The rumor Quest elseif (theRumor == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 3 and player:getMainLvl() >= 10) then player:startEvent(0x000d); elseif (theRumor == QUEST_ACCEPTED) then player:startEvent(0x000b); elseif (theRumor == QUEST_COMPLETED) then player:startEvent(0x000e); -- Standard dialog after "The Rumor" else player:startEvent(0x000a); -- 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,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0006) then player:setVar("TheHolyCrest_Event",2); elseif (csid == 0x0011) then player:tradeComplete(); player:addKeyItem(NEUTRALIZER); player:messageSpecial(KEYITEM_OBTAINED,NEUTRALIZER); player:setVar("troubleAtTheSluiceVar",0); elseif (csid == 0x000d and option == 1) then player:addQuest(SANDORIA,THE_RUMOR); elseif (csid == 0x000c) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4853); -- Scroll of Drain else player:tradeComplete(); player:addItem(4853); player:messageSpecial(ITEM_OBTAINED, 4853); -- Scroll of Drain player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,THE_RUMOR); end end npc:wait(0); end;
gpl-3.0
luastoned/turbo
spec/hash_spec.lua
12
1760
-- Turbo Unit test -- -- Copyright 2013 John Abrahamsen -- -- 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 ffi = require "ffi" if pcall(ffi.load, "ssl") then _G.TURBO_SSL = true local turbo = require "turbo" describe("turbo.hash Namespace", function() it("SHA1 class", function() local hash = turbo.hash.SHA1("lol") assert.equal(hash:hex(), "403926033d001b5279df37cbbe5287b7c7c267fa") end) it("works with nil initializer", function() local hash = turbo.hash.SHA1() hash:update("lol") hash:finalize() assert.equal(hash:hex(), "403926033d001b5279df37cbbe5287b7c7c267fa") end) it("works with nil initializer and multiple updates", function() local hash = turbo.hash.SHA1() hash:update("l") hash:update("o") hash:update("l") hash:finalize() assert.equal(hash:hex(), "403926033d001b5279df37cbbe5287b7c7c267fa") end) it("gives error on already finalized context", function() local hash = turbo.hash.SHA1("lol") assert.has.errors(function() hash:update("ol") end) end) it("gives error on not yet finalized context", function() local hash = turbo.hash.SHA1() hash:update("lol") assert.has.errors(function() hash:hex() end) end) end) end
apache-2.0
jshackley/darkstar
scripts/globals/mobs.lua
30
1617
----------------------------------- -- -- -- ----------------------------------- package.loaded["scripts/globals/conquest"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/globals/conquest"); require("scripts/globals/status"); ----------------------------------- -- ----------------------------------- -- function onMobDeathEx(mob, killer, isKillShot, killType) function onMobDeathEx(mob, killer, isKillShot, isWeaponSkillKill) -- DRK quest - Blade Of Darkness local BladeofDarkness = killer:getQuestStatus(BASTOK, BLADE_OF_DARKNESS); local BladeofDeath = killer:getQuestStatus(BASTOK, BLADE_OF_DEATH); local ChaosbringerKills = killer:getVar("ChaosbringerKills"); if (BladeofDarkness == QUEST_ACCEPTED or BladeofDeath == QUEST_ACCEPTED) then if (killer:getEquipID(SLOT_MAIN) == 16607 and isKillShot == true and isWeaponSkillKill == false) then if (ChaosbringerKills < 200) then killer:setVar("ChaosbringerKills", ChaosbringerKills + 1); end end end if (killer:getCurrentMission(WINDURST) == A_TESTING_TIME) then if (killer:hasCompletedMission(WINDURST,A_TESTING_TIME) and killer:getZoneID() == 118) then killer:setVar("testingTime_crea_count",killer:getVar("testingTime_crea_count") + 1); elseif (killer:hasCompletedMission(WINDURST,A_TESTING_TIME) == false and killer:getZoneID() == 117) then killer:setVar("testingTime_crea_count",killer:getVar("testingTime_crea_count") + 1); end end -- doMagiantTrialCheck(mob, killer, isKillShot, killType); end;
gpl-3.0
jshackley/darkstar
scripts/zones/Windurst_Woods/npcs/Hauh_Colphioh.lua
17
2809
----------------------------------- -- Area: Windurst Woods -- NPC: Hauh Colphioh -- Type: Guildworker's Union Representative -- @zone: 241 -- @pos -38.173 -1.25 -113.679 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); local keyitems = { [0] = { id = CLOTH_PURIFICATION, rank = 3, cost = 40000 }, [1] = { id = CLOTH_ENSORCELLMENT, rank = 3, cost = 40000 }, [2] = { id = SPINNING, rank = 3, cost = 10000 }, [3] = { id = FLETCHING, rank = 3, cost = 10000 }, [4] = { id = WAY_OF_THE_WEAVER, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15447, -- Weaver's Belt rank = 4, cost = 10000 }, [3] = { id = 13946, -- Magnifying Spectacles rank = 6, cost = 70000 }, [4] = { id = 14395, -- Weaver's Apron rank = 7, cost = 100000 }, [5] = { id = 198, -- Gilt Tapestry rank = 9, cost = 150000 }, [6] = { id = 337, -- Weaver's Signboard rank = 9, cost = 200000 }, [7] = { id = 15822, -- Tailor's Ring rank = 6, cost = 80000 }, [8] = { id = 3665, -- Spinning Wheel rank = 7, cost = 50000 }, [9] = { id = 3327, -- Weavers' Emblem rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x2729, 4); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 4, 0x2728, "guild_weaving", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2728) then unionRepresentativeTriggerFinish(player, option, target, 4, "guild_weaving", keyitems, items); elseif (csid == 0x2729) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
ziweiwu/ziweiwu.github.io
vendor/cache/ruby/2.4.0/gems/pygments.rb-0.6.3/vendor/pygments-main/tests/examplefiles/example.lua
102
8677
--[[ Auctioneer Advanced Version: <%version%> (<%codename%>) Revision: $Id: CoreMain.lua 2233 2007-09-25 03:57:33Z norganna $ URL: http://auctioneeraddon.com/ This is an addon for World of Warcraft that adds statistical history to the auction data that is collected when the auction is scanned, so that you can easily determine what price you will be able to sell an item for at auction or at a vendor whenever you mouse-over an item in the game License: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program(see GPL.txt); if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Note: This AddOn's source code is specifically designed to work with World of Warcraft's interpreted AddOn system. You have an implicit licence to use this AddOn with these facilities since that is its designated purpose as per: http://www.fsf.org/licensing/licenses/gpl-faq.html#InterpreterIncompat ]] --[[ See CoreAPI.lua for a description of the modules API ]] if (not AucAdvanced) then AucAdvanced = {} end if (not AucAdvancedData) then AucAdvancedData = {} end if (not AucAdvancedLocal) then AucAdvancedLocal = {} end if (not AucAdvancedConfig) then AucAdvancedConfig = {} end AucAdvanced.Version="<%version%>"; if (AucAdvanced.Version == "<".."%version%>") then AucAdvanced.Version = "5.0.DEV"; end local private = {} -- For our modular stats system, each stats engine should add their -- subclass to AucAdvanced.Modules.<type>.<name> and store their data into their own -- data table in AucAdvancedData.Stats.<type><name> if (not AucAdvanced.Modules) then AucAdvanced.Modules = {Stat={},Util={},Filter={}} end if (not AucAdvancedData.Stats) then AucAdvancedData.Stats = {} end if (not AucAdvancedLocal.Stats) then AucAdvancedLocal.Stats = {} end function private.TooltipHook(vars, ret, frame, name, hyperlink, quality, quantity, cost, additional) if EnhTooltip.LinkType(hyperlink) ~= "item" then return -- Auctioneer hooks into item tooltips only end -- Check to see if we need to force load scandata local getter = AucAdvanced.Settings.GetSetting if (getter("scandata.tooltip.display") and getter("scandata.force")) then AucAdvanced.Scan.GetImage() end for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.Processor) then engineLib.Processor("tooltip", frame, name, hyperlink, quality, quantity, cost, additional) end end end end function private.HookAH() hooksecurefunc("AuctionFrameBrowse_Update", AucAdvanced.API.ListUpdate) for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.Processor) then engineLib.Processor("auctionui") end end end end function private.OnLoad(addon) addon = addon:lower() -- Check if the actual addon itself is loading if (addon == "auc-advanced") then Stubby.RegisterAddOnHook("Blizzard_AuctionUi", "Auc-Advanced", private.HookAH) Stubby.RegisterFunctionHook("EnhTooltip.AddTooltip", 600, private.TooltipHook) for pos, module in ipairs(AucAdvanced.EmbeddedModules) do -- These embedded modules have also just been loaded private.OnLoad(module) end end -- Notify the actual module if it exists local auc, sys, eng = strsplit("-", addon) if (auc == "auc" and sys and eng) then for system, systemMods in pairs(AucAdvanced.Modules) do if (sys == system:lower()) then for engine, engineLib in pairs(systemMods) do if (eng == engine:lower() and engineLib.OnLoad) then engineLib.OnLoad(addon) end end end end end -- Check all modules' load triggers and pass event to processors for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.LoadTriggers and engineLib.LoadTriggers[addon]) then if (engineLib.OnLoad) then engineLib.OnLoad(addon) end end if (engineLib.Processor and auc == "auc" and sys and eng) then engineLib.Processor("load", addon) end end end end function private.OnUnload() for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if (engineLib.OnUnload) then engineLib.OnUnload() end end end end private.Schedule = {} function private.OnEvent(...) local event, arg = select(2, ...) if (event == "ADDON_LOADED") then local addon = string.lower(arg) if (addon:sub(1,4) == "auc-") then private.OnLoad(addon) end elseif (event == "AUCTION_HOUSE_SHOW") then -- Do Nothing for now elseif (event == "AUCTION_HOUSE_CLOSED") then AucAdvanced.Scan.Interrupt() elseif (event == "PLAYER_LOGOUT") then AucAdvanced.Scan.Commit(true) private.OnUnload() elseif event == "UNIT_INVENTORY_CHANGED" or event == "ITEM_LOCK_CHANGED" or event == "CURSOR_UPDATE" or event == "BAG_UPDATE" then private.Schedule["inventory"] = GetTime() + 0.15 end end function private.OnUpdate(...) if event == "inventory" then AucAdvanced.Post.AlertBagsChanged() end local now = GetTime() for event, time in pairs(private.Schedule) do if time > now then for system, systemMods in pairs(AucAdvanced.Modules) do for engine, engineLib in pairs(systemMods) do if engineLib.Processor then engineLib.Processor(event, time) end end end end private.Schedule[event] = nil end end private.Frame = CreateFrame("Frame") private.Frame:RegisterEvent("ADDON_LOADED") private.Frame:RegisterEvent("AUCTION_HOUSE_SHOW") private.Frame:RegisterEvent("AUCTION_HOUSE_CLOSED") private.Frame:RegisterEvent("UNIT_INVENTORY_CHANGED") private.Frame:RegisterEvent("ITEM_LOCK_CHANGED") private.Frame:RegisterEvent("CURSOR_UPDATE") private.Frame:RegisterEvent("BAG_UPDATE") private.Frame:RegisterEvent("PLAYER_LOGOUT") private.Frame:SetScript("OnEvent", private.OnEvent) private.Frame:SetScript("OnUpdate", private.OnUpdate) -- Auctioneer's debug functions AucAdvanced.Debug = {} local addonName = "Auctioneer" -- the addon's name as it will be displayed in -- the debug messages ------------------------------------------------------------------------------- -- Prints the specified message to nLog. -- -- syntax: -- errorCode, message = debugPrint([message][, category][, title][, errorCode][, level]) -- -- parameters: -- message - (string) the error message -- nil, no error message specified -- category - (string) the category of the debug message -- nil, no category specified -- title - (string) the title for the debug message -- nil, no title specified -- errorCode - (number) the error code -- nil, no error code specified -- level - (string) nLog message level -- Any nLog.levels string is valid. -- nil, no level specified -- -- returns: -- errorCode - (number) errorCode, if one is specified -- nil, otherwise -- message - (string) message, if one is specified -- nil, otherwise ------------------------------------------------------------------------------- function AucAdvanced.Debug.DebugPrint(message, category, title, errorCode, level) return DebugLib.DebugPrint(addonName, message, category, title, errorCode, level) end ------------------------------------------------------------------------------- -- Used to make sure that conditions are met within functions. -- If test is false, the error message will be written to nLog and the user's -- default chat channel. -- -- syntax: -- assertion = assert(test, message) -- -- parameters: -- test - (any) false/nil, if the assertion failed -- anything else, otherwise -- message - (string) the message which will be output to the user -- -- returns: -- assertion - (boolean) true, if the test passed -- false, otherwise ------------------------------------------------------------------------------- function AucAdvanced.Debug.Assert(test, message) return DebugLib.Assert(addonName, test, message) end
mit
jshackley/darkstar
scripts/zones/Nashmau/npcs/Fhe_Maksojha.lua
19
2163
----------------------------------- -- Area: Nashmau -- NPC: Fhe Maksojha -- Type: Standard NPC -- @pos 19.084 -7 71.287 53 ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local notmeanttobe = player:getQuestStatus(AHT_URHGAN,NOT_MEANT_TO_BE); local notMeantToBeProg = player:getVar("notmeanttobeCS"); if (notmeanttobe == QUEST_AVAILABLE) then player:startEvent(0x0125); elseif (notMeantToBeProg == 1) then player:startEvent(0x0127); elseif (notMeantToBeProg == 2) then player:startEvent(0x0126); elseif (notMeantToBeProg == 3) then player:startEvent(0x0128); elseif (notMeantToBeProg == 5) then player:startEvent(0x0129); elseif (notmeanttobe == QUEST_COMPLETED) then player:startEvent(0x012a); 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 == 0x0125) then player:setVar("notmeanttobeCS",1); player:addQuest(AHT_URHGAN,NOT_MEANT_TO_BE); elseif (csid == 0x0126) then player:setVar("notmeanttobeCS",3); elseif (csid == 0x0129) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2187,3); else player:setVar("notmeanttobeCS",0); player:addItem(2187,3); player:messageSpecial(ITEM_OBTAINEDX,2187,3); player:completeQuest(AHT_URHGAN,NOT_MEANT_TO_BE); end end end;
gpl-3.0
SwadicalRag/hash.js
plugins/lua/user_modules/tetris.lua
4
4093
local L = true; local n = false; LEFT = true; RIGHT = false; local prints = { [L] = "#"; [n] = "_"; }; local pieces = { { pos = {1,1}; shape = { {L,L,n,n}, {L,L,n,n}, {n,n,n,n}, {n,n,n,n}, }; size = {2,2}; offset = 0; }, { pos = {1,4}; shape = { {L,L,L,L}, {n,n,n,n}, {n,n,n,n}, {n,n,n,n}, }; size = {4,1}; offset = 0; }, { pos = {1,1}; shape = { {L,n,n,n}, {L,n,n,n}, {L,n,n,n}, {L,n,n,n}, }; size = {1,4}; offset = 0; }, { pos = {1,3}; shape = { {L,n,n,n}, {L,L,L,n}, {n,n,n,n}, {n,n,n,n}, }; size = {3,2}; offset = 0; }, { pos = {1,1}; shape = { {L,L,L,n}, {L,n,n,n}, {n,n,n,n}, {n,n,n,n}, }; size = {1,1}; offset = 0; }, { pos = {1,1}; shape = { {L,n,n,n}, {L,L,n,n}, {n,L,n,n}, {n,n,n,n}, }; size = {2,3}; offset = 0; }, { pos = {1,1}; shape = { {L,n,n,n}, {L,L,n,n}, {L,n,n,n}, {n,n,n,n}, }; size = {2,3}; offset = 0; }, { pos = {1,1}; shape = { {n,L,n,n}, {L,L,L,n}, {n,n,n,n}, {n,n,n,n}, }; size = {3,2}; offset = 0; }, { pos = {1,1}; shape = { {L,L,L,n}, {n,L,n,n}, {n,n,n,n}, {n,n,n,n}, }; size = {3,2}; offset = 0; }, }; local function write_piece_to_board(piece, board, what) local overwrote = false; for y = 1, piece.size[1] do for x = 1, piece.size[2] do if(piece.shape[x][y] == L) then if(board[y+piece.pos[2]-1][x+piece.pos[1]-1]) then overwrote = true; end board[y+piece.pos[2]-1][x+piece.pos[1]-1] = what; end end end return overwrote; end local function copy(x) local r = {}; for k,v in pairs(x) do r[k] = v; if(type(v) == "table") then r[k] = copy(v); end end return r; end local function generate_piece() return copy(pieces[math.random(1, #pieces)]); end function make_board(width, height) local r = {}; for y = 1, height do r[y] = {}; for x = 1, width do r[y][x] = n; end end r.size = {width, height}; r.active = generate_piece(); return r; end local function board_print(board) io.write".\r\n"; for y = 1, board.size[2] do for x = 1, board.size[1] do io.write(prints[board[y][x]]); end io.write"\r\n"; end end function board_tick(board, fall, x) local active = board.active; write_piece_to_board(active, board, n); local before_x, before_y = active.pos[1], active.pos[2]; if(fall) then active.pos[2] = active.pos[2] + 1; elseif(x ~= nil) then if(x == LEFT) then active.pos[1] = active.pos[1] - 1 elseif(x == RIGHT) then active.pos[1] = active.pos[1] + 1; end if(active.pos[1] < 1 or active.pos[1] > board.size[1]) then active.pos[1] = before_x; end end local biggest_y = 0; local hit = false; for y = 1, active.size[1] do for x = 1, active.size[2] do if(active.shape[x][y] == L) then biggest_y = y; if(active.pos[2] + biggest_y - 2 == board.size[2] or board[y+active.pos[2]-1][x+active.pos[1]-1] == L) then hit = true; end end end end if(hit) then active.pos[1] = before_x; active.pos[2] = before_y; end write_piece_to_board(active, board, L); local ded = false; if(hit and fall) then board.active = generate_piece(); ded = write_piece_to_board(board.active, board, L); end for y = board.size[2], -1 do local full = true; for x = 1, board.size[1] do if(board[y][x] == n) then full = false; break; end end if(full) then for y2 = y - 1, 1 do board[y2 + 1] = board[y2]; end board[1] = {n,n,n,n}; end end board_print(board); if(ded) then print("YOU DIED"); return true; end return false; end local board = nil; -- hash only function start_tetris() board = make_board(8, 8); timer.Create("TETRIS", 1, 0, function() if(not board) then timer.Remove("TETRIS"); return; end if(board_tick(board, true)) then board = nil; end end); end hook.Add("Message", "TETRIS", function(_,_,_) if(board and _:find"right") then board_tick(board, false, RIGHT); elseif(board and _:find"left") then board_tick(board, false, LEFT); end end)
cc0-1.0
sugiartocokrowibowo/Algorithm-Implementations
Golden_Ratio_Algorithms/Lua/Yonaba/golden_ratio.lua
26
3449
-- Golden Ratio approximation algorithms -- See: http://en.wikipedia.org/wiki/Golden_ratio -- Fuzzy equality test local function fuzzy_equal(a, b, eps) return (math.abs(a - b) < eps) end -- Computes an approximate value of the Golden Ratio -- Using a root based iteration. -- See: http://en.wikipedia.org/wiki/Golden_ratio#Alternative_forms -- seed : (optional) seed to start the computation (defaults to 1) -- acc : (optional) approximation accuracy (defaults to 1E-8) -- returns : an approximation of the Golden Ratio local function golden_ration_root_iteration(seed, acc) local phi, phi2 = seed or 1 acc = acc or 1e-8 repeat phi2 = phi phi = math.sqrt(1 + phi) until fuzzy_equal(phi, phi2, acc) return phi end -- Computes an approximate value of the Golden Ratio -- Using a fractional based iteration. -- See: http://en.wikipedia.org/wiki/Golden_ratio#Alternative_forms -- seed : (optional) seed to start the computation (defaults to 1) -- acc : (optional) approximation accuracy (defaults to 1E-8) -- returns : an approximation of the Golden Ratio local function golden_ration_fractional_iteration(seed, acc) local phi, phi2 = seed or 1 acc = acc or 1e-8 repeat phi2, phi = phi, 1 + (1 / phi) until fuzzy_equal(phi, phi2, acc) return phi end -- Computes an approximate value of the Golden Ratio -- Using Babylonian method. -- See: http://en.wikipedia.org/wiki/Golden_ratio#Decimal_expansion -- seed : (optional) seed to start the computation (defaults to 1) -- acc : (optional) approximation accuracy (defaults to 1E-8) -- returns : an approximation of the Golden Ratio local function golden_ration_babylonian_iteration(seed, acc) local phi, phi2 = seed or 1 acc = acc or 1e-8 repeat phi2 = phi phi = (phi * phi + 1) / (2 * phi - 1) until fuzzy_equal(phi, phi2, acc) return phi end -- Computes an approximate value of the Golden Ratio -- Using a Newton-Raphson solver (implemented as an external dependency) -- See: http://en.wikipedia.org/wiki/Golden_ratio#Calculation -- seed : (optional) seed to start the computation (defaults to 1) -- acc : (optional) approximation accuracy (defaults to 1E-8) -- returns : an approximation of the Golden Ratio local solve = require 'lib.newtonraphson' local function golden_ration_equation(seed, acc) return solve(function(x) return x * x - x - 1 end, seed, acc) end -- Computes an approximate value of the Golden Ratio -- Using Fibonacci series (implemented as an external dependency). -- See: http://en.wikipedia.org/wiki/Golden_ratio#Relationship_to_Fibonacci_sequence -- seed : (optional) seed to start the computation (defaults to 2) -- acc : (optional) approximation accuracy (defaults to 1E-8) -- returns : an approximation of the Golden Ratio local fib = (require 'lib.fib') local function golden_ration_fibonacci_iteration(seed, acc) seed, acc = seed or 2, acc or 1e-8 assert(seed >= 2, 'order must be greater than 1') local denum, num = fib(seed), fib(seed + 1) local phi, phi2 = num / denum repeat phi2 = phi seed = seed + 1 denum, num = num, fib(seed) phi = num / denum until fuzzy_equal(phi, phi2, acc) return phi end return { root = golden_ration_root_iteration, fractional = golden_ration_fractional_iteration, babylonian = golden_ration_babylonian_iteration, equation = golden_ration_equation, fibonacci = golden_ration_fibonacci_iteration }
mit
jshackley/darkstar
scripts/globals/items/bowl_of_humpty_soup.lua
35
1400
----------------------------------------- -- ID: 4521 -- Item: Bowl of Humpty Soup -- Food Effect: 240Min, All Races ----------------------------------------- -- Health % 6 -- Health Cap 35 -- Magic 5 -- Health Regen While Healing 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4521); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 6); target:addMod(MOD_FOOD_HP_CAP, 35); target:addMod(MOD_MP, 5); target:addMod(MOD_HPHEAL, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 6); target:delMod(MOD_FOOD_HP_CAP, 35); target:delMod(MOD_MP, 5); target:delMod(MOD_HPHEAL, 5); end;
gpl-3.0
10sa/Advanced-Nutscript
nutscript/plugins/broadcast/entities/entities/nut_bdcast.lua
1
1103
ENT.Type = "anim" ENT.PrintName = "방송 시스템" ENT.Author = "Chessnut" ENT.Spawnable = true ENT.AdminOnly = true ENT.Category = "Nutscript" ENT.PersistentSave = false; if (SERVER) then function ENT:Initialize() self:SetModel("models/props_lab/citizenradio.mdl") self:PhysicsInit(SOLID_VPHYSICS) self:SetMoveType(MOVETYPE_VPHYSICS) self:SetNetVar("active", false) self:SetUseType(SIMPLE_USE) self:SetColor( Color( 200, 200, 200, 255 ) ) local physicsObject = self:GetPhysicsObject() if (IsValid(physicsObject)) then physicsObject:Wake() end end function ENT:Use(activator) self:SetNetVar("active", !self:GetNetVar("active", false)) end else local GLOW_MATERIAL = Material("sprites/glow04_noz.vmt") local COLOR_ACTIVE = Color(0, 255, 0) local COLOR_INACTIVE = Color(255, 0, 0) function ENT:Draw() self:DrawModel() local position = self:GetPos() + self:GetForward() * 10 + self:GetUp() * 11 + self:GetRight() * 9.5 render.SetMaterial(GLOW_MATERIAL) render.DrawSprite(position, 14, 14, self:GetNetVar("active") and COLOR_ACTIVE or COLOR_INACTIVE) end end
mit
sugiartocokrowibowo/Algorithm-Implementations
Fibonacci_series/Lua/Yonaba/fib.lua
26
1110
-- Fibonacci series implementation -- See: http://en.wikipedia.org/wiki/Fibonacci_number -- Implementation note: -- With respect to Lua's array numbering, with starts at 1, -- the following assumes that, given a function F which returns -- the i-th term in a Fibonacci series, -- F(0) is undefined -- F(1) = 1 -- F(2) = 1 -- F(n) = F(n-1) + F(n-2), given any n > 2 -- Custom memoization function local function memoize(f) local _cache = {} return function (v) local _result = _cache[v] if not _result then _cache[v] = f(v) end return _cache[v] end end -- Recursive evaluation of fibonacci series -- n: the i-th Fibonacci number local function fib(n) if n > 0 and n <= 2 then return 1 end return fib(n-1) + fib(n-2) end -- Iterator for Fibonacci series -- usage: -- for count, value in fib_iter(limit) do ... end local function fib_iter(n) assert(n > 0, 'Expected n >= 0!') return coroutine.wrap(function() local a, b, k = 0, 1, 0 while k < n do a, b = b, a+b k = k + 1 coroutine.yield(k, a) end end) end return { fib = memoize(fib), fib_iter = fib_iter }
mit
simonhaines/vitamink
src/types/vector.lua
1
5468
-- Persistent vectors, modelled on Clojurescript vectors require("table") require("bit32") local function clone(array) -- 5.2 compatable -- Returns a copy of an array return table.pack(table.unpack(array)) end local function tailoffset(vector) -- Returns the offset (0-indexed) of the start of the tail node if vector.count < 32 then return 0 -- short-circuit the common case else return bit32.replace(vector.count - 1, 0, 0, 5) end end local function newpath(level, node) -- Creates a new node path to the root node if level == 0 then return node else return newpath(level - 5, {node}) end end local function pushtail(vector, level, parent, tail) -- Pushes the current tail into the vector and creates a new tail local node = clone(parent) local index = bit32.band(bit32.rshift(vector.count - 1, level), 0x1F) + 1 if level == 5 then node[index] = tail return node else local child = parent[index] if child == nil then node[index] = newpath(level - 5, tail) return node else node[index] = pushtail(vector, level - 5, child, tail) return node end end end local function findnode(vector, index) -- Finds the node containing the item at the index local function loop(node, level) if level > 0 then return loop(node[bit32.band(bit32.rshift(index - 1, level), 0x1F) + 1], level - 5) else return node end end if index > tailoffset(vector) then return vector.tail else return loop(vector.root, vector.shift) end end local function set(vector, level, node, index, value) -- Sets the value at the index returning a new vector local result = clone(node) if level == 0 then result[bit32.band(index - 1, 0x1F) + 1] = value return result else local subindex = bit32.band(bit32.rshift(index - 1, level), 0x1F) + 1 result[subindex] = set(vector, level - 5, node[subindex], index, value) return result end end local function poptail(vector, level, node) -- Sets the tail node to the previous node local subindex = bit32.band(bit32.rshift(vector.count - 2, level), 0x1F) + 1 if level > 5 then local newchild = poptail(vector, level - 5, node[subindex]) if newchild == nil and subindex == 1 then return nil else local result = clone(node) result[subindex] = newchild return result end elseif subindex == 1 then return nil else local result = clone(node) result[subindex] = nil return result end end -- Forward declarations local emptyvector local vector local vectormetatable = { tostring = function(self) return "<vector> " .. tostring(self.root) end, peek = function(self) if self.count > 0 then return self:get(self.count) else return nil end end, push = function(self, o) if (self.count - tailoffset(self)) < 32 then local newtail = clone(self.tail) table.insert(newtail, o) return vector(self.count + 1, self.shift, self.root, newtail) else local overflow = bit32.rshift(self.count, 5) > bit32.lshift(1, self.shift) local newshift, newroot if overflow then newshift = self.shift + 5 newroot = {self.root, newpath(self.shift, self.tail)} else newshift = self.shift newroot = pushtail(self, self.shift, self.root, self.tail) end return vector(self.count + 1, newshift, newroot, {o}) end end, pop = function(self) if self.count == 0 then error "Can't pop an empty vector" elseif self.count == 1 then return emptyvector elseif 1 < (self.count - tailoffset(self)) then local newtail = clone(self.tail) table.remove(newtail) return vector(self.count - 1, self.shift, self.root, newtail) else local newtail = findnode(self, self.count - 2) local newroot = poptail(self, self.shift, self.root) if newroot == nil then newroot = {} end if (5 < self.shift) and (newroot[2] == nil) then return vector(self.count - 1, self.shift - 5, newroot[1], newtail) else return vector(self.count - 1, self.shift, newroot, newtail) end end end, get = function(self, index) return findnode(self, index)[bit32.band(index - 1, 0x1F) + 1] end, set = function(self, index, value) if (index > 0) and (index <= self.count) then if tailoffset(self) < index then local newtail = clone(self.tail) newtail[bit32.band(index - 1, 0x1F) + 1] = value return vector(self.count, self.shift, self.root, newtail) else return vector(self.count, self.shift, set(self, self.shift, self.root, index, value), self.tail) end elseif index == (self.count + 1) then return self:push(value) else error("Index " .. index .. " out of bounds: [0," .. self.count .. "]") end end, __len = function(self) return self.count end, __index = function(self, index) if type(index) == "number" then return self:get(index) else return getmetatable(self)[index] end end, __newindex = function(self, index, value) error("Cannot assign to vector, use vector:set(index, value)") end } vector = function(count, shift, root, tail) return setmetatable({count = count, shift = shift, root = root, tail = tail}, vectormetatable) end emptyvector = vector(0, 5, {}, {}) return emptyvector
mit
Ombridride/minetest-minetestforfun-server
mods/homedecor_modpack/homedecor/furniture_medieval.lua
9
3237
local S = homedecor.gettext homedecor.register("bars", { description = S("Bars"), tiles = { "homedecor_generic_metal_black.png^[transformR270" }, node_box = { type = "fixed", fixed = { { -0.5, -0.50, -0.10, -0.4, 0.50, 0.10 }, { -0.1, -0.50, -0.10, 0.1, 0.50, 0.10 }, { 0.4, -0.50, -0.10, 0.5, 0.50, 0.10 }, { -0.5, -0.50, -0.05, 0.5, -0.45, 0.05 }, { -0.5, 0.45, -0.05, 0.5, 0.50, 0.05 }, }, }, selection_box = { type = "fixed", fixed = { -0.5, -0.5, -0.1, 0.5, 0.5, 0.1 }, }, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) --L Binding Bars homedecor.register("L_binding_bars", { description = S("Binding Bars"), tiles = { "homedecor_generic_metal_black.png^[transformR270" }, node_box = { type = "fixed", fixed = { { -0.10, -0.50, -0.50, 0.10, 0.50, -0.40 }, { -0.15, -0.50, -0.15, 0.15, 0.50, 0.15 }, { 0.40, -0.50, -0.10, 0.50, 0.50, 0.10 }, { 0.00, -0.50, -0.05, 0.50, -0.45, 0.05 }, { -0.05, -0.50, -0.50, 0.05, -0.45, 0.00 }, { 0.00, 0.45, -0.05, 0.50, 0.50, 0.05 }, { -0.05, 0.45, -0.50, 0.05, 0.50, 0.00 }, }, }, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) local chain_cbox = { type = "fixed", fixed = {-1/2, -1/2, 1/4, 1/2, 1/2, 1/2}, } homedecor.register("chains", { description = S("Chains"), mesh = "forniture_chains.obj", tiles = { "homedecor_generic_metal_black.png" }, inventory_image="forniture_chains_inv.png", selection_box = chain_cbox, walkable = false, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) homedecor.register("torch_wall", { description = S("Wall Torch"), mesh = "forniture_torch.obj", tiles = { { name="forniture_torch_flame.png", animation={ type="vertical_frames", aspect_w=40, aspect_h=40, length=1.0, }, }, "homedecor_generic_metal_black.png", "homedecor_generic_metal_black.png^[brighten", "forniture_coal.png", }, inventory_image="forniture_torch_inv.png", walkable = false, light_source = 14, selection_box = { type = "fixed", fixed = { -0.15, -0.45, 0.15, 0.15,0.35, 0.5 }, }, groups = {cracky=3}, }) local wl_cbox = { type = "fixed", fixed = { -0.2, -0.5, 0, 0.2, 0.5, 0.5 }, } homedecor.register("wall_lamp", { description = S("Wall Lamp"), mesh = "homedecor_wall_lamp.obj", tiles = {"homedecor_generic_metal_black.png^[brighten", "homedecor_generic_wood_luxury.png^[colorize:#000000:30", "homedecor_light.png", "homedecor_generic_metal_wrought_iron.png"}, use_texture_alpha = true, inventory_image = "homedecor_wall_lamp_inv.png", groups = {snappy=3}, light_source = 11, selection_box = wl_cbox, walkable = false }) minetest.register_alias("3dforniture:bars", "homedecor:bars") minetest.register_alias("3dforniture:L_binding_bars", "homedecor:L_binding_bars") minetest.register_alias("3dforniture:chains", "homedecor:chains") minetest.register_alias("3dforniture:torch_wall", "homedecor:torch_wall") minetest.register_alias('bars', 'homedecor:bars') minetest.register_alias('binding_bars', 'homedecor:L_binding_bars') minetest.register_alias('chains', 'homedecor:chains') minetest.register_alias('torch_wall', 'homedecor:torch_wall')
unlicense
myth384/AdiButtonAuras
rules/Priest.lua
1
3360
--[[ AdiButtonAuras - Display auras on action buttons. Copyright 2013-2014 Adirelle (adirelle@gmail.com) All rights reserved. This file is part of AdiButtonAuras. AdiButtonAuras is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. AdiButtonAuras is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with AdiButtonAuras. If not, see <http://www.gnu.org/licenses/>. --]] local _, addon = ... if not addon.isClass("PRIEST") then return end AdiButtonAuras:RegisterRules(function() Debug('Adding priest rules') return { ImportPlayerSpells { -- Import all spells for ... "PRIEST", -- ... but ... 17, -- Power Word: Shield 81661, -- Evangelism }, ShowPower { { 2944, -- Devouring Plague 64044, -- Psychic Horror }, "SHADOW_ORBS", }, Configure { "PWShield", L["Show Power Word: Shield or Weakened Soul on targeted ally."], 17, -- Power Word: Shield "ally", "UNIT_AURA", (function() local hasPWShield = BuildAuraHandler_Single("HELPFUL", "good", "ally", 17) local hasWeakenedSoul = BuildAuraHandler_Single("HARMFUL", "bad", "ally", 6788) return function(units, model) return hasPWShield(units, model) or hasWeakenedSoul(units, model) end end)(), }, ShowStacks { 81700, -- on Archangel 81661, -- show the stacks of Evangelism (buff) 5, -- number of max stacks "player", -- unit to track the buff on nil, -- no handler (else it will get a hint) nil, -- no highlight (the default ui highlights it) 81662, -- provider spell -> Evangelism (passive) }, ShowStacks { { 596, -- Prayer of Healing 2060, -- Heal 155245, -- Clarity of Purpose }, 63735, -- Serendipity (buff) 2, -- Max two stacks "player", 2, -- Hint at 2 stacks "hint", 63733, -- Serendipity (passive) }, ShowStacks { 33076, -- Prayer of Mending 155362, -- Word of Mending (buff) 10, -- Max 10 stacks }, } end) -- GLOBALS: AddRuleFor BuffAliases BuildAuraHandler_FirstOf BuildAuraHandler_Longest -- GLOBALS: BuildAuraHandler_Single BuildDesc BuildKey Configure DebuffAliases Debug -- GLOBALS: DescribeAllSpells DescribeAllTokens DescribeFilter DescribeHighlight -- GLOBALS: DescribeLPSSource GetComboPoints GetEclipseDirection GetNumGroupMembers -- GLOBALS: GetShapeshiftFormID GetSpellBonusHealing GetSpellInfo GetTime -- GLOBALS: GetTotemInfo HasPetSpells ImportPlayerSpells L LongestDebuffOf -- GLOBALS: PLAYER_CLASS PassiveModifier PetBuffs SelfBuffAliases SelfBuffs -- GLOBALS: SharedSimpleBuffs SharedSimpleDebuffs ShowPower SimpleBuffs -- GLOBALS: SimpleDebuffs UnitCanAttack UnitCastingInfo UnitChannelInfo UnitClass -- GLOBALS: UnitHealth UnitHealthMax UnitIsDeadOrGhost UnitIsPlayer UnitPower -- GLOBALS: UnitPowerMax UnitStagger bit ceil floor format ipairs math min pairs -- GLOBALS: print select string table tinsert GetPlayerBuff ShowStacks
gpl-3.0
LiberatorUSA/GUCEF
plugins/CORE/codecspluginSTBRUMMEHASH/premake4.lua
12
2365
-------------------------------------------------------------------- -- This file was automatically generated by ProjectGenerator -- which is tooling part the build system designed for GUCEF -- (Galaxy Unlimited Framework) -- For the latest info, see http://www.VanvelzenSoftware.com/ -- -- The contents of this file are placed in the public domain. Feel -- free to make use of it in any way you like. -------------------------------------------------------------------- -- -- Configuration for module: vfspluginZIP project( "vfspluginZIP" ) configuration( {} ) location( os.getenv( "PM4OUTPUTDIR" ) ) configuration( {} ) targetdir( os.getenv( "PM4TARGETDIR" ) ) configuration( {} ) language( "C++" ) configuration( {} ) kind( "SharedLib" ) configuration( {} ) links( { "gucefCORE", "gucefMT", "gucefVFS", "zziplib" } ) links( { "gucefCORE", "gucefMT", "gucefVFS", "zziplib" } ) configuration( {} ) defines( { "GUCEF_VFSPLUGIN_ZIP_BUILD_MODULE", "ZZIP_HAVE_STDINT_H" } ) links( { "z" } ) configuration( { LINUX } ) links( { "zlib" } ) links( { "zlib" } ) configuration( { WIN32 } ) links( { "zlib" } ) links( { "zlib" } ) configuration( { WIN64 } ) links( { "zlib" } ) links( { "zlib" } ) configuration( {} ) vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } } files( { "include/vfspluginZIP.h", "include/vfspluginZIP_config.h", "include/vfspluginZIP_CZIPArchive.h", "include/vfspluginZIP_CZipIOAccess.h", "include/vfspluginZIP_macros.h" } ) configuration( {} ) vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } } files( { "src/vfspluginZIP.cpp", "src/vfspluginZIP_CZIPArchive.cpp", "src/vfspluginZIP_CZipIOAccess.cpp" } ) configuration( {} ) includedirs( { "../../../common/include", "../../../dependencies/zziplib", "../../../dependencies/zziplib/zzip", "../../../gucefCORE/include", "../../../gucefMT/include", "../../../gucefVFS/include", "include" } ) configuration( { "ANDROID" } ) includedirs( { "../../../gucefCORE/include/android" } ) configuration( { "LINUX" } ) includedirs( { "../../../dependencies/zlib", "../../../gucefCORE/include/linux" } ) configuration( { "WIN32" } ) includedirs( { "../../../dependencies/zlib", "../../../gucefCORE/include/mswin" } ) configuration( { "WIN64" } ) includedirs( { "../../../dependencies/zlib", "../../../gucefCORE/include/mswin" } )
apache-2.0
jshackley/darkstar
scripts/globals/effects/healing.lua
4
1837
----------------------------------- -- -- EFFECT_HEALING -- -- Activated through the /heal command ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:setAnimation(33); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) local healtime = effect:getTickCount(); if (healtime > 1) then -- curse II also known as "zombie" if (not(target:hasStatusEffect(EFFECT_DISEASE)) and target:hasStatusEffect(EFFECT_PLAGUE) == false and target:hasStatusEffect(EFFECT_CURSE_II) == false) then local healHP = 0; if (target:getContinentID() == 1 and target:hasStatusEffect(EFFECT_SIGNET)) then healHP = 10+(3*math.floor(target:getMainLvl()/10))+(healtime-2)*(1+math.floor(target:getMaxHP()/300))+(target:getMod(MOD_HPHEAL)); else target:setTP(target:getTP()-10); healHP = 10+(healtime-2)+(target:getMod(MOD_HPHEAL)); end target:addHP(healHP); target:updateEnmityFromCure(target, healHP); -- Each rank of Clear Mind provides +3 hMP (via MOD_MPHEAL) -- Each tic of healing should be +1mp more than the last -- Clear Mind III increases this to +2, and Clear Mind V to +3 (via MOD_CLEAR_MIND) target:addMP(12+((healtime-2) * (1+target:getMod(MOD_CLEAR_MIND)))+(target:getMod(MOD_MPHEAL))); end end end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:setAnimation(0); target:delStatusEffect(EFFECT_LEAVEGAME); end;
gpl-3.0
jshackley/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Talwahn.lua
34
1032
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Talwahn -- 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(0x0290); 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
Victek/wrt1900ac-aa
veriksystems/luci-0.11/applications/luci-qos/luasrc/model/cbi/qos/qos.lua
6
2669
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id: qos.lua 9558 2012-12-18 13:58:22Z jow $ ]]-- local wa = require "luci.tools.webadmin" local fs = require "nixio.fs" m = Map("qos", translate("Quality of Service"), translate("With <abbr title=\"Quality of Service\">QoS</abbr> you " .. "can prioritize network traffic selected by addresses, " .. "ports or services.")) s = m:section(TypedSection, "interface", translate("Interfaces")) s.addremove = true s.anonymous = false e = s:option(Flag, "enabled", translate("Enable")) e.rmempty = false c = s:option(ListValue, "classgroup", translate("Classification group")) c:value("Default", translate("default")) c.default = "Default" s:option(Flag, "overhead", translate("Calculate overhead")) s:option(Flag, "halfduplex", translate("Half-duplex")) dl = s:option(Value, "download", translate("Download speed (kbit/s)")) dl.datatype = "and(uinteger,min(1))" ul = s:option(Value, "upload", translate("Upload speed (kbit/s)")) ul.datatype = "and(uinteger,min(1))" s = m:section(TypedSection, "classify", translate("Classification Rules")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true s.sortable = true t = s:option(ListValue, "target", translate("Target")) t:value("Priority", translate("priority")) t:value("Express", translate("express")) t:value("Normal", translate("normal")) t:value("Bulk", translate("low")) t.default = "Normal" srch = s:option(Value, "srchost", translate("Source host")) srch.rmempty = true srch:value("", translate("all")) wa.cbi_add_knownips(srch) dsth = s:option(Value, "dsthost", translate("Destination host")) dsth.rmempty = true dsth:value("", translate("all")) wa.cbi_add_knownips(dsth) l7 = s:option(ListValue, "layer7", translate("Service")) l7.rmempty = true l7:value("", translate("all")) local pats = io.popen("find /etc/l7-protocols/ -type f -name '*.pat'") if pats then local l while true do l = pats:read("*l") if not l then break end l = l:match("([^/]+)%.pat$") if l then l7:value(l) end end pats:close() end p = s:option(Value, "proto", translate("Protocol")) p:value("", translate("all")) p:value("tcp", "TCP") p:value("udp", "UDP") p:value("icmp", "ICMP") p.rmempty = true ports = s:option(Value, "ports", translate("Ports")) ports.rmempty = true ports:value("", translate("all")) bytes = s:option(Value, "connbytes", translate("Number of bytes")) return m
gpl-2.0
jshackley/darkstar
scripts/zones/LaLoff_Amphitheater/mobs/Ark_Angel_HM.lua
1
1628
----------------------------------- -- Area: LaLoff Amphitheater -- MOB: Ark Angel HM ----------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; ----------------------------------- require("scripts/zones/LaLoff_Amphitheater/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 50); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local mobid = mob:getID(); for member = mobid, mobid+7 do if (GetMobAction(member) == 16) then GetMobByID(member):updateEnmity(target); end end local hp = math.random(1,60); mob:setLocalVar("Mijin", hp); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local battletime = mob:getBattleTime(); local mstime = mob:getLocalVar("Mighty"); local mghp = mob:getLocalVar("Mijin"); if (battletime > mstime + 150) then mob:useMobAbility(432); mob:setLocalVar("Mighty", battletime); elseif (mob:getHPP() < mghp) then mob:useMobAbility(475); mob:setLocalVar("Mijin", 0); end end; ----------------------------------- -- onMobDeath Action ----------------------------------- function onMobDeath(mob,killer,ally) end;
gpl-3.0
Th2Evil/SuperPlus
libs/feedparser.lua
543
11955
local LOM = assert(require("lxp.lom"), "LuaExpat doesn't seem to be installed. feedparser kind of needs it to work...") local XMLElement = (loadfile "./libs/XMLElement.lua")() local dateparser = (loadfile "./libs/dateparser.lua")() local URL = (loadfile "./libs/url.lua")() local tinsert, tremove, tconcat = table.insert, table.remove, table.concat local pairs, ipairs = pairs, ipairs --- feedparser, similar to the Universal Feed Parser for python, but a good deal weaker. -- see http://feedparser.org for details about the Universal Feed Parser local feedparser= { _DESCRIPTION = "RSS and Atom feed parser", _VERSION = "feedparser 0.71" } local blanky = XMLElement.new() --useful in a whole bunch of places local function resolve(url, base_url) return URL.absolute(base_url, url) end local function rebase(el, base_uri) local xml_base = el:getAttr('xml:base') if not xml_base then return base_uri end return resolve(xml_base, base_uri) end local function parse_entries(entries_el, format_str, base) local entries = {} for i, entry_el in ipairs(entries_el) do local entry = {enclosures={}, links={}, contributors={}} local entry_base = rebase(entry_el, base) for i, el in ipairs(entry_el:getChildren('*')) do local tag = el:getTag() local el_base = rebase(el, entry_base) --title if tag == 'title' or tag == 'dc:title' or tag =='rdf:title' then --'dc:title' doesn't occur in atom feeds, but whatever. entry.title=el:getText() --link(s) elseif format_str == 'rss' and tag=='link' then entry.link=resolve(el:getText(), el_base) tinsert(entry.links, {href=entry.link}) elseif (format_str=='atom' and tag == 'link') or (format_str == 'rss' and tag=='atom:link') then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) --uri end tinsert(entry.links, link) if link.rel=='enclosure' then tinsert(entry.enclosures, { href=link.href, length=el:getAttr('length'), type=el:getAttr('type') }) end --rss enclosures elseif format_str == 'rss' and tag=='enclosure' then tinsert(entry.enclosures, { url=el:getAttr('url'), length=el:getAttr('length'), type=el:getAttr('type') }) --summary elseif (format_str=='atom' and tag=='summary') or (format_str=='rss' and(tag=='description' or tag=='dc:description' or tag=='rdf:description')) then entry.summary=el:getText() --TODO: summary_detail --content elseif (format_str=='atom' and tag=='content') or (format_str=='rss' and (tag=='body' or tag=='xhtml:body' or tag == 'fullitem' or tag=='content:encoded')) then entry.content=el:getText() --TODO: content_detail --published elseif (format_str == 'atom' and (tag=='published' or tag=='issued')) or (format_str == 'rss' and (tag=='dcterms:issued' or tag=='atom:published' or tag=='atom:issued')) then entry.published = el:getText() entry.published_parsed=dateparser.parse(entry.published) --updated elseif (format_str=='atom' and (tag=='updated' or tag=='modified')) or (format_str=='rss' and (tag=='dc:date' or tag=='pubDate' or tag=='dcterms:modified')) then entry.updated=el:getText() entry.updated_parsed=dateparser.parse(entry.updated) elseif tag=='created' or tag=='atom:created' or tag=='dcterms:created' then entry.created=el:getText() entry.created_parsed=dateparser.parse(entry.created) --id elseif (format_str =='atom' and tag=='id') or (format_str=='rss' and tag=='guid') then entry.id=resolve(el:getText(), el_base) -- this is a uri, right?... --author elseif format_str=='rss' and (tag=='author' or tag=='dc:creator') then --author tag should give the author's email. should I respect this? entry.author=(el:getChild('name') or el):getText() entry.author_detail={ name=entry.author } elseif format_str=='atom' and tag=='author' then entry.author=(el:getChild('name') or el):getText() entry.author_detail = { name=entry.author, email=(el:getChild('email') or blanky):getText() } local author_url = (el:getChild('url') or blanky):getText() if author_url and author_url ~= "" then entry.author_detail.href=resolve(author_url, rebase(el:getChild('url'), el_base)) end elseif tag=='category' or tag=='dc:subject' then --todo elseif tag=='source' then --todo end end --wrap up rss guid if format_str == 'rss' and (not entry.id) and entry_el:getAttr('rdf:about') then entry.id=resolve(entry_el:getAttr('rdf:about'), entry_base) --uri end --wrap up entry.link for i, link in pairs(entry.links) do if link.rel=="alternate" or (not link.rel) or link.rel=="" then entry.link=link.href --already resolved. break end end if not entry.link and format_str=='rss' then entry.link=entry.id end tinsert(entries, entry) end return entries end local function atom_person_construct(person_el, base_uri) local dude ={ name= (person_el:getChild('name') or blanky):getText(), email=(person_el:getChild('email') or blanky):getText() } local url_el = person_el:getChild('url') if url_el then dude.href=resolve(url_el:getText(), rebase(url_el, base_uri)) end return dude end local function parse_atom(root, base_uri) local res = {} local feed = { links = {}, contributors={}, language = root:getAttr('lang') or root:getAttr('xml:lang') } local root_base = rebase(root, base_uri) res.feed=feed res.format='atom' local version=(root:getAttr('version') or ''):lower() if version=="1.0" or root:getAttr('xmlns')=='http://www.w3.org/2005/Atom' then res.version='atom10' elseif version=="0.3" then res.version='atom03' else res.version='atom' end for i, el in ipairs(root:getChildren('*')) do local tag = el:getTag() local el_base=rebase(el, root_base) if tag == 'title' or tag == 'dc:title' or tag == 'atom10:title' or tag == 'atom03:title' then feed.title=el:getText() --sanitize! --todo: feed.title_detail --link stuff elseif tag=='link' then local link = {} for i, attr in ipairs{'rel','type', 'href','title'} do link[attr]= (attr=='href') and resolve(el:getAttr(attr), el_base) or el:getAttr(attr) end tinsert(feed.links, link) --subtitle elseif tag == 'subtitle' then feed.subtitle=el:getText() --sanitize! elseif not feed.subtitle and (tag == 'tagline' or tag =='atom03:tagline' or tag=='dc:description') then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() --sanitize! elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info elseif tag == 'info' then --whatever, nobody cared, anyway. feed.info = el:getText() --id elseif tag=='id' then feed.id=resolve(el:getText(), el_base) --this is a url, right?.,, --updated elseif tag == 'updated' or tag == 'dc:date' or tag == 'modified' or tag=='rss:pubDate' then feed.updated = el:getText() feed.updated_parsed=dateparser.parse(feed.updated) --author elseif tag=='author' or tag=='atom:author' then feed.author_detail=atom_person_construct(el, el_base) feed.author=feed.author_detail.name --contributors elseif tag=='contributor' or tag=='atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --icon elseif tag=='icon' then feed.icon=resolve(el:getText(), el_base) --logo elseif tag=='logo' then feed.logo=resolve(el:getText(), el_base) --language elseif tag=='language' or tag=='dc:language' then feed.language=feed.language or el:getText() --licence end end --feed.link (already resolved) for i, link in pairs(feed.links) do if link.rel=='alternate' or not link.rel or link.rel=='' then feed.link=link.href break end end res.entries=parse_entries(root:getChildren('entry'),'atom', root_base) return res end local function parse_rss(root, base_uri) local channel = root:getChild({'channel', 'rdf:channel'}) local channel_base = rebase(channel, base_uri) if not channel then return nil, "can't parse that." end local feed = {links = {}, contributors={}} local res = { feed=feed, format='rss', entries={} } --this isn't quite right at all. if root:getTag():lower()=='rdf:rdf' then res.version='rss10' else res.version='rss20' end for i, el in ipairs(channel:getChildren('*')) do local el_base=rebase(el, channel_base) local tag = el:getTag() if tag=='link' then feed.link=resolve(el:getText(), el_base) tinsert(feed.links, {href=feed.link}) --title elseif tag == 'title' or tag == 'dc:title' then feed.title=el:getText() --sanitize! --subtitle elseif tag == 'description' or tag =='dc:description' or tag=='itunes:subtitle' then feed.subtitle=el:getText() --sanitize! --rights elseif tag == 'copyright' or tag == 'dc:rights' then feed.rights=el:getText() --sanitize! --generator elseif tag == 'generator' then feed.generator=el:getText() elseif tag == 'admin:generatorAgent' then feed.generator = feed.generator or el:getAttr('rdf:resource') --info (nobody cares...) elseif tag == 'feedburner:browserFriendly' then feed.info = el:getText() --updated elseif tag == 'pubDate' or tag == 'dc:date' or tag == 'dcterms:modified' then feed.updated = el:getText() feed.updated_parsed = dateparser.parse(feed.updated) --author elseif tag=='managingEditor' or tag =='dc:creator' or tag=='itunes:author' or tag =='dc:creator' or tag=='dc:author' then feed.author=tconcat(el:getChildren('text()')) feed.author_details={name=feed.author} elseif tag=='atom:author' then feed.author_details = atom_person_construct(el, el_base) feed.author = feed.author_details.name --contributors elseif tag == 'dc:contributor' then tinsert(feed.contributors, {name=el:getText()}) elseif tag == 'atom:contributor' then tinsert(feed.contributors, atom_person_construct(el, el_base)) --image elseif tag=='image' or tag=='rdf:image' then feed.image={ title=el:getChild('title'):getText(), link=(el:getChild('link') or blanky):getText(), width=(el:getChild('width') or blanky):getText(), height=(el:getChild('height') or blanky):getText() } local url_el = el:getChild('url') if url_el then feed.image.href = resolve(url_el:getText(), rebase(url_el, el_base)) end --language elseif tag=='language' or tag=='dc:language' then feed.language=el:getText() --licence --publisher --tags end end res.entries=parse_entries(channel:getChildren('item'),'rss', channel_base) return res end --- parse feed xml -- @param xml_string feed xml, as a string -- @param base_url (optional) source url of the feed. useful when resolving relative links found in feed contents -- @return table with parsed feed info, or nil, error_message on error. -- the format of the returned table is much like that on http://feedparser.org, with the major difference that -- dates are parsed into unixtime. Most other fields are very much the same. function feedparser.parse(xml_string, base_url) local lom, err = LOM.parse(xml_string) if not lom then return nil, "couldn't parse xml. lxp says: " .. err or "nothing" end local rootElement = XMLElement.new(lom) local root_tag = rootElement:getTag():lower() if root_tag=='rdf:rdf' or root_tag=='rss' then return parse_rss(rootElement, base_url) elseif root_tag=='feed' then return parse_atom(rootElement, base_url) else return nil, "unknown feed format" end end --for the sake of backwards-compatibility, feedparser will export a global reference for lua < 5.3 if _VERSION:sub(-3) < "5.3" then _G.feedparser=feedparser end return feedparser
gpl-2.0
jshackley/darkstar
scripts/zones/Behemoths_Dominion/mobs/Behemoth.lua
7
1510
----------------------------------- -- Area: Behemoth's Dominion -- HNM: Behemoth ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) ally:addTitle(BEHEMOTHS_BANE); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local Behemoth = mob:getID(); local King_Behemoth = mob:getID()+1; local ToD = GetServerVariable("[POP]King_Behemoth"); local kills = GetServerVariable("[PH]King_Behemoth"); local popNow = (math.random(1,5) == 3 or kills > 6); if (LandKingSystem_HQ ~= 1 and ToD <= os.time(t) and popNow == true) then -- 0 = timed spawn, 1 = force pop only, 2 = BOTH if (LandKingSystem_NQ == 0) then DeterMob(Behemoth, true); end DeterMob(King_Behemoth, false); UpdateNMSpawnPoint(King_Behemoth); GetMobByID(King_Behemoth):setRespawnTime(math.random(75600,86400)); else if (LandKingSystem_NQ ~= 1) then UpdateNMSpawnPoint(Behemoth); mob:setRespawnTime(math.random(75600,86400)); SetServerVariable("[PH]King_Behemoth", kills + 1); end end end;
gpl-3.0
studio666/cjdns
contrib/lua/cjdns/admin.lua
42
2939
-- Cjdns admin module for Lua -- Written by Philip Horger common = require 'cjdns/common' AdminInterface = {} AdminInterface.__index = AdminInterface common.AdminInterface = AdminInterface function AdminInterface.new(properties) properties = properties or {} properties.host = properties.host or "127.0.0.1" properties.port = properties.port or 11234 properties.password = properties.password or nil properties.config = properties.config or common.ConfigFile.new("/etc/cjdroute.conf", false) properties.timeout = properties.timeout or 2 properties.util = common.UtilFunctions.new(properties) properties.router = common.RouterFunctions.new(properties) properties.udp = common.UDPInterface.new(properties) properties.perm = common.Permanence.new(properties) return setmetatable(properties, AdminInterface) end function AdminInterface:getIP() return socket.dns.toip(self.host) end function AdminInterface:send(object) local bencoded, err = bencode.encode(object) if err then return nil, err end local sock_obj = assert(socket.udp()) sock_obj:settimeout(self.timeout) local _, err = sock_obj:sendto(bencoded, assert(self:getIP()), self.port) if err then return nil, err end return sock_obj end function AdminInterface:recv(sock_obj) local retrieved, err = sock_obj:receive() if not retrieved then return nil, "ai:recv > " .. err end local bencoded, err = bencode.decode(retrieved) if bencoded then return bencoded else return nil, "ai:recv > " .. err end end function AdminInterface:call(request) local sock_obj, err = self:send(request) if err then return nil, "ai:call > " .. err end return self:recv(sock_obj) end function AdminInterface:getCookie() local cookie_response, err = self:call({ q = "cookie" }) if not cookie_response then return nil, "ai:getCookie > " .. err end return cookie_response.cookie end function AdminInterface:auth(request) local funcname = request.q local args = {} for k, v in pairs(request) do args[k] = v end -- Step 1: Get cookie local cookie, err = self:getCookie() if err then return nil, err end -- Step 2: Calculate hash1 (password + cookie) local plaintext1 = self.password .. cookie local hash1 = sha2.sha256hex(plaintext1) -- Step 3: Calculate hash2 (intermediate stage request) local request = { q = "auth", aq = funcname, args = args, hash = hash1, cookie = cookie } local plaintext2, err = bencode.encode(request) if err then return nil, err end local hash2 = sha2.sha256hex(plaintext2) -- Step 4: Update hash in request, then ship it out request.hash = hash2 return self:call(request) end
gpl-3.0
jshackley/darkstar
scripts/globals/items/walnut.lua
36
1072
----------------------------------------- -- ID: 5661 -- Item: Walnut -- Food Effect: 5Min, All Races ----------------------------------------- -- HP 30 ----------------------------------------- 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,300,5661); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30); end;
gpl-3.0
VincentGong/chess
cocos2d-x/cocos/scripting/lua-bindings/auto/api/Label.lua
3
10197
-------------------------------- -- @module Label -- @extend SpriteBatchNode,LabelProtocol -------------------------------- -- @function [parent=#Label] isClipMarginEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Label] enableShadow -- @param self -------------------------------- -- @function [parent=#Label] setDimensions -- @param self -- @param #unsigned int int -- @param #unsigned int int -------------------------------- -- @function [parent=#Label] getString -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Label] getHeight -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- @function [parent=#Label] disableEffect -- @param self -------------------------------- -- @function [parent=#Label] setTTFConfig -- @param self -- @param #cc._ttfConfig _ttfconfig -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Label] getTextColor -- @param self -- @return color4b_table#color4b_table ret (return value: color4b_table) -------------------------------- -- @function [parent=#Label] getCommonLineHeight -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Label] setWidth -- @param self -- @param #unsigned int int -------------------------------- -- @function [parent=#Label] getMaxLineWidth -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- @function [parent=#Label] getHorizontalAlignment -- @param self -- @return TextHAlignment#TextHAlignment ret (return value: cc.TextHAlignment) -------------------------------- -- @function [parent=#Label] setClipMarginEnabled -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Label] setString -- @param self -- @param #string str -------------------------------- -- @function [parent=#Label] setSystemFontName -- @param self -- @param #string str -------------------------------- -- @function [parent=#Label] setBMFontFilePath -- @param self -- @param #string str -- @param #cc.Vec2 vec2 -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Label] getFontAtlas -- @param self -- @return FontAtlas#FontAtlas ret (return value: cc.FontAtlas) -------------------------------- -- @function [parent=#Label] setSystemFontSize -- @param self -- @param #float float -------------------------------- -- @function [parent=#Label] updateContent -- @param self -------------------------------- -- @function [parent=#Label] getStringLength -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Label] setLineBreakWithoutSpace -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Label] getStringNumLines -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#Label] enableOutline -- @param self -- @param #color4b_table color4b -- @param #int int -------------------------------- -- overload function: setCharMap(cc.Texture2D, int, int, int) -- -- overload function: setCharMap(string, int, int, int) -- -- overload function: setCharMap(string) -- -- @function [parent=#Label] setCharMap -- @param self -- @param #string str -- @param #int int -- @param #int int -- @param #int int -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#Label] getDimensions -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Label] setMaxLineWidth -- @param self -- @param #unsigned int int -------------------------------- -- @function [parent=#Label] getSystemFontName -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Label] setVerticalAlignment -- @param self -- @param #cc.TextVAlignment textvalignment -------------------------------- -- @function [parent=#Label] getTTFConfig -- @param self -- @return _ttfConfig#_ttfConfig ret (return value: cc._ttfConfig) -------------------------------- -- @function [parent=#Label] getVerticalAlignment -- @param self -- @return TextVAlignment#TextVAlignment ret (return value: cc.TextVAlignment) -------------------------------- -- @function [parent=#Label] setTextColor -- @param self -- @param #color4b_table color4b -------------------------------- -- @function [parent=#Label] setHeight -- @param self -- @param #unsigned int int -------------------------------- -- @function [parent=#Label] getWidth -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- @function [parent=#Label] enableGlow -- @param self -- @param #color4b_table color4b -------------------------------- -- @function [parent=#Label] getLetter -- @param self -- @param #int int -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#Label] getSystemFontSize -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Label] getTextAlignment -- @param self -- @return TextHAlignment#TextHAlignment ret (return value: cc.TextHAlignment) -------------------------------- -- @function [parent=#Label] getBMFontFilePath -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Label] setHorizontalAlignment -- @param self -- @param #cc.TextHAlignment texthalignment -------------------------------- -- overload function: setAlignment(cc.TextHAlignment, cc.TextVAlignment) -- -- overload function: setAlignment(cc.TextHAlignment) -- -- @function [parent=#Label] setAlignment -- @param self -- @param #cc.TextHAlignment texthalignment -- @param #cc.TextVAlignment textvalignment -------------------------------- -- @function [parent=#Label] createWithBMFont -- @param self -- @param #string str -- @param #string str -- @param #cc.TextHAlignment texthalignment -- @param #int int -- @param #cc.Vec2 vec2 -- @return Label#Label ret (return value: cc.Label) -------------------------------- -- @function [parent=#Label] create -- @param self -- @return Label#Label ret (return value: cc.Label) -------------------------------- -- overload function: createWithCharMap(cc.Texture2D, int, int, int) -- -- overload function: createWithCharMap(string, int, int, int) -- -- overload function: createWithCharMap(string) -- -- @function [parent=#Label] createWithCharMap -- @param self -- @param #string str -- @param #int int -- @param #int int -- @param #int int -- @return Label#Label ret (retunr value: cc.Label) -------------------------------- -- @function [parent=#Label] createWithSystemFont -- @param self -- @param #string str -- @param #string str -- @param #float float -- @param #size_table size -- @param #cc.TextHAlignment texthalignment -- @param #cc.TextVAlignment textvalignment -- @return Label#Label ret (return value: cc.Label) -------------------------------- -- @function [parent=#Label] draw -- @param self -- @param #cc.Renderer renderer -- @param #cc.Mat4 mat4 -- @param #bool bool -------------------------------- -- @function [parent=#Label] addChild -- @param self -- @param #cc.Node node -- @param #int int -- @param #int int -------------------------------- -- @function [parent=#Label] setScaleY -- @param self -- @param #float float -------------------------------- -- @function [parent=#Label] setScaleX -- @param self -- @param #float float -------------------------------- -- @function [parent=#Label] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#Label] getScaleY -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Label] setBlendFunc -- @param self -- @param #cc.BlendFunc blendfunc -------------------------------- -- @function [parent=#Label] visit -- @param self -- @param #cc.Renderer renderer -- @param #cc.Mat4 mat4 -- @param #bool bool -------------------------------- -- @function [parent=#Label] getScaleX -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#Label] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#Label] setOpacityModifyRGB -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#Label] setScale -- @param self -- @param #float float -------------------------------- -- @function [parent=#Label] sortAllChildren -- @param self -------------------------------- -- @function [parent=#Label] updateDisplayedOpacity -- @param self -- @param #unsigned char char -------------------------------- -- @function [parent=#Label] getContentSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#Label] getBoundingBox -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- @function [parent=#Label] updateDisplayedColor -- @param self -- @param #color3b_table color3b return nil
mit
hockeychaos/Core-Scripts-1
CoreScriptsRoot/Modules/Server/ClientChat/DefaultClientChatModules/MessageCreatorModules/DefaultChatMessage.lua
2
4282
-- // FileName: DefaultChatMessage.lua -- // Written by: TheGamer101 -- // Description: Create a message label for a standard chat message. local clientChatModules = script.Parent.Parent local ChatSettings = require(clientChatModules:WaitForChild("ChatSettings")) local ChatConstants = require(clientChatModules:WaitForChild("ChatConstants")) local util = require(script.Parent:WaitForChild("Util")) function CreateMessageLabel(messageData, channelName) local fromSpeaker = messageData.FromSpeaker local message = messageData.Message local extraData = messageData.ExtraData or {} local useFont = extraData.Font or ChatSettings.DefaultFont local useTextSize = extraData.TextSize or ChatSettings.ChatWindowTextSize local useNameColor = extraData.NameColor or ChatSettings.DefaultNameColor local useChatColor = extraData.ChatColor or ChatSettings.DefaultMessageColor local useChannelColor = extraData.ChannelColor or useChatColor local tags = extraData.Tags or {} local formatUseName = string.format("[%s]:", fromSpeaker) local speakerNameSize = util:GetStringTextBounds(formatUseName, useFont, useTextSize) local numNeededSpaces = util:GetNumberOfSpaces(formatUseName, useFont, useTextSize) + 1 local BaseFrame, BaseMessage = util:CreateBaseMessage("", useFont, useTextSize, useChatColor) local NameButton = util:AddNameButtonToBaseMessage(BaseMessage, useNameColor, formatUseName, fromSpeaker) local ChannelButton = nil local guiObjectSpacing = UDim2.new(0, 0, 0, 0) if channelName ~= messageData.OriginalChannel then local formatChannelName = string.format("{%s}", messageData.OriginalChannel) ChannelButton = util:AddChannelButtonToBaseMessage(BaseMessage, useChannelColor, formatChannelName, messageData.OriginalChannel) guiObjectSpacing = UDim2.new(0, ChannelButton.Size.X.Offset + util:GetStringTextBounds(" ", useFont, useTextSize).X, 0, 0) numNeededSpaces = numNeededSpaces + util:GetNumberOfSpaces(formatChannelName, useFont, useTextSize) + 1 end local tagLabels = {} for i, tag in pairs(tags) do local tagColor = tag.TagColor or Color3.fromRGB(255, 0, 255) local tagText = tag.TagText or "???" local formatTagText = string.format("[%s] ", tagText) local label = util:AddTagLabelToBaseMessage(BaseMessage, tagColor, formatTagText) label.Position = guiObjectSpacing numNeededSpaces = numNeededSpaces + util:GetNumberOfSpaces(formatTagText, useFont, useTextSize) guiObjectSpacing = guiObjectSpacing + UDim2.new(0, label.Size.X.Offset, 0, 0) table.insert(tagLabels, label) end NameButton.Position = guiObjectSpacing local function UpdateTextFunction(messageObject) if messageData.IsFiltered then BaseMessage.Text = string.rep(" ", numNeededSpaces) .. messageObject.Message else BaseMessage.Text = string.rep(" ", numNeededSpaces) .. string.rep("_", messageObject.MessageLength) end end UpdateTextFunction(messageData) local function GetHeightFunction(xSize) return util:GetMessageHeight(BaseMessage, BaseFrame, xSize) end local FadeParmaters = {} FadeParmaters[NameButton] = { TextTransparency = {FadedIn = 0, FadedOut = 1}, TextStrokeTransparency = {FadedIn = 0.75, FadedOut = 1} } FadeParmaters[BaseMessage] = { TextTransparency = {FadedIn = 0, FadedOut = 1}, TextStrokeTransparency = {FadedIn = 0.75, FadedOut = 1} } for i, tagLabel in pairs(tagLabels) do local index = string.format("Tag%d", i) FadeParmaters[tagLabel] = { TextTransparency = {FadedIn = 0, FadedOut = 1}, TextStrokeTransparency = {FadedIn = 0.75, FadedOut = 1} } end if ChannelButton then FadeParmaters[ChannelButton] = { TextTransparency = {FadedIn = 0, FadedOut = 1}, TextStrokeTransparency = {FadedIn = 0.75, FadedOut = 1} } end local FadeInFunction, FadeOutFunction, UpdateAnimFunction = util:CreateFadeFunctions(FadeParmaters) return { [util.KEY_BASE_FRAME] = BaseFrame, [util.KEY_BASE_MESSAGE] = BaseMessage, [util.KEY_UPDATE_TEXT_FUNC] = UpdateTextFunction, [util.KEY_GET_HEIGHT] = GetHeightFunction, [util.KEY_FADE_IN] = FadeInFunction, [util.KEY_FADE_OUT] = FadeOutFunction, [util.KEY_UPDATE_ANIMATION] = UpdateAnimFunction } end return { [util.KEY_MESSAGE_TYPE] = ChatConstants.MessageTypeDefault, [util.KEY_CREATOR_FUNCTION] = CreateMessageLabel }
apache-2.0
jshackley/darkstar
scripts/globals/spells/bluemagic/chaotic_eye.lua
18
1455
----------------------------------------- -- Spell: Chaotic Eye -- Silences an enemy -- Spell cost: 13 MP -- Monster Type: Beasts -- Spell Type: Magical (Wind) -- Blue Magic Points: 2 -- Stat Bonus: AGI+1 -- Level: 32 -- Casting Time: 3 seconds -- Recast Time: 10 seconds -- Magic Bursts on: Detonation, Fragmentation, and Light -- Combos: Conserve MP ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_SILENCE; local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,typeEffect); local duration = 180 * resist; if (resist > 0.5) then -- Do it! if (target:isFacing(caster)) then if (target:addStatusEffect(typeEffect,1,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end; else spell:setMsg(75); end; else spell:setMsg(85); end; return typeEffect; end;
gpl-3.0
jshackley/darkstar
scripts/zones/Cloister_of_Frost/Zone.lua
32
1658
----------------------------------- -- -- Zone: Cloister_of_Frost (203) -- ----------------------------------- package.loaded["scripts/zones/Cloister_of_Frost/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Cloister_of_Frost/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(499.993,-1.696,523.343,194); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
jshackley/darkstar
scripts/zones/VeLugannon_Palace/mobs/Zipacna.lua
1
1801
----------------------------------- -- Area: VeLugannon Palace -- NPC: Zipacna ----------------------------------- local path = { -202, 0, 391, -209, 0, 387, -214, 0, 381, -238, 0, 380, -256, 4, 381, -261, 8, 400, -257, 12, 417, -240, 16, 420, -257, 12, 417, -261, 8, 400, -256, 4, 381, -238, 0, 380, -214, 0, 381, -209, 0, 387, -194, 0, 388, -179, 0, 379, -134, 0, 379, -115, 0, 417, -112, 0, 454, -105, 0, 460, -80, 0, 460, -65, 0, 459, -60, 0, 452, -59, 0, 420, 59, 0, 420, 60, 0, 429, 60, 0, 445, 62, 0, 456, 78, 0, 460, 108, 0, 458, 132, 0, 381, 185, 0, 380, 199, 0, 391, 218, 0, 380, 259, 4, 383, 258, 12, 418, 248, 14, 420, 219, 16, 420, 248, 14, 420, 258, 12, 418, 259, 4, 383, 218, 0, 380, 199, 0, 391, 185, 0, 380, 132, 0, 381, 108, 0, 458, 78, 0, 460, 62, 0, 456, 60, 0, 445, 60, 0, 429, 59, 0, 420, -59, 0, 420, -60, 0, 452, -65, 0, 459, -80, 0, 460, -105, 0, 460, -112, 0, 454, -115, 0, 417, -134, 0, 379, -179, 0, 379, -191, 0, 385, -195, 0, 396, -202, 0, 391, -209, 0, 387, -214, 0, 381, -238, 0, 380, -256, 4, 381, -261, 8, 400, -257, 12, 417, -240, 16, 420, -257, 12, 417, -261, 8, 400, -256, 4, 381, -238, 0, 380, -214, 0, 381, -209, 0, 387, -202, 0, 391, }; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; function onMobSpawn(mob) onMobRoam(mob); end; function onPath(mob) pathfind.patrol(mob, path, PATHFLAG_RUN); end; function onMobRoam(mob) -- move to start position if not moving if (mob:isFollowingPath() == false) then mob:pathThrough(pathfind.first(path), PATHFLAG_RUN); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) mob:setRespawnTime(math.random((10800),(14400))); -- respawn 3-4 hrs end;
gpl-3.0
jshackley/darkstar
scripts/zones/Port_Windurst/npcs/Martin.lua
19
1228
----------------------------------- -- Area: Port Windurst -- NPC: Martin -- Type: Standard NPC ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 4 do vHour = vHour - 6; end if ( vHour == -2) then vHour = 4; elseif ( vHour == -1) then vHour = 5; end local seconds = math.floor(2.4 * ((vHour * 60) + vMin)); player:startEvent( 0x0274, seconds, 0, 0, 0, 0, 0, 0, 0); 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
knipferrc/dotfiles
nvim/lua/user/project.lua
4
1835
local status_ok, project = pcall(require, "project_nvim") if not status_ok then return end project.setup({ ---@usage set to false to disable project.nvim. --- This is on by default since it's currently the expected behavior. active = true, on_config_done = nil, ---@usage set to true to disable setting the current-woriking directory --- Manual mode doesn't automatically change your root directory, so you have --- the option to manually do so using `:ProjectRoot` command. manual_mode = false, ---@usage Methods of detecting the root directory --- Allowed values: **"lsp"** uses the native neovim lsp --- **"pattern"** uses vim-rooter like glob pattern matching. Here --- order matters: if one is not detected, the other is used as fallback. You --- can also delete or rearangne the detection methods. -- detection_methods = { "lsp", "pattern" }, -- NOTE: lsp detection will get annoying with multiple langs in one project detection_methods = { "pattern" }, ---@usage patterns used to detect root dir, when **"pattern"** is in detection_methods patterns = { ".git", "_darcs", ".hg", ".bzr", ".svn", "Makefile", "package.json" }, ---@ Show hidden files in telescope when searching for files in a project show_hidden = false, ---@usage When set to false, you will get a message when project.nvim changes your directory. -- When set to false, you will get a message when project.nvim changes your directory. silent_chdir = true, ---@usage list of lsp client names to ignore when using **lsp** detection. eg: { "efm", ... } ignore_lsp = {}, ---@type string ---@usage path to store the project history for use in telescope datapath = vim.fn.stdpath("data"), }) local tele_status_ok, telescope = pcall(require, "telescope") if not tele_status_ok then return end telescope.load_extension('projects')
mit
jshackley/darkstar
scripts/globals/mobskills/Gusting_Gouge.lua
25
1025
--------------------------------------------- -- Gusting Gouge -- -- Description: Deals Wind damage in a threefold attack to targets in a fan-shaped area of effect. -- Type: Physical? -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Melee? -- Notes: Used only by Lamia equipped with a one-handed weapon. If they lost their weapon, they'll use Hysteric Barrage instead. --------------------------------------------- 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 = math.random(2, 3); local accmod = 1; local dmgmod = 1; 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); target:delHP(dmg); return dmg; end;
gpl-3.0
jshackley/darkstar
scripts/zones/Empyreal_Paradox/mobs/Promathia_2.lua
8
2578
----------------------------------- -- Area: Empyreal Paradox -- MOB: Promathia (phase 2) ----------------------------------- package.loaded["scripts/zones/Empyreal_Paradox/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Empyreal_Paradox/TextIDs"); require("scripts/globals/status"); require("scripts/globals/titles"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 50); mob:addMod(MOD_UFASTCAST,50); end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) local bcnmAllies = mob:getBattlefield():getAllies(); for i,v in pairs(bcnmAllies) do if (v:getName() == "Prishe") then if not v:getTarget() then v:entityAnimationPacket("prov"); v:showText(v, PRISHE_TEXT + 1); v:setLocalVar("ready", mob:getID()); end else v:addEnmity(mob,0,1); end end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) if (mob:AnimationSub() == 3 and not mob:hasStatusEffect(EFFECT_STUN)) then mob:AnimationSub(0); mob:stun(1500); elseif (mob:AnimationSub() == 2 and not mob:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then mob:AnimationSub(0); elseif (mob:AnimationSub() == 1 and not mob:hasStatusEffect(EFFECT_PHYSICAL_SHIELD)) then mob:AnimationSub(0); end local bcnmAllies = mob:getBattlefield():getAllies(); for i,v in pairs(bcnmAllies) do if not v:getTarget() then v:addEnmity(mob,0,1); end end end; ------------------------------------ -- onSpellPrecast ------------------------------------ function onSpellPrecast(mob, spell) if (spell:getID() == 218) then spell:setAoE(SPELLAOE_RADIAL); spell:setFlag(SPELLFLAG_HIT_ALL); spell:setRadius(30); spell:setAnimation(280); spell:setMPCost(1); elseif (spell:getID() == 219) then spell:setMPCost(1); end end; ------------------------------------ -- onMagicCastingCheck ------------------------------------ function onMagicCastingCheck(mob, target, spell) if math.random() > 0.75 then return 219; else return 218; end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, ally) end;
gpl-3.0
Keithenneu/Dota2-FullOverwrite
itemPurchase/generic.lua
1
23261
------------------------------------------------------------------------------- --- AUTHOR: Nostrademous, dralois --- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite ------------------------------------------------------------------------------- DEBUG = false local utils = require( GetScriptDirectory().."/utility" ) local items = require(GetScriptDirectory().."/itemPurchase/items" ) local gHeroVar = require( GetScriptDirectory().."/global_hero_data" ) local enemyData = require( GetScriptDirectory().."/enemy_data" ) --[[ The idea is that you get a list of starting items, utility items, core items and extension items. This class then decides which items to buy, considering what and how much damage the enemy mostly does, if we want offensive or defensive items and if we need anything else like consumables --]] ------------------------------------------------------------------------------- -- Helper Functions for accessing Global Hero Data ------------------------------------------------------------------------------- function setHeroVar(var, value) local bot = GetBot() gHeroVar.SetVar(bot:GetPlayerID(), var, value) end function getHeroVar(var) local bot = GetBot() return gHeroVar.GetVar(bot:GetPlayerID(), var) end ------------------------------------------------------------------------------- -- Declarations ------------------------------------------------------------------------------- BotsInit = require( "game/botsinit" ) local X = BotsInit.CreateGeneric() X.ItemsToBuyAsHardCarry = {} X.ItemsToBuyAsMid = {} X.ItemsToBuyAsOfflane = {} X.ItemsToBuyAsSupport = {} X.ItemsToBuyAsJungler = {} X.ItemsToBuyAsRoamer = {} X.PurchaseOrder = {} X.BoughtItems = {} X.StartingItems = {} X.UtilityItems = {} X.CoreItems = {} X.ExtensionItems = { OffensiveItems = {}, DefensiveItems = {} } X.SellItems = {} X.LastThink = -1000.0 X.LastSupportThink = -1000.0 X.LastExtensionThink = -1000.0 ------------------------------------------------------------------------------- -- Properties ------------------------------------------------------------------------------- function X:GetStartingItems() return self.StartingItems end function X:SetStartingItems(items) self.StartingItems = items end function X:GetUtilityItems() return self.UtilityItems end function X:SetUtilityItems(items) self.UtilityItems = items end function X:GetCoreItems() return self.CoreItems end function X:SetCoreItems(items) self.CoreItems = items end function X:GetExtensionItems() return self.ExtensionItems[1], self.ExtensionItems[2] end function X:SetExtensionItems(items) self.ExtensionItems = items end function X:GetSellItems() return self.SellItems end function X:SetSellItems(items) self.SellItems = items end ------------------------------------------------------------------------------- -- Think -- ToDo: Selling items for better ones ------------------------------------------------------------------------------- function X:UpdateTeamBuyList( sItem ) local myList = getHeroVar("TeamBuy") if #myList > 0 then local pos = utils.PosInTable(myList, sItem) if pos > 0 then table.remove(myList, pos) end end end function X:Think(bot) local tDelta = GameTime() - self.LastThink -- throttle think for better performance if tDelta > 0.1 then if ( GetGameState() ~= GAME_STATE_GAME_IN_PROGRESS and GetGameState() ~= GAME_STATE_PRE_GAME ) then return end -- Put Team-wide Logic Assigned Items in our list local myTeamBuyList = getHeroVar("TeamBuy") if #myTeamBuyList > 0 then for _, item in ipairs(myTeamBuyList) do if not utils.InTable(self.PurchaseOrder, item) then utils.myPrint("Adding team mandated item to my purchase list: ", item) table.insert(self.PurchaseOrder, 1, item) end end end -- Put support items in list if we are a support (even if we already wanted to buy something else) if GetNumCouriers() == 0 then self:BuySupportItems() elseif DotaTime() > 10 then self:BuySupportItems() end -- buy TPs if we are near a shop and don't have one if not utils.HaveTeleportation(bot) and bot:FindItemSlot("item_tpscroll") == ITEM_SLOT_TYPE_INVALID and not utils.InTable(self.PurchaseOrder, "item_tpscroll") and DotaTime() > 60*4 and (utils.NumberOfItems(bot) + utils.NumberOfItemsInBackpack(bot)) < 8 then if bot:DistanceFromFountain() < 1600 or bot:DistanceFromSideShop() < 1600 then table.insert(self.PurchaseOrder, 1, "item_tpscroll") end end -- If there's an item to be purchased already bail if ( (bot:GetNextItemPurchaseValue() > 0) and (bot:GetGold() < bot:GetNextItemPurchaseValue()) ) then return end -- If we want a new item we determine which one first if #self.PurchaseOrder == 0 then -- update order self:UpdatePurchaseOrder() end -- Consider selling items if bot:DistanceFromFountain() < constants.SHOP_USE_DISTANCE or bot:DistanceFromSecretShop() < constants.SHOP_USE_DISTANCE or bot:DistanceFromSideShop() < constants.SHOP_USE_DISTANCE then self:ConsiderSellingItems(bot) end -- Get the next item local sNextItem = self.PurchaseOrder[1] if sNextItem ~= nil then -- Set cost bot:SetNextItemPurchaseValue(GetItemCost(sNextItem)) -- Enough gold -> buy, remove if(bot:GetGold() >= GetItemCost(sNextItem)) then if bot:IsAlive() then if bot.SelfRef:getCurrentMode():GetName() ~= "shop" then bot:ActionImmediate_PurchaseItem(sNextItem) table.remove(self.PurchaseOrder, 1) UpdateTeamBuyList(sNextItem) bot:SetNextItemPurchaseValue(0) end end self.LastThink = GameTime() end end end end ------------------------------------------------------------------------------- -- Inits ------------------------------------------------------------------------------- function X:InitTable() -- Init tables based on role if (getHeroVar("Role") == role.ROLE_MID ) then self:SetStartingItems(self.ItemsToBuyAsMid.StartingItems) self:SetUtilityItems(self.ItemsToBuyAsMid.UtilityItems) self:SetCoreItems(self.ItemsToBuyAsMid.CoreItems) self:SetExtensionItems(self.ItemsToBuyAsMid.ExtensionItems) self:SetSellItems(self.ItemsToBuyAsMid.SellItems) return true elseif (getHeroVar("Role") == role.ROLE_HARDCARRY ) then self:SetStartingItems(self.ItemsToBuyAsHardCarry.StartingItems) self:SetUtilityItems(self.ItemsToBuyAsHardCarry.UtilityItems) self:SetCoreItems(self.ItemsToBuyAsHardCarry.CoreItems) self:SetExtensionItems(self.ItemsToBuyAsHardCarry.ExtensionItems) self:SetSellItems(self.ItemsToBuyAsHardCarry.SellItems) return true elseif (getHeroVar("Role") == role.ROLE_OFFLANE ) then self:SetStartingItems(self.ItemsToBuyAsOfflane.StartingItems) self:SetUtilityItems(self.ItemsToBuyAsOfflane.UtilityItems) self:SetCoreItems(self.ItemsToBuyAsOfflane.CoreItems) self:SetExtensionItems(self.ItemsToBuyAsOfflane.ExtensionItems) self:SetSellItems(self.ItemsToBuyAsOfflane.SellItems) return true elseif (getHeroVar("Role") == role.ROLE_HARDSUPPORT or getHeroVar("Role") == role.ROLE_SEMISUPPORT ) then self:SetStartingItems(self.ItemsToBuyAsSupport.StartingItems) self:SetUtilityItems(self.ItemsToBuyAsSupport.UtilityItems) self:SetCoreItems(self.ItemsToBuyAsSupport.CoreItems) self:SetExtensionItems(self.ItemsToBuyAsSupport.ExtensionItems) self:SetSellItems(self.ItemsToBuyAsSupport.SellItems) return true elseif (getHeroVar("Role") == role.ROLE_JUNGLER ) then self:SetStartingItems(self.ItemsToBuyAsJungler.StartingItems) self:SetUtilityItems(self.ItemsToBuyAsJungler.UtilityItems) self:SetCoreItems(self.ItemsToBuyAsJungler.CoreItems) self:SetExtensionItems(self.ItemsToBuyAsJungler.ExtensionItems) self:SetSellItems(self.ItemsToBuyAsJungler.SellItems) return true elseif (getHeroVar("Role") == role.ROLE_ROAMER ) then self:SetStartingItems(self.ItemsToBuyAsRoamer.StartingItems) self:SetUtilityItems(self.ItemsToBuyAsRoamer.UtilityItems) self:SetCoreItems(self.ItemsToBuyAsRoamer.CoreItems) self:SetExtensionItems(self.ItemsToBuyAsRoamer.ExtensionItems) self:SetSellItems(self.ItemsToBuyAsRoamer.SellItems) return true end end ------------------------------------------------------------------------------- -- Buy functions ------------------------------------------------------------------------------- function X:BuySupportItems() -- insert support items first if available if not utils.IsCore(GetBot()) then --[[ Idea: Buy starting items, then buy either core / extension items unless there is more important utility to buy. Upgrade courier at 3:00, buy all available wards and if needed detection (no smoke). ToDo: Function to return number of invisible enemies. Buying consumable items like raindrops if there is a lot of magical damage Buying salves/whatever for cores if it makes sense --]] local tDelta = GameTime() - self.LastSupportThink -- throttle support item decisions to every 10s if tDelta > 10.0 then if GetNumCouriers() == 0 then -- we have no courier, buy it table.insert(self.PurchaseOrder, 1, "item_courier") end -- buy flying courier if available (only 1x) if GetNumCouriers() > 0 and DotaTime() >= (3*60) and not gHeroVar.GetGlobalVar("FlyingCourier") then if not utils.InTable(self.BoughtItems, "item_flying_courier") then table.insert(self.PurchaseOrder, 1, "item_flying_courier") -- flying courier is the only item we put in the bought item list, -- wards etc. are not important to store table.insert(self.BoughtItems, "item_flying_courier") gHeroVar.SetGlobalVar("FlyingCourier", true) end end -- since smokes are not being used we don't buy them yet local wards = GetItemStockCount("item_ward_observer") -- buy all available wards local bot = GetBot() local item = utils.HaveItem(bot, "item_ward_observer") local currWardCount = 0 if item ~= nil then currWardCount = item:GetCurrentCharges() end if wards > 0 and currWardCount < 1 then if wards > 0 then table.insert(self.PurchaseOrder, 1, "item_ward_observer") wards = wards - 1 end end -- next support item think in 10 sec self.LastSupportThink = GameTime() end end end function X:GetPurchaseOrder() return self.PurchaseOrder end function X:UpdatePurchaseOrder() -- Still starting items to buy? if (#self.StartingItems == 0) then -- Still core items to buy? if( #self.CoreItems == 0) then -- Otherwise consider buying extension items local tDelta = GameTime() - self.LastExtensionThink -- last think over 10s ago? if tDelta > 10.0 then -- consider buying extensions self:ConsiderBuyingExtensions(bot) -- update last think time self.LastExtensionThink = GameTime() end else -- get next starting item in parts local toBuy = {} items:GetItemsTable(toBuy, items[self.CoreItems[1]]) -- single items will always be bought if #toBuy > 1 then -- go through bought items for _,p in pairs(self.BoughtItems) do -- get parts of this bought item local compare = {} items:GetItemsTable(compare, items[p]) -- more than 1 part? if #compare > 1 then local remove = true -- check if all parts of the bought item are in the item to buy for _,k in pairs(compare) do if not utils.InTable(toBuy, k) then remove = false end end -- if so remove all parts bought parts from the item to buy if remove then for _,k in pairs(compare) do local pos = utils.PosInTable(toBuy, k) table.remove(toBuy, pos) end -- remove the bought item also (since we are going to use it in the new item) local pos = utils.PosInTable(self.BoughtItems, p) table.remove(self.BoughtItems, pos) end else -- check if item was already bought if utils.InTable(toBuy, p) then -- if so remove it from the item to buy local pos = utils.PosInTable(toBuy, p) table.remove(toBuy, pos) -- remove it from bought items pos = utils.PosInTable(self.BoughtItems, p) table.remove(self.BoughtItems, pos) end end end end -- put all parts that we still need to buy in purchase order for _,p in pairs(toBuy) do table.insert(self.PurchaseOrder, p) end -- insert the item to buy in bought items, remove it from starting items table.insert(self.BoughtItems, self.CoreItems[1]) table.remove(self.CoreItems, 1) end else -- get next starting item in parts local toBuy = {} items:GetItemsTable(toBuy, items[self.StartingItems[1]]) -- single items will always be bought if #toBuy > 1 then -- go through bought items for _,p in pairs(self.BoughtItems) do -- get parts of this bought item local compare = {} items:GetItemsTable(compare, items[p]) -- more than 1 part? if #compare > 1 then local remove = true -- check if all parts of the bought item are in the item to buy for _,k in pairs(compare) do if not utils.InTable(toBuy, k) then remove = false end end -- if so remove all parts bought parts from the item to buy if remove then for _,k in pairs(compare) do local pos = utils.PosInTable(toBuy, k) table.remove(toBuy, pos) end -- remove the bought item also (since we are going to use it in the new item) local pos = utils.PosInTable(self.BoughtItems, p) table.remove(self.BoughtItems, pos) end else -- check if item was already bought if utils.InTable(toBuy, p) then -- if so remove it from the item to buy local pos = utils.PosInTable(toBuy, p) table.remove(toBuy, pos) -- remove it from bought items pos = utils.PosInTable(self.BoughtItems, p) table.remove(self.BoughtItems, pos) end end end end -- put all parts that we still need to buy in purchase order for _,p in pairs(toBuy) do table.insert(self.PurchaseOrder, p) end -- insert the item to buy in bought items, remove it from starting items table.insert(self.BoughtItems, self.StartingItems[1]) table.remove(self.StartingItems, 1) end end function X:ConsiderSellingItems(bot) local ItemsToConsiderSelling = self:GetSellItems() if utils.NumberOfItems(bot) == 6 and utils.NumberOfItemsInBackpack(bot) == 3 then local soldNum = 0 local alwaysSellIfNoRoom = {"item_tango_single", "item_tango", "item_clarity", "item_salve", "item_faerie_fire", "item_enchanted_mango"} ItemsToConsiderSelling = {unpack(alwaysSellIfNoRoom), unpack(ItemsToConsiderSelling)} while soldNum == 0 do if #ItemsToConsiderSelling > 0 then local ItemToSell = ItemsToConsiderSelling[1] -- Sell the item if ItemToSell ~= nil then local pos = bot:FindItemSlot(ItemToSell) if pos ~= ITEM_SLOT_TYPE_INVALID then if ItemToSell ~= "item_tango_single" then bot:ActionImmediate_SellItem(bot:GetItemInSlot(pos)) utils.myPrint("Selling: ", ItemToSell) table.remove(ItemsToConsiderSelling, 1) soldNum = soldNum + 1 else bot:ActionPush_DropItem(GetItemInSlot(pos), bot:GetLocation()) utils.myPrint("Dropping: ", ItemToSell) table.remove(ItemsToConsiderSelling, 1) soldNum = soldNum + 1 end else table.remove(ItemsToConsiderSelling, 1) end else utils.pause("bad item to sell") break end else if not utils.IsBusy(bot) and not utils.HaveItem(bot, "item_tpscroll") then if DEBUG then utils.pause("can't empty anything in inventory") end end break end end end end function X:ConsiderBuyingExtensions() local bot = GetBot() -- Start with 5s of time to do damage local DamageTime = 5 -- Get total disable time DamageTime = DamageTime + (enemyData.GetEnemyTeamSlowDuration() / 2) DamageTime = DamageTime + enemyData.GetEnemyTeamStunDuration() local SilenceCount = enemyData.GetEnemyTeamNumSilences() local TrueStrikeCount = enemyData.GetEnemyTeamNumTruestrike() local DamagePhysical, DamageMagical, DamagePure = enemyData.GetEnemyDmgs(bot:GetPlayerID(), 10.0) --[[ The damage numbers should be calculated, also the disable time and the silence counter should work Now there needs to be a decision process for what items should be bought exactly. That should account for retreat abilities, what damage is more dangerous to us, how much disable and most imporantly what type of disable the enemy has. Should also consider how fast the enemy is so that we can buy items to chase. --]] -- Determine if we have a retreat ability that we must be able to use (blinks etc) local retreatAbility if getHeroVar("HasMovementAbility") ~= nil then retreatAbility = true else retreatAbility = false end -- Remove evasion items if # true strike enemies > 1 if TrueStrikeCount > 0 then if utils.InTable(self.ExtensionItems.DefensiveItems, "item_solar_crest") then local ItemIndex = utils.PosInTable(self.ExtensionItems.DefensiveItems, "item_solar_crest") table.remove(self.ExtensionItems.DefensiveItems, ItemIndex) end if utils.InTable(self.ExtensionItems.OffensiveItems, "item_butterfly") then local ItemIndex = utils.PosInTable(self.ExtensionItems.DefensiveItems, "item_butterfly") table.remove(self.ExtensionItems.DefensiveItems, ItemIndex) end end -- Remove magic immunty if not needed if DamagePhysical > DamageMagical then if utils.InTable(self.ExtensionItems.DefensiveItems, "item_hood_of_defiance") or utils.InTable(self.ExtensionItems.DefensiveItems, "item_pipe") then --utils.myPrint(" Considering magic damage reduction") elseif utils.InTable(self.ExtensionItems.DefensiveItems, "item_black_king_bar") then if retreatAbility and SilenceCount > 1 then --utils.myPrint(" Considering buying bkb") elseif SilenceCount > 2 or DamageTime > 8 then --utils.myPrint(" Considering buying bkb") else local ItemIndex = utils.PosInTable(self.ExtensionItems.DefensiveItems, "item_black_king_bar") table.remove(self.ExtensionItems.DefensiveItems, ItemIndex) --utils.myPrint(" Removing bkb") end end elseif utils.InTable(self.ExtensionItems.DefensiveItems, "item_black_king_bar") then if retreatAbility and SilenceCount > 1 then if utils.InTable(self.ExtensionItems.DefensiveItems, "item_manta") then --utils.myPrint(" Considering buying manta") elseif utils.InTable(self.ExtensionItems.DefensiveItems, "item_cyclone") then --utils.myPrint(" Considering buying euls") else --utils.myPrint(" Considering buying bkb") end elseif SilenceCount > 2 then if DamageTime > 12 then --utils.myPrint(" Considering buying bkb") elseif utils.InTable(self.ExtensionItems.DefensiveItems, "item_manta") then --utils.myPrint(" Considering buying manta") elseif utils.InTable(self.ExtensionItems.DefensiveItems, "item_cyclone") then --utils.myPrint(" Considering buying euls") end else local ItemIndex = utils.PosInTable(self.ExtensionItems.DefensiveItems, "item_black_king_bar") table.remove(self.ExtensionItems.DefensiveItems, ItemIndex) --utils.myPrint(" Removing bkb") end else -- ToDo: Check if enemy has retreat abilities and consider therefore buying stun/silence end end ------------------------------------------------------------------------------- return X
gpl-3.0
jshackley/darkstar
scripts/zones/Windurst_Woods/npcs/Matata.lua
34
1781
----------------------------------- -- Area: Windurst Woods -- NPC: Matata -- Type: Standard NPC -- @zone: 241 -- @pos 131 -5 -109 -- Involved in quest: In a Stew ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CB = player:getQuestStatus(WINDURST,CHOCOBILIOUS); IAS = player:getQuestStatus(WINDURST,IN_A_STEW); IASvar = player:getVar("IASvar"); if (IAS == QUEST_ACCEPTED and IASvar == 1) then player:startEvent(0x00E9,0,0,4545); -- In a Stew in progress elseif (IAS == QUEST_ACCEPTED and IASvar == 2) then player:startEvent(0x00ED); -- In a Stew reminder elseif (IAS == QUEST_COMPLETED) then player:startEvent(0x00F1); -- new dialog after In a Stew elseif (CB == QUEST_COMPLETED) then player:startEvent(0x00E2); -- Chocobilious complete else -- Standard Dialog player:startEvent(0xdf); 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); -- In a Stew if (csid == 0x00E9) then player:setVar("IASvar",2); end end;
gpl-3.0
dani-sj/tekmilienod
plugins/anti_bot.lua
26
3209
local function isBotAllowed (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId local banned = redis:get(hash) return banned end local function allowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:set(hash, true) end local function disallowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:del(hash) end -- Is anti-bot enabled on chat local function isAntiBotEnabled (chatId) local hash = 'anti-bot:enabled:'..chatId local enabled = redis:get(hash) return enabled end local function enableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:del(hash) end local function isABot (user) -- Flag its a bot 0001000000000000 local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function kickUser(userId, chatId) local chat = 'chat#id'..chatId local user = 'user#id'..userId chat_del_user(chat, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) -- We wont return text if is a service msg if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' end end local chatId = msg.to.id if matches[1] == 'enable' then enableAntiBot(chatId) return 'ورود ربات ها ممنوع شد' end if matches[1] == 'disable' then disableAntiBot(chatId) return 'ورود ربات ها ازاد شد' end if matches[1] == 'allow' then local userId = matches[2] allowBot(userId, chatId) return 'Bot '..userId..' allowed' end if matches[1] == 'disallow' then local userId = matches[2] disallowBot(userId, chatId) return 'Bot '..userId..' disallowed' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABot(user) then print('It\'s a bot!') if isAntiBotEnabled(chatId) then print('Anti bot is enabled') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('This bot is allowed') end end end end end return { description = 'When bot enters group kick it.', usage = { '!antibot enable: Enable Anti-bot on current chat', '!antibot disable: Disable Anti-bot on current chat', '!antibot allow <botId>: Allow <botId> on this chat', '!antibot disallow <botId>: Disallow <botId> on this chat' }, patterns = { '^!antibot (allow) (%d+)$', '^!antibot (disallow) (%d+)$', '^!antibot (enable)$', '^!antibot (disable)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run } --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
jshackley/darkstar
scripts/zones/Southern_San_dOria/npcs/Daggao.lua
17
1975
----------------------------------- -- Area: Southern San d'Oria -- NPC: Daggao -- Involved in Quest: Peace for the Spirit, Lure of the Wildcat (San d'Oria) -- @pos 89 0 119 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,0) == false) then player:startEvent(0x032a); elseif (player:getVar("peaceForTheSpiritCS") == 3) then player:startEvent(0x0048); elseif (player:getVar("peaceForTheSpiritCS") == 5) then player:startEvent(0x0049); else player:startEvent(0x003c); 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 == 0x032a) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",0,true); elseif (csid == 0x0048) then player:setVar("peaceForTheSpiritCS",4); end end;
gpl-3.0
slanska/flexilite
src_lua/flexi_CreateClass.lua
1
7962
--- --- Created by slanska. --- DateTime: 2017-11-01 11:34 PM --- --[[ select flexi('create class', class_name [, class_def_JSON]) or select flexi('class create', class_name [, class_def_JSON]) or select flexi('create', class_name [, class_def_JSON]) or select flexi('class', class_name [, class_def_JSON]) Expected parameters: class_name - required class_def_JSON - optional. If not set, class with ad-hoc properties and no predefined properties will be created ]] local json = cjson or require 'cjson' local schema = require 'schema' local tablex = require 'pl.tablex' local ClassDef = require 'ClassDef' local List = require 'pl.List' local table_insert = table.insert local string = _G.string local alt_cls = require('flexi_AlterClass') local AlterClass, MergeClassDefinitions = alt_cls.AlterClass, alt_cls.MergeClassDefinitions -- Inserts row into .classes table, to get class ID ---@param self DBContext ---@param classDef ClassDef local function insertNewClass(self, classDef) -- Save new class record to get ID classDef.Name:resolve(classDef) self:execStatement("insert into [.classes] (NameID) values (:ClassNameID);", { ClassNameID = classDef.Name.id, }) classDef.D.ClassID = self.db:last_insert_rowid() classDef.ClassID = classDef.D.ClassID end --- Creates multiple classes from schema definition ---@param self DBContext ---@param schemaDef table ---@param createVirtualTable boolean local function createMultiClasses(self, schemaDef, createVirtualTable) -- Check schema for class definitions local err = schema.CheckSchema(schemaDef, self.ClassDef.MultiClassSchema) if err then local s = schema.FormatOutput(err) error(s) end --[[ Classes' processing is done in few steps (or phases) 1) Classes are added to NAMClasses, so that they become available for lookup by class name 2) Properties are iterated and beforeApplyDef method gets fired, if applicable 3) Class records are saved in .classes table so that classes get their persistent IDs 4) Properties are saved in database (applyDef). They get persistent IDs. At this point 5) Classes get their indexes applied and class definitions are saved (JSON portion only) 6) apply new-and-modified classes ]] -- Utility function to iterate over all classes and their properties ---@param callback function @comment (className: string, ClassDef, propName: string, PropDef) local function forEachNAMClassProp(callback) if self.NAMClasses ~= nil then for className, classDef in pairs(self.NAMClasses) do if type(className) == 'string' and classDef.Properties ~= nil then for propName, propDef in pairs(classDef.Properties) do callback(className, classDef, propName, propDef) end end end end end ---@param className string ---@param classDef ClassDef ---@param propName string ---@param propDef PropertyDef local function virtualTableOrNAM(className, classDef, propName, propDef) -- TODO end ---@param className string ---@param classDef ClassDef ---@param propName string ---@param propDef PropertyDef local function beforeSaveProp(_, _, _, propDef) propDef:beforeSaveToDB() end ---@param className string ---@param classDef ClassDef ---@param propName stringn ---@param propDef PropertyDef local function saveProp(_, _, _, propDef) propDef:saveToDB() end local newClasses = {} for className, classDef in pairs(schemaDef) do local classID = self:getClassIdByName(className, false) if classID ~= 0 then error(string.format('Class %s already exists', className)) end -- validate name if not self:isNameValid(className) then error('Invalid class name ' .. className) end if createVirtualTable == 0 then createVirtualTable = false elseif createVirtualTable == nil then createVirtualTable = self.config.createVirtualTable or false end if createVirtualTable then -- TODO Is this right way? -- Call virtual table creation local sqlStr = string.format("create virtual table [%s] using flexi_data ('%q');", className, classDef) self.db:exec(sqlStr) -- TODO Supply class ID --return string.format('Virtual flexi_data table [%s] created', className) else local clsObject = self.ClassDef { newClassName = className, data = classDef, DBContext = self } -- TODO Set ctloMask clsObject.D.ctloMask = 0 clsObject.D.VirtualTable = false -- Check if class is fully resolved, i.e. does not have references to non-existing classes clsObject.D.Unresolved = false insertNewClass(self, clsObject) self:setNAMClass(clsObject) table_insert(newClasses, clsObject) end end forEachNAMClassProp(beforeSaveProp) forEachNAMClassProp(saveProp) for _, clsObject in ipairs(newClasses) do ClassDef.ApplyIndexing(nil, clsObject) clsObject:saveToDB() end self:applyNAMClasses() self.ActionQueue:run() end ---@param self DBContext ---@param className string ---@param classDef table ---@param createVirtualTable boolean ---@return string @comment result of operation local function createSingleClass(self, className, classDef, createVirtualTable) local schemaDef = { [className] = classDef } local savedActQue = self.ActionQueue == nil and self:setActionQueue() or self.ActionQueue local result, errMsg = pcall(createMultiClasses, self, schemaDef, createVirtualTable) if savedActQue ~= nil then self:setActionQueue(savedActQue) end if not result then error(errMsg) end return string.format('Class [%s] has been created', className) end --- Internal function to create class ---@param self DBContext ---@param className string ---@param classDef table @comment decoded JSON ---@param createVirtualTable boolean --- Used to avoid multiple to/from JSON conversion local function CreateClass(self, className, classDef, createVirtualTable) if type(classDef) == 'string' then classDef = json.decode(classDef) elseif not classDef then classDef = { properties = {}, allowAnyProps = true, } end return createSingleClass(self, className, classDef, createVirtualTable) end --[[ Creates multiple classes Classes are defined in JSON object, by name. They are processed in few steps, to provide referential integrity: 1) After schema validation, all classes are saved in .classes table. Their IDs get established 2) Properties get updated ("applied"), with possible creation of reverse referencing and other properties and classes. No changes are saved yet. 2) All class properties get saved in .class_props table, to get IDs. No processing or validation happened yet. 3) Final steps - class Data gets updated with referenced class and property IDs and saved ]] ---@param self DBContext ---@param schemaJson string ---@param createVirtualTable boolean local function CreateSchema(self, schemaJson, createVirtualTable) local classSchema = json.decode(schemaJson) local savedActQue = self.ActionQueue == nil and self:setActionQueue() or self.ActionQueue local result, errMsg = pcall(createMultiClasses, self, classSchema, createVirtualTable) if savedActQue ~= nil then self:setActionQueue(savedActQue) end if not result then error(errMsg) end local cnt = tablex.size(classSchema) return string.format('%d class(es) have been created', cnt) end return { CreateClass = CreateClass, CreateSchema = CreateSchema }
mpl-2.0
Ombridride/minetest-minetestforfun-server
mods/trm_pyramids/init.lua
9
5065
--[[ This is an example Treasure Registration Mod (TRM) for the default mod. It is meant to use together with the default mod and the treasurer mod. This TRM registers a bunch of items found in the default mod. Note that the probabilities may not be very well balanced, this file is just there as an example. It, however, can still be used in actual gameplay. A TRM is really nothing more than a list of item names, probabilities, preciousnesses, and optionally a given amount and tool wear. The only function ever called is treasurer.register_treasure. See also treasurer’s documentation for more info. ]] --[[ The following entries all use a rarity value and a count value in range format. Note that the range format is a table with two value, the first being the minimum and the second being the maximum value. ]] --[[ The next entry means: this treasure consists of 1 to 10 gold ingots and has a rarity of 0.01 and a preciousness of 7 (out of 10) ]] treasurer.register_treasure("default:gold_ingot",0.01,7,{1,10}) -- The following entries are similar treasurer.register_treasure("default:bronze_ingot",0.02,5,{1,16}) treasurer.register_treasure("default:copper_ingot",0.06,3,{1,17}) treasurer.register_treasure("default:steel_ingot",0.09,4,{1,20}) treasurer.register_treasure("default:clay_brick",0.1,5,{2,12}) treasurer.register_treasure("default:coal_lump",0.2,2,{3,10}) treasurer.register_treasure("default:obsidian_shard",0.05,5,{3,20}) treasurer.register_treasure("default:obsidian_shard",0.0005,5,{21,90}) treasurer.register_treasure("default:mese_crystal",0.008,9,{1,5}) treasurer.register_treasure("default:diamond",0.001,9,{1,3}) --[[ here is a constant (=non-random) count given with a rarity of 0.0001, exactly 4 diamonds spawn]] treasurer.register_treasure("default:diamond",0.0001,9,4) -- an example of a treasure with preciousness of 10 treasurer.register_treasure("default:diamond_block",0.00002,10,1) -- by the way, as you see, it is not forbidden to register the same item twice. treasurer.register_treasure("default:paper",0.1,2,{3,6}) treasurer.register_treasure("default:stick",0.1,2,{1,15}) treasurer.register_treasure("default:stick",0.05,2,{16,33}) treasurer.register_treasure("default:book",0.1,4,{1,2}) treasurer.register_treasure("default:mese_crystal_fragment",0.01,3,{1,9}) treasurer.register_treasure("default:sapling",0.05,2,{1,20}) treasurer.register_treasure("default:junglesapling",0.03,3,{1,5}) treasurer.register_treasure("default:apple",0.2,2,{1,7}) treasurer.register_treasure("default:shovel_wood",0.02,2) treasurer.register_treasure("default:shovel_stone",0.050,3) treasurer.register_treasure("default:shovel_steel",0.07,5) treasurer.register_treasure("default:shovel_bronze",0.006,6) treasurer.register_treasure("default:shovel_mese",0.0012,8) treasurer.register_treasure("default:shovel_diamond",0.0008,9) treasurer.register_treasure("default:axe_wood",0.02,2) treasurer.register_treasure("default:axe_stone",0.045,3) treasurer.register_treasure("default:axe_steel",0.05,5) treasurer.register_treasure("default:axe_bronze",0.005,6) treasurer.register_treasure("default:axe_mese",0.0002,8) treasurer.register_treasure("default:axe_diamond",0.000125,9) --[[ Here are some examples for wear. wear is the 5th parameter the format of wear is identical to the format of count note that the 3rd parameter (count) is nil which causes the script to use the default value We could as well have written an 1 here. ]] treasurer.register_treasure("default:axe_wood",0.04,1,nil,{100,10000}) -- wear = randomly between 100 and 10000 treasurer.register_treasure("default:axe_stone",0.09,2,nil,{500,11000}) treasurer.register_treasure("default:axe_steel",0.1,4,nil,{600,18643}) treasurer.register_treasure("default:axe_bronze",0.01,5,nil,{750,20000}) treasurer.register_treasure("default:axe_mese",0.0002,7,nil,{1000,22000}) treasurer.register_treasure("default:axe_diamond",0.0001,8,nil,{2000,30000}) treasurer.register_treasure("default:pick_wood",0.005,2) treasurer.register_treasure("default:pick_stone",0.018,3) treasurer.register_treasure("default:pick_steel",0.02,5) treasurer.register_treasure("default:pick_bronze",0.004,6) treasurer.register_treasure("default:pick_mese",0.008,8) treasurer.register_treasure("default:pick_diamond",0.005,9) treasurer.register_treasure("default:sword_wood",0.001,2) treasurer.register_treasure("default:sword_stone",0.016,3) treasurer.register_treasure("default:sword_steel",0.02,5) treasurer.register_treasure("default:sword_bronze",0.015,6) treasurer.register_treasure("default:sword_mese",0.007,8) treasurer.register_treasure("default:sword_diamond",0.0035,9) treasurer.register_treasure("default:rail",0.01,5,15) treasurer.register_treasure("default:rail",0.02,5,{1,5}) treasurer.register_treasure("default:fence_wood",0.1,4,{1,7}) -- If the count is omitted, it deaults to 1. treasurer.register_treasure("default:sign_wall",0.1,4) treasurer.register_treasure("default:ladder",0.1,3,{1,2}) treasurer.register_treasure("default:torch",0.2,2,{1,5})
unlicense
jshackley/darkstar
scripts/zones/Labyrinth_of_Onzozo/mobs/Goblin_Mercenary.lua
2
1028
----------------------------------- -- Area: Labyrinth of Onzozo -- MOB: Goblin Mercenary -- Note: Place holder Soulstealer Skullnix ----------------------------------- require("scripts/zones/Labyrinth_of_Onzozo/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkGoVregime(ally,mob,771,2); checkGoVregime(ally,mob,772,2); checkGoVregime(ally,mob,774,2); local mob = mob:getID(); if (Soulstealer_Skullnix_PH[mob] ~= nil) then local ToD = GetServerVariable("[POP]Soulstealer_Skullnix"); if (ToD <= os.time(t) and GetMobAction(Soulstealer_Skullnix) == 0) then if (math.random((1),(20)) == 5) then UpdateNMSpawnPoint(Soulstealer_Skullnix); GetMobByID(Soulstealer_Skullnix):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Soulstealer_Skullnix", mob); DeterMob(mob, true); end end end end;
gpl-3.0
Mizugola/MeltingSaga
engine/Lib/Extlibs/pl/Map.lua
5
2669
--- A Map class. -- -- > Map = require 'Lib.Extlibs.pl.Map' -- > m = Map{one=1,two=2} -- > m:update {three=3,four=4,two=20} -- > = m == M{one=1,two=20,three=3,four=4} -- true -- -- Dependencies: `pl.utils`, `pl.class`, `pl.tablex`, `pl.pretty` -- @classmod pl.Map local tablex = require 'Lib.Extlibs.pl.tablex' local utils = require 'Lib.Extlibs.pl.utils' local stdmt = utils.stdmt local deepcompare = tablex.deepcompare local Map = stdmt.Map local Set = stdmt.Set local class = require 'Lib.Extlibs.pl.class' -- the Map class --------------------- class(nil,nil,Map) function Map:_init (t) local mt = getmetatable(t) if mt == Set or mt == Map then self:update(t) else return t -- otherwise assumed to be a map-like table end end local function makelist(t) return setmetatable(t, require('Lib.Extlibs.pl.List')) end --- list of keys. Map.keys = tablex.keys --- list of values. Map.values = tablex.values --- return an iterator over all key-value pairs. function Map:iter () return pairs(self) end --- return a List of all key-value pairs, sorted by the keys. function Map:items() local ls = makelist(tablex.pairmap (function (k,v) return makelist {k,v} end, self)) ls:sort(function(t1,t2) return t1[1] < t2[1] end) return ls end -- Will return the existing value, or if it doesn't exist it will set -- a default value and return it. function Map:setdefault(key, defaultval) return self[key] or self:set(key,defaultval) or defaultval end --- size of map. -- note: this is a relatively expensive operation! -- @class function -- @name Map:len Map.len = tablex.size --- put a value into the map. -- This will remove the key if the value is `nil` -- @param key the key -- @param val the value function Map:set (key,val) self[key] = val end --- get a value from the map. -- @param key the key -- @return the value, or nil if not found. function Map:get (key) return rawget(self,key) end local index_by = tablex.index_by --- get a list of values indexed by a list of keys. -- @param keys a list-like table of keys -- @return a new list function Map:getvalues (keys) return makelist(index_by(self,keys)) end --- update the map using key/value pairs from another table. -- @tab table -- @function Map:update Map.update = tablex.update --- equality between maps. -- @within metamethods -- @tparam Map m another map. function Map:__eq (m) -- note we explicitly ask deepcompare _not_ to use __eq! return deepcompare(self,m,true) end --- string representation of a map. -- @within metamethods function Map:__tostring () --return pretty_write(self,'') end return Map
mit
doctorluk/ULX-Age-Verificator
ageverificator/lua/autorun/server/sv_ageverificator.lua
1
20128
-- Made by Luk -- http://steamcommunity.com/id/doctorluk/ -- Version: 1.3 -- https://github.com/doctorluk/ULX-Age-Verificator if SERVER then if not AGECHECK_LANGUAGE then include( "ageverificator_config.lua" ) end -- Make sure we always get valid Zodiacs from the player's net message VALID_ZODIACS = AGECHECK_ZODIACS util.AddNetworkString( "agecheck_send" ) util.AddNetworkString( "agecheck_onplayerconnect" ) util.AddNetworkString( "agecheck_checknecessity" ) -- Since we shift from multiple entries per STEAM-ID to single ones with timestamps, it's the easiest way to just create a new table function ageverify_upgradeAgeTable() ServerLog( "[WARNING] Age Verification: FLUSHING agecheck DATABASE TO UPDATE TO THE LATEST DATABASE VERSION!\n" ) local query = "DROP TABLE agecheck; CREATE TABLE agecheck ( id INTEGER PRIMARY KEY AUTOINCREMENT, times INTEGER, steamid TEXT, name TEXT, age INTEGER, day INTEGER, month INTEGER, year INTEGER, zodiac TEXT, date DATETIME DEFAULT CURRENT_TIMESTAMP )" local result = sql.Query( query ) end -- This simply deletes entries older than a month function ageverify_cleanupTable() ServerLog( "Age Verification: Performing cleanup of old entries...\n" ) local query = "DELETE FROM agecheck WHERE date <= datetime('now', '-1 month')" local result = sql.Query( query ) end -- This function was taken from the AWarn 2 plugin here: http://forums.ulyssesmod.net/index.php/topic,7125.0.html -- It's nice to alter existing functions for your own purpose. I've got no idea of LUA and doing stuff from scratch is hard sometimes function ageverify_checkAgeTable() -- Check existance and/or create the table that will hold the entered data if sql.TableExists( "agecheck" ) then ServerLog( "Age Verification: agecheck Table is existing!\n" ) -- Add date column if not exists -- Get table info local query = "PRAGMA table_info(agecheck)" local result = sql.Query( query ) local addDate = true -- Check if column 'date' is in there, if not we add it for k, v in pairs( result ) do if v["name"] == "date" then addDate = false end end if addDate then ageverify_upgradeAgeTable() end else local query = "CREATE TABLE agecheck ( id INTEGER PRIMARY KEY AUTOINCREMENT, times INTEGER, steamid TEXT, name TEXT, age INTEGER, day INTEGER, month INTEGER, year INTEGER, zodiac TEXT, date DATETIME DEFAULT CURRENT_TIMESTAMP )" result = sql.Query( query ) ServerLog( "Age Verification: Creating Age Verification Table...\n" ) if sql.TableExists( "agecheck" ) then ServerLog( "Age Verification: Age Verification Table created sucessfully.\n" ) else ServerLog( "[ERROR] Age Verification: Trouble creating the Age Verification Table\n" ) ServerLog( "[ERROR] Age Verification: " .. sql.LastError( result ).."\n" ) end end -- Check existance and/or create the table that will hold people who passed enough times if sql.TableExists( "agecheck_done" ) then ServerLog( "Age Verification: agecheck_done Table is existing!\n" ) else local query = "CREATE TABLE agecheck_done ( id INTEGER PRIMARY KEY AUTOINCREMENT, steamid TEXT, name TEXT )" result = sql.Query( query ) ServerLog( "Age Verification: Creating Age Verification Done Table...\n" ) if sql.TableExists( "agecheck" ) then ServerLog( "Age Verification: Age Verification Done Table created sucessfully.\n" ) else ServerLog( "[ERROR] Age Verification: Trouble creating the Age Verification Done Table\n" ) ServerLog( "[ERROR] Age Verification: " .. sql.LastError( result ).."\n" ) end end ageverify_cleanupTable() end hook.Add( "Initialize", "age_check_init", ageverify_checkAgeTable ) -- I'm not sure if people could change the net messages, I suspect that is easy, so we make sure -- the received Zodiac is one that we offered him to choose function ageverify_isZodiacValid( zodiac ) return table.HasValue( VALID_ZODIACS, zodiac ) end -- This is a painful function that checks if the day and month entered matches -- the zodiac sign, credits to Heady for making it -- It overlaps sometimes due to the fact that multiple online sources round off the days differently function ageverify_isValidZodiacDate( day_, month_, zodiac ) local day = tonumber( day_ ) local month = tonumber( month_ ) -- "Aries" / "Widder" if zodiac == VALID_ZODIACS[1] then if ( day >= 21 and month == 3 ) or ( day <= 20 and month == 4 ) then return true end -- "Taurus" / "Stier" elseif zodiac == VALID_ZODIACS[2] then if ( day >= 21 and month == 4 ) or ( day <= 21 and month == 5 ) then return true end -- "Gemini" / "Zwillinge" elseif zodiac == VALID_ZODIACS[3] then if ( day >= 21 and month == 5 ) or ( day <= 21 and month == 6 ) then return true end -- "Cancer" / "Krebs" elseif zodiac == VALID_ZODIACS[4] then if ( day >= 22 and month == 6 ) or ( day <= 22 and month == 7 ) then return true end -- "Leo" / "Löwe" elseif zodiac == VALID_ZODIACS[5] then if ( day >= 23 and month == 7 ) or ( day <= 23 and month == 8 ) then return true end -- "Virgo" / "Jungfrau" elseif zodiac == VALID_ZODIACS[6] then if ( day >= 23 and month == 8 ) or ( day <= 23 and month == 9 ) then return true end -- "Libra" / "Waage" elseif zodiac == VALID_ZODIACS[7] then if ( day >= 23 and month == 9 ) or ( day <= 23 and month == 10 ) then return true end -- "Scorpio" / "Skorpion" elseif zodiac == VALID_ZODIACS[8] then if ( day >= 23 and month == 10 ) or ( day <= 22 and month == 11 ) then return true end -- "Saggitarius" / "Schütze" elseif zodiac == VALID_ZODIACS[9] then if ( day >= 23 and month == 11 ) or ( day <= 21 and month == 12 ) then return true end -- "Capricornus" / "Steinbock" elseif zodiac == VALID_ZODIACS[10] then if ( day >= 21 and month == 12 ) or ( day <= 20 and month == 1 ) then return true end -- "Aquarius" / "Wassermann" elseif zodiac == VALID_ZODIACS[11] then if ( day >= 20 and month == 1 ) or ( day <= 19 and month == 2 ) then return true end -- "Pisces" / "Fische" elseif zodiac == VALID_ZODIACS[12] then if ( day >= 19 and month == 2 ) or ( day <= 20 and month == 3 ) then return true end end return false end -- Taken from stackoverflow and modified -- Source: https://stackoverflow.com/questions/12542853/how-to-validate-if-a-string-is-a-valid-date-or-not-in-lua function ageverify_isValidDate( d, m, y ) if d < 0 or d > 31 or m < 0 or m > 12 or y < 0 then -- Cases that don't make sense return false elseif m == 4 or m == 6 or m == 9 or m == 11 then -- Apr, Jun, Sep, Nov can have at most 30 days return d <= 30 elseif m == 2 then -- Feb if y%400 == 0 or (y%100 ~= 0 and y%4 == 0) then -- if leap year, days can be at most 29 return d <= 29 else -- else 28 days is the max return d <= 28 end else -- all other months can have at most 31 days return d <= 31 end end -- Approximately calculating the amount of seconds it will take until this person is finally -- in the age to join the server -- To prevent publishing of people's birthdates on ban websites, we add up to 5 days from the ban length function ageverify_getSecondsUntilAge( day_, month_, year_ ) local currentSeconds = tonumber( os.time() ) local playerSecondsSinceBirth = tonumber( os.time( { year = year_, month = month_, day = day_, hour = 0, min = 0, sec = 0, isdst = false } ) ) local leapdays = math.floor( AGECHECK_MINIMUM_AGE / 4 ) local leapdayCompensation = leapdays * 86400 local secondsNeededTillAge = AGECHECK_MINIMUM_AGE * 365 * 24 * 60 * 60 + leapdayCompensation local alittlerandomnessalwayshelps = math.random( 432000 ) local secondsLeft = secondsNeededTillAge - ( currentSeconds - playerSecondsSinceBirth ) + alittlerandomnessalwayshelps -- Ban someone at least for 5 days to prevent silly ban times if secondsNeededTillAge < 432000 then secondsLeft = 432000 end return secondsLeft end -- That should be easy to understand, shouldn't it? function ageverify_isOldEnough( day, month, year ) return ageverify_getAge( day, month, year ) >= AGECHECK_MINIMUM_AGE end -- Check whether his entered age is matching his birthday function ageverify_isAgeMatching( age, day, month, year ) return age == math.floor( ageverify_getAge( day, month, year ) ) end -- It seemed easy to use os.time for calculation of years -- but that wasn't the case. Actually it was quite difficult to calculate -- In the end we have to add leapday seconds to the equation to get the actual date -- Otherwise we get false results for players that would turn, let's say 18, in two days and are considered 18 already -- if we don't remove the leap days that happened. The leapday calculation is lazy, I know function ageverify_getAge( day_, month_, year_ ) local currentSeconds = tonumber( os.time() ) local playerSecondsSinceBirth = tonumber( os.time( { year = year_, month = month_, day = day_, hour = 0, min = 0, sec = 0, isdst = false } ) ) local years = ( currentSeconds - playerSecondsSinceBirth ) / 60 / 60 / 24 / 365 -- Calculate how many leap years have passed since the player's birth local approximatedLeapYears = math.floor( years / 4 ) -- Substract those additional days from the final calculation years = ( currentSeconds - playerSecondsSinceBirth - ( approximatedLeapYears * 86400 ) ) / 60 / 60 / 24 / 365 return years end -- Checks whether a player is required to be tested by checking the whitelist function ageverify_needsToBeTested( sid ) local query = "SELECT * FROM agecheck_done WHERE steamid='" .. sid .. "'" local result = sql.Query( query ) if result then return AGECHECK_MAXIMUM_TEST end local wasTested = ageverify_getPreviousEntry( sid ) if wasTested then return 1 else return 0 end end -- Gets a player's previous entry data function ageverify_getPreviousEntry( sid ) local query = "SELECT * FROM agecheck WHERE steamid='" .. sid .. "'" result = sql.Query( query ) return result end -- Deletes player's entry from the agecheck database function ageverify_flushEntriesFromSteamid( sid ) local query = "DELETE FROM agecheck WHERE steamid='" .. sid .. "'" result = sql.Query( query ) end -- Empties the agecheck database function ageverify_flushAllEntries( ) local query = "DELETE FROM agecheck" result = sql.Query( query ) end -- Empties the whitelist function ageverify_flushAllDoneEntries( ) local query = "DELETE FROM agecheck_done" result = sql.Query( query ) end -- Gets all active entries in the agecheck database function ageverify_getAgecheckCount( ) local query = "SELECT COUNT(*) as count FROM agecheck" result = sql.Query( query ) if result then return result[1].count else return 0 end end -- Gets all whitelist entries in the agecheck_done database function ageverify_getAgecheckWhitelistCount( ) local query = "SELECT COUNT(*) as count FROM agecheck_done" result = sql.Query( query ) if result then return result[1].count else return 0 end end -- Check if all of the newly entered data matches all previously entered data function ageverify_isMatchingPreviousAnswer( data ) local sid = data[1] local age = data[2] local day = data[3] local month = data[4] local year = data[5] local zodiac = data[6] local previous = ageverify_getPreviousEntry( sid ) if not previous then return true end if previous[1].day ~= day or previous[1].month ~= month or previous[1].year ~= year or previous[1].zodiac ~= zodiac then return false end return true end -- Once a player enters his details, print the results to moderators or admins on the server who are allowed access to -- ulx seebirthdayentry function ageverify_notifyAdmins( ply, age, day, month, year, zodiac ) local validZodiacColor = Color( 0, 255, 0, 255 ) local validZodiac = "[GOOD]" if not ageverify_isValidZodiacDate( day, month, zodiac ) then validZodiacColor = Color( 255, 0, 0, 255 ) validZodiac = "[WRONG]" end local ageColor_1 = Color( 0, 255, 0, 255 ) local ageGood_1 = age >= AGECHECK_MINIMUM_AGE if not ageGood_1 then ageColor_1 = Color( 255, 0, 0, 255 ) end local ageColor_2 = Color( 0, 255, 0, 255 ) local ageGood_2 = math.floor( ageverify_getAge( day, month, year ) ) == age if not ageGood_2 then ageColor_2 = Color( 255, 0, 0, 255 ) end local players = player.GetAll() for _, player in ipairs( players ) do if ULib.ucl.query( player, "ulx seebirthdayentry" ) then ULib.tsayColor( player, true, Color( 255, 0, 0, 255 ), "[CONFIDENTIAL] ", Color( 255, 255, 0, 255 ), "Player '", Color( 0, 255, 255, 255 ), ply:Nick(), Color( 255, 255, 0, 255 ), "'", Color( 255, 255, 0, 255 ), " -> Age: ", ageColor_1, age .. "", Color( 255, 255, 0, 255 ), ", Date of Birth: ", Color( 0, 255, 0, 255 ), day .. "." .. month .. "." .. year, Color( 255, 255, 0, 255 ), " [", ageColor_2, math.floor( ageverify_getAge( day, month, year ) ) .. "", Color( 255, 255, 0, 255 ), "] ", Color( 255, 255, 0, 255 ), ", ", Color( 0, 255, 0, 255 ), zodiac .. " ", validZodiacColor, validZodiac ) end end end -- Print ban to chat function ageverify_reportBan( target_ply, banText, duration ) local time = " (#i minute(s))" if duration == 0 then time = " (permanent)" elseif duration == -1 then time = "" end local str = banText .. time ulx.fancyLogAdmin( target_ply, str, duration ) end -- Forward ban to Sourcebans if installed, otherwise ban via ULX function ageverify_doBan( ply, length, reason, admin_steamid ) if SBAN.Player_Ban then SBAN.Player_Ban( ply, length, reason, admin_steamid ) else RunConsoleCommand( "ulx", "banid", ply:SteamID(), length / 60, reason ) end end -- This is the main logic behind all of it -- Run checks and react to the entered data accordingly function ageverify_addEntry( data ) local ply = player.GetBySteamID( data[1] ) local sid = data[1] local age = tonumber( data[2] ) local day = tonumber( data[3] ) local month = tonumber( data[4] ) local year = tonumber( data[5] ) local zodiac = data[6] ageverify_notifyAdmins( ply, age, day, month, year, zodiac ) if not ageverify_isZodiacValid( zodiac ) then return end print( "AgeverifyDebug: " .. ply:Nick() .. ", " .. ply:SteamID() .. " -> " .. day .. "." .. month .. "." .. year .. ", " .. zodiac ) local length = 0 -- Check for invalid dates first, this is the most ass-y way of entering birthdays if not ageverify_isValidDate( day, month, year ) then print( "AgeverifyDebug: INVALID DATE!" ) ageverify_reportBan( ply, AGECHECK_BAN_REASON_OTHER_WRONG_DATE, 0 ) ageverify_doBan( ply, 0, AGECHECK_BAN_REASON_WRONG_DATE, AGECHECK_SBAN_STEAMID ) return end -- Check whether the age entries of the player (age AND birthday) are okay if age < AGECHECK_MINIMUM_AGE or not ageverify_isOldEnough( day, month, year ) then print( "AgeverifyDebug: TOO YOUNG!" ) if age < math.floor( ageverify_getAge( day, month, year ) ) then length = ( ( AGECHECK_MINIMUM_AGE - age ) * 365 * 24 * 60 * 60 ) - ( 365 * 24 * 60 * 60 / 2 ) -- Statistically we expect the average time it will take for a player to reach the age to be half a year less than what is left in years, so if he is 1 year too young, we wait half a year. 3 years too young we wait 2.5 years etc. else length = ageverify_getSecondsUntilAge( day, month, year ) -- If the birthday results in a lower age, we expect the birthday to be valid and ban him according to the duration of that end ageverify_reportBan( ply, AGECHECK_BAN_REASON_OTHER_TOO_YOUNG, -1 ) ageverify_doBan( ply, length, AGECHECK_BAN_REASON_TOO_YOUNG, AGECHECK_SBAN_STEAMID ) return end -- Check whether the entered age and the entered birthday both result in the same age if not ageverify_isAgeMatching( age, day, month, year ) then print( "AgeverifyDebug: AGE MISMATCH!" ) ageverify_reportBan( ply, AGECHECK_BAN_REASON_OTHER_AGE_MISMATCH, -1 ) ageverify_doBan( ply, AGECHECK_DEFAULT_BAN_DURATION, AGECHECK_BAN_REASON_AGE_MISMATCH, AGECHECK_SBAN_STEAMID ) return end -- Check for valid zodiac if not ageverify_isValidZodiacDate( day, month, zodiac ) then print( "AgeverifyDebug: INVALID ZODIAC!" ) ageverify_reportBan( ply, AGECHECK_BAN_REASON_OTHER_WRONG_ZODIAC, AGECHECK_DEFAULT_BAN_DURATION ) ageverify_doBan( ply, AGECHECK_DEFAULT_BAN_DURATION, AGECHECK_BAN_REASON_WRONG_ZODIAC, AGECHECK_SBAN_STEAMID ) return end -- Check for consistent answers if not ageverify_isMatchingPreviousAnswer( data ) then print( "AgeverifyDebug: DATA NOT PERSISTENT!" ) ageverify_reportBan( ply, AGECHECK_BAN_REASON_OTHER_DATA_NOT_PERSISTENT, AGECHECK_DEFAULT_BAN_DURATION ) ageverify_doBan( ply, AGECHECK_DEFAULT_BAN_DURATION, AGECHECK_BAN_REASON_DATA_NOT_PERSISTENT, AGECHECK_SBAN_STEAMID ) return end -- Check the amount of checks there have been for this player local query = "SELECT times FROM agecheck WHERE steamid='" .. sid .. "'" local result = sql.Query( query ) -- If there were not checks before, we add the first if not result then query = "INSERT INTO agecheck VALUES ( NULL, 1, '" .. sid .. "', '" .. sql.SQLStr( ply:Nick(), true ) .. "', '" .. age .. "', '" .. day .. "', '" .. month .. "', '" .. year .. "', '" .. zodiac .. "', CURRENT_TIMESTAMP )" result = sql.Query( query ) -- If there were at least one entry, we increment the amount of times this person was tested and update the date elseif tonumber( result[1].times ) < AGECHECK_MAXIMUM_TEST then query = "UPDATE agecheck SET times=times+1, date=CURRENT_TIMESTAMP WHERE steamid='" .. sid .. "'" result = sql.Query( query ) -- If the person has reached the amount of maximum tests, his data is removed and he's added to the whitelist else ageverify_flushEntriesFromSteamid( sid ) query = "INSERT INTO agecheck_done VALUES ( NULL, '" .. sid .. "', '" .. sql.SQLStr( ply:Nick(), true ) .. "' )" result = sql.Query( query ) end end -- Net message to open the agecheck on the client's PC function ageverify_startCheck( ply, probability, shouldShow ) net.Start( "agecheck_checknecessity" ) net.WriteString( AGECHECK_LANGUAGE ) net.WriteString( AGECHECK_TITLE ) net.WriteString( AGECHECK_TOP_TEXT_ONE ) net.WriteString( AGECHECK_TOP_TEXT_TWO ) net.WriteString( AGECHECK_FORM_TITLE ) net.WriteString( AGECHECK_DISCLAIMER ) net.WriteTable( AGECHECK_ZODIACS ) net.WriteString( shouldShow ) -- For some reason WriteBit and ReadBit didn't work net.WriteFloat( probability ) net.Send( ply ) end -- Receival of the entered data by the client net.Receive( "agecheck_send", function( len, ply ) local message = "" message = net.ReadString() message = string.Split( message, " " ) ageverify_addEntry( message ) end) -- Receival of the client's Steam-ID upon connection or map load + logic whether -- the player should be given the form or not net.Receive( "agecheck_onplayerconnect", function( len, ply ) local steamid = net.ReadString() local probability = AGECHECK_PROBABILITY local playerGroup = ply:GetUserGroup() if AGECHECK_USE_EXCLUDED then local shouldContinue = true for _, group in ipairs( AGECHECK_EXCLUDED_GROUPS ) do if playerGroup == group then shouldContinue = false end end if not shouldContinue then ageverify_flushEntriesFromSteamid( steamid ) -- Make sure we remove all entries if the player has reached a group that isnt checked return end else local shouldContinue = false for _, group in ipairs( AGECHECK_INCLUDED_GROUPS ) do if playerGroup == group then shouldContinue = true end end if not shouldContinue then ageverify_flushEntriesFromSteamid( steamid ) -- Make sure we remove all entries if the player has reached a group that isnt checked return end end local shouldShow = ageverify_needsToBeTested( steamid ) if shouldShow < AGECHECK_MAXIMUM_TEST then if AGECHECK_FORCE_FIRST_TIME and shouldShow == 0 then probability = 100 end shouldShow = "true" else shouldShow = "false" end ageverify_startCheck( player.GetBySteamID( steamid ), probability, shouldShow ) end ) end
mit
jshackley/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Luck_Rune.lua
34
1089
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Luck Rune -- Involved in Quest: Mhaura Fortune -- @pos 573.245 24.999 199.560 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Pashhow_Marshlands/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
jshackley/darkstar
scripts/zones/Behemoths_Dominion/TextIDs.lua
15
1076
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. SENSE_OF_FOREBODING = 6399; -- You are suddenly overcome with a sense of foreboding... NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. IRREPRESSIBLE_MIGHT = 6402; -- An aura of irrepressible might threatens to overwhelm you... -- ZM4 Dialog ZILART_MONUMENT = 7218; -- It is an ancient Zilart monument.?Prompt? ALREADY_OBTAINED_FRAG = 7215; -- You have already obtained this monument's FOUND_ALL_FRAGS = 7217; -- You have obtained ! You now have all 8 fragments of light! CANNOT_REMOVE_FRAG = 7214; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...?Prompt? -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
Ombridride/minetest-minetestforfun-server
mods/christmas_craft/crafts.lua
9
8508
minetest.register_craft({ output = "christmas_craft:christmas_lights 4", recipe = { {"farming:string","default:mese_crystal", "farming:string"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:christmas_leaves 4", recipe = { {"default:leaves","default:leaves"}, {"default:leaves","default:leaves"}, } }) minetest.register_craft({ output = "christmas_craft:christmas_wreath ", recipe = { {"christmas_craft:christmas_leaves","christmas_craft:christmas_leaves","christmas_craft:christmas_leaves"}, {"christmas_craft:christmas_leaves","","christmas_craft:christmas_leaves"}, {"christmas_craft:christmas_leaves","christmas_craft:red_ribbon","christmas_craft:christmas_leaves"}, } }) --[[minetest.register_craft({ output = "christmas_craft:snow_block", recipe = { {"default:snow","default:snow","default:snow"}, {"default:snow","default:snow","default:snow"}, {"default:snow","default:snow","default:snow"}, } })]] minetest.register_craft({ output = "christmas_craft:snowman", recipe = { {"default:coal_lump","default:snow","default:coal_lump"}, {"default:snow","default:snow","default:snow"}, {"default:coal_lump","default:coal_lump","default:coal_lump"}, } }) minetest.register_craft({ output = "christmas_craft:christmas_star ", recipe = { {"","default:gold_ingot",""}, {"default:gold_ingot","default:gold_ingot","default:gold_ingot"}, {"default:gold_ingot","","default:gold_ingot"}, } }) --[[minetest.register_craft({ output = "default:snow 9", recipe = { {"christmas_craft:snow_block"}, } })]] -------------------------- -- baubles - -------------------------- minetest.register_craft({ output = "christmas_craft:red_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:red", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:yellow_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:yellow", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:green_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:green", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:blue_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:blue", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:orange_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:orange", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:pink_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:pink", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:violet_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","dye:violet", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) minetest.register_craft({ output = "christmas_craft:silver_baubles 8", recipe = { {"default:glass","default:gold_ingot", "default:glass"}, {"default:glass","", "default:glass"}, {"default:glass","default:glass", "default:glass"}, } }) -------------------------- -- presents - -------------------------- -- paper colour craft -- minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_red', recipe = {'dye:red','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_blue', recipe = {'dye:blue','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_green', recipe = {'dye:green','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_yellow', recipe = {'dye:yellow','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_yellow', recipe = {'dye:yellow','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_violet', recipe = {'dye:violet','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_orange', recipe = {'dye:orange','default:paper'}, }) minetest.register_craft({ type = "shapeless", output = 'christmas_craft:paper_pink', recipe = {'dye:pink','default:paper'}, }) -- ribbon craft -- minetest.register_craft({ type = "shapeless", output = 'christmas_craft:red_ribbon', recipe = {'dye:red','farming:string'}, }) -- wish list craft -- minetest.register_craft({ type = "shapeless", output = 'christmas_craft:wish_list', recipe = {'group:stick','default:mese_crystal','default:paper','dye:black'}, }) -- present box -- minetest.register_craft({ output = "christmas_craft:present_box", recipe = { {"default:paper","default:paper", "default:paper"}, {"default:paper","christmas_craft:wish_list", "default:paper"}, {"default:paper","default:paper", "default:paper"}, } }) -- present craft -- minetest.register_craft({ output = "christmas_craft:Christmas_present", recipe = { {"default:paper","christmas_craft:red_ribbon", "default:paper"}, {"default:paper","christmas_craft:present_box", "default:paper"}, {"default:paper","christmas_craft:red_ribbon", "default:paper"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_red", recipe = { {"christmas_craft:paper_red","christmas_craft:red_ribbon", "christmas_craft:paper_red"}, {"christmas_craft:paper_red","christmas_craft:present_box", "christmas_craft:paper_red"}, {"christmas_craft:paper_red","christmas_craft:red_ribbon", "christmas_craft:paper_red"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_blue", recipe = { {"christmas_craft:paper_blue","christmas_craft:red_ribbon", "christmas_craft:paper_blue"}, {"christmas_craft:paper_blue","christmas_craft:present_box", "christmas_craft:paper_blue"}, {"christmas_craft:paper_blue","christmas_craft:red_ribbon", "christmas_craft:paper_blue"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_green", recipe = { {"christmas_craft:paper_green","christmas_craft:red_ribbon", "christmas_craft:paper_green"}, {"christmas_craft:paper_green","christmas_craft:present_box", "christmas_craft:paper_green"}, {"christmas_craft:paper_green","christmas_craft:red_ribbon", "christmas_craft:paper_green"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_yellow", recipe = { {"christmas_craft:paper_yellow","christmas_craft:red_ribbon", "christmas_craft:paper_yellow"}, {"christmas_craft:paper_yellow","christmas_craft:present_box", "christmas_craft:paper_yellow"}, {"christmas_craft:paper_yellow","christmas_craft:red_ribbon", "christmas_craft:paper_yellow"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_orange", recipe = { {"christmas_craft:paper_orange","christmas_craft:red_ribbon", "christmas_craft:paper_orange"}, {"christmas_craft:paper_orange","christmas_craft:present_box", "christmas_craft:paper_orange"}, {"christmas_craft:paper_orange","christmas_craft:red_ribbon", "christmas_craft:paper_orange"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_pink", recipe = { {"christmas_craft:paper_pink","christmas_craft:red_ribbon", "christmas_craft:paper_pink"}, {"christmas_craft:paper_pink","christmas_craft:present_box", "christmas_craft:paper_pink"}, {"christmas_craft:paper_pink","christmas_craft:red_ribbon", "christmas_craft:paper_pink"}, } }) minetest.register_craft({ output = "christmas_craft:Christmas_present_violet", recipe = { {"christmas_craft:paper_violet","christmas_craft:red_ribbon", "christmas_craft:paper_violet"}, {"christmas_craft:paper_violet","christmas_craft:present_box", "christmas_craft:paper_violet"}, {"christmas_craft:paper_violet","christmas_craft:red_ribbon", "christmas_craft:paper_violet"}, } })
unlicense
Ombridride/minetest-minetestforfun-server
mods/snow/src/aliases.lua
9
6741
-- Some aliases for compatibility switches and some to make "/give" commands -- a little easier minetest.register_alias("snow:needles", "default:pine_needles") minetest.register_alias("snow:snow", "default:snow") minetest.register_alias("default_snow", "default:snow") minetest.register_alias("snow:snowball", "default:snow") minetest.register_alias("snowball", "default:snow") minetest.register_alias("snowballs", "default:snow") minetest.register_alias("snow_ball", "default:snow") minetest.register_alias("snow:ice", "default:ice") minetest.register_alias("ice", "default:ice") minetest.register_alias("default_ice", "default:ice") minetest.register_alias("snow:dirt_with_snow", "default:dirt_with_snow") minetest.register_alias("dirtwithsnow", "default:dirt_with_snow") minetest.register_alias("snowdirt", "default:dirt_with_snow") minetest.register_alias("snowydirt", "default:dirt_with_snow") minetest.register_alias("snow:snow_block", "default:snowblock") minetest.register_alias("default:snow_block", "default:snowblock") minetest.register_alias("snowblocks", "default:snowblock") minetest.register_alias("snowbrick", "snow:snow_brick") minetest.register_alias("bricksnow", "snow:snow_brick") minetest.register_alias("snowbricks", "snow:snow_brick") minetest.register_alias("snowybricks", "snow:snow_brick") minetest.register_alias("icysnow", "snow:snow_cobble") minetest.register_alias("snowcobble", "snow:snow_cobble") minetest.register_alias("snowycobble", "snow:snow_cobble") minetest.register_alias("cobblesnow", "snow:snow_cobble") minetest.register_alias("snow:leaves", "default:pine_needles") minetest.register_alias("snow:sapling_pine", "default:pine_sapling") -- To clean up my first stairsplus attempt. -- Stair minetest.register_alias(":default:stair_snowblock", "moreblocks:stair_snowblock") minetest.register_alias(":default:stair_snowblock_half", "moreblocks:stair_snowblock_half") minetest.register_alias(":default:stair_snowblock_right_half", "moreblocks:stair_snowblock_right_half") minetest.register_alias(":default:stair_snowblock_inner", "moreblocks:stair_snowblock_inner") minetest.register_alias(":default:stair_snowblock_outer", "moreblocks:stair_snowblock_outer") minetest.register_alias(":default:stair_snowblock_alt", "moreblocks:stair_snowblock_alt") minetest.register_alias(":default:stair_snowblock_alt_1", "moreblocks:stair_snowblock_alt_1") minetest.register_alias(":default:stair_snowblock_alt_2", "moreblocks:stair_snowblock_2") minetest.register_alias(":default:stair_snowblock_alt_4", "moreblocks:stair_snowblock_alt_4") minetest.register_alias(":default:stair_ice", "moreblocks:stair_ice") minetest.register_alias(":default:stair_ice_half", "moreblocks:stair_ice_half") minetest.register_alias(":default:stair_ice_right_half", "moreblocks:stair_ice_right_half") minetest.register_alias(":default:stair_ice_inner", "moreblocks:stair_ice_inner") minetest.register_alias(":default:stair_ice_outer", "moreblocks:stair_ice_outer") minetest.register_alias(":default:stair_ice_alt", "moreblocks:stair_ice_alt") minetest.register_alias(":default:stair_ice_alt_1", "moreblocks:stair_ice_alt_1") minetest.register_alias(":default:stair_ice_alt_2", "moreblocks:stair_ice_2") minetest.register_alias(":default:stair_ice_alt_4", "moreblocks:stair_ice_alt_4") -- Slab minetest.register_alias(":default:slab_snowblock", "moreblocks:slab_snowblock") minetest.register_alias(":default:slab_snowblock_quarter", "moreblocks:slab_snowblock_quarter") minetest.register_alias(":default:slab_snowblock_three_quarter", "moreblocks:slab_snowblock_three_quarter") minetest.register_alias(":default:slab_snowblock_1", "moreblocks:slab_snowblock_1") minetest.register_alias(":default:slab_snowblock_2", "moreblocks:slab_snowblock_2") minetest.register_alias(":default:slab_snowblock_14", "moreblocks:slab_snowblock_14") minetest.register_alias(":default:slab_snowblock_15", "moreblocks:slab_snowblock_15") minetest.register_alias(":default:slab_ice", "moreblocks:slab_ice") minetest.register_alias(":default:slab_ice_quarter", "moreblocks:slab_ice_quarter") minetest.register_alias(":default:slab_ice_three_quarter", "moreblocks:slab_ice_three_quarter") minetest.register_alias(":default:slab_ice_1", "moreblocks:slab_ice_1") minetest.register_alias(":default:slab_ice_2", "moreblocks:slab_ice_2") minetest.register_alias(":default:slab_ice_14", "moreblocks:slab_ice_14") minetest.register_alias(":default:slab_ice_15", "moreblocks:slab_ice_15") -- Panel minetest.register_alias(":default:panel_snowblock", "moreblocks:panel_snowblock") minetest.register_alias(":default:panel_snowblock_1", "moreblocks:panel_snowblock_1") minetest.register_alias(":default:panel_snowblock_2", "moreblocks:panel_snowblock_2") minetest.register_alias(":default:panel_snowblock_4", "moreblocks:panel_snowblock_4") minetest.register_alias(":default:panel_snowblock_12", "moreblocks:panel_snowblock_12") minetest.register_alias(":default:panel_snowblock_14", "moreblocks:panel_snowblock_14") minetest.register_alias(":default:panel_snowblock_15", "moreblocks:panel_snowblock_15") minetest.register_alias(":default:panel_ice", "moreblocks:panel_ice") minetest.register_alias(":default:panel_ice_1", "moreblocks:panel_ice_1") minetest.register_alias(":default:panel_ice_2", "moreblocks:panel_ice_2") minetest.register_alias(":default:panel_ice_4", "moreblocks:panel_ice_4") minetest.register_alias(":default:panel_ice_12", "moreblocks:panel_ice_12") minetest.register_alias(":default:panel_ice_14", "moreblocks:panel_ice_14") minetest.register_alias(":default:panel_ice_15", "moreblocks:panel_ice_15") -- Micro minetest.register_alias(":default:micro_snowblock", "moreblocks:micro_snowblock") minetest.register_alias(":default:micro_snowblock_1", "moreblocks:micro_snowblock_1") minetest.register_alias(":default:micro_snowblock_2", "moreblocks:micro_snowblock_2") minetest.register_alias(":default:micro_snowblock_4", "moreblocks:micro_snowblock_4") minetest.register_alias(":default:micro_snowblock_12", "moreblocks:micro_snowblock_12") minetest.register_alias(":default:micro_snowblock_14", "moreblocks:micro_snowblock_14") minetest.register_alias(":default:micro_snowblock_15", "moreblocks:micro_snowblock_15") minetest.register_alias(":default:micro_ice", "moreblocks:micro_ice") minetest.register_alias(":default:micro_ice_1", "moreblocks:micro_ice_1") minetest.register_alias(":default:micro_ice_2", "moreblocks:micro_ice_2") minetest.register_alias(":default:micro_ice_4", "moreblocks:micro_ice_4") minetest.register_alias(":default:micro_ice_12", "moreblocks:micro_ice_12") minetest.register_alias(":default:micro_ice_14", "moreblocks:micro_ice_14") minetest.register_alias(":default:micro_ice_15", "moreblocks:micro_ice_15")
unlicense
DipColor/mehrabon3
plugins/translate.lua
674
1637
--[[ -- Translate text using Google Translate. -- http://translate.google.com/translate_a/single?client=t&ie=UTF-8&oe=UTF-8&hl=en&dt=t&tl=en&sl=auto&text=hello --]] do function translate(source_lang, target_lang, text) local path = "http://translate.google.com/translate_a/single" -- URL query parameters local params = { client = "t", ie = "UTF-8", oe = "UTF-8", hl = "en", dt = "t", tl = target_lang or "en", sl = source_lang or "auto", text = URL.escape(text) } local query = format_http_params(params, true) local url = path..query local res, code = https.request(url) -- Return nil if error if code > 200 then return nil end local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "") return trans end function run(msg, matches) -- Third pattern if #matches == 1 then print("First") local text = matches[1] return translate(nil, nil, text) end -- Second pattern if #matches == 2 then print("Second") local target = matches[1] local text = matches[2] return translate(nil, target, text) end -- First pattern if #matches == 3 then print("Third") local source = matches[1] local target = matches[2] local text = matches[3] return translate(source, target, text) end end return { description = "Translate some text", usage = { "!translate text. Translate the text to English.", "!translate target_lang text.", "!translate source,target text", }, patterns = { "^!translate ([%w]+),([%a]+) (.+)", "^!translate ([%w]+) (.+)", "^!translate (.+)", }, run = run } end
gpl-2.0
jshackley/darkstar
scripts/globals/quests.lua
13
38222
require("scripts/globals/npc_util"); ----------------------------------- -- -- QUESTS ID -- ----------------------------------- QUEST_AVAILABLE = 0; QUEST_ACCEPTED = 1; QUEST_COMPLETED = 2; ----------------------------------- -- Areas ID ----------------------------------- SANDORIA = 0; BASTOK = 1; WINDURST = 2; JEUNO = 3; OTHER_AREAS = 4; OUTLANDS = 5; AHT_URHGAN = 6; CRYSTAL_WAR = 7; ABYSSEA = 8; ----------------------------------- -- San d'Oria - 0 ----------------------------------- A_SENTRY_S_PERIL = 0; -- ± -- WATER_OF_THE_CHEVAL = 1; -- ± -- ROSEL_THE_ARMORER = 2; -- ± -- THE_PICKPOCKET = 3; -- ± -- FATHER_AND_SON = 4; -- + -- THE_SEAMSTRESS = 5; -- + -- THE_DISMAYED_CUSTOMER = 6; -- + -- THE_TRADER_IN_THE_FOREST = 7; -- + -- THE_SWEETEST_THINGS = 8; -- + -- THE_VICASQUE_S_SERMON = 9; -- + -- A_SQUIRE_S_TEST = 10; -- + -- GRAVE_CONCERNS = 11; -- ± -- THE_BRUGAIRE_CONSORTIUM = 12; -- + -- LIZARD_SKINS = 15; -- + -- FLYERS_FOR_REGINE = 16; -- + -- GATES_TO_PARADISE = 18; -- + -- A_SQUIRE_S_TEST_II = 19; -- + -- TO_CURE_A_COUGH = 20; -- + -- TIGER_S_TEETH = 23; -- ± -- UNDYING_FLAMES = 26; -- + -- A_PURCHASE_OF_ARMS = 27; -- + -- A_KNIGHT_S_TEST = 29; -- + -- THE_MEDICINE_WOMAN = 30; -- + -- BLACK_TIGER_SKINS = 31; -- + -- GROWING_FLOWERS = 58; -- ± -- TRIAL_BY_ICE = 59; -- + -- THE_GENERAL_S_SECRET = 60; -- ± -- THE_RUMOR = 61; -- ± -- HER_MAJESTY_S_GARDEN = 62; -- + -- INTRODUCTION_TO_TEAMWORK = 63; INTERMEDIATE_TEAMWORK = 64; ADVANCED_TEAMWORK = 65; GRIMY_SIGNPOSTS = 66; -- + -- A_JOB_FOR_THE_CONSORTIUM = 67; TROUBLE_AT_THE_SLUICE = 68; -- + -- THE_MERCHANT_S_BIDDING = 69; -- ± -- UNEXPECTED_TREASURE = 70; BLACKMAIL = 71; -- + -- THE_SETTING_SUN = 72; -- + -- DISTANT_LOYALTIES = 74; THE_RIVALRY = 75; -- ± -- THE_COMPETITION = 76; -- ± -- STARTING_A_FLAME = 77; -- ± -- FEAR_OF_THE_DARK = 78; -- + -- WARDING_VAMPIRES = 79; -- + -- SLEEPLESS_NIGHTS = 80; -- ± -- LUFET_S_LAKE_SALT = 81; -- ± -- HEALING_THE_LAND = 82; -- ± -- SORCERY_OF_THE_NORTH = 83; -- ± -- THE_CRIMSON_TRIAL = 84; -- ± -- ENVELOPED_IN_DARKNESS = 85; -- ± -- PEACE_FOR_THE_SPIRIT = 86; -- ± -- MESSENGER_FROM_BEYOND = 87; -- ± -- PRELUDE_OF_BLACK_AND_WHITE = 88; -- ± -- PIEUJE_S_DECISION = 89; -- + -- SHARPENING_THE_SWORD = 90; -- ± -- A_BOY_S_DREAM = 91; -- ± -- UNDER_OATH = 92; THE_HOLY_CREST = 93; -- + -- A_CRAFTSMAN_S_WORK = 94; -- ± -- CHASING_QUOTAS = 95; -- + -- KNIGHT_STALKER = 96; -- + -- ECO_WARRIOR_SAN = 97; METHODS_CREATE_MADNESS = 98; SOULS_IN_SHADOW = 99; A_TASTE_FOR_MEAT = 100; -- ± -- EXIT_THE_GAMBLER = 101; -- ± -- OLD_WOUNDS = 102; ESCORT_FOR_HIRE_SAN_D_ORIA = 103; A_DISCERNING_EYE_SAN_D_ORIA = 104; A_TIMELY_VISIT = 105; FIT_FOR_A_PRINCE = 106; TRIAL_SIZE_TRIAL_BY_ICE = 107; -- + -- SIGNED_IN_BLOOD = 108; -- + -- TEA_WITH_A_TONBERRY = 109; SPICE_GALS = 110; OVER_THE_HILLS_AND_FAR_AWAY = 112; LURE_OF_THE_WILDCAT_SAN_D_ORIA = 113; -- ± -- ATELLOUNE_S_LAMENT = 114; THICK_SHELLS = 117; -- ± -- FOREST_FOR_THE_TREES = 118; ----------------------------------- -- Bastok - 1 ----------------------------------- THE_SIREN_S_TEAR = 0; -- ± -- BEAUTY_AND_THE_GALKA = 1; -- ± -- WELCOME_TO_BASTOK = 2; -- + -- GUEST_OF_HAUTEUR = 3; THE_QUADAV_S_CURSE = 4; -- ± -- OUT_OF_ONE_S_SHELL = 5; -- ± -- HEARTS_OF_MYTHRIL = 6; -- ± -- THE_ELEVENTH_S_HOUR = 7; -- ± -- SHADY_BUSINESS = 8; -- ± -- A_FOREMAN_S_BEST_FRIEND = 9; -- ± -- BREAKING_STONES = 10; -- + -- THE_COLD_LIGHT_OF_DAY = 11; -- + -- GOURMET = 12; -- ± -- THE_ELVAAN_GOLDSMITH = 13; -- ± -- A_FLASH_IN_THE_PAN = 14; -- ± -- SMOKE_ON_THE_MOUNTAIN = 15; -- ± -- STAMP_HUNT = 16; -- + -- FOREVER_TO_HOLD = 17; -- ± -- TILL_DEATH_DO_US_PART = 18; -- ± -- FALLEN_COMRADES = 19; -- ± -- RIVALS = 20; -- + -- MOM_THE_ADVENTURER = 21; -- + -- THE_SIGNPOST_MARKS_THE_SPOT = 22; -- + -- PAST_PERFECT = 23; -- ± -- STARDUST = 24; -- + -- MEAN_MACHINE = 25; -- ± -- CID_S_SECRET = 26; -- ± -- THE_USUAL = 27; -- ± -- BLADE_OF_DARKNESS = 28; -- ± -- FATHER_FIGURE = 29; -- ± -- THE_RETURN_OF_THE_ADVENTURER = 30; -- ± -- DRACHENFALL = 31; -- + -- VENGEFUL_WRATH = 32; -- ± -- BEADEAUX_SMOG = 33; -- + -- THE_CURSE_COLLECTOR = 34; -- + -- FEAR_OF_FLYING = 35; -- + -- THE_WISDOM_OF_ELDERS = 36; -- ± -- GROCERIES = 37; -- ± -- THE_BARE_BONES = 38; -- ± -- MINESWEEPER = 39; -- ± -- THE_DARKSMITH = 40; -- ± -- BUCKETS_OF_GOLD = 41; -- ± -- THE_STARS_OF_IFRIT = 42; -- ± -- LOVE_AND_ICE = 43; -- ± -- BRYGID_THE_STYLIST = 44; -- ± -- THE_GUSTABERG_TOUR = 45; BITE_THE_DUST = 46; -- ± -- BLADE_OF_DEATH = 47; -- + -- SILENCE_OF_THE_RAMS = 48; -- ± -- ALTANA_S_SORROW = 49; -- + -- A_LADY_S_HEART = 50; -- ± -- GHOSTS_OF_THE_PAST = 51; -- ± -- THE_FIRST_MEETING = 52; -- ± -- TRUE_STRENGTH = 53; -- ± -- THE_DOORMAN = 54; -- ± -- THE_TALEKEEPER_S_TRUTH = 55; -- ± -- THE_TALEKEEPER_S_GIFT = 56; -- ± -- DARK_LEGACY = 57; -- ± -- DARK_PUPPET = 58; -- ± -- BLADE_OF_EVIL = 59; -- ± -- AYAME_AND_KAEDE = 60; -- ± -- TRIAL_BY_EARTH = 61; -- ± -- A_TEST_OF_TRUE_LOVE = 62; -- ± -- LOVERS_IN_THE_DUSK = 63; -- ± -- WISH_UPON_A_STAR = 64; ECO_WARRIOR_BAS = 65; THE_WEIGHT_OF_YOUR_LIMITS = 66; SHOOT_FIRST_ASK_QUESTIONS_LATER = 67; INHERITANCE = 68; THE_WALLS_OF_YOUR_MIND = 69; ESCORT_FOR_HIRE_BASTOK = 70; A_DISCERNING_EYE_BASTOK = 71; TRIAL_SIZE_TRIAL_BY_EARTH = 72; -- + -- FADED_PROMISES = 73; BRYGID_THE_STYLIST_RETURNS = 74; -- ± -- OUT_OF_THE_DEPTHS = 75; ALL_BY_MYSELF = 76; A_QUESTION_OF_FAITH = 77; RETURN_OF_THE_DEPTHS = 78; TEAK_ME_TO_THE_STARS = 79; HYPER_ACTIVE = 80; THE_NAMING_GAME = 81; CHIPS = 82; BAIT_AND_SWITCH = 83; LURE_OF_THE_WILDCAT_BASTOK = 84; ACHIEVING_TRUE_POWER = 85; TOO_MANY_CHEFS = 86; A_PROPER_BURIAL = 87; FULLY_MENTAL_ALCHEMIST = 88; SYNERGUSTIC_PURSUITS = 89; THE_WONDROUS_WHATCHAMACALLIT = 90; ----------------------------------- -- Windurst - 2 ----------------------------------- HAT_IN_HAND = 0; -- + -- A_FEATHER_IN_ONE_S_CAP = 1; -- + -- A_CRISIS_IN_THE_MAKING = 2; -- + -- MAKING_AMENDS = 3; -- + -- MAKING_THE_GRADE = 4; -- + -- IN_A_PICKLE = 5; -- + -- WONDERING_MINSTREL = 6; -- + -- A_POSE_BY_ANY_OTHER_NAME = 7; -- + -- MAKING_AMENS = 8; -- + -- THE_MOONLIT_PATH = 9; -- + -- STAR_STRUCK = 10; -- ± -- BLAST_FROM_THE_PAST = 11; -- + -- A_SMUDGE_ON_ONE_S_RECORD = 12; -- ± -- CHASING_TALES = 13; -- + -- FOOD_FOR_THOUGHT = 14; -- + -- OVERNIGHT_DELIVERY = 15; -- + -- WATER_WAY_TO_GO = 16; -- + -- BLUE_RIBBON_BLUES = 17; -- + -- THE_ALL_NEW_C_3000 = 18; -- + -- THE_POSTMAN_ALWAYS_KO_S_TWICE = 19; -- + -- EARLY_BIRD_CATCHES_THE_BOOKWORM = 20; -- + -- CATCH_IT_IF_YOU_CAN = 21; -- + -- ALL_AT_SEA = 23; THE_ALL_NEW_C_2000 = 24; -- ± -- MIHGO_S_AMIGO = 25; -- + -- ROCK_RACKETTER = 26; -- + -- CHOCOBILIOUS = 27; -- + -- TEACHER_S_PET = 28; -- + -- REAP_WHAT_YOU_SOW = 29; -- + -- GLYPH_HANGER = 30; -- + -- THE_FANGED_ONE = 31; -- + -- CURSES_FOILED_AGAIN_1 = 32; -- + -- CURSES_FOILED_AGAIN_2 = 33; -- + -- MANDRAGORA_MAD = 34; -- + -- TO_BEE_OR_NOT_TO_BEE = 35; -- + -- TRUTH_JUSTICE_AND_THE_ONION_WAY = 36; -- + -- MAKING_HEADLINES = 37; -- + -- SCOOPED = 38; CREEPY_CRAWLIES = 39; -- + -- KNOW_ONE_S_ONIONS = 40; -- + -- INSPECTOR_S_GADGET = 41; -- + -- ONION_RINGS = 42; -- + -- A_GREETING_CARDIAN = 43; -- + -- LEGENDARY_PLAN_B = 44; -- + -- IN_A_STEW = 45; -- + -- LET_SLEEPING_DOGS_LIE = 46; CAN_CARDIANS_CRY = 47; -- + -- WONDER_WANDS = 48; -- + -- HEAVEN_CENT = 49; SAY_IT_WITH_FLOWERS = 50; -- + -- HOIST_THE_JELLY_ROGER = 51; -- + -- SOMETHING_FISHY = 52; -- + -- TO_CATCH_A_FALLIHG_STAR = 53; -- + -- PAYING_LIP_SERVICE = 60; -- + -- THE_AMAZIN_SCORPIO = 61; -- + -- TWINSTONE_BONDING = 62; -- + -- CURSES_FOILED_A_GOLEM = 63; -- + -- ACTING_IN_GOOD_FAITH = 64; -- ± -- FLOWER_CHILD = 65; -- ± -- THE_THREE_MAGI = 66; -- ± -- RECOLLECTIONS = 67; -- ± -- THE_ROOT_OF_THE_PROBLEM = 68; THE_TENSHODO_SHOWDOWN = 69; -- + -- AS_THICK_AS_THIEVES = 70; -- + -- HITTING_THE_MARQUISATE = 71; -- + -- SIN_HUNTING = 72; -- + -- FIRE_AND_BRIMSTONE = 73; -- + -- UNBRIDLED_PASSION = 74; -- + -- I_CAN_HEAR_A_RAINBOW = 75; -- + -- CRYING_OVER_ONIONS = 76; -- + -- WILD_CARD = 77; -- + -- THE_PROMISE = 78; -- + -- NOTHING_MATTERS = 79; TORAIMARAI_TURMOIL = 80; -- + -- THE_PUPPET_MASTER = 81; -- + -- CLASS_REUNION = 82; -- + -- CARBUNCLE_DEBACLE = 83; -- + -- ECO_WARRIOR_WIN = 84; -- + -- FROM_SAPLINGS_GROW = 85; ORASTERY_WOES = 86; BLOOD_AND_GLORY = 87; ESCORT_FOR_HIRE_WINDURST = 88; A_DISCERNING_EYE_WINDURST = 89; TUNING_IN = 90; TUNING_OUT = 91; ONE_GOOD_DEED = 92; WAKING_DREAMS = 93; -- + -- LURE_OF_THE_WILDCAT_WINDURST = 94; BABBAN_NY_MHEILLEA = 95; ----------------------------------- -- Jeuno - 3 ----------------------------------- CREST_OF_DAVOI = 0; -- + -- SAVE_MY_SISTER = 1; -- + -- A_CLOCK_MOST_DELICATE = 2; -- + -- SAVE_THE_CLOCK_TOWER = 3; -- + -- CHOCOBO_S_WOUNDS = 4; -- + -- SAVE_MY_SON = 5; -- + -- A_CANDLELIGHT_VIGIL = 6; -- + -- THE_WONDER_MAGIC_SET = 7; -- + -- THE_KIND_CARDIAN = 8; -- + -- YOUR_CRYSTAL_BALL = 9; -- + -- COLLECT_TARUT_CARDS = 10; -- + -- THE_OLD_MONUMENT = 11; -- + -- A_MINSTREL_IN_DESPAIR = 12; -- + -- RUBBISH_DAY = 13; -- + -- NEVER_TO_RETURN = 14; -- + -- COMMUNITY_SERVICE = 15; -- + -- COOK_S_PRIDE = 16; -- + -- TENSHODO_MEMBERSHIP = 17; -- + -- THE_LOST_CARDIAN = 18; -- + -- PATH_OF_THE_BEASTMASTER = 19; -- + -- PATH_OF_THE_BARD = 20; -- + -- THE_CLOCKMASTER = 21; -- + -- CANDLE_MAKING = 22; -- + -- CHILD_S_PLAY = 23; -- + -- NORTHWARD = 24; -- + -- THE_ANTIQUE_COLLECTOR = 25; -- + -- DEAL_WITH_TENSHODO = 26; -- + -- THE_GOBBIEBAG_PART_I = 27; -- + -- THE_GOBBIEBAG_PART_II = 28; -- + -- THE_GOBBIEBAG_PART_III = 29; -- + -- THE_GOBBIEBAG_PART_IV = 30; -- + -- MYSTERIES_OF_BEADEAUX_I = 31; -- + -- MYSTERIES_OF_BEADEAUX_II = 32; -- + -- MYSTERY_OF_FIRE = 33; MYSTERY_OF_WATER = 34; MYSTERY_OF_EARTH = 35; MYSTERY_OF_WIND = 36; MYSTERY_OF_ICE = 37; MYSTERY_OF_LIGHTNING = 38; MYSTERY_OF_LIGHT = 39; MYSTERY_OF_DARKNESS = 40; FISTFUL_OF_FURY = 41; -- + -- THE_GOBLIN_TAILOR = 42; -- + -- PRETTY_LITTLE_THINGS = 43; -- ± -- BORGHERTZ_S_WARRING_HANDS = 44; -- + -- BORGHERTZ_S_STRIKING_HANDS = 45; -- + -- BORGHERTZ_S_HEALING_HANDS = 46; -- + -- BORGHERTZ_S_SORCEROUS_HANDS = 47; -- + -- BORGHERTZ_S_VERMILLION_HANDS = 48; -- + -- BORGHERTZ_S_SNEAKY_HANDS = 49; -- + -- BORGHERTZ_S_STALWART_HANDS = 50; -- + -- BORGHERTZ_S_SHADOWY_HANDS = 51; -- + -- BORGHERTZ_S_WILD_HANDS = 52; -- + -- BORGHERTZ_S_HARMONIOUS_HANDS = 53; -- + -- BORGHERTZ_S_CHASING_HANDS = 54; -- + -- BORGHERTZ_S_LOYAL_HANDS = 55; -- + -- BORGHERTZ_S_LURKING_HANDS = 56; -- + -- BORGHERTZ_S_DRAGON_HANDS = 57; -- + -- BORGHERTZ_S_CALLING_HANDS = 58; -- + -- AXE_THE_COMPETITION = 59; WINGS_OF_GOLD = 60; -- ± -- SCATTERED_INTO_SHADOW = 61; -- ± -- A_NEW_DAWN = 62; PAINFUL_MEMORY = 63; -- + -- THE_REQUIEM = 64; -- + -- THE_CIRCLE_OF_TIME = 65; -- + -- SEARCHING_FOR_THE_RIGHT_WORDS = 66; BEAT_AROUND_THE_BUSHIN = 67; -- + -- DUCAL_HOSPITALITY = 68; IN_THE_MOOD_FOR_LOVE = 69; EMPTY_MEMORIES = 70; HOOK_LINE_AND_SINKER = 71; A_CHOCOBO_S_TALE = 72; A_REPUTATION_IN_RUINS = 73; THE_GOBBIEBAG_PART_V = 74; -- + -- THE_GOBBIEBAG_PART_VI = 75; -- + -- BEYOND_THE_SUN = 76; UNLISTED_QUALITIES = 77; GIRL_IN_THE_LOOKING_GLASS = 78; MIRROR_MIRROR = 79; -- + -- PAST_REFLECTIONS = 80; BLIGHTED_GLOOM = 81; BLESSED_RADIANCE = 82; MIRROR_IMAGES = 83; CHAMELEON_CAPERS = 84; REGAINING_TRUST = 85; STORMS_OF_FATE = 86; MIXED_SIGNALS = 87; SHADOWS_OF_THE_DEPARTED = 88; APOCALYPSE_NIGH = 89; LURE_OF_THE_WILDCAT_JEUNO = 90; -- ± -- THE_ROAD_TO_AHT_URHGAN = 91; -- + -- CHOCOBO_ON_THE_LOOSE = 92; THE_GOBBIEBAG_PART_VII = 93; -- + -- THE_GOBBIEBAG_PART_VIII = 94; -- + -- LAKESIDE_MINUET = 95; THE_UNFINISHED_WALTZ = 96; -- ± -- THE_ROAD_TO_DIVADOM = 97; COMEBACK_QUEEN = 98; A_FURIOUS_FINALE = 99; THE_MIRACULOUS_DALE = 100; CLASH_OF_THE_COMRADES = 101; UNLOCKING_A_MYTH_WARRIOR = 102; UNLOCKING_A_MYTH_MONK = 103; UNLOCKING_A_MYTH_WHITE_MAGE = 104; UNLOCKING_A_MYTH_BLACK_MAGE = 105; UNLOCKING_A_MYTH_RED_MAGE = 106; UNLOCKING_A_MYTH_THIEF = 107; UNLOCKING_A_MYTH_PALADIN = 108; UNLOCKING_A_MYTH_DARK_KNIGHT = 109; UNLOCKING_A_MYTH_BEASTMASTER = 110; UNLOCKING_A_MYTH_BARD = 111; UNLOCKING_A_MYTH_RANGER = 112; UNLOCKING_A_MYTH_SAMURAI = 113; UNLOCKING_A_MYTH_NINJA = 114; UNLOCKING_A_MYTH_DRAGOON = 115; UNLOCKING_A_MYTH_SUMMONER = 116; UNLOCKING_A_MYTH_BLUE_MAGE = 117; UNLOCKING_A_MYTH_CORSAIR = 118; UNLOCKING_A_MYTH_PUPPETMASTER = 119; UNLOCKING_A_MYTH_DANCER = 120; UNLOCKING_A_MYTH_SCHOLAR = 121; THE_GOBBIEBAG_PART_IX = 123; -- + -- THE_GOBBIEBAG_PART_X = 124; -- + -- IN_DEFIANT_CHALLENGE = 128; -- + -- ATOP_THE_HIGHEST_MOUNTAINS = 129; -- + -- WHENCE_BLOWS_THE_WIND = 130; -- + -- RIDING_ON_THE_CLOUDS = 131; -- + -- SHATTERING_STARS = 132; -- + -- NEW_WORLDS_AWAIT = 133; EXPANDING_HORIZONS = 134; BEYOND_THE_STARS = 135; DORMANT_POWERS_DISLODGED = 136; BEYOND_INFINITY = 137; A_TRIAL_IN_TANDEM = 160; A_TRIAL_IN_TANDEM_REDUX = 161; YET_ANOTHER_TRIAL_IN_TANDEM = 162; A_QUATERNARY_TRIAL_IN_TANDEM = 163; A_TRIAL_IN_TANDEM_REVISITED = 164; ALL_IN_THE_CARDS = 166; MARTIAL_MASTERY = 167; VW_OP_115_VALKURM_DUSTER = 168; VW_OP_118_BUBURIMU_SQUALL = 169; PRELUDE_TO_PUISSANCE = 170; ----------------------------------- -- Other Areas - 4 ----------------------------------- RYCHARDE_THE_CHEF = 0; -- + -- WAY_OF_THE_COOK = 1; -- + -- UNENDING_CHASE = 2; -- + -- HIS_NAME_IS_VALGEIR = 3; -- + -- EXPERTISE = 4; -- + -- THE_CLUE = 5; -- + -- THE_BASICS = 6; -- + -- ORLANDO_S_ANTIQUES = 7; -- + -- THE_SAND_CHARM = 8; -- + -- A_POTTER_S_PREFERENCE = 9; -- + -- THE_OLD_LADY = 10; -- + -- FISHERMAN_S_HEART = 11; DONATE_TO_RECYCLING = 16; -- + -- UNDER_THE_SEA = 17; -- + -- ONLY_THE_BEST = 18; -- + -- EN_EXPLORER_S_FOOTSTEPS = 19; -- + -- CARGO = 20; -- + -- THE_GIFT = 21; -- + -- THE_REAL_GIFT = 22; -- + -- THE_RESCUE = 23; -- + -- ELDER_MEMORIES = 24; -- + -- TEST_MY_METTLE = 25; INSIDE_THE_BELLY = 26; -- ± -- TRIAL_BY_LIGHTNING = 27; -- ± -- TRIAL_SIZE_TRIAL_BY_LIGHTNING = 28; -- + -- IT_S_RAINING_MANNEQUINS = 29; RECYCLING_RODS = 30; PICTURE_PERFECT = 31; WAKING_THE_BEAST = 32; SURVIVAL_OF_THE_WISEST = 33; A_HARD_DAY_S_KNIGHT = 64; X_MARKS_THE_SPOT = 65; A_BITTER_PAST = 66; THE_CALL_OF_THE_SEA = 67; PARADISE_SALVATION_AND_MAPS = 68; GO_GO_GOBMUFFIN = 69; THE_BIG_ONE = 70; FLY_HIGH = 71; UNFORGIVEN = 72; SECRETS_OF_OVENS_LOST = 73; PETALS_FOR_PARELBRIAUX = 74; ELDERLY_PURSUITS = 75; IN_THE_NAME_OF_SCIENCE = 76; BEHIND_THE_SMILE = 77; KNOCKING_ON_FORBIDDEN_DOORS = 78; CONFESSIONS_OF_A_BELLMAKER = 79; IN_SEARCH_OF_THE_TRUTH = 80; UNINVITED_GUESTS = 81; TANGO_WITH_A_TRACKER = 82; REQUIEM_OF_SIN = 83; VW_OP_026_TAVNAZIAN_TERRORS = 84; VW_OP_004_BIBIKI_BOMBARDMENT = 85; BOMBS_AWAY = 96; MITHRAN_DELICACIES = 97; GIVE_A_MOOGLE_A_BREAK = 100; THE_MOOGLE_PICNIC = 101; MOOGLE_IN_THE_WILD = 102; MISSIONARY_MOBLIN = 103; FOR_THE_BIRDS = 104; BETTER_THE_DEMON_YOU_KNOW = 105; AN_UNDERSTANDING_OVERLORD = 106; AN_AFFABLE_ADAMANTKING = 107; A_MORAL_MANIFEST = 108; A_GENEROUS_GENERAL = 109; RECORDS_OF_EMINENCE = 110; UNITY_CONCORD = 111; ----------------------------------- -- Outlands - 5 ----------------------------------- -- Kazham (1-15) THE_FIREBLOOM_TREE = 1; GREETINGS_TO_THE_GUARDIAN = 2; -- + -- A_QUESTION_OF_TASTE = 3; EVERYONES_GRUDGING = 4; YOU_CALL_THAT_A_KNIFE = 6; MISSIONARY_MAN = 7; -- ± -- GULLIBLES_TRAVELS = 8; -- + -- EVEN_MORE_GULLIBLES_TRAVELS = 9; -- + -- PERSONAL_HYGIENE = 10; -- + -- THE_OPO_OPO_AND_I = 11; -- + -- TRIAL_BY_FIRE = 12; -- ± -- CLOAK_AND_DAGGER = 13; A_DISCERNING_EYE_KAZHAM = 14; TRIAL_SIZE_TRIAL_BY_FIRE = 15; -- + -- -- Voidwatch (100-105) VOIDWATCH_OPS_BORDER_CROSSING = 100; VW_OP_054_ELSHIMO_LIST = 101; VW_OP_101_DETOUR_TO_ZEPWELL = 102; VW_OP_115_LI_TELOR_VARIANT = 103; SKYWARD_HO_VOIDWATCHER = 104; -- Norg (128-149) THE_SAHAGINS_KEY = 128; -- ± -- FORGE_YOUR_DESTINY = 129; -- ± -- BLACK_MARKET = 130; MAMA_MIA = 131; STOP_YOUR_WHINING = 132; -- + -- TRIAL_BY_WATER = 133; -- + -- EVERYONES_GRUDGE = 134; SECRET_OF_THE_DAMP_SCROLL = 135; -- ± -- THE_SAHAGINS_STASH = 136; -- + -- ITS_NOT_YOUR_VAULT = 137; -- + -- LIKE_A_SHINING_SUBLIGAR = 138; -- + -- LIKE_A_SHINING_LEGGINGS = 139; -- + -- THE_SACRED_KATANA = 140; -- ± -- YOMI_OKURI = 141; -- ± -- A_THIEF_IN_NORG = 142; -- ± -- TWENTY_IN_PIRATE_YEARS = 143; -- ± -- I_LL_TAKE_THE_BIG_BOX = 144; -- ± -- TRUE_WILL = 145; -- ± -- THE_POTENTIAL_WITHIN = 146; BUGI_SODEN = 147; TRIAL_SIZE_TRIAL_BY_WATER = 148; -- + -- AN_UNDYING_PLEDGE = 149; -- Misc (160-165) WRATH_OF_THE_OPO_OPOS = 160; WANDERING_SOULS = 161; SOUL_SEARCHING = 162; DIVINE_MIGHT = 163; -- ± -- DIVINE_MIGHT_REPEAT = 164; -- ± -- OPEN_SESAME = 165; -- Rabao (192-201) DONT_FORGET_THE_ANTIDOTE = 192; -- ± -- THE_MISSING_PIECE = 193; -- ± -- TRIAL_BY_WIND = 194; -- ± -- THE_KUFTAL_TOUR = 195; THE_IMMORTAL_LU_SHANG = 196; -- ± -- TRIAL_SIZE_TRIAL_BY_WIND = 197; -- ± -- CHASING_DREAMS = 199; -- CoP Quest THE_SEARCH_FOR_GOLDMANE = 200; -- CoP Quest INDOMITABLE_SPIRIT = 201; -- ± -- ----------------------------------- -- Aht Urhgan - 6 ----------------------------------- KEEPING_NOTES = 0; ARTS_AND_CRAFTS = 1; OLDUUM = 2; -- + -- GOT_IT_ALL = 3; -- + -- GET_THE_PICTURE = 4; AN_EMPTY_VESSEL = 5; -- + -- LUCK_OF_THE_DRAW = 6; -- ± -- NO_STRINGS_ATTACHED = 7; -- + -- FINDING_FAULTS = 8; GIVE_PEACE_A_CHANCE = 9; THE_ART_OF_WAR = 10; na = 11; A_TASTE_OF_HONEY = 12; SUCH_SWEET_SORROW = 13; FEAR_OF_THE_DARK_II = 14; -- + -- COOK_A_ROON = 15; THE_DIE_IS_CAST = 16; TWO_HORN_THE_SAVAGE = 17; TOTOROONS_TREASURE_HUNT = 18; WHAT_FRIENDS_ARE_FOR = 19; ROCK_BOTTOM = 20; BEGINNINGS = 21; OMENS = 22; TRANSFORMATIONS = 23; EQUIPED_FOR_ALL_OCCASIONS = 24; -- + -- NAVIGATING_THE_UNFRIENDLY_SEAS = 25; -- + -- AGAINST_ALL_ODDS = 26; THE_WAYWARD_AUTOMATION = 27; OPERATION_TEATIME = 28; PUPPETMASTER_BLUES = 29; MOMENT_OF_TRUTH = 30; THREE_MEN_AND_A_CLOSET = 31; -- + -- FIVE_SECONDS_OF_FAME = 32; DELIVERING_THE_GOODS = 61; -- + -- VANISHING_ACT = 62; -- + -- STRIKING_A_BALANCE = 63; NOT_MEANT_TO_BE = 64; -- + -- LED_ASTRAY = 65; RAT_RACE = 66; -- + -- THE_PRINCE_AND_THE_HOPPER = 67; VW_OP_050_AHT_URGAN_ASSAULT = 68; VW_OP_068_SUBTERRAINEAN_SKIRMISH= 69; AN_IMPERIAL_HEIST = 70; DUTIES_TASKS_AND_DEEDS = 71; FORGING_A_NEW_MYTH = 72; COMING_FULL_CIRCLE = 73; WAKING_THE_COLLOSSUS = 74; DIVINE_INTERFERANCE = 75; THE_RIDER_COMETH = 76; UNWAVERING_RESOLVE = 77; A_STYGIAN_PACT = 78; ----------------------------------- -- Crystal War - 7 ----------------------------------- LOST_IN_TRANSLOCATION = 0; MESSAGE_ON_THE_WINDS = 1; THE_WEEKLY_ADVENTURER = 2; HEALING_HERBS = 3; REDEEMING_ROCKS = 4; THE_DAWN_OF_DELECTABILITY = 5; A_LITTLE_KNOWLEDGE = 6; -- + -- THE_FIGHTING_FOURTH = 7; SNAKE_ON_THE_PLAINS = 8; -- + -- STEAMED_RAMS = 9; -- + -- SEEING_SPOTS = 10; -- + -- THE_FLIPSIDE_OF_THINGS = 11; BETTER_PART_OF_VALOR = 12; FIRES_OF_DISCONTENT = 13; HAMMERING_HEARTS = 14; GIFTS_OF_THE_GRIFFON = 15; CLAWS_OF_THE_GRIFFON = 16; THE_TIGRESS_STIRS = 17; -- + -- THE_TIGRESS_STRIKES = 18; LIGHT_IN_THE_DARKNESS = 19; BURDEN_OF_SUSPICION = 20; EVIL_AT_THE_INLET = 21; THE_FUMBLING_FRIAR = 22; REQUIEM_FOR_THE_DEPARTED = 23; BOY_AND_THE_BEAST = 24; WRATH_OF_THE_GRIFFON = 25; THE_LOST_BOOK = 26; KNOT_QUITE_THERE = 27; A_MANIFEST_PROBLEM = 28; BEANS_AHOY = 29; -- + -- BEAST_FROM_THE_EAST = 30; THE_SWARM = 31; ON_SABBATICAL = 32; DOWNWARD_HELIX = 33; SEEING_BLOOD_RED = 34; STORM_ON_THE_HORIZON = 35; FIRE_IN_THE_HOLE = 36; PERILS_OF_THE_GRIFFON = 37; IN_A_HAZE_OF_GLORY = 38; WHEN_ONE_MAN_IS_NOT_ENOUGH = 39; A_FEAST_FOR_GNATS = 40; SAY_IT_WITH_A_HANDBAG = 41; QUELLING_THE_STORM = 42; HONOR_UNDER_FIRE = 43; THE_PRICE_OF_VALOR = 44; BONDS_THAT_NEVER_DIE = 45; THE_LONG_MARCH_NORTH = 46; THE_FORBIDDEN_PATH = 47; A_JEWELERS_LAMENT = 48; BENEATH_THE_MASK = 49; WHAT_PRICE_LOYALTY = 50; SONGBIRDS_IN_A_SNOWSTORM = 51; BLOOD_OF_HEROES = 52; SINS_OF_THE_MOTHERS = 53; HOWL_FROM_THE_HEAVENS = 54; SUCCOR_TO_THE_SIDHE = 55; THE_YOUNG_AND_THE_THREADLESS = 56; SON_AND_FATHER = 57; THE_TRUTH_LIES_HID = 58; BONDS_OF_MYTHRIL = 59; CHASING_SHADOWS = 60; FACE_OF_THE_FUTURE = 61; MANIFEST_DESTINY = 62; AT_JOURNEYS_END = 63; HER_MEMORIES_HOMECOMING_QUEEN = 64; HER_MEMORIES_OLD_BEAN = 65; HER_MEMORIES_THE_FAUX_PAS = 66; HER_MEMORIES_THE_GRAVE_RESOLVE = 67; HER_MEMORIES_OPERATION_CUPID = 68; HER_MEMORIES_CARNELIAN_FOOTFALLS = 69; HER_MEMORIES_AZURE_FOOTFALLS = 70; HER_MEMORIES_VERDURE_FOOTFALLS = 71; HER_MEMORIES_OF_MALIGN_MALADIES = 72; GUARDIAN_OF_THE_VOID = 80; DRAFTED_BY_THE_DUCHY = 81; BATTLE_ON_A_NEW_FRONT = 82; VOIDWALKER_OP_126 = 83; A_CAIT_CALLS = 84; THE_TRUTH_IS_OUT_THERE = 85; REDRAFTED_BY_THE_DUCHY = 86; A_NEW_MENACE = 87; NO_REST_FOR_THE_WEARY = 88; A_WORLD_IN_FLUX = 89; BETWEEN_A_ROCK_AND_RIFT = 90; A_FAREWELL_TO_FELINES = 91; THIRD_TOUR_OF_DUCHY = 92; GLIMMER_OF_HOPE = 93; BRACE_FOR_THE_UNKNOWN = 94; PROVENANCE = 95; CRYSTAL_GUARDIAN = 96; ENDINGS_AND_BEGINNINGS = 97; AD_INFINITUM = 98; ----------------------------------- -- Abyssea - 8 ----------------------------------- -- For some reason these did not match dat file order, -- had to adjust IDs >120 after using @addquest CATERING_CAPERS = 0; GIFT_OF_LIGHT = 1; FEAR_OF_THE_DARK_III = 2; AN_EYE_FOR_REVENGE = 3; UNBREAK_HIS_HEART = 4; EXPLOSIVE_ENDEAVORS = 5; THE_ANGLING_ARMORER = 6; WATER_OF_LIFE = 7; OUT_OF_TOUCH = 8; LOST_MEMORIES = 9; HOPE_BLOOMS_ON_THE_BATTLEFIELD = 10; OF_MALNOURISHED_MARTELLOS = 11; ROSE_ON_THE_HEATH = 12; FULL_OF_HIMSELF_ALCHEMIST = 13; THE_WALKING_WOUNDED = 14; SHADY_BUSINESS_REDUX = 15; ADDLED_MIND_UNDYING_DREAMS = 16; THE_SOUL_OF_THE_MATTER = 17; SECRET_AGENT_MAN = 18; PLAYING_PAPARAZZI = 19; HIS_BOX_HIS_BELOVED = 20; WEAPONS_NOT_WORRIES = 21; CLEANSING_THE_CANYON = 22; SAVORY_SALVATION = 23; BRINGING_DOWN_THE_MOUNTAIN = 24; A_STERLING_SPECIMEN = 25; FOR_LOVE_OF_A_DAUGHTER = 26; SISTERS_IN_CRIME = 27; WHEN_GOOD_CARDIANS_GO_BAD = 28; TANGLING_WITH_TONGUE_TWISTERS = 29; A_WARD_TO_END_ALL_WARDS = 30; THE_BOXWATCHERS_BEHEST = 31; HIS_BRIDGE_HIS_BELOVED = 32; BAD_COMMUNICATION = 33; FAMILY_TIES = 34; AQUA_PURA = 35; AQUA_PURAGA = 36; WHITHER_THE_WHISKER = 37; SCATTERED_SHELLS_SCATTERED_MIND = 38; WAYWARD_WARES = 39; LOOKING_FOR_LOOKOUTS = 40; FLOWN_THE_COOP = 41; THREADBARE_TRIBULATIONS = 42; AN_OFFER_YOU_CANT_REFUSE = 43; SOMETHING_IN_THE_AIR = 44; AN_ACRIDIDAEN_ANODYNE = 45; HAZY_PROSPECTS = 46; FOR_WANT_OF_A_POT = 47; MISSING_IN_ACTION = 48; I_DREAM_OF_FLOWERS = 49; DESTINY_ODYSSEY = 50; UNIDENTIFIED_RESEARCH_OBJECT = 51; COOKBOOK_OF_HOPE_RESTORING = 52; SMOKE_OVER_THE_COAST = 53; SOIL_AND_GREEN = 54; DROPPING_THE_BOMB = 55; WANTED_MEDICAL_SUPPLIES = 56; VOICES_FROM_BEYOND = 57; BENEVOLENCE_LOST = 58; BRUGAIRES_AMBITION = 59; CHOCOBO_PANIC = 60; THE_EGG_ENTHUSIAST = 61; GETTING_LUCKY = 62; HER_FATHERS_LEGACY = 63; THE_MYSTERIOUS_HEAD_PATROL = 64; MASTER_MISSING_MASTER_MISSED = 65; THE_PERILS_OF_KORORO = 66; LET_THERE_BE_LIGHT = 67; LOOK_OUT_BELOW = 68; HOME_HOME_ON_THE_RANGE = 69; IMPERIAL_ESPIONAGE = 70; IMPERIAL_ESPIONAGE_II = 71; BOREAL_BLOSSOMS = 72; BROTHERS_IN_ARMS = 73; SCOUTS_ASTRAY = 74; FROZEN_FLAME_REDUX = 75; SLIP_SLIDIN_AWAY = 76; CLASSROOMS_WITHOUT_BORDERS = 77; THE_SECRET_INGREDIENT = 78; HELP_NOT_WANTED = 79; THE_TITUS_TOUCH = 80; SLACKING_SUBORDINATES = 81; MOTHERLY_LOVE = 82; LOOK_TO_THE_SKY = 83; THE_UNMARKED_TOMB = 84; PROOF_OF_THE_LION = 85; BRYGID_THE_STYLIST_STRIKES_BACK = 86; DOMINION_OP_01_ALTEPA = 87; DOMINION_OP_02_ALTEPA = 88; DOMINION_OP_03_ALTEPA = 89; DOMINION_OP_04_ALTEPA = 90; DOMINION_OP_05_ALTEPA = 91; DOMINION_OP_06_ALTEPA = 92; DOMINION_OP_07_ALTEPA = 93; DOMINION_OP_08_ALTEPA = 94; DOMINION_OP_09_ALTEPA = 95; DOMINION_OP_10_ALTEPA = 96; DOMINION_OP_11_ALTEPA = 97; DOMINION_OP_12_ALTEPA = 98; DOMINION_OP_13_ALTEPA = 99; DOMINION_OP_14_ALTEPA = 100; DOMINION_OP_01_ULEGUERAND = 101; DOMINION_OP_02_ULEGUERAND = 102; DOMINION_OP_03_ULEGUERAND = 103; DOMINION_OP_04_ULEGUERAND = 104; DOMINION_OP_05_ULEGUERAND = 105; DOMINION_OP_06_ULEGUERAND = 106; DOMINION_OP_07_ULEGUERAND = 107; DOMINION_OP_08_ULEGUERAND = 108; DOMINION_OP_09_ULEGUERAND = 109; DOMINION_OP_10_ULEGUERAND = 110; DOMINION_OP_11_ULEGUERAND = 111; DOMINION_OP_12_ULEGUERAND = 112; DOMINION_OP_13_ULEGUERAND = 113; DOMINION_OP_14_ULEGUERAND = 114; DOMINION_OP_01_GRAUBERG = 115; DOMINION_OP_02_GRAUBERG = 116; DOMINION_OP_03_GRAUBERG = 117; DOMINION_OP_04_GRAUBERG = 118; DOMINION_OP_05_GRAUBERG = 119; DOMINION_OP_06_GRAUBERG = 120; DOMINION_OP_07_GRAUBERG = 121; DOMINION_OP_08_GRAUBERG = 122; DOMINION_OP_09_GRAUBERG = 123; WARD_WARDEN_I_ATTOHWA = 124; WARD_WARDEN_I_MISAREAUX = 125; WARD_WARDEN_I_VUNKERL = 126; WARD_WARDEN_II_ATTOHWA = 127; WARD_WARDEN_II_MISAREAUX = 128; WARD_WARDEN_II_VUNKERL = 129; DESERT_RAIN_I_ATTOHWA = 130; DESERT_RAIN_I_MISAREAUX = 131; DESERT_RAIN_I_VUNKERL = 132; DESERT_RAIN_II_ATTOHWA = 133; DESERT_RAIN_II_MISAREAUX = 134; DESERT_RAIN_II_VUNKERL = 135; CRIMSON_CARPET_I_ATTOHWA = 136; CRIMSON_CARPET_I_MISAREAUX = 137; CRIMSON_CARPET_I_VUNKERL = 138; CRIMSON_CARPET_II_ATTOHWA = 139; CRIMSON_CARPET_II_MISAREAUX = 140; CRIMSON_CARPET_II_VUNKERL = 141; REFUEL_AND_REPLENISH_LA_THEINE = 142; REFUEL_AND_REPLENISH_KONSCHTAT = 143; REFUEL_AND_REPLENISH_TAHRONGI = 144; REFUEL_AND_REPLENISH_ATTOHWA = 145; REFUEL_AND_REPLENISH_MISAREAUX = 146; REFUEL_AND_REPLENISH_VUNKERL = 147; REFUEL_AND_REPLENISH_ALTEPA = 148; REFUEL_AND_REPLENISH_ULEGUERAND = 149; REFUEL_AND_REPLENISH_GRAUBERG = 150; A_MIGHTIER_MARTELLO_LA_THEINE = 151; A_MIGHTIER_MARTELLO_KONSCHTAT = 152; A_MIGHTIER_MARTELLO_TAHRONGI = 153; A_MIGHTIER_MARTELLO_ATTOHWA = 154; A_MIGHTIER_MARTELLO_MISAREAUX = 155; A_MIGHTIER_MARTELLO_VUNKERL = 156; A_MIGHTIER_MARTELLO_ALTEPA = 157; A_MIGHTIER_MARTELLO_ULEGUERAND = 158; A_MIGHTIER_MARTELLO_GRAUBERG = 159; A_JOURNEY_BEGINS = 160; -- + -- THE_TRUTH_BECKONS = 161; -- + -- DAWN_OF_DEATH = 162; A_GOLDSTRUCK_GIGAS = 163; TO_PASTE_A_PEISTE = 164; MEGADRILE_MENACE = 165; THE_FORBIDDEN_FRONTIER = 166; FIRST_CONTACT = 167; AN_OFFICER_AND_A_PIRATE = 168; HEART_OF_MADNESS = 169; TENUOUS_EXISTENCE = 170; CHAMPIONS_OF_ABYSSEA = 171; THE_BEAST_OF_BASTORE = 172; A_DELECTABLE_DEMON = 173; A_FLUTTERY_FIEND = 174; SCARS_OF_ABYSSEA = 175; A_BEAKED_BLUSTERER = 176; A_MAN_EATING_MITE = 177; AN_ULCEROUS_URAGNITE = 178; HEROES_OF_ABYSSEA = 179; A_SEA_DOGS_SUMMONS = 180; DEATH_AND_REBIRTH = 181; EMISSARIES_OF_GOD = 182; BENEATH_A_BLOOD_RED_SKY = 183; THE_WYRM_GOD = 184; MEANWHILE_BACK_ON_ABYSSEA = 185; A_MOONLIGHT_REQUITE = 186; DOMINION_OP_10_GRAUBERG = 187; DOMINION_OP_11_GRAUBERG = 188; DOMINION_OP_12_GRAUBERG = 189; DOMINION_OP_13_GRAUBERG = 190; DOMINION_OP_14_GRAUBERG = 191;
gpl-3.0
VincentGong/chess
cocos2d-x/cocos/scripting/lua-bindings/auto/api/PhysicsWorld.lua
3
2730
-------------------------------- -- @module PhysicsWorld -------------------------------- -- @function [parent=#PhysicsWorld] getGravity -- @param self -- @return Vec2#Vec2 ret (return value: cc.Vec2) -------------------------------- -- @function [parent=#PhysicsWorld] getAllBodies -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#PhysicsWorld] setGravity -- @param self -- @param #cc.Vec2 vec2 -------------------------------- -- @function [parent=#PhysicsWorld] getSpeed -- @param self -- @return float#float ret (return value: float) -------------------------------- -- overload function: removeBody(int) -- -- overload function: removeBody(cc.PhysicsBody) -- -- @function [parent=#PhysicsWorld] removeBody -- @param self -- @param #cc.PhysicsBody physicsbody -------------------------------- -- @function [parent=#PhysicsWorld] removeJoint -- @param self -- @param #cc.PhysicsJoint physicsjoint -- @param #bool bool -------------------------------- -- @function [parent=#PhysicsWorld] getUpdateRate -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsWorld] setSpeed -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsWorld] getShapes -- @param self -- @param #cc.Vec2 vec2 -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#PhysicsWorld] removeAllJoints -- @param self -------------------------------- -- @function [parent=#PhysicsWorld] getShape -- @param self -- @param #cc.Vec2 vec2 -- @return PhysicsShape#PhysicsShape ret (return value: cc.PhysicsShape) -------------------------------- -- @function [parent=#PhysicsWorld] removeAllBodies -- @param self -------------------------------- -- @function [parent=#PhysicsWorld] getDebugDrawMask -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsWorld] setDebugDrawMask -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsWorld] getBody -- @param self -- @param #int int -- @return PhysicsBody#PhysicsBody ret (return value: cc.PhysicsBody) -------------------------------- -- @function [parent=#PhysicsWorld] setUpdateRate -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsWorld] addJoint -- @param self -- @param #cc.PhysicsJoint physicsjoint return nil
mit
jshackley/darkstar
scripts/zones/Throne_Room/mobs/Shadow_Lord.lua
1
5239
----------------------------------- -- Area: Throne Room -- MOB: Shadow Lord -- Mission 5-2 BCNM Fight ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) -- 1st form -- after change magic or physical immunity every 5min or 1k dmg -- 2nd form -- the Shadow Lord will do nothing but his Implosion attack. This attack hits everyone in the battlefield, but he only has 4000 HP if (mob:getID() < 17453060) then -- first phase AI -- once he's under 50% HP, start changing immunities and attack patterns if (mob:getHP() / mob:getMaxHP() <= 0.5) then -- have to keep track of both the last time he changed immunity and the HP he changed at local changeTime = mob:getLocalVar("changeTime"); local changeHP = mob:getLocalVar("changeHP"); -- subanimation 0 is first phase subanim, so just go straight to magic mode if (mob:AnimationSub() == 0) then mob:AnimationSub(1); mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD); mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0); mob:SetAutoAttackEnabled(false); mob:SetMagicCastingEnabled(true); mob:setMobMod(MOBMOD_MAGIC_COOL, 2); --and record the time and HP this immunity was started mob:setLocalVar("changeTime", mob:getBattleTime()); mob:setLocalVar("changeHP", mob:getHP()); -- subanimation 2 is physical mode, so check if he should change into magic mode elseif (mob:AnimationSub() == 2 and (mob:getHP() <= changeHP - 1000 or mob:getBattleTime() - changeTime > 300)) then mob:AnimationSub(1); mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD); mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0); mob:SetAutoAttackEnabled(false); mob:SetMagicCastingEnabled(true); mob:setMobMod(MOBMOD_MAGIC_COOL, 2); mob:setLocalVar("changeTime", mob:getBattleTime()); mob:setLocalVar("changeHP", mob:getHP()); -- subanimation 1 is magic mode, so check if he should change into physical mode elseif (mob:AnimationSub() == 1 and (mob:getHP() <= changeHP - 1000 or mob:getBattleTime() - changeTime > 300)) then -- and use an ability before changing mob:useMobAbility(417); mob:AnimationSub(2); mob:delStatusEffect(EFFECT_MAGIC_SHIELD); mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD, 0, 1, 0, 0); mob:SetAutoAttackEnabled(true); mob:SetMagicCastingEnabled(false); mob:setMobMod(MOBMOD_MAGIC_COOL, 10); mob:setLocalVar("changeTime", mob:getBattleTime()); mob:setLocalVar("changeHP", mob:getHP()); end end else -- second phase AI: Implode every 9 seconds if (mob:getBattleTime() % 9 == 0) then mob:useMobAbility(413); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) if (mob:getID() < 17453060) then ally:startEvent(0x7d04); ally:setVar("mobid",mob:getID()); else ally:addTitle(SHADOW_BANISHER); end -- reset everything on death mob:AnimationSub(0); mob:SetAutoAttackEnabled(true); mob:SetMagicCastingEnabled(true); mob:delStatusEffect(EFFECT_MAGIC_SHIELD); mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) -- reset everything on despawn mob:AnimationSub(0); mob:SetAutoAttackEnabled(true); mob:SetMagicCastingEnabled(true); mob:delStatusEffect(EFFECT_MAGIC_SHIELD); mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("updateCSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("finishCSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x7d04) then local mobid = player:getVar("mobid"); DespawnMob(mobid); player:setVar("mobid",0); --first phase dies, spawn second phase ID, make him engage, and disable -- magic, auto attack, and abilities (all he does is case Implode by script) mob = SpawnMob(mobid+3); mob:updateEnmity(player); mob:SetMagicCastingEnabled(false); mob:SetAutoAttackEnabled(false); mob:SetMobAbilityEnabled(false); end end;
gpl-3.0
ff94315/hiwifi-openwrt-HC5661-HC5761
staging_dir/target-mipsel_r2_uClibc-0.9.33.2/root-ralink/usr/lib/lua/ssl.lua
4
2319
------------------------------------------------------------------------------ -- LuaSec 0.4.1 -- Copyright (C) 2006-2011 Bruno Silvestre -- ------------------------------------------------------------------------------ module("ssl", package.seeall) require("ssl.core") require("ssl.context") _VERSION = "0.4.1" _COPYRIGHT = "LuaSec 0.4.1 - Copyright (C) 2006-2011 Bruno Silvestre\n" .. "LuaSocket 2.0.2 - Copyright (C) 2004-2007 Diego Nehab" -- Export functions rawconnection = core.rawconnection rawcontext = context.rawcontext -- -- -- local function optexec(func, param, ctx) if param then if type(param) == "table" then return func(ctx, unpack(param)) else return func(ctx, param) end end return true end -- -- -- function newcontext(cfg) local succ, msg, ctx -- Create the context ctx, msg = context.create(cfg.protocol) if not ctx then return nil, msg end -- Mode succ, msg = context.setmode(ctx, cfg.mode) if not succ then return nil, msg end -- Load the key if cfg.key then succ, msg = context.loadkey(ctx, cfg.key, cfg.password) if not succ then return nil, msg end end -- Load the certificate if cfg.certificate then succ, msg = context.loadcert(ctx, cfg.certificate) if not succ then return nil, msg end end -- Load the CA certificates if cfg.cafile or cfg.capath then succ, msg = context.locations(ctx, cfg.cafile, cfg.capath) if not succ then return nil, msg end end -- Set the verification options succ, msg = optexec(context.setverify, cfg.verify, ctx) if not succ then return nil, msg end -- Set SSL options succ, msg = optexec(context.setoptions, cfg.options, ctx) if not succ then return nil, msg end -- Set the depth for certificate verification if cfg.depth then succ, msg = context.setdepth(ctx, cfg.depth) if not succ then return nil, msg end end return ctx end -- -- -- function wrap(sock, cfg) local ctx, msg if type(cfg) == "table" then ctx, msg = newcontext(cfg) if not ctx then return nil, msg end else ctx = cfg end local s, msg = core.create(ctx) if s then core.setfd(s, sock:getfd()) sock:setfd(core.invalidfd) return s end return nil, msg end
gpl-2.0
BeyondTeam/TeleBeyond
plugins/supergroup.lua
1
111051
--Begin supergrpup.lua --Check members #Add supergroup local function check_member_super(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg if success == 0 then send_large_msg(receiver, "ابتدا منو ادمین سوپر گروه کنید!") end for k,v in pairs(result) do local member_id = v.peer_id if member_id ~= our_id then -- SuperGroup configuration data[tostring(msg.to.id)] = { group_type = 'SuperGroup', long_id = msg.to.peer_id, moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.title, '_', ' '), lock_arabic = 'no', lock_link = "yes", lock_url = "yes", flood = 'yes', lock_spam = 'yes', lock_sticker = 'no', member = 'no', lock_bots = 'yes', lock_tags = 'yes', public = 'yes', lock_rtl = 'no', expiretime = 'null', welcome = '✅', chat = '✅', kickme = '✅', --lock_contacts = 'no', strict = 'no' } } 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) local text = 'سوپر گروه اضافه شد' return reply_msg(msg.id, text, ok_cb, false) end end end --Check Members #rem supergroup local function check_member_superrem(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) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local text = 'سوپر گروه حذف شد و ربات آن را به رسمیت نمیشناسد' return reply_msg(msg.id, text, ok_cb, false) end end end --Function to Add supergroup local function superadd(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_super,{receiver = receiver, data = data, msg = msg}) end --Function to remove supergroup local function superrem(msg) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) channel_get_users(receiver, check_member_superrem,{receiver = receiver, data = data, msg = msg}) end --Get and output admins and bots in supergroup local function callback(cb_extra, success, result) local i = 1 local chat_name = string.gsub(cb_extra.msg.to.print_name, "_", " ") local member_type = cb_extra.member_type local text = member_type.." for "..chat_name..":\n" for k,v in pairsByKeys(result) do if not v.first_name then name = " " else vname = v.first_name:gsub("‮", "") name = vname:gsub("_", " ") end text = text.."\n"..i.." - "..name.."["..v.peer_id.."]" i = i + 1 end send_large_msg(cb_extra.receiver, text) end local function callback_clean_bots (extra, success, result) local msg = extra.msg local receiver = 'channel#id'..msg.to.id local channel_id = msg.to.id for k,v in pairs(result) do local bot_id = v.peer_id kick_user(bot_id,channel_id) end end --Get and output info about supergroup local function callback_info(cb_extra, success, result) local title ="اطلاعات سوپر گروه ["..result.title.."]\n\n" local user_num = "تعداد عضو: "..result.participants_count.."\n" local admin_num = "تعداد ادمین: "..result.admins_count.."\n" local kicked_num = "تعداد افراد اخراج شده: "..result.kicked_count.."\n\n" local channel_id = "آیدی سوپر گروه: "..result.peer_id.."\n" if result.username then channel_username = "Username: @"..result.username else channel_username = "" end local text = title..admin_num..user_num..kicked_num..channel_id..channel_username send_large_msg(cb_extra.receiver, text) end --Get and output members of supergroup local function callback_who(cb_extra, success, result) local text = "Members for "..cb_extra.receiver local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then username = " @"..v.username else username = "" end text = text.."\n"..i.." - "..name.." "..username.." [ "..v.peer_id.." ]\n" --text = text.."\n"..username i = i + 1 end local file = io.open("./groups/lists/supergroups/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/"..cb_extra.receiver..".txt", ok_cb, false) post_msg(cb_extra.receiver, text, ok_cb, false) end --Get and output list of kicked users for supergroup local function callback_kicked(cb_extra, success, result) --vardump(result) local text = "Kicked Members for SuperGroup "..cb_extra.receiver.."\n\n" local i = 1 for k,v in pairsByKeys(result) do if not v.print_name then name = " " else vname = v.print_name:gsub("‮", "") name = vname:gsub("_", " ") end if v.username then name = name.." @"..v.username end text = text.."\n"..i.." - "..name.." [ "..v.peer_id.." ]\n" i = i + 1 end local file = io.open("./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", "w") file:write(text) file:flush() file:close() send_document(cb_extra.receiver,"./groups/lists/supergroups/kicked/"..cb_extra.receiver..".txt", ok_cb, false) --send_large_msg(cb_extra.receiver, text) end --Begin supergroup locks 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 'ضد تبلیغ از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'ضد تبلیغ فعال شد' 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 'ضد تبلیغ از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'ضد تبلیغ غیرفعال شد' end end local function lock_group_cmd(msg, data, target) if not is_momod(msg) then return end local group_cmd_lock = data[tostring(target)]['settings']['lock_cmd'] if group_cmd_lock == 'yes' then return 'قفل دستورات از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_cmd'] = 'yes' save_data(_config.moderation.data, data) return 'قفل دستورات فعال شد' end end local function unlock_group_cmd(msg, data, target) if not is_momod(msg) then return end local group_cmd_lock = data[tostring(target)]['settings']['lock_cmd'] if group_cmd_lock == 'no' then return 'قفل دستورات از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_cmd'] = 'no' save_data(_config.moderation.data, data) return 'قفل دستورات غیرفعال شد' end end local function lock_group_url(msg, data, target) if not is_momod(msg) then return end local group_url_lock = data[tostring(target)]['settings']['lock_url'] if group_url_lock == 'yes' then return 'ضد Url از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_url'] = 'yes' save_data(_config.moderation.data, data) return 'ضد Url فعال شد' end end local function unlock_group_url(msg, data, target) if not is_momod(msg) then return end local group_url_lock = data[tostring(target)]['settings']['lock_url'] if group_url_lock == 'no' then return 'ضد Url از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_url'] = 'no' save_data(_config.moderation.data, data) return 'ضد Url غیرفعال شد' end end local function lock_group_spam(msg, data, target) if not is_momod(msg) then return end if not is_owner(msg) then return "شما صاحب گروه نیستید!" end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'yes' then return 'ضد اسپم از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_spam'] = 'yes' save_data(_config.moderation.data, data) return 'ضد اسپم فعال شد' end end local function unlock_group_spam(msg, data, target) if not is_momod(msg) then return end local group_spam_lock = data[tostring(target)]['settings']['lock_spam'] if group_spam_lock == 'no' then return 'ضد اسپم از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_spam'] = 'no' save_data(_config.moderation.data, data) return 'ضد اسپم غیرفعال شد' end end local function lock_group_flood(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 'ضد فلود از قبل فعال بوده است' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'ضد فلود فعال شد' end end local function unlock_group_flood(msg, data, target) if not is_momod(msg) then return end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'ضد فلود از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'ضد فلود غیرفعال شد' end 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/Persian is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic/Persian has been unlocked' end end]] local function lock_group_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 'کاربران گروه از قبل قفل بوده است' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'کاربران گروه قفل شدند' 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 'کاربران گروه قفل نبوده است' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'کاربران گروه از قفل خارج شدند' 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 'محافظت دربرابر ورود ربات ها از قبل فعال بود.' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'محافظت دربرابر ورود ربات ها فعال شد.' 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 'محافظت دربرابر ورود ربات ها از قبل فعال نبود.' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'محافظت دربرابر ربات ها غیر فعال شد.' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "" end local group_tag_lock = data[tostring(target)]['settings']['lock_tags'] if group_tag_lock == 'yes' then return 'ضد تگ از قبل فعال بود' else data[tostring(target)]['settings']['lock_tags'] = 'yes' save_data(_config.moderation.data, data) return 'ضد تگ فعال شد' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "" end local group_tag_lock = data[tostring(target)]['settings']['lock_tags'] if group_tag_lock == 'no' then return 'ضد تگ از قبل غیرفعال بود' else data[tostring(target)]['settings']['lock_tags'] = 'no' save_data(_config.moderation.data, data) return 'ضد تگ غیر فعال شد' 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_welcome(msg, data, target) if not is_momod(msg) then return end local group_welcome_lock = data[tostring(target)]['settings']['welcome'] if group_welcome_lock == '✅' then return 'پیام خوش امد گویی از قبل فعال بوده است' else data[tostring(target)]['settings']['welcome'] = '✅' save_data(_config.moderation.data, data) return 'پیام خوش امد گویی فعال شد' end end local function unlock_group_welcome(msg, data, target) if not is_momod(msg) then return end local group_welcome_lock = data[tostring(target)]['settings']['welcome'] if group_welcome_lock == '❌' then return 'پیام خوش امد گویی از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['welcome'] = '❌' save_data(_config.moderation.data, data) return 'پیام خوش امد گویی غیرفعال شد' end end local function lock_group_chatrobot(msg, data, target) if not is_momod(msg) then return end local group_chatrobot_lock = data[tostring(target)]['settings']['chat'] if group_chatrobot_lock == '✅' then return 'چت با ربات از قبل فعال بوده است' else data[tostring(target)]['settings']['chat'] = '✅' save_data(_config.moderation.data, data) return 'چت با ربات فعال شد' end end local function unlock_group_chatrobot(msg, data, target) if not is_momod(msg) then return end local group_chatrobot_lock = data[tostring(target)]['settings']['chat'] if group_chatrobot_lock == '❌' then return 'چت با ربات از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['chat'] = '❌' save_data(_config.moderation.data, data) return 'چت با ربات غیرفعال شد' end end local function lock_group_kickme(msg, data, target) if not is_momod(msg) then return end local group_kickme_lock = data[tostring(target)]['settings']['kickme'] if group_kickme_lock == '✅' then return 'دستور kickme از قبل فعال بوده است' else data[tostring(target)]['settings']['kickme'] = '✅' save_data(_config.moderation.data, data) return 'دستور kickme فعال شد' end end local function unlock_group_kickme(msg, data, target) if not is_momod(msg) then return end local group_kickme_lock = data[tostring(target)]['settings']['kickme'] if group_kickme_lock == '❌' then return 'دستور kickme از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['kickme'] = '❌' save_data(_config.moderation.data, data) return 'دستور kickme غیرفعال شد' 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 'ضد استیکر از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_sticker'] = 'yes' save_data(_config.moderation.data, data) return 'ضد استیکر فعال شد' 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 'ضد استیکر از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_sticker'] = 'no' save_data(_config.moderation.data, data) return 'ضد استیکر غیرفعال شد' end end local function lock_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 == 'yes' then return 'ضد اشتراک گذاشتن مخاطب از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_contacts'] = 'yes' save_data(_config.moderation.data, data) return 'ضد اشتراک گذاشتن مخاطب فعال شد' 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 'ضد اشتراک گذاشتن مخاطب از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_contacts'] = 'no' save_data(_config.moderation.data, data) return 'ضد اشتراک گذاشتن مخاطب غیرفعال شد' end end local function enable_strict_rules(msg, data, target) if not is_momod(msg) then return end local group_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == '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_strict_lock = data[tostring(target)]['settings']['strict'] if group_strict_lock == '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 --End supergroup locks --'Set supergroup rules' function local function set_rulesmod(msg, data, target) if not is_momod(msg) then return end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'قوانین گروه ثبت شد' end --'Get supergroup rules' function local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'قوانین گروه در دسترس نیست' end local rules = data[tostring(msg.to.id)][data_cat] local group_name = data[tostring(msg.to.id)]['settings']['set_name'] local rules = group_name..' \nقوانین گروه:\n\n'..rules:gsub("/n", " ") return rules end --Set supergroup to public or not public function local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید!" end local group_public_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_public_lock == 'yes' then return 'گروه از قبل عمومی بوده است' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'گروه عمومی شد' end local function unlock_group_porn(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید!" end local porn = data[tostring(target)]['settings']['lock_porn'] if porn == '🔓' then return 'محتوای بزرگ سالان از قبل غیرفعال بوده است' else data[tostring(target)]['settings']['lock_porn'] = '🔓' save_data(_config.moderation.data, data) return 'محتوای بزرگ سالان غیرفعال شد' end end local function lock_group_porn(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید!" end local porn = data[tostring(target)]['settings']['lock_porn'] if porn == '🔐' then return 'محتوای بزرگ سالان از قبل فعال بوده است' else data[tostring(target)]['settings']['lock_porn'] = '🔐' save_data(_config.moderation.data, data) return 'محتوای بزرگ سالان فعال شد' end end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return end local group_public_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_public_lock == 'no' then return 'گروه از قبل خصوصی بوده است' else data[tostring(target)]['settings']['public'] = 'no' data[tostring(target)]['long_id'] = msg.to.long_id save_data(_config.moderation.data, data) return 'گروه خصوصی شد' end end --Show supergroup settings; function function show_supergroup_settingsmod(msg, target) if not is_momod(msg) then return 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 if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['public'] then data[tostring(target)]['settings']['public'] = 'yes' end end --[[if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_rtl'] then data[tostring(target)]['settings']['lock_rtl'] = 'no' end end]] if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_bots'] then data[tostring(target)]['settings']['lock_bots'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_tags'] then data[tostring(target)]['settings']['lock_tags'] = 'yes' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_url'] then data[tostring(target)]['settings']['lock_url'] = 'yes' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_member'] then data[tostring(target)]['settings']['lock_member'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_cmd'] then data[tostring(target)]['settings']['lock_cmd'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['welcome'] then data[tostring(target)]['settings']['welcome'] = '✅' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['chat'] then data[tostring(target)]['settings']['chat'] = '✅' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['kickme'] then data[tostring(target)]['settings']['kickme'] = '✅' end end local group_type = "Normal" if data[tostring(msg.to.id)]['group_type'] then group_type = data[tostring(msg.to.id)]['group_type'] end local version = "1.0" if redis:get('bot:version') then version = redis:get('bot:version') end local expiretime = redis:hget('expiretime', get_receiver(msg)) local expire = '' if not expiretime then expire = expire..'Unlimited' else local now = tonumber(os.time()) expire = expire..math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1 end local settings = data[tostring(target)]['settings'] local text = "*SuperGroup Settings :*\n*["..msg.to.print_name:gsub("_"," ").."]*\n\n_SuperGroup Public : "..settings.public.."_\n_Lock SuperGroup Link : "..settings.lock_link.."_\n_Lock SuperGroup Url : "..settings.lock_url.."_\n_Lock SuperGroup Tags : "..settings.lock_tags.."_\n_Lock SuperGroup Member : "..settings.lock_member.."_\n_Lock SuperGroup Spam : "..settings.lock_spam.."_\n_Lock SuperGroup Flood : "..settings.flood.."_\n_Bots Protection : "..settings.lock_bots.."_\n_Flood Sensitivity : "..NUM_MSG_MAX.."_\n_Bot Commands : "..settings.lock_cmd.."_\n_Welcome Message : "..settings.welcome.."_\n_Chat With Robot : "..settings.chat.."_\n_Kickme Command : "..settings.kickme.."_\n_SuperGroup Type :_ *"..group_type.."*\n_Bot Version :_ *"..version.."*\n_Strict Settings : "..settings.strict.."_\n_Expiry Date SuperGroup :_ *"..expire.."* _Day_\n\n[Beyond Team Channel](Telegram.Me/BeyondTeam)" --local text = ":["..msg.to.print_name:gsub("_"," ").."] تنظیمات سوپر گروه\n\n> قفل کاربران گروه: "..settings.lock_member.."\n> قفل تبلیغ: "..settings.lock_link.."\n> قفل اسپم: "..settings.lock_spam.."\n> قفل فلود: "..settings.flood.."\n> حساسیت ضد فلود: "..NUM_MSG_MAX.."\n> Strict settings: "..settings.strict local text = string.gsub(text,'yes','🔐') local text = string.gsub(text,'no','🔓') send_api_msg(msg, get_receiver_api(msg), text, true, 'md') end function show_supergroup_mutes(msg, target) if not is_momod(msg) then return end local data = load_data(_config.moderation.data) if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_text'] then data[tostring(target)]['settings']['mute_text'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_audio'] then data[tostring(target)]['settings']['mute_audio'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_service'] then data[tostring(target)]['settings']['mute_service'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_photo'] then data[tostring(target)]['settings']['mute_photo'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_forward'] then data[tostring(target)]['settings']['mute_forward'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_reply'] then data[tostring(target)]['settings']['mute_reply'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_emoji'] then data[tostring(target)]['settings']['mute_emoji'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_video'] then data[tostring(target)]['settings']['mute_video'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_gif'] then data[tostring(target)]['settings']['mute_gif'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_doc'] then data[tostring(target)]['settings']['mute_doc'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['mute_all'] then data[tostring(target)]['settings']['mute_all'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_porn'] then data[tostring(target)]['settings']['lock_porn'] = 'no' end end if data[tostring(target)]['settings'] then if not data[tostring(target)]['settings']['lock_contacts'] then data[tostring(target)]['settings']['lock_contacts'] = '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 local settings = data[tostring(target)]['settings'] local text = "*MuteList For :*\n*["..msg.to.print_name:gsub("_"," ").."]*\n\n_Mute SuperGroup All : "..settings.mute_all.."_\n_Mute SuperGroup Text : "..settings.mute_text.."_\n_Mute SuperGroup Sticker : "..settings.lock_sticker.."_\n_Mute SuperGroup Photo : "..settings.mute_photo.."_\n_Mute SuperGroup Video : "..settings.mute_video.."_\n_Mute SuperGroup Audio : "..settings.mute_audio.."_\n_Mute SuperGroup Gifs : "..settings.mute_gif.."_\n_Mute SuperGroup Contact : "..settings.lock_contacts.."_\n_Mute SuperGroup File : "..settings.mute_doc.."_\n_Mute SuperGroup Forward : "..settings.mute_forward.."_\n_Mute SuperGroup Reply : "..settings.mute_reply.."_\n_Mute SuperGroup Emoji : "..settings.mute_emoji.."_\n_Mute SuperGroup TgService : "..settings.mute_service.."_\n\n[Beyond Team Channel](Telegram.Me/BeyondTeam)" local text = string.gsub(text,'yes','🔇') local text = string.gsub(text,'no','🔊') send_api_msg(msg, get_receiver_api(msg), text, true, 'md') end local function set_welcomemod(msg, data, target) if not is_momod(msg) then return "شما مدیر گروه نیستید" end local data_cat = 'welcome_msg' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'پیام خوش امد گویی :\n'..rules..'\n---------------\nبرای نمایش نام کاربر و نام گروه یا قوانین میتوانید به صورت زیر عمل کنید\n\n /set welcome salam {name} be goroohe {group} khosh amadid \n ghavanine gorooh: {rules} \n\nربات به صورت هوشمند نام گروه , نام کاربر و قوانین را به جای {name}و{group} و {rules} اضافه میکند.' end local function set_expiretime(msg, data, target) if not is_sudo(msg) then return "شما ادمین ربات نیستید!" end local hash = 'expiretime' local expired = matches[2]..'.'..matches[3]..'.'..matches[4] redis:hset (hash, get_receiver(msg), expired) return 'تاریخ انقضای گروه به '..expired..' ست شد' end local function promote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' از قبل مدیر گروه بوده است') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) end local function demote_admin(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' مدیر گروه نیست') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) end local function promote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'channel#id', '') local member_tag_username = string.gsub(member_username, '@', '(at)') if not data[group] then return send_large_msg(receiver, 'سوپر گروه اضافه نشده است!') end if data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_username..' از قبل مدیر گروه بوده است') end data[group]['moderators'][tostring(user_id)] = member_tag_username save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' به لیست مدیران گروه اضافه شد') end local function demote2(receiver, member_username, user_id) local data = load_data(_config.moderation.data) local member_tag_username = string.gsub(member_username, '@', '(at)') local group = string.gsub(receiver, 'channel#id', '') if not data[group] then return send_large_msg(receiver, 'گروه اضافه نشده است!') end if not data[group]['moderators'][tostring(user_id)] then return send_large_msg(receiver, member_tag_username..' مدیر گروه نیست') end data[group]['moderators'][tostring(user_id)] = nil save_data(_config.moderation.data, data) send_large_msg(receiver, member_username..' از لیست مدیران گروه پاک شد') 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 'سوپر گروه اضافه نشده است!' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'هیچ مدیری در گروه وجود ندارد' end local i = 1 local message = 'لیست مدیران گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do if string.match(v , "(at)") then v = v:gsub(".at.","@") end message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end --silent_user By @SoLiD021 function silentuser_by_reply(extra, success, result) local user_id = result.from.peer_id local receiver = extra.receiver local chat_id = result.to.peer_id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then return send_large_msg(receiver, " ["..user_id.."] از قبل به لیست Mute کاربران اضافه شده بود") end if is_owner(extra.msg) then mute_user(chat_id, user_id) return send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") end end local function silentuser_by_id(extra, success, result) local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then return send_large_msg(receiver, " ["..user_id.."] از قبل به لیست Mute کاربران اضافه شده بود") end if is_owner(extra.msg) then mute_user(chat_id, user_id) return send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") end end local function silentuser_by_username(extra, success, result) local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then return send_large_msg(receiver, " ["..user_id.."] از قبل به لیست Mute کاربران اضافه شده بود") end if is_owner(extra.msg) then mute_user(chat_id, user_id) return send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") end end --unsilent_user By @SoLiD021 function unsilentuser_by_reply(extra, success, result) local user_id = result.from.peer_id local receiver = extra.receiver local chat_id = result.to.peer_id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] از لیست Mute کاربران حذف شد") else send_large_msg(receiver, "["..user_id.."] از قبل در لیست Mute کاربران نبوده") end end local function unsilentuser_by_id(extra, success, result) local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] از لیست Mute کاربران حذف شد") else send_large_msg(receiver, "["..user_id.."] از قبل در لیست Mute کاربران نبوده") end end local function unsilentuser_by_username(extra, success, result) local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] از لیست Mute کاربران حذف شد") else send_large_msg(receiver, "["..user_id.."] از قبل در لیست Mute کاربران نبوده") end end -- Start by reply actions function get_message_callback(extra, success, result) local get_cmd = extra.get_cmd local msg = extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") if get_cmd == "id" and not result.action then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for: ["..result.from.peer_id.."]") id1 = send_large_msg(channel, result.from.peer_id) elseif get_cmd == 'id' and result.action 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 else user_id = result.peer_id end local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id by service msg for: ["..user_id.."]") id1 = send_large_msg(channel, user_id) end elseif get_cmd == "idfrom" then local channel = 'channel#id'..result.to.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] obtained id for msg fwd from: ["..result.fwd_from.peer_id.."]") id2 = send_large_msg(channel, result.fwd_from.peer_id) elseif get_cmd == 'channel_block' and not result.action then local member_id = result.from.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end --savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply") kick_user(member_id, channel_id) elseif get_cmd == 'channel_block' and result.action and result.action.type == 'chat_add_user' then local user_id = result.action.user.peer_id local channel_id = result.to.peer_id if member_id == msg.from.id then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(msg.from.id) then return send_large_msg("channel#id"..channel_id, "شما نمی توانید ادمین/مدیران/صاحب گروه را اخراج کنید") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "شما نمی توانید سایر ادمین ها را اخراج کنید") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..user_id.."] by reply to sev. msg.") kick_user(user_id, channel_id) elseif get_cmd == "del" then delete_msg(result.id, ok_cb, false) savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted a message by reply") elseif get_cmd == "setadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id channel_set_admin(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." به لیست سرپرستان گروه اضافه شد" else text = "[ "..user_id.." ] به لیست سرپرستان گروه اضافه شد" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..user_id.."] as admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "demoteadmin" then local user_id = result.from.peer_id local channel_id = "channel#id"..result.to.peer_id if is_admin2(result.from.peer_id) then return send_large_msg(channel_id, "شما ادمین کل را نمی توانید برکنار کنید") end channel_demote(channel_id, "user#id"..user_id, ok_cb, false) if result.from.username then text = "@"..result.from.username.." از لیست سرپرستان گروه حذف شد" else text = "[ "..user_id.." ] از لیست مدیران گروه پاک شد" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted: ["..user_id.."] from admin by reply") send_large_msg(channel_id, text) elseif get_cmd == "setowner" then local group_owner = data[tostring(result.to.peer_id)]['set_owner'] if group_owner then local channel_id = 'channel#id'..result.to.peer_id if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(channel_id, user, ok_cb, false) end local user_id = "user#id"..result.from.peer_id channel_set_admin(channel_id, user_id, ok_cb, false) data[tostring(result.to.peer_id)]['set_owner'] = tostring(result.from.peer_id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set: ["..result.from.peer_id.."] as owner by reply") if result.from.username then text = "@"..result.from.username.." [ "..result.from.peer_id.." ] به صاحب گروه منتصب شد" else text = "[ "..result.from.peer_id.." ] به صاحب گروه منتصب شد" end send_large_msg(channel_id, text) end elseif get_cmd == "promote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") promote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == "demote" then local receiver = result.to.peer_id local full_name = (result.from.first_name or '')..' '..(result.from.last_name or '') local member_name = full_name:gsub("‮", "") local member_username = member_name:gsub("_", " ") if result.from.username then member_username = '@'.. result.from.username end local member_id = result.from.peer_id if result.to.peer_type == 'channel' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted mod: @"..member_username.."["..result.from.peer_id.."] by reply") demote2("channel#id"..result.to.peer_id, member_username, member_id) --channel_set_mod(channel_id, user, ok_cb, false) end elseif get_cmd == 'mute_user' then 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 if action == 'chat_add_user_link' then if result.from then user_id = result.from.peer_id end end else user_id = result.from.peer_id end local receiver = extra.receiver local chat_id = msg.to.id print(user_id) print(chat_id) if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, "["..user_id.."] از لیست Mute کاربران حذف شد") elseif is_admin1(msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") end end end --By ID actions local function cb_user_info(extra, success, result) local receiver = extra.receiver local user_id = result.peer_id local get_cmd = extra.get_cmd local data = load_data(_config.moderation.data) --[[if get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" else text = "[ "..result.peer_id.." ] has been set as an admin" end send_large_msg(receiver, text)]] if get_cmd == "demoteadmin" then if is_admin2(result.peer_id) then return send_large_msg(receiver, "شما ادمین کل را نمی توانید برکنار کنید") end local user_id = "user#id"..result.peer_id channel_demote(receiver, user_id, ok_cb, false) if result.username then text = "@"..result.username.." از لیست سرپرستان گروه حذف شد" send_large_msg(receiver, text) else text = "[ "..result.peer_id.." ] از لیست سرپرستان گروه حذف شد" send_large_msg(receiver, text) end elseif get_cmd == "promote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end promote2(receiver, member_username, user_id) elseif get_cmd == "demote" then if result.username then member_username = "@"..result.username else member_username = string.gsub(result.print_name, '_', ' ') end demote2(receiver, member_username, user_id) end end -- Begin resolve username actions local function callbackres(extra, success, result) local member_id = result.peer_id local member_username = "@"..result.username local get_cmd = extra.get_cmd if get_cmd == "res" then local user = result.peer_id local name = string.gsub(result.print_name, "_", " ") local channel = 'channel#id'..extra.channelid send_large_msg(channel, user..'\n'..name) return user elseif get_cmd == "id" then local user = result.peer_id local channel = 'channel#id'..extra.channelid send_large_msg(channel, user) return user elseif get_cmd == "invite" then local receiver = extra.channel local user_id = "user#id"..result.peer_id channel_invite(receiver, user_id, ok_cb, false) --[[elseif get_cmd == "channel_block" then local user_id = result.peer_id local channel_id = extra.channelid local sender = extra.sender if member_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(member_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(member_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end kick_user(user_id, channel_id) elseif get_cmd == "setadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel channel_set_admin(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." has been set as an admin" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." has been set as an admin" send_large_msg(channel_id, text) end elseif get_cmd == "setowner" then local receiver = extra.channel local channel = string.gsub(receiver, 'channel#id', '') local from_id = extra.from_id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then local user = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..result.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(result.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.." ["..from_id.."] set ["..result.peer_id.."] as owner by username") if result.username then text = member_username.." [ "..result.peer_id.." ] added as owner" else text = "[ "..result.peer_id.." ] added as owner" end send_large_msg(receiver, text) end]] elseif get_cmd == "promote" then local receiver = extra.channel local user_id = result.peer_id --local user = "user#id"..result.peer_id promote2(receiver, member_username, user_id) --channel_set_mod(receiver, user, ok_cb, false) elseif get_cmd == "demote" then local receiver = extra.channel local user_id = result.peer_id local user = "user#id"..result.peer_id demote2(receiver, member_username, user_id) elseif get_cmd == "demoteadmin" then local user_id = "user#id"..result.peer_id local channel_id = extra.channel if is_admin2(result.peer_id) then return send_large_msg(channel_id, "شما ادمین کل را نمی توانید برکنار کنید") end channel_demote(channel_id, user_id, ok_cb, false) if result.username then text = "@"..result.username.." از لیست سرپرستان گروه حذف شد" send_large_msg(channel_id, text) else text = "@"..result.peer_id.." از لیست سرپرستان گروه حذف شد" send_large_msg(channel_id, text) end local receiver = extra.channel local user_id = result.peer_id demote_admin(receiver, member_username, user_id) elseif get_cmd == 'mute_user' then local user_id = result.peer_id local receiver = extra.receiver local chat_id = string.gsub(receiver, 'channel#id', '') if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] از لیست Mute کاربران پاک شد") elseif is_owner(extra.msg) then mute_user(chat_id, user_id) send_large_msg(receiver, " ["..user_id.."] به لیست Mute کاربران اضافه شد") end end end --End resolve username actions --Begin non-channel_invite username actions local function in_channel_cb(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local msg = cb_extra.msg local data = load_data(_config.moderation.data) local print_name = user_print_name(cb_extra.msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local member = cb_extra.username local memberid = cb_extra.user_id if member then text = 'No user @'..member..' in this SuperGroup.' else text = 'No user ['..memberid..'] in this SuperGroup.' end if get_cmd == "channel_block" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = v.peer_id local channel_id = cb_extra.msg.to.id local sender = cb_extra.msg.from.id if user_id == sender then return send_large_msg("channel#id"..channel_id, "Leave using kickme command") end if is_momod2(user_id, channel_id) and not is_admin2(sender) then return send_large_msg("channel#id"..channel_id, "You can't kick mods/owner/admins") end if is_admin2(user_id) then return send_large_msg("channel#id"..channel_id, "You can't kick other admins") end if v.username then text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..v.username.." ["..v.peer_id.."]") else text = "" savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: ["..v.peer_id.."]") end kick_user(user_id, channel_id) end end elseif get_cmd == "setadmin" then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local user_id = "user#id"..v.peer_id local channel_id = "channel#id"..cb_extra.msg.to.id channel_set_admin(channel_id, user_id, ok_cb, false) if v.username then text = "@"..v.username.." ["..v.peer_id.."] به لیست سرپرستان گروه اضافه شد" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..v.username.." ["..v.peer_id.."]") else text = "["..v.peer_id.."] به لیست سرپرستان گروه اضافه شد" savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin "..v.peer_id) end if v.username then member_username = "@"..v.username else member_username = string.gsub(v.print_name, '_', ' ') end local receiver = channel_id local user_id = v.peer_id promote_admin(receiver, member_username, user_id) end send_large_msg(channel_id, text) end elseif get_cmd == 'setowner' then for k,v in pairs(result) do vusername = v.username vpeer_id = tostring(v.peer_id) if vusername == member or vpeer_id == memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end local user_id = "user#id"..v.peer_id channel_set_admin(receiver, user_id, ok_cb, false) data[tostring(channel)]['set_owner'] = tostring(v.peer_id) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..v.peer_id.."] as owner by username") if result.username then text = member_username.." ["..v.peer_id.."] به صاحب گروه منتصب شد" else text = "به صاحب گروه منتصب شد ["..v.peer_id.."]" end end elseif memberid and vusername ~= member and vpeer_id ~= memberid then local channel = string.gsub(receiver, 'channel#id', '') local from_id = cb_extra.msg.from.id local group_owner = data[tostring(channel)]['set_owner'] if group_owner then if not is_admin2(tonumber(group_owner)) and not is_support(tonumber(group_owner)) then local user = "user#id"..group_owner channel_demote(receiver, user, ok_cb, false) end data[tostring(channel)]['set_owner'] = tostring(memberid) save_data(_config.moderation.data, data) savelog(channel, name_log.."["..from_id.."] set ["..memberid.."] as owner by username") text = "["..memberid.."] به صاحب گروه منتصب شد" end end end end send_large_msg(receiver, text) end --End non-channel_invite username actions function muted_user_list2(chat_id) local hash = 'mute_user:'..chat_id local list = redis:smembers(hash) local text = "لیست کاربران Mute شده ["..chat_id.."]:\n\n" for k,v in pairsByKeys(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then local print_name = string.gsub(user_info.print_name, "_", " ") local print_name = string.gsub(print_name, "‮", "") text = text..k.." - "..print_name.." ["..v.."]\n" else text = text..k.." - [ "..v.." ]\n" end end return text end --'Set supergroup photo' function local function set_supergroup_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/channel_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) channel_set_photo(receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) send_large_msg(receiver, 'عکس جدید با موفقیت ذخیره شد', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'عملیات ناموفق، مجددا تلاش کنید!', ok_cb, false) end end --Run function local function run(msg, matches) if msg.to.type == 'chat' then if matches[1]:lower() == 'tosuper' then if not is_admin1(msg) then return end local receiver = get_receiver(msg) chat_upgrade(receiver, ok_cb, false) end elseif msg.to.type == 'channel'then if matches[1]:lower() == 'tosuper' then if not is_admin1(msg) then return end return "از قبل سوپر گروه بوده است" end end if msg.to.type == 'channel' then local support_id = msg.from.id local receiver = get_receiver(msg) local print_name = user_print_name(msg.from):gsub("‮", "") local name_log = print_name:gsub("_", " ") local data = load_data(_config.moderation.data) if matches[1]:lower() == 'add' and not matches[2] then if not is_admin1(msg) and not is_support(support_id) then return end if is_super_group(msg) then return reply_msg(msg.id, 'سوپر گروه از قبل اضافه شده است!', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") added") savelog(msg.to.id, name_log.." ["..msg.from.id.."] added SuperGroup") superadd(msg) set_mutes(msg.to.id) channel_set_admin(receiver, 'user#id'..msg.from.id, ok_cb, false) end if matches[1]:lower() == 'rem' and is_admin1(msg) and not matches[2] then if not is_super_group(msg) then return reply_msg(msg.id, 'سوپر گروه اضافه نشده است!', ok_cb, false) end print("SuperGroup "..msg.to.print_name.."("..msg.to.id..") removed") superrem(msg) rem_mutes(msg.to.id) end if matches[1]:lower() == "gpinfo" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup info") channel_info(receiver, callback_info, {receiver = receiver, msg = msg}) end if matches[1]:lower() == "admins" then --if not is_owner(msg) and not is_support(msg.from.id) then -- return --end member_type = 'Admins' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup Admins list") admins = channel_get_admins(receiver,callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1]:lower() == "owner" then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "این گروه صاحبی ندارد.\nلطفا با نوشتن دستور زیر به گروه پشتیبانی ربات بیاید و اطلاع دهید\n/linksp" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "صاحب گروه می باشد ["..group_owner..']' end if matches[1]:lower() == "modlist" then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) -- channel_get_admins(receiver,callback, {receiver = receiver}) end if matches[1]:lower() == "bots" and is_momod(msg) then member_type = 'Bots' savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup bots list") channel_get_bots(receiver, callback, {receiver = receiver, msg = msg, member_type = member_type}) end if matches[1]:lower() == "who" and not matches[2] and is_momod(msg) then local user_id = msg.from.peer_id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup users list") channel_get_users(receiver, callback_who, {receiver = receiver}) end if matches[1]:lower() == "kicked" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested Kicked users list") channel_get_kicked(receiver, callback_kicked, {receiver = receiver}) end if matches[1]:lower() == 'del' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'del', msg = msg } delete_msg(msg.id, ok_cb, false) get_message(msg.reply_id, get_message_callback, cbreply_extra) end end if matches[1]:lower() == 'block' and is_momod(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'channel_block', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1]:lower() == 'block' and string.match(matches[2], '^%d+$') then --[[local user_id = matches[2] local channel_id = msg.to.id if is_momod2(user_id, channel_id) and not is_admin2(user_id) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: [ user#id"..user_id.." ]") kick_user(user_id, channel_id)]] local get_cmd = 'channel_block' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif msg.text:match("@[%a%d]") then --[[local cbres_extra = { channelid = msg.to.id, get_cmd = 'channel_block', sender = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked: @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'channel_block' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1]:lower() == 'id' then if type(msg.reply_id) ~= "nil" and is_momod(msg) and not matches[2] then local cbreply_extra = { get_cmd = 'id', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif type(msg.reply_id) ~= "nil" and matches[2] == "from" and is_momod(msg) then local cbreply_extra = { get_cmd = 'idfrom', msg = msg } get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif msg.text:match("@[%a%d]") then local cbres_extra = { channelid = msg.to.id, get_cmd = 'id' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested ID for: @"..username) resolve_username(username, callbackres, cbres_extra) else savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup ID") return "آی دی (ID) سوپر گروه " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == '' then if msg.to.type == 'channel' then return 'این دستور در سوپر گروه غیرفعال است' end end if matches[1]:lower() == 'newlink' and is_momod(msg)then local function callback_link (extra , success, result) local receiver = get_receiver(msg) if success == 0 then send_large_msg(receiver, '*خطا: دریافت لینک گروه ناموفق*\nدلیل: ربات سازنده گروه نمی باشد.\nاز دستور setlink/ برای ثبت لینک استفاده کنید') data[tostring(msg.to.id)]['settings']['set_link'] = nil save_data(_config.moderation.data, data) else send_large_msg(receiver, "لینک جدید ساخته شد\n\nبرای نمایش لینک جدید، دستور زیر را تایپ کنی\n/link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] attempted to create a new SuperGroup link") export_channel_link(receiver, callback_link, false) end if matches[1]:lower() == 'setlink' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = 'waiting' save_data(_config.moderation.data, data) return 'لطفا لینک جدید را ارسال کنید' end if msg.text then if msg.text:match("^(https://telegram.me/joinchat/%S+)$") and data[tostring(msg.to.id)]['settings']['set_link'] == 'waiting' and is_owner(msg) then data[tostring(msg.to.id)]['settings']['set_link'] = msg.text save_data(_config.moderation.data, data) return "لینک ست شد" end end if matches[1]:lower() == 'link' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "برای اولین بار ابتدا باید newlink/ را تایپ کنید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") local text = "لینک ورود به سوپر گروه :\n["..msg.to.title.."]("..group_link..")" send_api_msg(msg,get_receiver_api(msg),text,true,'md',msg.to.title,group_link) end if matches[1]:lower() == 'gplink' then if not is_momod(msg) then return end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "برای اولین بار ابتدا باید newlink/ را تایپ کنید" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "لینک سوپر گروه:\n"..group_link end if matches[1]:lower() == "invite" and is_sudo(msg) then local cbres_extra = { channel = get_receiver(msg), get_cmd = "invite" } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] invited @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1]:lower() == 'res' and is_momod(msg) then local cbres_extra = { channelid = msg.to.id, get_cmd = 'res' } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] resolved username: @"..username) resolve_username(username, callbackres, cbres_extra) end if matches[1]:lower() == 'kick' and is_momod(msg) then local receiver = channel..matches[3] local user = "user#id"..matches[2] chaannel_kick(receiver, user, ok_cb, false) end if matches[1]:lower() == 'setadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setadmin', msg = msg } setadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1]:lower() == 'setadmin' and string.match(matches[2], '^%d+$') then --[[] local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'setadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd})]] local get_cmd = 'setadmin' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1]:lower() == 'setadmin' and not string.match(matches[2], '^%d+$') then --[[local cbres_extra = { channel = get_receiver(msg), get_cmd = 'setadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] set admin @"..username) resolve_username(username, callbackres, cbres_extra)]] local get_cmd = 'setadmin' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1]:lower() == 'demoteadmin' then if not is_support(msg.from.id) and not is_owner(msg) then return end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demoteadmin', msg = msg } demoteadmin = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1]:lower() == 'demoteadmin' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demoteadmin' user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1]:lower() == 'demoteadmin' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demoteadmin' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted admin @"..username) resolve_username(username, callbackres, cbres_extra) end end if matches[1]:lower() == 'setowner' and is_owner(msg) then if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'setowner', msg = msg } setowner = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1]:lower() == 'setowner' and string.match(matches[2], '^%d+$') then --[[ local group_owner = data[tostring(msg.to.id)]['set_owner'] if group_owner then local receiver = get_receiver(msg) local user_id = "user#id"..group_owner if not is_admin2(group_owner) and not is_support(group_owner) then channel_demote(receiver, user_id, ok_cb, false) end local user = "user#id"..matches[2] channel_set_admin(receiver, user, ok_cb, false) data[tostring(msg.to.id)]['set_owner'] = tostring(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]] local get_cmd = 'setowner' local msg = msg local user_id = matches[2] channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, user_id=user_id}) elseif matches[1]:lower() == 'setowner' and not string.match(matches[2], '^%d+$') then local get_cmd = 'setowner' local msg = msg local username = matches[2] local username = string.gsub(matches[2], '@', '') channel_get_users (receiver, in_channel_cb, {get_cmd=get_cmd, receiver=receiver, msg=msg, username=username}) end end if matches[1]:lower() == 'promote' then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط صاحب گروه توانایی اضافه کردن مدیر را دارد" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'promote', msg = msg } promote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1] == 'promote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif matches[1]:lower() == 'promote' and not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'promote', } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1]:lower() == 'setmod' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_set_mod(channel, user_id, ok_cb, false) return "به ادمین گروه منتصب شد" end if matches[1]:lower() == 'remmod' and is_sudo(msg) then channel = get_receiver(msg) user_id = 'user#id'..matches[2] channel_demote(channel, user_id, ok_cb, false) return "از ادمین گروه برداشته شد" end if matches[1]:lower() == 'demote' then if not is_momod(msg) then return end if not is_owner(msg) then return "فقط صاحب گروه قادر به حذف کردن مدیر می باشد" end if type(msg.reply_id) ~= "nil" then local cbreply_extra = { get_cmd = 'demote', msg = msg } demote = get_message(msg.reply_id, get_message_callback, cbreply_extra) elseif matches[1]:lower() == 'demote' and string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local user_id = "user#id"..matches[2] local get_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted user#id"..matches[2]) user_info(user_id, cb_user_info, {receiver = receiver, get_cmd = get_cmd}) elseif not string.match(matches[2], '^%d+$') then local cbres_extra = { channel = get_receiver(msg), get_cmd = 'demote' } local username = matches[2] local username = string.gsub(matches[2], '@', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @"..username) return resolve_username(username, callbackres, cbres_extra) end end if matches[1]:lower() == "setname" and is_momod(msg) then local receiver = get_receiver(msg) local set_name = string.gsub(matches[2], '_', '') savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..matches[2]) rename_channel(receiver, set_name, ok_cb, false) end if msg.service and msg.action.type == 'chat_rename' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] renamed SuperGroup to: "..msg.to.title) data[tostring(msg.to.id)]['settings']['set_name'] = msg.to.title save_data(_config.moderation.data, data) end if matches[1]:lower() == "setdesc" and is_momod(msg) then local receiver = get_receiver(msg) local about_text = matches[2] local data_cat = 'description' local target = msg.to.id data[tostring(target)][data_cat] = about_text save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup description to: "..about_text) channel_set_about(receiver, about_text, ok_cb, false) return "موضوع گروه عوض شد\n\nبرای دیدن تغییرات، Description گروه را مشاهده کنید" end if matches[1]:lower() == "setusername" and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username Set.\n\nSelect the chat again to see the changes.") elseif success == 0 then send_large_msg(receiver, "Failed to set SuperGroup username.\nUsername may already be taken.\n\nNote: Username can use a-z, 0-9 and underscores.\nMinimum length is 5 characters.") end end local username = string.gsub(matches[2], '@', '') channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[1]:lower() == 'uexpiretime' and not matches[3] then savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group expire time to [unlimited]") expired = 'Unlimited' local target = get_receiver(msg) local hash = 'expiretime:'..target redis:hset(hash, expired) return 'تاریخ انقضای گروه به '..expired..' تغییر یافت' end if matches[1]:lower() == 'expiretime' then if tonumber(matches[2]) < 95 or tonumber(matches[2]) > 96 then return "اولین match باید بین 95 تا 96 باشد" end if tonumber(matches[3]) < 01 or tonumber(matches[3]) > 12 then return "دومین match باید بین 01 تا 12 باشد" end if tonumber(matches[4]) < 01 or tonumber(matches[4]) > 31 then return "سومین match باید بین 01 تا 31 باشد" end expired = matches[2]..'.'..matches[3]..'.'..matches[4] local target = get_receiver(msg) local hash = 'expiretime:'..target redis:set(hash, expired) savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group expire time to ["..matches[2]/matches[3]/matches[4].."]") return 'تاریخ انقضای گروه به '..expired..' تغییر یافت' end if matches[1]:lower() == 'setrules' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[2].."]") return set_rulesmod(msg, data, target) end if matches[1] == 'setwlc' and is_momod(msg) then rules = matches[2] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group welcome to ["..matches[2].."]") return set_welcomemod(msg, data, target) end if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set new SuperGroup photo") load_photo(msg.id, set_supergroup_photo, msg) return end end if matches[1]:lower() == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] started setting new SuperGroup photo") return 'برای تغییر عکس گروه ،یک عکس بفرستید' end if matches[1]:lower() == 'clean' then if not is_momod(msg) then return end if not is_momod(msg) then return "فقط مدیر قادر به حذف تمامی مدیران می باشد" end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then return 'هیچ مدیری در این گروه وجود ندارد' end 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") return 'تمامی مدیران از لیست مدیریت پاک شدند' end if matches[2] == 'rules' then local data_cat = 'rules' if data[tostring(msg.to.id)][data_cat] == nil then return "قانون یا قوانینی ثبت نشده است" end 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") return 'قوانین گروه پاک شد' end if matches[2]:lower() == 'welcome' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group welcome message to ["..matches[3].."]") return set_welcomemod(msg, data, target) end if matches[2] == 'desc' then local receiver = get_receiver(msg) local about_text = ' ' local data_cat = 'description' if data[tostring(msg.to.id)][data_cat] == nil then return 'موضوعی برای گروه ثبت نشده است' end 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") channel_set_about(receiver, about_text, ok_cb, false) return "موضوع گروه پاک شد" end if matches[2] == 'banlist' then local chat_id = msg.to.id local hash = 'banned:'..chat_id send_large_msg(get_receiver(msg), "لیست بن پاک شد.") redis:del(hash) end if matches[2] == 'silentlist' then chat_id = msg.to.id local hash = 'mute_user:'..chat_id redis:del(hash) return "لیست تمامی کاربران Mute شده پاک شد" end if matches[2] == 'username' and is_admin1(msg) then local function ok_username_cb (extra, success, result) local receiver = extra.receiver if success == 1 then send_large_msg(receiver, "SuperGroup username cleaned.") elseif success == 0 then send_large_msg(receiver, "Failed to clean SuperGroup username.") end end local username = "" channel_set_username(receiver, username, ok_username_cb, {receiver=receiver}) end if matches[2] == "bots" and is_momod(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked all SuperGroup bots") channel_get_bots(receiver, callback_clean_bots, {msg = msg}) end end if matches[1]:lower() == 'lock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link posting ") return lock_group_links(msg, data, target) end if matches[2] == 'cmd' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bot commands ") return lock_group_cmd(msg, data, target) end if matches[2] == 'url' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked url posting ") return lock_group_url(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked spam ") return lock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_flood(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] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(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] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tags ") return lock_group_tag(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] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked enabled strict settings") return enable_strict_rules(msg, data, target) end end if matches[1]:lower() == 'unlock' and is_momod(msg) then local target = msg.to.id if matches[2] == 'link' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link posting") return unlock_group_links(msg, data, target) end if matches[2] == 'cmd' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bot commands") return unlock_group_cmd(msg, data, target) end if matches[2] == 'url' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked url posting") return unlock_group_url(msg, data, target) end if matches[2] == 'spam' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked spam") return unlock_group_spam(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood") return unlock_group_flood(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] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(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] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tags ") return unlock_group_tag(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] == 'strict' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked disabled strict settings") return disable_strict_rules(msg, data, target) end end if matches[1]:lower() == 'setflood' then if not is_momod(msg) then return end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "عدد اشتباه، باید بین [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 'تعداد اسپم روی '..matches[2]..' ست شد' end if matches[1]:lower() == '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 SuperGroup to: not public") return unset_public_membermod(msg, data, target) end end if matches[1]:lower() == 'mute' then if not is_momod(msg) then return end local chat_id = msg.to.id local target = 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_audio'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فایل های صوتی فعال شد" else return "فیلتر فایل های صوتی از قبل فعال بوده است" end end if matches[2] == 'forward' then local msg_type = 'Forward' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_forward'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فروارد فعال شد" else return "فیلتر فروارد از قبل فعال بوده است" end end if matches[2] == 'reply' then local msg_type = 'Reply' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_reply'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر ریپلی فعال شد" else return "فیلتر ریپلی از قبل فعال بوده است" end end if matches[2] == 'emoji' then local msg_type = 'Emoji' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_emoji'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر ایموجی فعال شد" else return "فیلتر ایموجی از قبل فعال بوده است" end end if matches[2] == 'sticker' or matches[2] == 'stickers' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] mute sticker posting") return lock_group_sticker(msg, data, target) end if matches[2] == 'contact' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] mute contact posting") return lock_group_contacts(msg, data, target) end if matches[2] == 'porn' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] mute porn ") return lock_group_porn(msg, data, target) end if matches[2] == 'service' then local msg_type = 'service' if not is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_service'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر پیام ورود و خروج افراد فعال شد" else return "فیلتر پیام ورود و خروج افراد از قبل فعال بوده است" 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_photo'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر عکس فعال شد" else return "فیلتر عکس از قبل فعال بوده است" 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_video'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فیلم فعال شد" else return "فیلتر فیلم از قبل فعال بوده است" end end if matches[2] == 'gif' 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_gif'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر Gif فعال شد" else return "فیلتر Gif از قبل فعال بوده است" end end if matches[2] == 'doc' 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_doc'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر فایل ها فعال شد" else return "فیلتر فایل ها از قبل فعال بوده است" 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_text'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر ارسال متن فعال شد" else return "فیلتر ارسال متن از قبل فعال بوده است" 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 SuperGroup to: mute "..msg_type) mute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_all'] = 'yes' save_data(_config.moderation.data, data) return "فیلتر تمامی پیام ها فعال شد" else return "فیلتر تمامی پیام ها از قبل فعال بوده است" end end end if matches[1]:lower() == 'unmute' then if not is_momod(msg) then return end local chat_id = msg.to.id local target = 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 SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_audio'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فایل های صوتی غیرفعال شد" else return "فیلتر فایل های صوتی از قبل غیرفعال بوده است" end end if matches[2] == 'forward' then local msg_type = 'Forward' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_forward'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فروارد غیرفعال شد" else return "فیلتر فروارد از قبل غیرفعال بوده است" end end if matches[2] == 'reply' then local msg_type = 'Reply' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_reply'] = 'no' save_data(_config.moderation.data, data) return "فیلتر ریپلی غیرفعال شد" else return "فیلتر ریپلی از قبل غیرفعال بوده است" end end if matches[2] == 'emoji' then local msg_type = 'Emoji' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_emoji'] = 'no' save_data(_config.moderation.data, data) return "فیلتر ایموجی غیرفعال شد" else return "فیلتر ایموجی از قبل غیرفعال بوده است" end end if matches[2] == 'sticker' or matches[2] == 'stickers' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unmute sticker posting") return unlock_group_sticker(msg, data, target) end if matches[2] == 'contact' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unmute contact posting") return unlock_group_contacts(msg, data, target) end if matches[2] == 'porn' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unmute porn ") return unlock_group_porn(msg, data, target) end if matches[2] == 'service' then local msg_type = 'service' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_service'] = 'no' save_data(_config.moderation.data, data) return "فیلتر پیام ورود و خروج افراد غیرفعال شد" else return "فیلتر پیام ورود و خروج افراد از قبل غیرفعال بوده است" 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 SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_photo'] = 'no' save_data(_config.moderation.data, data) return "فیلتر عکس غیرفعال شد" else return "فیلتر عکس از قبل غیرفعال بوده است" 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 SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_video'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فیلم غیرفعال شد" else return "فیلتر فیلم از قبل غیرفعال بوده است" end end if matches[2] == 'gif' then local msg_type = 'Gifs' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_gif'] = 'no' save_data(_config.moderation.data, data) return "فیلتر Gif غیرفعال شد" else return "فیلتر Gif از قبل غیرفعال بوده است" end end if matches[2] == 'doc' then local msg_type = 'Documents' if is_muted(chat_id, msg_type..': yes') then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_doc'] = 'no' save_data(_config.moderation.data, data) return "فیلتر فایل ها غیرفعال شد" else return "فیلتر فایل ها از قبل غیرفعال بوده است" 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 SuperGroup to: unmute message") unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_text'] = 'no' save_data(_config.moderation.data, data) return "فیلتر ارسال متن غیرفعال شد" else return "فیلتر ارسال متن از قبل غیرفعال بوده است" 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 SuperGroup to: unmute "..msg_type) unmute(chat_id, msg_type) data[tostring(msg.to.id)]['settings']['mute_all'] = 'no' save_data(_config.moderation.data, data) return "فیلتر تمامی پیام ها غیرفعال شد" else return "فیلتر تمامی پیام ها از قبل غیرفعال بوده است" end end end if matches[1]:lower() == 'wlc' then local target = msg.to.id if matches[2]:lower() == 'enable' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked welcome ") return lock_group_welcome(msg, data, target) end if matches[2] == 'disable' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked welcome ") return unlock_group_welcome(msg, data, target) end end if matches[1]:lower() == 'chat' then local target = msg.to.id if matches[2]:lower() == 'enable' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked welcome ") return lock_group_chatrobot(msg, data, target) end if matches[2] == 'disable' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked welcome ") return unlock_group_chatrobot(msg, data, target) end end if matches[1]:lower() == 'kickme' then local target = msg.to.id if matches[2]:lower() == 'enable' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] enabled kickme ") return lock_group_kickme(msg, data, target) end if matches[2] == 'disable' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] disabled kickme ") return unlock_group_kickme(msg, data, target) end end --By @SoLiD021 if matches[1]:lower() == "silent" 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) muteuser = get_message(msg.reply_id, silentuser_by_reply, {receiver = receiver, msg = msg}) elseif matches[1]:lower() == "silent" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then return "["..user_id.."] از قبل به لیست Mute کاربران اضافه شده بود" end if is_momod(msg) then mute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."] to the muted users list") return "["..user_id.."] به لیست Mute کاربران اضافه شد" end elseif matches[1]:lower() == "silent" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, silentuser_by_username, {receiver = receiver, get_cmd = get_cmd, msg=msg}) end end --By @SoLiD021 if matches[1]:lower() == "unsilent" 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) muteuser = get_message(msg.reply_id, unsilentuser_by_reply, {receiver = receiver, msg = msg}) elseif matches[1]:lower() == "unsilent" and string.match(matches[2], '^%d+$') then local user_id = matches[2] if is_muted_user(chat_id, user_id) then unmute_user(chat_id, user_id) savelog(msg.to.id, name_log.." ["..msg.from.id.."] removed ["..user_id.."] from the muted users list") return "["..user_id.."] از لیست Mute کاربران حذف شد" else return "["..user_id.."] از قبل در لیست Mute کاربران نبوده" end elseif matches[1]:lower() == "unsilent" and not string.match(matches[2], '^%d+$') then local receiver = get_receiver(msg) local username = matches[2] local username = string.gsub(matches[2], '@', '') resolve_username(username, unsilentuser_by_username, {receiver = receiver, msg=msg}) end end if matches[1]:lower() == "mutelist" and is_momod(msg) then local target = msg.to.id if not has_mutes(target) then set_mutes(target) return show_supergroup_mutes(msg, target) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup muteslist") return show_supergroup_mutes(msg, target) end --Arian if matches[1]:lower() == "silentlist" and is_momod(msg) then local chat_id = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup mutelist") local hash = 'mute_user:'..msg.to.id local list = redis:smembers(hash) local text = "لیست کاربران Mute شده ["..msg.to.id.."]:\n\n" for k,v in pairsByKeys(list) do local user_info = redis:hgetall('user:'..v) if user_info and user_info.print_name then local print_name = string.gsub(user_info.print_name, "_", " ") local print_name = string.gsub(print_name, "‮", "") text = text..k.." - "..print_name.." ["..v.."]\n" else text = text..k.." - [ "..v.." ]\n" end end return text end if matches[1]:lower() == 'settings' and is_momod(msg) then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested SuperGroup settings ") return show_supergroup_settingsmod(msg, target) end if matches[1]:lower() == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end --[[if matches[1] == 'help' and not is_owner(msg) then text = "Dar Hale Sakhte shodan:|" reply_msg(msg.id, text, ok_cb, false) elseif matches[1] == 'help' and is_owner(msg) then local name_log = user_print_name(msg.from) savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /superhelp") return super_help() end]] if matches[1] == 'peer_id' and is_admin1(msg)then text = msg.to.peer_id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end if matches[1] == 'msg.to.id' and is_admin1(msg) then text = msg.to.id reply_msg(msg.id, text, ok_cb, false) post_large_msg(receiver, text) end --Admin Join Service Message if msg.service then local action = msg.action.type if action == 'chat_add_user_link' then if is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Admin ["..msg.from.id.."] joined the SuperGroup via link") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.from.id) and not is_owner2(msg.from.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.from.id savelog(msg.to.id, name_log.." Support member ["..msg.from.id.."] joined the SuperGroup") channel_set_mod(receiver, user, ok_cb, false) end end if action == 'chat_add_user' then if is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Admin ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_admin(receiver, user, ok_cb, false) end if is_support(msg.action.user.id) and not is_owner2(msg.action.user.id) then local receiver = get_receiver(msg) local user = "user#id"..msg.action.user.id savelog(msg.to.id, name_log.." Support member ["..msg.action.user.id.."] added to the SuperGroup by [ "..msg.from.id.." ]") channel_set_mod(receiver, user, ok_cb, false) end end end if matches[1] == 'msg.to.peer_id' then post_large_msg(receiver, msg.to.peer_id) 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 = { "^[!/#]([Aa]dd)$", "^[!/]([Rr]em)$", "^[!/]([Mm]ove) (.*)$", "^[!/]([Gg][Pp][Ii]nfo)$", "^[!/]([Aa]dmins)$", "^[!/]([Oo]wner)$", "^[!/]([Mm]odlist)$", "^[!/]([Bb]ots)$", "^[!/]([Ww]ho)$", "^[!/]([Kk]icked)$", "^[!/]([Bb]lock) (.*)", "^[!/]([Bb]lock)", "^[!/]([Tt]osuper)$", --"^[!/]([Ii][Dd])$", --"^[!/]([Ii][Dd]) (.*)$", "^[!/]([Kk]ickme) (.*)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Nn]ewlink)$", "^[!/]([Ss]etlink)$", "^[!/]([Ll]ink)$", "^[!/]([Hh]plink)$", "^[!/]([Gg]plink)$", "^[!/]([Hh]plink)$", "^[!/]([Rr]es) (.*)$", "^[!/]([Ss]etadmin) (.*)$", "^[!/]([Ss]etadmin)", "^[!/]([Dd]emoteadmin) (.*)$", "^[!/]([Dd]emoteadmin)", "^[!/]([Ss]etowner) (.*)$", "^[!/]([Ss]etowner)$", "^[!/]([Pp]romote) (.*)$", "^[!/]([Pp]romote)", "^[!/]([Dd]emote) (.*)$", "^[!/]([Dd]emote)", "^[!/]([Ss]etname) (.*)$", --"^[!/]([Ss]etwlc) (.*)$", "^[!/]([Ss]etdesc) (.*)$", "^[!/]([Ss]etrules) (.*)$", "^[!/]([Ss]etphoto)$", "^[!/]([Ss]etusername) (.*)$", "^[!/]([Uu][Ee]xpiretime)$", "^[!/]([Ee]xpiretime) (.*) (.*) (.*)$", "^[!/]([Dd]el)$", "^[!/]([Ll]ock) (.*)$", "^[!/]([Uu]nlock) (.*)$", "^[!/]([Mm]ute) ([^%s]+)$", "^[!/]([Uu]nmute) ([^%s]+)$", "^[!/]([Ss]ilent)$", "^[!/]([Ss]ilent) (.*)$", "^[!/]([Uu]nsilent)$", "^[!/]([Uu]nsilent) (.*)$", "^[!/]([Pp]ublic) (.*)$", "^[!/]([Ss]ettings)$", "^[!/]([Rr]ules)$", "^[!/]([Ss]etflood) (%d+)$", "^[!/]([Cc]lean) (.*)$", --"^[!/]([Hh]elp)$", "^[!/]([Ss]ilentlist)$", "^[!/]([Mm]utelist)$", "[!/](setmod) (.*)", "[!/](remmod) (.*)", "^[!/]([Ww]lc) (.*)$", "^[!/]([Cc]hat) (.*)$", "^([Aa]dd)$", "^([Rr]em)$", "^([Mm]ove) (.*)$", "^([Gg][Pp][Ii]nfo)$", "^([Aa]dmins)$", "^([Oo]wner)$", "^([Mm]odlist)$", "^([Bb]ots)$", "^([Ww]ho)$", "^([Kk]icked)$", "^([Bb]lock) (.*)", "^([Bb]lock)", "^([Tt]osuper)$", --"^([Ii][Dd])$", --"^([Ii][Dd]) (.*)$", "^([Kk]ickme) (.*)$", "^([Kk]ick) (.*)$", "^([Nn]ewlink)$", "^([Ss]etlink)$", "^([Ll]ink)$", "^([Hh]plink)$", "^([Gg]plink)$", "^([Hh]plink)$", "^([Rr]es) (.*)$", "^([Ss]etadmin) (.*)$", "^([Ss]etadmin)", "^([Dd]emoteadmin) (.*)$", "^([Dd]emoteadmin)", "^([Ss]etowner) (.*)$", "^([Ss]etowner)$", "^([Pp]romote) (.*)$", "^([Pp]romote)", "^([Dd]emote) (.*)$", "^([Dd]emote)", "^([Ss]etname) (.*)$", --"^([Ss]etwlc) (.*)$", "^([Ss]etdesc) (.*)$", "^([Ss]etrules) (.*)$", "^([Ss]etphoto)$", "^([Ss]etusername) (.*)$", "^([Uu][Ee]xpiretime)$", "^([Ee]xpiretime) (.*) (.*) (.*)$", "^([Dd]el)$", "^([Ll]ock) (.*)$", "^([Uu]nlock) (.*)$", "^([Mm]ute) ([^%s]+)$", "^([Uu]nmute) ([^%s]+)$", "^([Ss]ilent)$", "^([Ss]ilent) (.*)$", "^([Uu]nsilent)$", "^([Uu]nsilent) (.*)$", "^([Pp]ublic) (.*)$", "^([Ss]ettings)$", "^([Rr]ules)$", "^([Ss]etflood) (%d+)$", "^([Cc]lean) (.*)$", --"^([Hh]elp)$", "^([Ss]ilentlist)$", "^([Mm]utelist)$", "(setmod) (.*)", "(remmod) (.*)", "^([Ww]lc) (.*)$", "^([Cc]hat) (.*)$", "^(https://telegram.me/joinchat/%S+)$", --"msg.to.peer_id", "%[(document)%]", "%[(photo)%]", "%[(video)%]", "%[(audio)%]", "%[(contact)%]", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process } --End supergrpup.lua --By @Rondoozle
agpl-3.0
jshackley/darkstar
scripts/zones/Windurst_Waters/npcs/Chomo_Jinjahl.lua
33
1210
----------------------------------- -- Area: Windurst Waters -- NPC: Chomo Jinjahl -- Guild Merchant NPC: Cooking Guild -- @pos -105.094 -2.222 73.791 238 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(5302,5,20,7)) then player:showText(npc,CHOMOJINJAHL_SHOP_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); end;
gpl-3.0
Victek/wrt1900ac-aa
feeds/xwrt/webif-iw-lua/files/usr/lib/lua/lua-xwrt/xwrt/util.lua
18
3762
require("webif2.addon.string") require("webif2.xwrt.translator") local string = string local io = io local os = os local pairs, ipairs = pairs, ipairs local table = table local type = type local print = print local tostring, tonumber = tostring, tonumber local __TOCHECK = __TOCHECK local __UCI_CMD = __UCI_CMD local __ERROR = __ERROR local __FORM = __FORM local assert = assert local loadstring = loadstring local tr = tr local page = page module("lua-xwrt.xwrt.util") function show_table(t,idx) local idx = idx or 0 local str = string.rep(" ",idx) for k, v in pairs(t) do if type(v) == "table" then print(str..k) show_table(v,idx+1) else print(str..tostring(k).." => "..tostring(v)) end end end function intdiv(a,b) a = tonumber(a) or 0 b = tonumber(b) or 0 if a == 0 then return 0 end if b == 0 then return a end local c = (a % b) if c == 0 then return a/b, 0 else return ((a-c)/b), c end end -- Load File function file_load(filename) local data = "" local error = "" local BUFSIZE = 2^15 -- 32K local f = file_exists( filename ) if f == true then f = assert(io.open(filename,"r")) -- open input file else f = false end if f then while true do local lines, rest = f:read(BUFSIZE, "*line") if not lines then break end if rest then lines = lines .. rest .. '\n' end data = data ..lines end else return "No such file or directory", 0 end return data, string.len(data) end function file_exists( file ) local f = io.open( file, "r" ) if f then io.close( f ) return true else return false end end function file2table(filename,clean) local t = {} local f = file_exists( filename ) if f == false then return nil, "file do not exists" end f = io.open(filename,"r") for line in f:lines() do t[#t+1] = line end return t end function uptime() t = {} info = io.popen("uptime") for linea in info:lines() do linea = string.gsub(linea,".+ up ([0-9 a-z]) ","%1") local i,e = string.find(linea,", load average: ") t["loadavg"]=string.sub(linea,e) t["uptime"]=string.sub(linea,0,i-1) end info:close() return t end function isEnabled(str) local ls = io.popen("ls /etc/rc.d") for line in ls:lines() do if string.match(line,str) then return true end end return false end function isRunning(str) local ls = io.popen("ps") for line in ls:lines() do if string.match(line,str) then return true, line end end return false, "Not running" end -- To read a tables sort by Keys function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end function table2string(t,nl,idx) local idx = idx or 0 local str = string.rep(" ",idx) local ret = "" for k, v in pairs(t) do if type(v) == "table" then ret = ret .. str .. "start_" .. k .. nl ret = ret .. table2string(v,nl,idx+1) ret = ret .. str .. "end_" .. k .. nl else ret = ret .. str..tostring(k).." => "..tostring(v)..nl end end return ret end function dirList(path) local dir = {} fdir = io.popen("find "..path.."/* -type d") for line in fdir:lines() do -- __, __, line = string.find(line,".*/(.+):") -- if line then dir[#dir+1] = line -- end end fdir:close() return dir end function fileList(path) local dir = {} local full = fullpath or false fdir = io.popen("ls "..path) for line in fdir:lines() do if not string.match(line,":") then -- __, __, line = string.find(line,".*/(.+)") if line then dir[#dir+1] = line end end end fdir:close() return dir end
gpl-2.0
jshackley/darkstar
scripts/zones/Windurst_Woods/npcs/Aja-Panja.lua
38
1038
----------------------------------- -- Area: Windurst Woods -- NPC: Aja-Panja -- Type: Standard NPC -- @zone: 241 -- @pos -7.251 -6.55 -134.127 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00f7); 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
jshackley/darkstar
scripts/zones/Bibiki_Bay/npcs/Toh_Zonikki.lua
19
4706
----------------------------------- -- Area: Bibiki Bay -- NPC: Toh Zonikki -- Type: Clamming NPC -- @pos -371 -1 -421 4 ----------------------------------- package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil; require("scripts/zones/Bibiki_Bay/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- Local Variables ----------------------------------- local clammingItems = { 1311, -- Oxblood 885, -- Turtle Shell 1193, -- HQ Crab Shell 1446, -- Lacquer Tree Log 4318, -- Bibiki Urchin 1586, -- Titanictus Shell 5124, -- Tropical Clam 690, -- Elm Log 887, -- Coral Fragment 703, -- Petrified Log 691, -- Maple Log 4468, -- Pamamas 3270, -- HQ Pugil Scales 888, -- Seashell 4328, -- Hobgoblin Bread 485, -- Broken Willow Rod 510, -- Goblin Armor 5187, -- Elshimo Coconut 507, -- Goblin Mail 881, -- Crab Shell 4325, -- Hobgoblin Pie 936, -- Rock Salt 4361, -- Nebimonite 864, -- Fish Scales 4484, -- Shall Shell 624, -- Pamtam Kelp 1654, -- Igneous Rock 17296, -- Pebble 5123, -- Jacknife 5122 -- Bibiki Slug }; ----------------------------------- -- Local Functions ----------------------------------- local function giveClammedItems(player) for item = 1, table.getn(clammingItems) do local clammedItemQty = player:getVar("ClammedItem_" .. clammingItems[item]); if (clammedItemQty > 0) then if (player:addItem(clammingItems[item],clammedItemQty)) then player:messageSpecial(YOU_OBTAIN, clammingItems[item], clammedItemQty); player:setVar("ClammedItem_" .. clammingItems[item], 0); else player:messageSpecial(WHOA_HOLD_ON_NOW); break; end end end end; local function owePlayerClammedItems(player) for item = 1, table.getn(clammingItems) do if (player:getVar("ClammedItem_" .. clammingItems[item]) > 0) then return true; end end return false; end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if ( player:hasKeyItem(CLAMMING_KIT)) then -- Player has clamming kit if (player:getVar("ClammingKitBroken") == 1) then -- Broken bucket player:startEvent(0x001E, 0, 0, 0, 0, 0, 0, 0, 0); else --Bucket not broken player:startEvent(0x001D, 0, 0, 0, 0, 0, 0, 0, 0); end else -- Player does not have clamming kit if (owePlayerClammedItems(player)) then player:messageSpecial(YOU_GIT_YER_BAG_READY); giveClammedItems(player); else player:startEvent(0x001C, 500, 0, 0, 0, 0, 0, 0, 0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x001C) then local enoughMoney = 2; -- Not enough money if (player:getGil() >= 500) then enoughMoney = 1; --Player has enough Money end player:updateEvent(CLAMMING_KIT, enoughMoney, 0, 0, 0, 500, 0, 0); elseif (csid == 0x001D) then local clammingKitSize = player:getVar("ClammingKitSize"); player:updateEvent( player:getVar("ClammingKitWeight"), clammingKitSize, clammingKitSize, clammingKitSize + 50, 0, 0, 0, 0); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x001C) then if (option == 1) then -- Give 50pz clamming kit player:setVar("ClammingKitSize", 50); player:addKeyItem(CLAMMING_KIT); player:delGil(500); player:messageSpecial(KEYITEM_OBTAINED,CLAMMING_KIT); end elseif (csid == 0x001D) then if (option == 2) then -- Give player clammed items player:setVar("ClammingKitSize", 0); player:setVar("ClammingKitWeight", 0); player:delKeyItem(CLAMMING_KIT); player:messageSpecial(YOU_RETURN_THE,CLAMMING_KIT); giveClammedItems(player); elseif (option == 3) then -- Get bigger kit local clammingKitSize = player:getVar("ClammingKitSize") + 50; player:setVar("ClammingKitSize", clammingKitSize); player:messageSpecial(YOUR_CLAMMING_CAPACITY, 0, 0, clammingKitSize); end elseif ( csid == 0x001E) then -- Broken bucket player:setVar("ClammingKitSize", 0); player:setVar("ClammingKitBroken", 0); player:setVar("ClammingKitWeight", 0); player:delKeyItem(CLAMMING_KIT); player:messageSpecial(YOU_RETURN_THE,CLAMMING_KIT); end end;
gpl-3.0
sugiartocokrowibowo/Algorithm-Implementations
Best_First_Search/Lua/Yonaba/utils/bheap.lua
78
2454
-- Binary Heap data structure implementation -- See: http://www.policyalmanac.org/games/binaryHeaps.htm -- Adapted from: https://github.com/Yonaba/Binary-Heaps local PATH = (...):gsub('%.bheap$','') local class = require (PATH .. '.class') -- Looks for item in an array local function findIndex(array, item) for k,v in ipairs(array) do if v == item then return k end end end -- Percolates up to restore heap property local function sift_up(bheap, index) if index == 1 then return end local pIndex if index <= 1 then return end if index%2 == 0 then pIndex = index/2 else pIndex = (index-1)/2 end if not bheap._sort(bheap._heap[pIndex], bheap._heap[index]) then bheap._heap[pIndex], bheap._heap[index] = bheap._heap[index], bheap._heap[pIndex] sift_up(bheap, pIndex) end end -- Percolates down to restore heap property local function sift_down(bheap,index) local lfIndex,rtIndex,minIndex lfIndex = 2*index rtIndex = lfIndex + 1 if rtIndex > bheap.size then if lfIndex > bheap.size then return else minIndex = lfIndex end else if bheap._sort(bheap._heap[lfIndex],bheap._heap[rtIndex]) then minIndex = lfIndex else minIndex = rtIndex end end if not bheap._sort(bheap._heap[index],bheap._heap[minIndex]) then bheap._heap[index],bheap._heap[minIndex] = bheap._heap[minIndex],bheap._heap[index] sift_down(bheap,minIndex) end end -- Binary heap class -- Instantiates minHeaps by default local bheap = class() function bheap:initialize() self.size = 0 self._sort = function(a,b) return a < b end self._heap = {} end -- Clears the heap function bheap:clear() self._heap = {} self.size = 0 end -- Checks if the heap is empty function bheap:isEmpty() return (self.size==0) end -- Pushes a new item into the heap function bheap:push(item) self.size = self.size + 1 self._heap[self.size] = item sift_up(self, self.size) end -- Pops the lowest (or highest) best item out of the heap function bheap:pop() local root if self.size > 0 then root = self._heap[1] self._heap[1] = self._heap[self.size] self._heap[self.size] = nil self.size = self.size-1 if self.size > 1 then sift_down(self, 1) end end return root end -- Sorts a specific item in the heap function bheap:sort(item) if self.size <= 1 then return end local i = findIndex(self._heap, item) if i then sift_up(self, i) end end return bheap
mit
Shrike78/Shilke2D
Samples/FileSystem/IO_functions.lua
1
1335
require("Shilke2D/include") function test() print(IO.getBaseDir()) print(IO.getWorkingDir(false)) print(IO.getWorkingDir(true)) print(IO.getAbsolutePath("PlanetCute/PlanetCute.lua", false)) print(IO.getAbsolutePath("PlanetCute/PlanetCute.lua", true)) print(IO.getAbsolutePath("/PlanetCute/PlanetCute.lua", false)) print(IO.getAbsolutePath("/PlanetCute/PlanetCute.lua", true)) print(IO.exists("PlanetCute/PlanetCute.lua")) print(IO.isFile("PlanetCute/PlanetCute.lua")) print(IO.isDirectory("PlanetCute/PlanetCute.lua")) print(IO.exists("PlanetCute")) print(IO.isFile("PlanetCute")) print(IO.isDirectory("PlanetCute")) print(table.dump(IO.lsFiles())) print(table.dump(IO.lsDirectories())) print(table.dump(IO.ls())) IO.affirmPath("test1") IO.affirmPath("/test2") print(IO.deleteDirectory("test1")) print(IO.deleteDirectory("/test2")) print(IO.getFile("/Assets/PlanetCute/PlanetCute.lua")) print(IO.dofile("PlanetCute/PlanetCute.lua")) end --Setup is called once at the beginning of the application, just after Shilke2D initialization phase --here everything should be set up for the following execution function setup() test() IO.setWorkingDir("Assets") test() end --shilke2D initialization. it requires width, height and fps. Optional a scale value for x / y. shilke2D = Shilke2D(320,240,60) shilke2D:start()
mit
dani-sj/tekmilienod
plugins/inrealm.lua
92
25223
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.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 set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" 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 return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(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, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] 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 end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_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 if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
jshackley/darkstar
scripts/zones/Sauromugue_Champaign/npcs/Tiger_Bones.lua
17
1730
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Tiger Bones -- Involed in Quest: The Fanged One. -- @pos 666 -8 -379 120 ------------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,THE_FANGED_ONE) == QUEST_ACCEPTED) then deadTiger = player:getVar("TheFangedOne_Died"); if (deadTiger == 1 and player:hasKeyItem(OLD_TIGERS_FANG) == false) then player:addKeyItem(OLD_TIGERS_FANG); player:messageSpecial(KEYITEM_OBTAINED, OLD_TIGERS_FANG); elseif (deadTiger == 0) then if (GetMobAction(17268808) == 0) then SpawnMob(17268808):addStatusEffect(EFFECT_POISON,40,10,210); player:messageSpecial(OLD_SABERTOOTH_DIALOG_I); player:setVar("TheFangedOne_Died",1); end end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Victek/wrt1900ac-aa
veriksystems/luci-0.11/libs/nixio/docsrc/CHANGELOG.lua
95
1036
--- Changes and improvements. module "CHANGELOG" --- Service Release. -- <ul> -- <li>Added getifaddrs() function.</li> -- <li>Added getsockopt(), setsockopt(), getsockname() and getpeername() -- directly to TLS-socket objects unifying the socket interface.</li> -- <li>Added support for CyaSSL as cryptographical backend.</li> -- <li>Added support for x509 certificates in DER format.</li> -- <li>Added support for splice() in UnifiedIO.copyz().</li> -- <li>Added interface to inject chunks into UnifiedIO.linesource() buffer.</li> -- <li>Changed TLS behaviour to explicitely separate servers and clients.</li> -- <li>Fixed usage of signed datatype breaking Base64 decoding.</li> -- <li>Fixed namespace clashes for nixio.fs.</li> -- <li>Fixed splice() support for some exotic C libraries.</li> -- <li>Reconfigure axTLS cryptographical provider and mark it as obsolete.</li> -- </ul> -- @class table -- @name 0.3 -- @return ! --- Initial Release. -- <ul> -- <li>Initial Release</li> -- </ul> -- @class table -- @name 0.2 -- @return !
gpl-2.0
jshackley/darkstar
scripts/zones/North_Gustaberg/npcs/Cavernous_Maw_2.lua
58
1887
----------------------------------- -- Area: North Gustaberg -- NPC: Cavernous Maw -- @pos -78 -0.5 600 106 -- Teleports Players to Abyssea - Grauberg ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/abyssea"); require("scripts/zones/North_Gustaberg/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, AN_ULCEROUS_URAGNITE) == QUEST_AVAILABLE) then player:startEvent(0); else player:startEvent(908,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 Action ----------------------------------- function onEventFinish(player,csid,option) -- print("CSID:",csid); -- print("RESULT:",option); if (csid == 0) then player:addQuest(ABYSSEA, AN_ULCEROUS_URAGNITE); elseif (csid == 1) then -- Killed Amphitrite elseif (csid == 908 and option == 1) then player:setPos(-555,31,-760,0,254); end end;
gpl-3.0
iofun/treehouse
luerl/a8d96f9f101896509588e74ab62d3d8f.lua
1
2077
-- Our unit function table local this_unit = {} -- Where we are and fast we move local x, y, dx, dy -- Our name local name = "Protoss_Robotics_Facility" -- Our color local color = "yellow" -- Our BWAPI unit type local type = 155 -- Size of a clock tick msec local tick -- It's me, the unit structure local me = unit.self() -- The standard local variables local label = "large_structure" local armor = 1 local hitpoints,shield = 500,500 local ground_damage,air_damage = 0,0 local ground_cooldown,air_cooldown = 0,0 local ground_range,air_range = 0,0 local sight = 320 local supply = 0 local build_time = 1200 local build_score = 300 local destroy_score = 900 local mineral = 200 local gas = 200 local holdkey = "" -- The size of the region local xsize,ysize = region.size() -- The unit interface. function this_unit.start() end function this_unit.get_position() return x,y end function this_unit.set_position(a1, a2) x,y = a1,a2 end function this_unit.get_speed() return dx,dy end function this_unit.set_speed(a1, a2) dx,dy = a1,a2 end function this_unit.set_tick(a1) tick = a1 end local function move_xy_bounce(x, y, dx, dy, valid_x, valid_y) local nx = x + dx local ny = y + dy -- Bounce off the edge if (not valid_x(nx)) then nx = x - dx dx = -dx end -- Bounce off the edge if (not valid_y(ny)) then ny = y - dy dy = -dy end return nx, ny, dx, dy end local function move(x, y, dx, dy) local nx,ny,ndx,ndy = move_xy_bounce(x, y, dx, dy, region.valid_x, region.valid_y) -- Where we were and where we are now. local osx,osy = region.sector(x, y) local nsx,nsy = region.sector(nx, ny) if (osx ~= nsx or osy ~= nsy) then -- In new sector, move us to the right sector region.rem_sector(x, y) region.add_sector(nx, ny) end return nx,ny,ndx,ndy end function this_unit.tick() x,y,dx,dy = move(x, y, dx, dy) end function this_unit.attack() -- The unit has been zapped and will die region.rem_sector(x, y) end -- Return the unit table return this_unit
agpl-3.0
LiberatorUSA/GUCEF
platform/gucefIMAGE/premake5.lua
1
2773
-------------------------------------------------------------------- -- This file was automatically generated by ProjectGenerator -- which is tooling part the build system designed for GUCEF -- (Galaxy Unlimited Framework) -- For the latest info, see http://www.VanvelzenSoftware.com/ -- -- The contents of this file are placed in the public domain. Feel -- free to make use of it in any way you like. -------------------------------------------------------------------- -- -- Configuration for module: gucefIMAGE project( "gucefIMAGE" ) configuration( {} ) location( os.getenv( "PM5OUTPUTDIR" ) ) configuration( {} ) targetdir( os.getenv( "PM5TARGETDIR" ) ) configuration( {} ) language( "C++" ) configuration( {} ) kind( "SharedLib" ) configuration( {} ) links( { "gucefCORE", "gucefMT" } ) links( { "gucefCORE", "gucefMT" } ) configuration( {} ) defines( { "GUCEFIMAGE_BUILD_MODULE" } ) configuration( {} ) vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } } files( { "include/CGUCEFIMAGEModule.h", "include/gucefIMAGE.h", "include/gucefIMAGEDLLInit.h", "include/gucefIMAGE_CGUIImageCodec.h", "include/gucefIMAGE_CIImageCodec.h", "include/gucefIMAGE_CIMGCodec.h", "include/gucefIMAGE_CImage.h", "include/gucefIMAGE_CImageCodecPlugin.h", "include/gucefIMAGE_CImageCodecPluginManager.h", "include/gucefIMAGE_CImageCodecRegistry.h", "include/gucefIMAGE_CImageGlobal.h", "include/gucefIMAGE_CPixel.h", "include/gucefIMAGE_CPixelMap.h", "include/gucefIMAGE_CPluginImageCodecItem.h", "include/gucefIMAGE_ETypes.h", "include/gucefIMAGE_config.h", "include/gucefIMAGE_imagedata.h", "include/gucefIMAGE_macros.h" } ) configuration( {} ) vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } } files( { "src/CGUCEFIMAGEModule.cpp", "src/gucefIMAGE.cpp", "src/gucefIMAGE_CCPluginImageCodecItem.cpp", "src/gucefIMAGE_CGUIImageCodec.cpp", "src/gucefIMAGE_CIImageCodec.cpp", "src/gucefIMAGE_CIMGCodec.cpp", "src/gucefIMAGE_CImage.cpp", "src/gucefIMAGE_CImageCodecPlugin.cpp", "src/gucefIMAGE_CImageCodecPluginManager.cpp", "src/gucefIMAGE_CImageCodecRegistry.cpp", "src/gucefIMAGE_CImageGlobal.cpp", "src/gucefIMAGE_CPixel.cpp", "src/gucefIMAGE_CPixelMap.cpp" } ) configuration( {} ) includedirs( { "../../common/include", "../gucefCORE/include", "../gucefMT/include", "include" } ) configuration( { "ANDROID" } ) includedirs( { "../gucefCORE/include/android" } ) configuration( { "LINUX32" } ) includedirs( { "../gucefCORE/include/linux" } ) configuration( { "LINUX64" } ) includedirs( { "../gucefCORE/include/linux" } ) configuration( { "WIN32" } ) includedirs( { "../gucefCORE/include/mswin" } ) configuration( { "WIN64" } ) includedirs( { "../gucefCORE/include/mswin" } )
apache-2.0
ScottNZ/OpenRA
mods/cnc/maps/nod01/nod01.lua
14
3143
InitialForcesA = { "bggy", "e1", "e1", "e1", "e1" } InitialForcesB = { "e1", "e1", "bggy", "e1", "e1" } RifleInfantryReinforcements = { "e1", "e1" } RocketInfantryReinforcements = { "e3", "e3", "e3", "e3", "e3" } SendInitialForces = function() Media.PlaySpeechNotification(nod, "Reinforce") Reinforcements.Reinforce(nod, InitialForcesA, { StartSpawnPointLeft.Location, StartRallyPoint.Location }, 5) Reinforcements.Reinforce(nod, InitialForcesB, { StartSpawnPointRight.Location, StartRallyPoint.Location }, 10) end SendFirstInfantryReinforcements = function() Media.PlaySpeechNotification(nod, "Reinforce") Reinforcements.Reinforce(nod, RifleInfantryReinforcements, { StartSpawnPointRight.Location, StartRallyPoint.Location }, 15) end SendSecondInfantryReinforcements = function() Media.PlaySpeechNotification(nod, "Reinforce") Reinforcements.Reinforce(nod, RifleInfantryReinforcements, { StartSpawnPointLeft.Location, StartRallyPoint.Location }, 15) end SendLastInfantryReinforcements = function() Media.PlaySpeechNotification(nod, "Reinforce") -- Move the units properly into the map before they start attacking local forces = Reinforcements.Reinforce(nod, RocketInfantryReinforcements, { VillageSpawnPoint.Location, VillageRallyPoint.Location }, 8) Utils.Do(forces, function(a) a.Stance = "Defend" a.CallFunc(function() a.Stance = "AttackAnything" end) end) end WorldLoaded = function() nod = Player.GetPlayer("Nod") gdi = Player.GetPlayer("GDI") villagers = Player.GetPlayer("Villagers") Trigger.OnObjectiveAdded(nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(nod, function() Media.PlaySpeechNotification(nod, "Win") end) Trigger.OnPlayerLost(nod, function() Media.PlaySpeechNotification(nod, "Lose") end) NodObjective1 = nod.AddPrimaryObjective("Kill Nikoomba.") NodObjective2 = nod.AddPrimaryObjective("Destroy the village.") NodObjective3 = nod.AddSecondaryObjective("Destroy all GDI troops in the area.") GDIObjective1 = gdi.AddPrimaryObjective("Eliminate all Nod forces.") Trigger.OnKilled(Nikoomba, function() nod.MarkCompletedObjective(NodObjective1) Trigger.AfterDelay(DateTime.Seconds(1), function() SendLastInfantryReinforcements() end) end) Camera.Position = StartRallyPoint.CenterPosition SendInitialForces() Trigger.AfterDelay(DateTime.Seconds(30), SendFirstInfantryReinforcements) Trigger.AfterDelay(DateTime.Seconds(60), SendSecondInfantryReinforcements) end Tick = function() if DateTime.GameTime > 2 then if nod.HasNoRequiredUnits() then gdi.MarkCompletedObjective(GDIObjective1) end if villagers.HasNoRequiredUnits() then nod.MarkCompletedObjective(NodObjective2) end if gdi.HasNoRequiredUnits() then nod.MarkCompletedObjective(NodObjective3) end end end
gpl-3.0
Ombridride/minetest-minetestforfun-server
mods/mobs/bunny.lua
7
2060
-- Bunny by ExeterDad mobs:register_mob("mobs:bunny", { -- animal, monster, npc type = "animal", -- is it aggressive passive = true, reach = 1, -- health & armor hp_min = 3, hp_max = 6, armor = 200, -- textures and model collisionbox = {-0.268, -0.5, -0.268, 0.268, 0.167, 0.268}, visual = "mesh", mesh = "mobs_bunny.b3d", drawtype = "front", textures = { {"mobs_bunny_grey.png"}, {"mobs_bunny_brown.png"}, {"mobs_bunny_white.png"}, }, -- sounds sounds = {}, makes_footstep_sound = false, -- speed and jump walk_velocity = 1, run_velocity = 2, runaway = true, jump = true, -- drops meat when dead drops = { {name = "mobs:meat_raw", chance = 1, min = 1, max = 2}, }, -- damaged by water_damage = 1, lava_damage = 4, light_damage = 0, fear_height = 2, -- model animation animation = { speed_normal = 15, stand_start = 1, stand_end = 15, walk_start = 16, walk_end = 24, punch_start = 16, punch_end = 24, }, -- follows carrot from farming redo follow = {"farming:carrot", "farming_plus:carrot_item"}, view_range = 8, -- eat carrots replace_rate = 10, replace_what = {"farming:carrot_7", "farming:carrot_8", "farming_plus:carrot"}, replace_with = "air", -- right click to pick up rabbit on_rightclick = function(self, clicker) -- feed or tame if mobs:feed_tame(self, clicker, 4, true, true) then return end -- Monty Python tribute local item = clicker:get_wielded_item() if item:get_name() == "mobs:lava_orb" then if not minetest.setting_getbool("creative_mode") then item:take_item() clicker:set_wielded_item(item) end self.object:set_properties({ textures = {"mobs_bunny_evil.png"}, }) self.type = "monster" self.object:set_hp(20) return end mobs:capture_mob(self, clicker, 30, 50, 80, false, nil) end, attack_type = "dogfight", damage = 5, }) mobs:spawn_specific("mobs:bunny", {"default:dirt_with_grass"}, {"air"}, 8, 20, 30, 15000, 2, -31000, 31000, true, true) mobs:register_egg("mobs:bunny", "Bunny", "mobs_bunny_inv.png", 1)
unlicense
iofun/treehouse
luerl/6531923c8f81b03535d041faa14c867c.lua
1
2158
-- The Queen is a quick-flying air unit with the ability to cast multiple spells. -- Our unit function table local this_unit = {} -- Where we are and fast we move local x, y, dx, dy -- Our name local name = "Zerg_Queen" -- Our color local color = "red" -- Our BWAPI unit type local type = 45 -- Our label local label = "zerg_unit" -- Our category local category = "medium_air" -- Size of a clock tick msec local tick -- It's me, the unit structure local me = unit.self() -- The standard local variables local armor = 0 local hitpoints,shield = 120,0 local ground_damage,air_damage = 0,0 local ground_cooldown,air_cooldown = 0,0 local ground_range,air_range = 0,0 local sight = 10 local speed = 4.963 local supply = 2 local cooldown = 32 local mineral = 100 local gas = 100 local holdkey = "q" -- The size of the region local xsize,ysize = region.size() -- The unit interface. function this_unit.start() end function this_unit.get_position() return x,y end function this_unit.set_position(a1, a2) x,y = a1,a2 end function this_unit.get_speed() return dx,dy end function this_unit.set_speed(a1, a2) dx,dy = a1,a2 end function this_unit.set_tick(a1) tick = a1 end local function move_xy_bounce(x, y, dx, dy, valid_x, valid_y) local nx = x + dx local ny = y + dy -- Bounce off the edge if (not valid_x(nx)) then nx = x - dx dx = -dx end -- Bounce off the edge if (not valid_y(ny)) then ny = y - dy dy = -dy end return nx, ny, dx, dy end local function move(x, y, dx, dy) local nx,ny,ndx,ndy = move_xy_bounce(x, y, dx, dy, region.valid_x, region.valid_y) -- Where we were and where we are now. local osx,osy = region.sector(x, y) local nsx,nsy = region.sector(nx, ny) if (osx ~= nsx or osy ~= nsy) then -- In new sector, move us to the right sector region.rem_sector(x, y) region.add_sector(nx, ny) end return nx,ny,ndx,ndy end function this_unit.tick() x,y,dx,dy = move(x, y, dx, dy) end function this_unit.attack() -- The unit has been zapped and will die region.rem_sector(x, y) end -- Return the unit table return this_unit
agpl-3.0
andremm/lua-parser
lua-parser/parser.lua
1
19466
--[[ This module implements a parser for Lua 5.3 with LPeg, and generates an Abstract Syntax Tree that is similar to the one generated by Metalua. For more information about Metalua, please, visit: https://github.com/fab13n/metalua-parser block: { stat* } stat: `Do{ stat* } | `Set{ {lhs+} {expr+} } -- lhs1, lhs2... = e1, e2... | `While{ expr block } -- while e do b end | `Repeat{ block expr } -- repeat b until e | `If{ (expr block)+ block? } -- if e1 then b1 [elseif e2 then b2] ... [else bn] end | `Fornum{ ident expr expr expr? block } -- for ident = e, e[, e] do b end | `Forin{ {ident+} {expr+} block } -- for i1, i2... in e1, e2... do b end | `Local{ {ident+} {expr+}? } -- local i1, i2... = e1, e2... | `Localrec{ ident expr } -- only used for 'local function' | `Goto{ <string> } -- goto str | `Label{ <string> } -- ::str:: | `Return{ <expr*> } -- return e1, e2... | `Break -- break | apply expr: `Nil | `Dots | `Boolean{ <boolean> } | `Number{ <number> } | `String{ <string> } | `Function{ { `Id{ <string> }* `Dots? } block } | `Table{ ( `Pair{ expr expr } | expr )* } | `Op{ opid expr expr? } | `Paren{ expr } -- significant to cut multiple values returns | apply | lhs apply: `Call{ expr expr* } | `Invoke{ expr `String{ <string> } expr* } lhs: `Id{ <string> } | `Index{ expr expr } opid: -- includes additional operators from Lua 5.3 and all relational operators 'add' | 'sub' | 'mul' | 'div' | 'idiv' | 'mod' | 'pow' | 'concat' | 'band' | 'bor' | 'bxor' | 'shl' | 'shr' | 'eq' | 'ne' | 'lt' | 'gt' | 'le' | 'ge' | 'and' | 'or' | 'unm' | 'len' | 'bnot' | 'not' ]] local lpeg = require "lpeglabel" lpeg.locale(lpeg) local P, S, V = lpeg.P, lpeg.S, lpeg.V local C, Carg, Cb, Cc = lpeg.C, lpeg.Carg, lpeg.Cb, lpeg.Cc local Cf, Cg, Cmt, Cp, Cs, Ct = lpeg.Cf, lpeg.Cg, lpeg.Cmt, lpeg.Cp, lpeg.Cs, lpeg.Ct local Lc, T = lpeg.Lc, lpeg.T local alpha, digit, alnum = lpeg.alpha, lpeg.digit, lpeg.alnum local xdigit = lpeg.xdigit local space = lpeg.space -- error message auxiliary functions local labels = { { "ErrExtra", "unexpected character(s), expected EOF" }, { "ErrInvalidStat", "unexpected token, invalid start of statement" }, { "ErrEndIf", "expected 'end' to close the if statement" }, { "ErrExprIf", "expected a condition after 'if'" }, { "ErrThenIf", "expected 'then' after the condition" }, { "ErrExprEIf", "expected a condition after 'elseif'" }, { "ErrThenEIf", "expected 'then' after the condition" }, { "ErrEndDo", "expected 'end' to close the do block" }, { "ErrExprWhile", "expected a condition after 'while'" }, { "ErrDoWhile", "expected 'do' after the condition" }, { "ErrEndWhile", "expected 'end' to close the while loop" }, { "ErrUntilRep", "expected 'until' at the end of the repeat loop" }, { "ErrExprRep", "expected a conditions after 'until'" }, { "ErrForRange", "expected a numeric or generic range after 'for'" }, { "ErrEndFor", "expected 'end' to close the for loop" }, { "ErrExprFor1", "expected a starting expression for the numeric range" }, { "ErrCommaFor", "expected ',' to split the start and end of the range" }, { "ErrExprFor2", "expected an ending expression for the numeric range" }, { "ErrExprFor3", "expected a step expression for the numeric range after ','" }, { "ErrInFor", "expected '=' or 'in' after the variable(s)" }, { "ErrEListFor", "expected one or more expressions after 'in'" }, { "ErrDoFor", "expected 'do' after the range of the for loop" }, { "ErrDefLocal", "expected a function definition or assignment after local" }, { "ErrNameLFunc", "expected a function name after 'function'" }, { "ErrEListLAssign", "expected one or more expressions after '='" }, { "ErrEListAssign", "expected one or more expressions after '='" }, { "ErrFuncName", "expected a function name after 'function'" }, { "ErrNameFunc1", "expected a function name after '.'" }, { "ErrNameFunc2", "expected a method name after ':'" }, { "ErrOParenPList", "expected '(' for the parameter list" }, { "ErrCParenPList", "expected ')' to close the parameter list" }, { "ErrEndFunc", "expected 'end' to close the function body" }, { "ErrParList", "expected a variable name or '...' after ','" }, { "ErrLabel", "expected a label name after '::'" }, { "ErrCloseLabel", "expected '::' after the label" }, { "ErrGoto", "expected a label after 'goto'" }, { "ErrRetList", "expected an expression after ',' in the return statement" }, { "ErrVarList", "expected a variable name after ','" }, { "ErrExprList", "expected an expression after ','" }, { "ErrOrExpr", "expected an expression after 'or'" }, { "ErrAndExpr", "expected an expression after 'and'" }, { "ErrRelExpr", "expected an expression after the relational operator" }, { "ErrBOrExpr", "expected an expression after '|'" }, { "ErrBXorExpr", "expected an expression after '~'" }, { "ErrBAndExpr", "expected an expression after '&'" }, { "ErrShiftExpr", "expected an expression after the bit shift" }, { "ErrConcatExpr", "expected an expression after '..'" }, { "ErrAddExpr", "expected an expression after the additive operator" }, { "ErrMulExpr", "expected an expression after the multiplicative operator" }, { "ErrUnaryExpr", "expected an expression after the unary operator" }, { "ErrPowExpr", "expected an expression after '^'" }, { "ErrExprParen", "expected an expression after '('" }, { "ErrCParenExpr", "expected ')' to close the expression" }, { "ErrNameIndex", "expected a field name after '.'" }, { "ErrExprIndex", "expected an expression after '['" }, { "ErrCBracketIndex", "expected ']' to close the indexing expression" }, { "ErrNameMeth", "expected a method name after ':'" }, { "ErrMethArgs", "expected some arguments for the method call (or '()')" }, { "ErrArgList", "expected an expression after ',' in the argument list" }, { "ErrCParenArgs", "expected ')' to close the argument list" }, { "ErrCBraceTable", "expected '}' to close the table constructor" }, { "ErrEqField", "expected '=' after the table key" }, { "ErrExprField", "expected an expression after '='" }, { "ErrExprFKey", "expected an expression after '[' for the table key" }, { "ErrCBracketFKey", "expected ']' to close the table key" }, { "ErrDigitHex", "expected one or more hexadecimal digits after '0x'" }, { "ErrDigitDeci", "expected one or more digits after the decimal point" }, { "ErrDigitExpo", "expected one or more digits for the exponent" }, { "ErrQuote", "unclosed string" }, { "ErrHexEsc", "expected exactly two hexadecimal digits after '\\x'" }, { "ErrOBraceUEsc", "expected '{' after '\\u'" }, { "ErrDigitUEsc", "expected one or more hexadecimal digits for the UTF-8 code point" }, { "ErrCBraceUEsc", "expected '}' after the code point" }, { "ErrEscSeq", "invalid escape sequence" }, { "ErrCloseLStr", "unclosed long string" }, } local function throw(label) label = "Err" .. label for i, labelinfo in ipairs(labels) do if labelinfo[1] == label then return T(i) end end error("Label not found: " .. label) end local function expect (patt, label) return patt + throw(label) end -- regular combinators and auxiliary functions local function token (patt) return patt * V"Skip" end local function sym (str) return token(P(str)) end local function kw (str) return token(P(str) * -V"IdRest") end local function dec(n) return n - 1 end local function tagC (tag, patt) return Ct(Cg(Cp(), "pos") * Cg(Cc(tag), "tag") * patt * Cg(Cp() / dec, "end_pos")) end local function unaryOp (op, e) return { tag = "Op", pos = e.pos, end_pos = e.end_pos, [1] = op, [2] = e } end local function binaryOp (e1, op, e2) if not op then return e1 else return { tag = "Op", pos = e1.pos, end_pos = e2.end_pos, [1] = op, [2] = e1, [3] = e2 } end end local function sepBy (patt, sep, label) if label then return patt * Cg(sep * expect(patt, label))^0 else return patt * Cg(sep * patt)^0 end end local function chainOp (patt, sep, label) return Cf(sepBy(patt, sep, label), binaryOp) end local function commaSep (patt, label) return sepBy(patt, sym(","), label) end local function tagDo (block) block.tag = "Do" return block end local function fixFuncStat (func) if func[1].is_method then table.insert(func[2][1], 1, { tag = "Id", [1] = "self" }) end func[1] = {func[1]} func[2] = {func[2]} return func end local function addDots (params, dots) if dots then table.insert(params, dots) end return params end local function insertIndex (t, index) return { tag = "Index", pos = t.pos, end_pos = index.end_pos, [1] = t, [2] = index } end local function markMethod(t, method) if method then return { tag = "Index", pos = t.pos, end_pos = method.end_pos, is_method = true, [1] = t, [2] = method } end return t end local function makeIndexOrCall (t1, t2) if t2.tag == "Call" or t2.tag == "Invoke" then local t = { tag = t2.tag, pos = t1.pos, end_pos = t2.end_pos, [1] = t1 } for k, v in ipairs(t2) do table.insert(t, v) end return t end return { tag = "Index", pos = t1.pos, end_pos = t2.end_pos, [1] = t1, [2] = t2[1] } end -- grammar local G = { V"Lua", Lua = V"Shebang"^-1 * V"Skip" * V"Block" * expect(P(-1), "Extra"); Shebang = P"#!" * (P(1) - P"\n")^0; Block = tagC("Block", V"Stat"^0 * V"RetStat"^-1); Stat = V"IfStat" + V"DoStat" + V"WhileStat" + V"RepeatStat" + V"ForStat" + V"LocalStat" + V"FuncStat" + V"BreakStat" + V"LabelStat" + V"GoToStat" + V"FuncCall" + V"Assignment" + sym(";") + -V"BlockEnd" * throw("InvalidStat"); BlockEnd = P"return" + "end" + "elseif" + "else" + "until" + -1; IfStat = tagC("If", V"IfPart" * V"ElseIfPart"^0 * V"ElsePart"^-1 * expect(kw("end"), "EndIf")); IfPart = kw("if") * expect(V"Expr", "ExprIf") * expect(kw("then"), "ThenIf") * V"Block"; ElseIfPart = kw("elseif") * expect(V"Expr", "ExprEIf") * expect(kw("then"), "ThenEIf") * V"Block"; ElsePart = kw("else") * V"Block"; DoStat = kw("do") * V"Block" * expect(kw("end"), "EndDo") / tagDo; WhileStat = tagC("While", kw("while") * expect(V"Expr", "ExprWhile") * V"WhileBody"); WhileBody = expect(kw("do"), "DoWhile") * V"Block" * expect(kw("end"), "EndWhile"); RepeatStat = tagC("Repeat", kw("repeat") * V"Block" * expect(kw("until"), "UntilRep") * expect(V"Expr", "ExprRep")); ForStat = kw("for") * expect(V"ForNum" + V"ForIn", "ForRange") * expect(kw("end"), "EndFor"); ForNum = tagC("Fornum", V"Id" * sym("=") * V"NumRange" * V"ForBody"); NumRange = expect(V"Expr", "ExprFor1") * expect(sym(","), "CommaFor") *expect(V"Expr", "ExprFor2") * (sym(",") * expect(V"Expr", "ExprFor3"))^-1; ForIn = tagC("Forin", V"NameList" * expect(kw("in"), "InFor") * expect(V"ExprList", "EListFor") * V"ForBody"); ForBody = expect(kw("do"), "DoFor") * V"Block"; LocalStat = kw("local") * expect(V"LocalFunc" + V"LocalAssign", "DefLocal"); LocalFunc = tagC("Localrec", kw("function") * expect(V"Id", "NameLFunc") * V"FuncBody") / fixFuncStat; LocalAssign = tagC("Local", V"NameList" * (sym("=") * expect(V"ExprList", "EListLAssign") + Ct(Cc()))); Assignment = tagC("Set", V"VarList" * sym("=") * expect(V"ExprList", "EListAssign")); FuncStat = tagC("Set", kw("function") * expect(V"FuncName", "FuncName") * V"FuncBody") / fixFuncStat; FuncName = Cf(V"Id" * (sym(".") * expect(V"StrId", "NameFunc1"))^0, insertIndex) * (sym(":") * expect(V"StrId", "NameFunc2"))^-1 / markMethod; FuncBody = tagC("Function", V"FuncParams" * V"Block" * expect(kw("end"), "EndFunc")); FuncParams = expect(sym("("), "OParenPList") * V"ParList" * expect(sym(")"), "CParenPList"); ParList = V"NameList" * (sym(",") * expect(tagC("Dots", sym("...")), "ParList"))^-1 / addDots + Ct(tagC("Dots", sym("..."))) + Ct(Cc()); -- Cc({}) generates a bug since the {} would be shared across parses LabelStat = tagC("Label", sym("::") * expect(V"Name", "Label") * expect(sym("::"), "CloseLabel")); GoToStat = tagC("Goto", kw("goto") * expect(V"Name", "Goto")); BreakStat = tagC("Break", kw("break")); RetStat = tagC("Return", kw("return") * commaSep(V"Expr", "RetList")^-1 * sym(";")^-1); NameList = tagC("NameList", commaSep(V"Id")); VarList = tagC("VarList", commaSep(V"VarExpr", "VarList")); ExprList = tagC("ExpList", commaSep(V"Expr", "ExprList")); Expr = V"OrExpr"; OrExpr = chainOp(V"AndExpr", V"OrOp", "OrExpr"); AndExpr = chainOp(V"RelExpr", V"AndOp", "AndExpr"); RelExpr = chainOp(V"BOrExpr", V"RelOp", "RelExpr"); BOrExpr = chainOp(V"BXorExpr", V"BOrOp", "BOrExpr"); BXorExpr = chainOp(V"BAndExpr", V"BXorOp", "BXorExpr"); BAndExpr = chainOp(V"ShiftExpr", V"BAndOp", "BAndExpr"); ShiftExpr = chainOp(V"ConcatExpr", V"ShiftOp", "ShiftExpr"); ConcatExpr = V"AddExpr" * (V"ConcatOp" * expect(V"ConcatExpr", "ConcatExpr"))^-1 / binaryOp; AddExpr = chainOp(V"MulExpr", V"AddOp", "AddExpr"); MulExpr = chainOp(V"UnaryExpr", V"MulOp", "MulExpr"); UnaryExpr = V"UnaryOp" * expect(V"UnaryExpr", "UnaryExpr") / unaryOp + V"PowExpr"; PowExpr = V"SimpleExpr" * (V"PowOp" * expect(V"UnaryExpr", "PowExpr"))^-1 / binaryOp; SimpleExpr = tagC("Number", V"Number") + tagC("String", V"String") + tagC("Nil", kw("nil")) + tagC("Boolean", kw("false") * Cc(false)) + tagC("Boolean", kw("true") * Cc(true)) + tagC("Dots", sym("...")) + V"FuncDef" + V"Table" + V"SuffixedExpr"; FuncCall = Cmt(V"SuffixedExpr", function(s, i, exp) return exp.tag == "Call" or exp.tag == "Invoke", exp end); VarExpr = Cmt(V"SuffixedExpr", function(s, i, exp) return exp.tag == "Id" or exp.tag == "Index", exp end); SuffixedExpr = Cf(V"PrimaryExpr" * (V"Index" + V"Call")^0, makeIndexOrCall); PrimaryExpr = V"Id" + tagC("Paren", sym("(") * expect(V"Expr", "ExprParen") * expect(sym(")"), "CParenExpr")); Index = tagC("DotIndex", sym("." * -P".") * expect(V"StrId", "NameIndex")) + tagC("ArrayIndex", sym("[" * -P(S"=[")) * expect(V"Expr", "ExprIndex") * expect(sym("]"), "CBracketIndex")); Call = tagC("Invoke", Cg(sym(":" * -P":") * expect(V"StrId", "NameMeth") * expect(V"FuncArgs", "MethArgs"))) + tagC("Call", V"FuncArgs"); FuncDef = kw("function") * V"FuncBody"; FuncArgs = sym("(") * commaSep(V"Expr", "ArgList")^-1 * expect(sym(")"), "CParenArgs") + V"Table" + tagC("String", V"String"); Table = tagC("Table", sym("{") * V"FieldList"^-1 * expect(sym("}"), "CBraceTable")); FieldList = sepBy(V"Field", V"FieldSep") * V"FieldSep"^-1; Field = tagC("Pair", V"FieldKey" * expect(sym("="), "EqField") * expect(V"Expr", "ExprField")) + V"Expr"; FieldKey = sym("[" * -P(S"=[")) * expect(V"Expr", "ExprFKey") * expect(sym("]"), "CBracketFKey") + V"StrId" * #("=" * -P"="); FieldSep = sym(",") + sym(";"); Id = tagC("Id", V"Name"); StrId = tagC("String", V"Name"); -- lexer Skip = (V"Space" + V"Comment")^0; Space = space^1; Comment = P"--" * V"LongStr" / function () return end + P"--" * (P(1) - P"\n")^0; Name = token(-V"Reserved" * C(V"Ident")); Reserved = V"Keywords" * -V"IdRest"; Keywords = P"and" + "break" + "do" + "elseif" + "else" + "end" + "false" + "for" + "function" + "goto" + "if" + "in" + "local" + "nil" + "not" + "or" + "repeat" + "return" + "then" + "true" + "until" + "while"; Ident = V"IdStart" * V"IdRest"^0; IdStart = alpha + P"_"; IdRest = alnum + P"_"; Number = token((V"Hex" + V"Float" + V"Int") / tonumber); Hex = (P"0x" + "0X") * expect(xdigit^1, "DigitHex"); Float = V"Decimal" * V"Expo"^-1 + V"Int" * V"Expo"; Decimal = digit^1 * "." * digit^0 + P"." * -P"." * expect(digit^1, "DigitDeci"); Expo = S"eE" * S"+-"^-1 * expect(digit^1, "DigitExpo"); Int = digit^1; String = token(V"ShortStr" + V"LongStr"); ShortStr = P'"' * Cs((V"EscSeq" + (P(1)-S'"\n'))^0) * expect(P'"', "Quote") + P"'" * Cs((V"EscSeq" + (P(1)-S"'\n"))^0) * expect(P"'", "Quote"); EscSeq = P"\\" / "" -- remove backslash * ( P"a" / "\a" + P"b" / "\b" + P"f" / "\f" + P"n" / "\n" + P"r" / "\r" + P"t" / "\t" + P"v" / "\v" + P"\n" / "\n" + P"\r" / "\n" + P"\\" / "\\" + P"\"" / "\"" + P"\'" / "\'" + P"z" * space^0 / "" + digit * digit^-2 / tonumber / string.char + P"x" * expect(C(xdigit * xdigit), "HexEsc") * Cc(16) / tonumber / string.char + P"u" * expect("{", "OBraceUEsc") * expect(C(xdigit^1), "DigitUEsc") * Cc(16) * expect("}", "CBraceUEsc") / tonumber / (utf8 and utf8.char or string.char) -- true max is \u{10FFFF} -- utf8.char needs Lua 5.3 -- string.char works only until \u{FF} + throw("EscSeq") ); LongStr = V"Open" * C((P(1) - V"CloseEq")^0) * expect(V"Close", "CloseLStr") / function (s, eqs) return s end; Open = "[" * Cg(V"Equals", "openEq") * "[" * P"\n"^-1; Close = "]" * C(V"Equals") * "]"; Equals = P"="^0; CloseEq = Cmt(V"Close" * Cb("openEq"), function (s, i, closeEq, openEq) return #openEq == #closeEq end); OrOp = kw("or") / "or"; AndOp = kw("and") / "and"; RelOp = sym("~=") / "ne" + sym("==") / "eq" + sym("<=") / "le" + sym(">=") / "ge" + sym("<") / "lt" + sym(">") / "gt"; BOrOp = sym("|") / "bor"; BXorOp = sym("~" * -P"=") / "bxor"; BAndOp = sym("&") / "band"; ShiftOp = sym("<<") / "shl" + sym(">>") / "shr"; ConcatOp = sym("..") / "concat"; AddOp = sym("+") / "add" + sym("-") / "sub"; MulOp = sym("*") / "mul" + sym("//") / "idiv" + sym("/") / "div" + sym("%") / "mod"; UnaryOp = kw("not") / "not" + sym("-") / "unm" + sym("#") / "len" + sym("~") / "bnot"; PowOp = sym("^") / "pow"; } local parser = {} local validator = require("lua-parser.validator") local validate = validator.validate local syntaxerror = validator.syntaxerror function parser.parse (subject, filename) local errorinfo = { subject = subject, filename = filename } lpeg.setmaxstack(1000) local ast, label, errorpos = lpeg.match(G, subject, nil, errorinfo) if not ast then local errmsg = labels[label][2] return ast, syntaxerror(errorinfo, errorpos, errmsg) end return validate(ast, errorinfo) end return parser
mit
bsmr-games/OpenRA
mods/ra/maps/soviet-04a/reinforcements_teams.lua
20
2642
Civs = { civ1, civ2, civ3 } Village = { civ1, civ2, civ3, village1, village2, village5 } SovietMCV = { "mcv" } InfantryReinfGreece = { "e1", "e1", "e1", "e1", "e1" } Avengers = { "jeep", "1tnk", "2tnk", "2tnk", "1tnk" } Patrol1Group = { "jeep", "jeep", "2tnk", "2tnk" } Patrol2Group = { "jeep", "1tnk", "1tnk", "1tnk" } AlliedInfantryTypes = { "e1", "e3" } AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" } InfAttack = { } ArmorAttack = { } SovietStartToBasePath = { StartPoint.Location, SovietBasePoint.Location } InfReinfPath = { SWRoadPoint.Location, InVillagePoint.Location } ArmorReinfPath = { NRoadPoint.Location, CrossroadsNorthPoint.Location } Patrol1Path = { NearRadarPoint.Location, ToRadarPoint.Location, InVillagePoint.Location, ToRadarPoint.Location } Patrol2Path = { BridgeEntrancePoint.Location, NERoadTurnPoint.Location, CrossroadsEastPoint.Location, BridgeEntrancePoint.Location } VillageCamArea = { CPos.New(68, 75),CPos.New(68, 76),CPos.New(68, 77),CPos.New(68, 78),CPos.New(68, 79), CPos.New(68, 80), CPos.New(68, 81), CPos.New(68, 82) } if Map.Difficulty == "Easy" then ArmorReinfGreece = { "jeep", "1tnk", "1tnk" } else ArmorReinfGreece = { "jeep", "jeep", "1tnk", "1tnk", "1tnk" } end AttackPaths = { { VillageEntrancePoint }, { BridgeEntrancePoint, NERoadTurnPoint, CrossroadsEastPoint } } ReinfInf = function() Reinforcements.Reinforce(Greece, InfantryReinfGreece, InfReinfPath, 0, function(soldier) soldier.Hunt() end) end ReinfArmor = function() if not Radar.IsDead and Radar.Owner == Greece then RCheck = true Reinforcements.Reinforce(Greece, ArmorReinfGreece, ArmorReinfPath, 0, function(soldier) soldier.Hunt() end) end end BringPatrol1 = function() local units = Reinforcements.Reinforce(Greece, Patrol1Group, { SWRoadPoint.Location }, 0) Utils.Do(units, function(patrols) patrols.Patrol(Patrol1Path, true, 250) end) if not Radar.IsDead and Radar.Owner == Greece then Trigger.OnAllKilled(units, function() if Map.Difficulty == "Hard" then Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol1) else Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol1) end end) end end BringPatrol2 = function() local units = Reinforcements.Reinforce(Greece, Patrol2Group, { NRoadPoint.Location }, 0) Utils.Do(units, function(patrols) patrols.Patrol(Patrol2Path, true, 250) end) if not Radar.IsDead and Radar.Owner == Greece then Trigger.OnAllKilled(units, function() if Map.Difficulty == "Hard" then Trigger.AfterDelay(DateTime.Minutes(4), BringPatrol2) else Trigger.AfterDelay(DateTime.Minutes(7), BringPatrol2) end end) end end
gpl-3.0
jshackley/darkstar
scripts/zones/Buburimu_Peninsula/npcs/Stone_Monument.lua
32
1299
----------------------------------- -- Area: Buburimu Peninsula -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos 320.755 -4.000 368.722 118 ----------------------------------- package.loaded["scripts/zones/Buburimu_Peninsula/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Buburimu_Peninsula/TextIDs"); ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0384); end; ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then player:tradeComplete(); player:addItem(570); player:messageSpecial(ITEM_OBTAINED,570); player:setVar("anExplorer-CurrentTablet",0x02000); 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
wilhantian/catui
catui/Control/UIImage.lua
2
2440
--[[ The MIT License (MIT) Copyright (c) 2016 WilhanTian 田伟汉 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- ------------------------------------- -- UIImage -- @usage -- local img = UIImage:new("img/gem.png") ------------------------------------- local UIImage = UIControl:extend("UIImage", { drawable = nil }) ------------------------------------- -- construct ------------------------------------- function UIImage:init(fileName) UIControl.init(self) self:setImage(fileName) self:resetSize() self.events:on(UI_DRAW, self.onDraw, self) end ------------------------------------- -- (callback) -- draw self ------------------------------------- function UIImage:onDraw() local box = self:getBoundingBox() local x, y = box:getX(), box:getY() local w, h = box:getWidth(), box:getHeight() love.graphics.draw(self.drawable, x, y) end ------------------------------------- -- set a image -- @string fileName file path ------------------------------------- function UIImage:setImage(fileName) if fileName then self.drawable = love.graphics.newImage(fileName) end end ------------------------------------- -- reset size ------------------------------------- function UIImage:resetSize() if self.drawable then self:setWidth(self.drawable:getWidth()) self:setHeight(self.drawable:getHeight()) else self:setWidth(0) self:setHeight(0) end end return UIImage
mit
SpRoXx/GTW-RPG
[resources]/GTWgroups/c_gui.lua
2
12332
--[[ ******************************************************************************** Project owner: RageQuit community Project name: GTW-RPG Developers: Sebbe (smart), Mr_Moose Source code: https://github.com/GTWCode/GTW-RPG/ Bugtracker: http://forum.404rq.com/bug-reports/ Suggestions: http://forum.404rq.com/mta-servers-development/ Version: Open source License: BSD 2-Clause Status: Stable release ******************************************************************************** ]]-- --[[ Initialize group system GUI elements ]]-- function makeGUI() window = guiCreateWindow(0, 0, 770, 550, "Grand Theft Walrus - groups", false) guiWindowSetSizable(window, false) guiSetAlpha(window, 1.00) guiSetVisible(window, false) mainPanel = guiCreateTabPanel(6, 23, 758, 520, false, window) exports.GTWgui:setDefaultFont(mainPanel, 10) minePanel = guiCreateTab("Information", mainPanel) myGroupLabel = guiCreateLabel(20, 10, 280, 20, "Current group: ", false, minePanel) exports.GTWgui:setDefaultFont(myGroupLabel, 10) myGroupRankLabel = guiCreateLabel(20, 30, 280, 20, "Group rank: ", false, minePanel) exports.GTWgui:setDefaultFont(myGroupRankLabel, 10) dateJoinedLabel = guiCreateLabel(20, 50, 280, 20, "Date joined: ", false, minePanel) exports.GTWgui:setDefaultFont(dateJoinedLabel, 10) mineListInvites = guiCreateGridList(10, 80, 730, 366, false, minePanel) guiGridListAddColumn(mineListInvites, "Group", 0.3) guiGridListAddColumn(mineListInvites, "Sent by", 0.3) guiGridListAddColumn(mineListInvites, "Time", 0.3) exports.GTWgui:setDefaultFont(mineListInvites, 10) reject_inviteButton = guiCreateButton(124, 450, 110, 36, "Reject Invite", false, minePanel) accept_inviteButton = guiCreateButton(10, 450, 110, 36, "Accept Invite", false, minePanel) createGroupButton = guiCreateButton(640, 10, 100, 30, "Create", false, minePanel) createGroupEdit = guiCreateEdit(486, 10, 150, 30, "", false, minePanel) leaveGroupButton = guiCreateButton(640, 44, 100, 30, "Leave", false, minePanel) groupListButton = guiCreateButton(238, 450, 110, 36, "Group List", false, minePanel) exports.GTWgui:setDefaultFont(reject_inviteButton, 10) exports.GTWgui:setDefaultFont(accept_inviteButton, 10) exports.GTWgui:setDefaultFont(createGroupButton, 10) exports.GTWgui:setDefaultFont(leaveGroupButton, 10) exports.GTWgui:setDefaultFont(groupListButton, 10) adminPanel = guiCreateTab("Management", mainPanel) adminMembsList = guiCreateGridList(10, 10, 730, 430, false, adminPanel) guiGridListAddColumn(adminMembsList, "Last Nick", 0.19) guiGridListAddColumn(adminMembsList, "Account", 0.19) guiGridListAddColumn(adminMembsList, "Rank", 0.19) guiGridListAddColumn(adminMembsList, "Last time online", 0.19) guiGridListAddColumn(adminMembsList, "Warning Level", 0.19) viewSetRankButton = guiCreateButton(11, 444, 104, 36, "Set Rank", false, adminPanel) logButton = guiCreateButton(115, 444, 104, 36, "View Log", false, adminPanel) viewAdminInviteButton = guiCreateButton(219, 444, 104, 36, "Invite Player(s)", false, adminPanel) blackListButton = guiCreateButton(333, 444, 104, 36, "Blacklist", false, adminPanel) manageRanksButton = guiCreateButton(437, 444, 104, 36, "Manage Ranks", false, adminPanel) viewWarnsButton = guiCreateButton(541, 444, 104, 36, "Warn Player", false, adminPanel) viewMessageButton = guiCreateButton(645, 444, 104, 36, "Set Message", false, adminPanel) --kickPlayerButton = guiCreateButton(216, 220, 92, 30, "Kick Player", false, adminPanel) exports.GTWgui:setDefaultFont(adminMembsList, 10) exports.GTWgui:setDefaultFont(viewSetRankButton, 10) exports.GTWgui:setDefaultFont(logButton, 10) exports.GTWgui:setDefaultFont(viewAdminInviteButton, 10) exports.GTWgui:setDefaultFont(blackListButton, 10) exports.GTWgui:setDefaultFont(manageRanksButton, 10) exports.GTWgui:setDefaultFont(viewWarnsButton, 10) exports.GTWgui:setDefaultFont(viewMessageButton, 10) messageWindow = guiCreateWindow(602, 341, 455, 350, "Group Message", false) guiWindowSetSizable(messageWindow, false) guiSetAlpha(messageWindow, 1.00) messageMemo = guiCreateMemo(9, 18, 436, 283, "", false, messageWindow) messageCloseButton = guiCreateButton(165, 311, 108, 29, "Close", false, messageWindow) messageSaveButton = guiCreateButton(10, 311, 108, 29, "Save", false, messageWindow) guiSetVisible(messageWindow, false) inviteWindow = guiCreateWindow(680, 277, 301, 414, "Invite Player", false) guiWindowSetSizable(inviteWindow, false) guiSetAlpha(inviteWindow, 1.00) inviteSearchEdit = guiCreateEdit(9, 25, 282, 33, "", false, inviteWindow) inviteList = guiCreateGridList(11, 62, 280, 302, false, inviteWindow) guiGridListAddColumn(inviteList, "Name", 0.5) inviteCloseButton = guiCreateButton(13, 372, 78, 32, "Close", false, inviteWindow) inviteButton = guiCreateButton(213, 372, 78, 30, "Invite", false, inviteWindow) guiSetVisible(inviteWindow, false) listWindow = guiCreateWindow(680, 289, 297, 373, "Group List", false) guiWindowSetSizable(listWindow, false) guiSetAlpha(listWindow, 1.00) listEdit = guiCreateEdit(9, 23, 278, 33, "", false, listWindow) groupListGrid = guiCreateGridList(9, 61, 278, 271, false, listWindow) guiGridListAddColumn(groupListGrid, "Group", 0.4) guiGridListAddColumn(groupListGrid, "Founder", 0.3) guiGridListAddColumn(groupListGrid, "Members", 0.2) closeGroupList = guiCreateButton(10, 335, 277, 28, "Close", false, listWindow) guiSetVisible(listWindow, false) warnWindow = guiCreateWindow(668, 296, 280, 167, "", false) guiWindowSetSizable(warnWindow, false) guiSetAlpha(warnWindow, 1.00) warningReasonEdit = guiCreateEdit(9, 26, 258, 38, "Reason", false, warnWindow) warningLevelEdit = guiCreateEdit(9, 74, 258, 38, "Warning Level", false, warnWindow) warningCloseButton = guiCreateButton(9, 130, 88, 27, "Close", false, warnWindow) warnButton = guiCreateButton(179, 132, 88, 25, "Warn", false, warnWindow) guiSetVisible(warnWindow, false) permWindow = guiCreateWindow(679, 289, 275, 446, "Rank Management", false) guiWindowSetSizable(permWindow, false) guiSetAlpha(permWindow, 1.00) rankCombo = guiCreateComboBox(9, 23, 238, 150, "Select Rank", false, permWindow) --permEdit = guiCreateEdit(9, 23, 254, 36, "", false, permWindow) permEditButton = guiCreateButton(9, 403, 72, 33, "Edit", false, permWindow) permDeleteButton = guiCreateButton(99, 403, 72, 33, "Delete", false, permWindow) permCloseButton = guiCreateButton(185, 403, 72, 33, "Close", false, permWindow) rankScrollPanel = guiCreateScrollPane(9, 51, 250, 307, false, permWindow) permAddEdit = guiCreateEdit(12, 364, 159, 21, "", false, permWindow) addRankButton = guiCreateButton(185, 362, 72, 23, "Add Rank", false, permWindow) guiSetVisible(permWindow, false) --[[GUIEditor.window[1] = guiCreateWindow(652, 300, 296, 301, "Set Rank", false) guiWindowSetSizable(GUIEditor.window[1], false) guiSetAlpha(GUIEditor.window[1], 1.00) GUIEditor.combobox[1] = guiCreateComboBox(20, 94, 250, 161, "", false, GUIEditor.window[1]) GUIEditor.label[1] = guiCreateLabel(-17, 46, 290, 80, "Set the rank of account: .. to : ..", false, GUIEditor.combobox[1]) guiSetFont(GUIEditor.label[1], "clear-normal") guiLabelSetHorizontalAlign(GUIEditor.label[1], "center", false) GUIEditor.button[1] = guiCreateButton(10, 259, 73, 32, "Cancel", false, GUIEditor.window[1]) GUIEditor.button[2] = guiCreateButton(209, 259, 73, 32, "Set Rank", false, GUIEditor.window[1]) GUIEditor.label[2] = guiCreateLabel(0, 21, 296, 55, "Account Selected:\nCurrent Rank:\nWL:", false, GUIEditor.window[1]) guiSetFont(GUIEditor.label[2], "clear-normal") guiLabelSetHorizontalAlign(GUIEditor.label[2], "center", false)--]] setRankWindow = guiCreateWindow(652, 300, 291, 265, "Set Rank", false) guiWindowSetSizable(setRankWindow, false) guiSetAlpha(setRankWindow, 1.00) setRankCombo = guiCreateComboBox(20, 94, 250, 161, "Select Rank", false, setRankWindow) setRankLabel1 = guiCreateLabel(-16, 46, 290, 80, "Set the rank of account: to : ", false, setRankCombo) guiLabelSetColor(setRankLabel1, 0, 255, 0) guiSetFont(setRankLabel1, "clear-normal") guiLabelSetHorizontalAlign(setRankLabel1, "center", false) setRankClose = guiCreateButton(20, 223, 73, 32, "Cancel", false, setRankWindow) setRankButton = guiCreateButton(197, 223, 73, 32, "Set Rank", false, setRankWindow) accountSelectedRank = guiCreateLabel(0, 21, 296, 55, "Account Selected:\nCurrent Rank:\nWL:", false, setRankWindow) guiSetFont(accountSelectedRank, "clear-normal") guiLabelSetColor(accountSelectedRank, 0, 255, 0) guiLabelSetHorizontalAlign(accountSelectedRank, "center", false) guiSetVisible(setRankWindow, false) addEventHandler("onClientGUIClick", addRankButton, addRank, false) addEventHandler("onClientGUIClick", setRankButton, setRank, false) addEventHandler("onClientGUIClick", viewSetRankButton, viewSetRank, false) addEventHandler("onClientGUIClick", setRankCombo, clickOnRankCombo, false) addEventHandler("onClientGUIClick", permEditButton, editRank, false) addEventHandler("onClientGUIClick", closeGroupList, function() guiSetVisible(listWindow, false) end, false) addEventHandler("onClientGUIClick", permCloseButton, function() guiSetVisible(permWindow, false) end, false) addEventHandler("onClientGUIClick", setRankClose, function() guiSetVisible(setRankWindow, false) end, false) addEventHandler("onClientGUIClick", groupListButton, show_group_list, false) addEventHandler("onClientGUIClick", warnButton, warnAccount, false) addEventHandler("onClientGUIClick", manageRanksButton, showRanks, false) addEventHandler("onClientGUIClick", viewWarnsButton, showWarn, false) addEventHandler("onClientGUIClick", rankCombo, selectRank, false) addEventHandler("onClientGUIClick", viewMessageButton, function() guiSetVisible(messageWindow, true) guiBringToFront(messageWindow) end, false) addEventHandler("onClientGUIClick", messageCloseButton, function() guiSetVisible(messageWindow, false) end, false) addEventHandler("onClientGUIClick", warningCloseButton, function() guiSetVisible(warnWindow, false) end, false) addEventHandler("onClientGUIClick", messageSaveButton, saveMessage, false) addEventHandler("onClientGUIClick", logButton, function() triggerServerEvent("GTWgroups.showLog", root) end, false) addEventHandler("onClientGUIClick", viewAdminInviteButton, function() guiSetVisible(inviteWindow, true) guiBringToFront(inviteWindow) openInviteSearch() end, false) addEventHandler("onClientGUIClick", inviteCloseButton, function() guiSetVisible(inviteWindow, false) end, false) addEventHandler("onClientGUIClick", leaveGroupButton, confirmDelete, false) addEventHandler("onClientGUIClick", permDeleteButton, deleteGroupRankAttempt, false) addEventHandler("onClientGUIClick", inviteButton, invite_player, false) addEventHandler("onClientGUIChanged", inviteSearchEdit, search_invite, false) addEventHandler("onClientGUIChanged", listEdit, search_group_list, false) addEventHandler("onClientGUIClick", reject_inviteButton, reject_invite, false) addEventHandler("onClientGUIClick", accept_inviteButton, accept_invite, false) addEventHandler("onClientGUIClick", createGroupButton, make_group, false) addEventHandler("onClientGUIClick", createGroupEdit, function() if (guiGetText(source) == "Group Name") then guiSetText(source, "") end end, false) addEventHandler("onClientGUIClick", warningReasonEdit, function() if (guiGetText(source) == "Reason") then guiSetText(source, "") end end, false) addEventHandler("onClientGUIClick", warningLevelEdit, function() if (guiGetText(source) == "Warning Level") then guiSetText(source, "") end end, false) addEventHandler("onClientGUIClick", inviteSearchEdit, function() if (guiGetText(source) == "Search..") then guiSetText(source, "") end end, false) centerAllWindows(resourceRoot) end addEventHandler("onClientResourceStart", resourceRoot, makeGUI) --[[ Center all windows within the resource ]]-- function centerAllWindows(res) for ind, element in ipairs(getElementsByType("gui-window", res)) do centerWindow(element) end end --[[ Center window element ]]-- function centerWindow(window) local sx, sy = guiGetScreenSize() local width, heigh = guiGetSize(window, false) local x, y = (sx-width) / 2, (sy-heigh) / 2 guiSetPosition(window, x, y, false) end
bsd-2-clause
BeyondTeam/TeleBeyond
plugins/setsticker.lua
1
1385
local function tosticker(msg, success, result) local receiver = get_receiver(msg) if success then local user_id = msg.from.id local file = './info/'..user_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) send_large_msg(receiver, 'استیکر برای '..msg.from.id..' ثبت شد.', ok_cb, false) redis:del("sticker:setsticker") 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 == 'document' and redis:get("sticker:setsticker") then if redis:get("sticker:setsticker") == 'waiting' then load_document(msg.id, tosticker, msg) end end end if matches[1] == "setsticker" then redis:set("sticker:setsticker", "waiting") return 'اکنون استیکر مورد نظر خود را ارسال کنید.' end if matches[1]:lower() == 'mysticker' then --Your bot name send_document(get_receiver(msg), "./info/"..msg.from.id..".webp", ok_cb, false) end end return { patterns = { "^[!#/](setsticker)$", "^[!#/]([Mm]ysticker)$", "%[(document)%]", }, run = run, }
agpl-3.0
jshackley/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Fochacha.lua
19
2525
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Fochacha -- Type: Standard NPC -- @pos 2.897 -1 -10.781 50 -- Quest: Delivering the Goods ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vanishingact = player:getQuestStatus(AHT_URHGAN,VANISHING_ACT); local deliveryGoodsProg = player:getVar("deliveringTheGoodsCS"); local vanishActProg = player:getVar("vanishingactCS"); if (player:getQuestStatus(AHT_URHGAN,DELIVERING_THE_GOODS) == QUEST_AVAILABLE) then player:startEvent(0x0027); elseif (deliveryGoodsProg == 1) then player:startEvent(0x002e); elseif (deliveryGoodsProg == 2) then player:startEvent(0x0029); elseif (vanishingact == QUEST_ACCEPTED and vanishActProg == 2) then player:startEvent(0x002b); elseif (vanishActProg == 3) then player:startEvent(0x0030); elseif (vanishActProg == 4) then player:startEvent(0x0031); elseif (vanishingact == QUEST_COMPLETED) then player:startEvent(0x003b); else player:startEvent(0x002f); 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 == 0x0027) then player:addQuest(AHT_URHGAN,DELIVERING_THE_GOODS); player:setVar("deliveringTheGoodsCS",1); elseif (csid == 0x0029) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINEDX,2184,3); else player:setVar("deliveringTheGoodsCS",0); player:addItem(2184,3); player:messageSpecial(ITEM_OBTAINEDX,2184,3); player:completeQuest(AHT_URHGAN,DELIVERING_THE_GOODS); player:setVar("VANISHING_ACT_waitJPMidnight",getMidnight()); end elseif (csid == 0x002b) then player:setVar("vanishingactCS",3); end end;
gpl-3.0
jshackley/darkstar
scripts/zones/Mhaura/npcs/Bihoro-Guhoro.lua
17
1509
----------------------------------- -- Area: Mhaura -- NPC: Bihoro-Guhoro -- Involved in Quest: Riding on the Clouds -- @pos -28 -8 41 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 7) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2ee); 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
jshackley/darkstar
scripts/zones/Port_San_dOria/npcs/Meinemelle.lua
38
1130
----------------------------------- -- Area: Port San d'Oria -- NPC: Meinemelle -- Type: Standard NPC -- @zone: 232 -- @pos -8.289 -9.3 -146.093 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
jshackley/darkstar
scripts/zones/Bhaflau_Remnants/mobs/Colibri.lua
16
1620
----------------------------------- -- Area: Mamook -- MOB: Colibri ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) local delay = mob:getLocalVar("delay"); local LastCast = mob:getLocalVar("LAST_CAST"); local spell = mob:getLocalVar("COPY_SPELL"); if (mob:AnimationSub() == 1) then if (mob:getBattleTime() - LastCast > 30) then mob:setLocalVar("COPY_SPELL", 0); mob:setLocalVar("delay", 0); mob:AnimationSub(0); end if (spell > 0 and mob:hasStatusEffect(EFFECT_SILENCE) == false) then if (delay >= 3) then mob:castSpell(spell); mob:setLocalVar("COPY_SPELL", 0); mob:setLocalVar("delay", 0); mob:AnimationSub(0); else mob:setLocalVar("delay", delay+1); end end end end; ----------------------------------- -- onMagicHit ----------------------------------- function onMagicHit(caster, target, spell) if (spell:tookEffect() and (caster:isPC() or caster:isPet()) and spell:getSpellGroup() ~= SPELLGROUP_BLUE ) then target:setLocalVar("COPY_SPELL", spell:getID()); target:setLocalVar("LAST_CAST", target:getBattleTime()); target:AnimationSub(1); end return 1; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) end;
gpl-3.0