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
db260179/openwrt-bpi-r1-luci
libs/luci-lib-nixio/docsrc/nixio.lua
151
15824
--- General POSIX IO library. module "nixio" --- Look up a hostname and service via DNS. -- @class function -- @name nixio.getaddrinfo -- @param host hostname to lookup (optional) -- @param family address family [<strong>"any"</strong>, "inet", "inet6"] -- @param service service name or port (optional) -- @return Table containing one or more tables containing: <ul> -- <li>family = ["inet", "inet6"]</li> -- <li>socktype = ["stream", "dgram", "raw"]</li> -- <li>address = Resolved IP-Address</li> -- <li>port = Resolved Port (if service was given)</li> -- </ul> --- Reverse look up an IP-Address via DNS. -- @class function -- @name nixio.getnameinfo -- @param ipaddr IPv4 or IPv6-Address -- @return FQDN --- (Linux, BSD) Get a list of available network interfaces and their addresses. -- @class function -- @name nixio.getifaddrs -- @return Table containing one or more tables containing: <ul> -- <li>name = Interface Name</li> -- <li>family = ["inet", "inet6", "packet"]</li> -- <li>addr = Interface Address (IPv4, IPv6, MAC, ...)</li> -- <li>broadaddr = Broadcast Address</li> -- <li>dstaddr = Destination Address (Point-to-Point)</li> -- <li>netmask = Netmask (if available)</li> -- <li>prefix = Prefix (if available)</li> -- <li>flags = Table of interface flags (up, multicast, loopback, ...)</li> -- <li>data = Statistics (Linux, "packet"-family)</li> -- <li>hatype = Hardware Type Identifier (Linix, "packet"-family)</li> -- <li>ifindex = Interface Index (Linux, "packet"-family)</li> -- </ul> --- Get protocol entry by name. -- @usage This function returns nil if the given protocol is unknown. -- @class function -- @name nixio.getprotobyname -- @param name protocol name to lookup -- @return Table containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Get protocol entry by number. -- @usage This function returns nil if the given protocol is unknown. -- @class function -- @name nixio.getprotobynumber -- @param proto protocol number to lookup -- @return Table containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Get all or a specifc proto entry. -- @class function -- @name nixio.getproto -- @param proto protocol number or name to lookup (optional) -- @return Table (or if no parameter is given, a table of tables) -- containing the following fields: <ul> -- <li>name = Protocol Name</li> -- <li>proto = Protocol Number</li> -- <li>aliases = Table of alias names</li> -- </ul> --- Create a new socket and bind it to a network address. -- This function is a shortcut for calling nixio.socket and then bind() -- on the socket object. -- @usage This functions calls getaddrinfo(), socket(), -- setsockopt() and bind() but NOT listen(). -- @usage The <em>reuseaddr</em>-option is automatically set before binding. -- @class function -- @name nixio.bind -- @param host Hostname or IP-Address (optional, default: all addresses) -- @param port Port or service description -- @param family Address family [<strong>"any"</strong>, "inet", "inet6"] -- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"] -- @return Socket Object --- Create a new socket and connect to a network address. -- This function is a shortcut for calling nixio.socket and then connect() -- on the socket object. -- @usage This functions calls getaddrinfo(), socket() and connect(). -- @class function -- @name nixio.connect -- @param host Hostname or IP-Address (optional, default: localhost) -- @param port Port or service description -- @param family Address family [<strong>"any"</strong>, "inet", "inet6"] -- @param socktype Socket Type [<strong>"stream"</strong>, "dgram"] -- @return Socket Object --- Open a file. -- @class function -- @name nixio.open -- @usage Although this function also supports the traditional fopen() -- file flags it does not create a file stream but uses the open() syscall. -- @param path Filesystem path to open -- @param flags Flag string or number (see open_flags). -- [<strong>"r"</strong>, "r+", "w", "w+", "a", "a+"] -- @param mode File mode for newly created files (see chmod, umask). -- @see nixio.umask -- @see nixio.open_flags -- @return File Object --- Generate flags for a call to open(). -- @class function -- @name nixio.open_flags -- @usage This function cannot fail and will never return nil. -- @usage The "nonblock" and "ndelay" flags are aliases. -- @usage The "nonblock", "ndelay" and "sync" flags are no-ops on Windows. -- @param flag1 First Flag ["append", "creat", "excl", "nonblock", "ndelay", -- "sync", "trunc", "rdonly", "wronly", "rdwr"] -- @param ... More Flags [-"-] -- @return flag to be used as second paramter to open --- Duplicate a file descriptor. -- @class function -- @name nixio.dup -- @usage This funcation calls dup2() if <em>newfd</em> is set, otherwise dup(). -- @param oldfd Old descriptor [File Object, Socket Object (POSIX only)] -- @param newfd New descriptor to serve as copy (optional) -- @return File Object of new descriptor --- Create a pipe. -- @class function -- @name nixio.pipe -- @return File Object of the read end -- @return File Object of the write end --- Get the last system error code. -- @class function -- @name nixio.errno -- @return Error code --- Get the error message for the corresponding error code. -- @class function -- @name nixio.strerror -- @param errno System error code -- @return Error message --- Sleep for a specified amount of time. -- @class function -- @usage Not all systems support nanosecond precision but you can expect -- to have at least maillisecond precision. -- @usage This function is not signal-protected and may fail with EINTR. -- @param seconds Seconds to wait (optional) -- @param nanoseconds Nanoseconds to wait (optional) -- @name nixio.nanosleep -- @return true --- Generate events-bitfield or parse revents-bitfield for poll. -- @class function -- @name nixio.poll_flags -- @param mode1 revents-Flag bitfield returned from poll to parse OR -- ["in", "out", "err", "pri" (POSIX), "hup" (POSIX), "nval" (POSIX)] -- @param ... More mode strings for generating the flag [-"-] -- @see nixio.poll -- @return table with boolean fields reflecting the mode parameter -- <strong>OR</strong> bitfield to use for the events-Flag field --- Wait for some event on a file descriptor. -- poll() sets the revents-field of the tables provided by fds to a bitfield -- indicating the events that occured. -- @class function -- @usage This function works in-place on the provided table and only -- writes the revents field, you can use other fields on your demand. -- @usage All metamethods on the tables provided as fds are ignored. -- @usage The revents-fields are not reset when the call times out. -- You have to check the first return value to be 0 to handle this case. -- @usage If you want to wait on a TLS-Socket you have to use the underlying -- socket instead. -- @usage On Windows poll is emulated through select(), can only be used -- on socket descriptors and cannot take more than 64 descriptors per call. -- @usage This function is not signal-protected and may fail with EINTR. -- @param fds Table containing one or more tables containing <ul> -- <li> fd = I/O Descriptor [Socket Object, File Object (POSIX)]</li> -- <li> events = events to wait for (bitfield generated with poll_flags)</li> -- </ul> -- @param timeout Timeout in milliseconds -- @name nixio.poll -- @see nixio.poll_flags -- @return number of ready IO descriptors -- @return the fds-table with revents-fields set --- (POSIX) Clone the current process. -- @class function -- @name nixio.fork -- @return the child process id for the parent process, 0 for the child process --- (POSIX) Send a signal to one or more processes. -- @class function -- @name nixio.kill -- @param target Target process of process group. -- @param signal Signal to send -- @return true --- (POSIX) Get the parent process id of the current process. -- @class function -- @name nixio.getppid -- @return parent process id --- (POSIX) Get the user id of the current process. -- @class function -- @name nixio.getuid -- @return process user id --- (POSIX) Get the group id of the current process. -- @class function -- @name nixio.getgid -- @return process group id --- (POSIX) Set the group id of the current process. -- @class function -- @name nixio.setgid -- @param gid New Group ID -- @return true --- (POSIX) Set the user id of the current process. -- @class function -- @name nixio.setuid -- @param gid New User ID -- @return true --- (POSIX) Change priority of current process. -- @class function -- @name nixio.nice -- @param nice Nice Value -- @return true --- (POSIX) Create a new session and set the process group ID. -- @class function -- @name nixio.setsid -- @return session id --- (POSIX) Wait for a process to change state. -- @class function -- @name nixio.waitpid -- @usage If the "nohang" is given this function becomes non-blocking. -- @param pid Process ID (optional, default: any childprocess) -- @param flag1 Flag (optional) ["nohang", "untraced", "continued"] -- @param ... More Flags [-"-] -- @return process id of child or 0 if no child has changed state -- @return ["exited", "signaled", "stopped"] -- @return [exit code, terminate signal, stop signal] --- (POSIX) Get process times. -- @class function -- @name nixio.times -- @return Table containing: <ul> -- <li>utime = user time</li> -- <li>utime = system time</li> -- <li>cutime = children user time</li> -- <li>cstime = children system time</li> -- </ul> --- (POSIX) Get information about current system and kernel. -- @class function -- @name nixio.uname -- @return Table containing: <ul> -- <li>sysname = operating system</li> -- <li>nodename = network name (usually hostname)</li> -- <li>release = OS release</li> -- <li>version = OS version</li> -- <li>machine = hardware identifier</li> -- </ul> --- Change the working directory. -- @class function -- @name nixio.chdir -- @param path New working directory -- @return true --- Ignore or use set the default handler for a signal. -- @class function -- @name nixio.signal -- @param signal Signal -- @param handler ["ign", "dfl"] -- @return true --- Get the ID of the current process. -- @class function -- @name nixio.getpid -- @return process id --- Get the current working directory. -- @class function -- @name nixio.getcwd -- @return workign directory --- Get the current environment table or a specific environment variable. -- @class function -- @name nixio.getenv -- @param variable Variable (optional) -- @return environment table or single environment variable --- Set or unset a environment variable. -- @class function -- @name nixio.setenv -- @usage The environment variable will be unset if value is ommited. -- @param variable Variable -- @param value Value (optional) -- @return true --- Execute a file to replace the current process. -- @class function -- @name nixio.exec -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param ... Parameters --- Invoke the shell and execute a file to replace the current process. -- @class function -- @name nixio.execp -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param ... Parameters --- Execute a file with a custom environment to replace the current process. -- @class function -- @name nixio.exece -- @usage The name of the executable is automatically passed as argv[0] -- @usage This function does not return on success. -- @param executable Executable -- @param arguments Argument Table -- @param environment Environment Table (optional) --- Sets the file mode creation mask. -- @class function -- @name nixio.umask -- @param mask New creation mask (see chmod for format specifications) -- @return the old umask as decimal mode number -- @return the old umask as mode string --- (Linux) Get overall system statistics. -- @class function -- @name nixio.sysinfo -- @return Table containing: <ul> -- <li>uptime = system uptime in seconds</li> -- <li>loads = {loadavg1, loadavg5, loadavg15}</li> -- <li>totalram = total RAM</li> -- <li>freeram = free RAM</li> -- <li>sharedram = shared RAM</li> -- <li>bufferram = buffered RAM</li> -- <li>totalswap = total SWAP</li> -- <li>freeswap = free SWAP</li> -- <li>procs = number of running processes</li> -- </ul> --- Create a new socket. -- @class function -- @name nixio.socket -- @param domain Domain ["inet", "inet6", "unix"] -- @param type Type ["stream", "dgram", "raw"] -- @return Socket Object --- (POSIX) Send data from a file to a socket in kernel-space. -- @class function -- @name nixio.sendfile -- @param socket Socket Object -- @param file File Object -- @param length Amount of data to send (in Bytes). -- @return bytes sent --- (Linux) Send data from / to a pipe in kernel-space. -- @class function -- @name nixio.splice -- @param fdin Input I/O descriptor -- @param fdout Output I/O descriptor -- @param length Amount of data to send (in Bytes). -- @param flags (optional, bitfield generated by splice_flags) -- @see nixio.splice_flags -- @return bytes sent --- (Linux) Generate a flag bitfield for a call to splice. -- @class function -- @name nixio.splice_flags -- @param flag1 First Flag ["move", "nonblock", "more"] -- @param ... More flags [-"-] -- @see nixio.splice -- @return Flag bitfield --- (POSIX) Open a connection to the system logger. -- @class function -- @name nixio.openlog -- @param ident Identifier -- @param flag1 Flag 1 ["cons", "nowait", "pid", "perror", "ndelay", "odelay"] -- @param ... More flags [-"-] --- (POSIX) Close the connection to the system logger. -- @class function -- @name nixio.closelog --- (POSIX) Write a message to the system logger. -- @class function -- @name nixio.syslog -- @param priority Priority ["emerg", "alert", "crit", "err", "warning", -- "notice", "info", "debug"] -- @param message --- (POSIX) Set the logmask of the system logger for current process. -- @class function -- @name nixio.setlogmask -- @param priority Priority ["emerg", "alert", "crit", "err", "warning", -- "notice", "info", "debug"] --- (POSIX) Encrypt a user password. -- @class function -- @name nixio.crypt -- @param key Key -- @param salt Salt -- @return password hash --- (POSIX) Get all or a specific user group. -- @class function -- @name nixio.getgr -- @param group Group ID or groupname (optional) -- @return Table containing: <ul> -- <li>name = Group Name</li> -- <li>gid = Group ID</li> -- <li>passwd = Password</li> -- <li>mem = {Member #1, Member #2, ...}</li> -- </ul> --- (POSIX) Get all or a specific user account. -- @class function -- @name nixio.getpw -- @param user User ID or username (optional) -- @return Table containing: <ul> -- <li>name = Name</li> -- <li>uid = ID</li> -- <li>gid = Group ID</li> -- <li>passwd = Password</li> -- <li>dir = Home directory</li> -- <li>gecos = Information</li> -- <li>shell = Shell</li> -- </ul> --- (Linux, Solaris) Get all or a specific shadow password entry. -- @class function -- @name nixio.getsp -- @param user username (optional) -- @return Table containing: <ul> -- <li>namp = Name</li> -- <li>expire = Expiration Date</li> -- <li>flag = Flags</li> -- <li>inact = Inactivity Date</li> -- <li>lstchg = Last change</li> -- <li>max = Maximum</li> -- <li>min = Minimum</li> -- <li>warn = Warning</li> -- <li>pwdp = Password Hash</li> -- </ul> --- Create a new TLS context. -- @class function -- @name nixio.tls -- @param mode TLS-Mode ["client", "server"] -- @return TLSContext Object
apache-2.0
gfgtdf/wesnoth-old
data/campaigns/World_Conquest/lua/map/postgeneration/4B_Volcanic.lua
4
8171
-- Volcanic function world_conquest_tek_map_repaint_4b() set_terrain { "Ql,Md,Md^Xm", f.terrain("U*,U*^Uf"), exact = false, percentage = 10, } set_terrain { "Ql,Uu,Uh,Uh,Uu^Uf,Qxu,Uh^Uf", f.terrain("Xu"), } set_terrain { "Ql,Uu^Uf,Qxu,Uh^Uf,Uh,Uh,Uu,Ql,Md", f.terrain("Mm^Xm"), fraction = 2, } set_terrain { "Ql,Uu^Uf,Qxu,Uh^Uf", f.all( f.terrain("Hh^F*"), f.adjacent(f.terrain("Ql,Uu,Uh,Uu^Uf,Qxu,Uh^Uf")) ), fraction = 3, } set_terrain { "Uh", f.all( f.terrain("Hh"), f.adjacent(f.terrain("Ql,Uu,Uh,Uu^Uf,Qxu,Uh^Uf,Ur")) ), fraction = 3, } wct_fill_lava_chasms() set_terrain { "Uh", f.all( f.adjacent(f.terrain("Ql")), f.terrain("Hh*^*") ), layer = "base", } set_terrain { "Ur", f.all( f.terrain("Re"), f.none( f.radius(999, f.terrain("Ch*^*,Kh*^*"), f.terrain("Re")) ) ), } for obsidian_i = 1, 3 do set_terrain { "Ur", f.all( f.adjacent(f.terrain("Ql,Uu^*,Qxu,Uh^*,Ur^*")), f.terrain("G*^*") ), layer = "base", } end for scorched_i = 1, 2 do set_terrain { "Rd", f.all( f.radius(2, f.terrain("Ql,Uu^*,Qxu,Uh^*,Ur^*,Rd")), f.terrain("G*^*") ), layer = "base", } end -- change villages set_terrain { "Ur^Vu", f.terrain("Ur^V*"), } set_terrain { "*^Vd", f.terrain("*^Vhh"), layer = "overlay", } set_terrain { "*^Vo", f.terrain("*^Ve"), layer = "overlay", } set_terrain { "Gd^Vc", f.terrain("G*^Vh"), } set_terrain { "*^Vh", f.terrain("*^Vht"), layer = "overlay", } set_terrain { "Rd^Vhh", f.terrain("Rd^Vh"), } set_terrain { "Ds^Vct", f.terrain("Dd^Vda"), fraction = 3, } if wesnoth.random(2) == 1 then set_terrain { "Ur^Vd", f.terrain("Ur^Vu"), fraction_rand = "2..3", } end if wesnoth.random(2) == 1 then set_terrain { "Rd^Vd", f.terrain("Rd^Vhh"), fraction_rand = "2..3", } end if wesnoth.random(2) == 1 then set_terrain { "Ds^Vd", f.terrain("D*^V*"), fraction_rand = "3..4", } end -- dry terrain set_terrain { "Sm", f.terrain("Ss^*"), layer = "base", } set_terrain { "Gd", f.terrain("G*^*"), layer = "base", } set_terrain { "Md", f.terrain("M*^*"), layer = "base", } set_terrain { "Hhd", f.terrain("Hh^*"), layer = "base", } set_terrain { "*^Fdw", f.all( f.terrain("U*^F*"), f.none( f.terrain("*^Fet") ) ), layer = "overlay", } set_terrain { "*^Fmw", f.all( f.terrain("Rd^F*"), f.none( f.terrain("Rd^Fet") ) ), layer = "overlay", } set_terrain { "*^Fetd", f.terrain("*^Fet"), layer = "overlay", } -- change some forest set_terrain { "Gd^Fdw,Gd^Fmw", f.terrain("G*^Ft"), fraction = 3, } set_terrain { "Gd^Fms,Gd^Fmw,Gd^Fet", f.terrain("G*^Ft"), fraction = 2, } set_terrain { "Hhd^Fdw,Hhd^Fmw", f.terrain("Hhd^Ft"), fraction = 3, } set_terrain { "Hhd^Fms,Hhd^Fmw", f.terrain("Hhd^Ft"), fraction = 2, } -- difumine dry/grass border set_terrain { "Rd", f.all( f.terrain("Gd"), f.adjacent(f.terrain("Rd")) ), fraction = 3, } set_terrain { "Gd", f.all( f.terrain("Rd"), f.adjacent(f.terrain("Gd")) ), fraction = 3, } -- create volcanos where possible and force one local terrain_to_change = map:get_locations(f.all( f.terrain("Ql"), f.adjacent(f.terrain("M*,M*^Xm"), "se,s,sw", 2), f.adjacent(f.terrain("K*^*,C*^*,*^V"), "se,s,sw", 0) )) if #terrain_to_change > 0 then local loc = terrain_to_change[wesnoth.random(#terrain_to_change)] set_terrain { "Md^Xm", f.all( f.none(f.terrain("M*^*")), f.adjacent(f.is_loc(loc), "ne,n,nw") ) } end set_terrain { "Mv", f.all( f.terrain("Ql"), f.adjacent(f.terrain("Md^Xm,Md"), "se,s,sw", 3) ), } local terrain_to_change = map:get_locations(f.terrain("Mv")) for i, v in ipairs(terrain_to_change) do local loc = terrain_to_change[i] table.insert(prestart_event, wml.tag.sound_source { id = "volcano" .. tostring(i), sounds = "rumble.ogg", delay = 450000, chance = 1, x = loc[1], y = loc[2], full_range = 5, fade_range = 5, loop = 0, }) end -- some volcanic coast and reefs set_terrain { "Uue", f.all( f.terrain("Ww,Wo"), f.adjacent(f.terrain("S*^*")) ), fraction = 2, } set_terrain { "Uue,Wwr", f.all( f.terrain("Ww,Wo"), f.adjacent(f.terrain("Uu*,Ur,Uh,D*^*")) ), fraction_rand = "9..11", } set_terrain { "Uue", f.all( f.terrain("Ds"), f.adjacent(f.terrain("U*,S*^*,W*^*,Gd,Rd")) ), fraction_rand = "9..11", } set_terrain { "Uue", f.all( f.terrain("Ds"), f.adjacent(f.terrain("U*")) ), fraction_rand = "9..11", } -- rubble set_terrain { "Rd^Dr,Hhd^Dr", f.all( f.terrain("Hhd"), f.adjacent(f.terrain("Rd*^*")), f.radius(4, f.all( )) ), fraction_rand = "16..20", } set_terrain { "Ur^Dr,Hhd^Dr", f.all( f.terrain("Hhd"), f.adjacent(f.terrain("U*^*")) ), fraction_rand = "10..15", } set_terrain { "Uu^Dr,Uh^Dr", f.terrain("Uh"), fraction_rand = "9..13", } -- mushrooms, base amount in map surface local terrain_to_change = map:get_locations(f.terrain("Hhd,Hhd^F^*")) helper.shuffle(terrain_to_change) local r = helper.rand(tostring(total_tiles // 600) .. ".." .. tostring(total_tiles // 300)) for mush_i = 1, math.min(r, #terrain_to_change) do map:set_terrain(terrain_to_change[mush_i], "Hhd^Uf") end -- chances of few orcish castles wct_possible_map4_castle("Co", 2) -- craters set_terrain { "Dd^Dc", f.terrain("Dd"), fraction_rand = "4..6", } -- grass near muddy or earthy cave become dark dirt set_terrain { "Rb", f.all( f.adjacent(f.terrain("S*^*,Uue"), nil, "2-6"), f.terrain("G*^*") ), } -- some small mushrooms on dark dirt set_terrain { "Rb^Em", f.terrain("Rb"), fraction_rand = "9..11", } -- some extra reefs set_terrain { "Wwr", f.all( f.terrain("Ww,Wo"), f.adjacent(f.terrain("Ds,Ww,Uu")) ), fraction_rand = "18..22", } -- whirpools local whirlpool_candidats = map:get_locations(f.all( f.terrain("Ww"), f.adjacent(f.terrain("Wo")), f.adjacent(f.terrain("Uue")) )) helper.shuffle(whirlpool_candidats) for i = 1, #whirlpool_candidats // wesnoth.random(4, 15) do local loc = whirlpool_candidats[i] table.insert(prestart_event, wml.tag.item { image = "scenery/whirlpool.png", x = loc[1], y = loc[2], }) table.insert(prestart_event, wml.tag.sound_source { id = "whirlppol" .. tostring(i), sounds = "mermen-hit.wav", delay = 90000, chance = 1, x = loc[1], y = loc[2], full_range = 5, fade_range = 5, loop = 0, }) end -- dessert sand no near water or village set_terrain { "Dd", f.all( f.adjacent(f.terrain("W*^*,*^V*"), nil, 0), f.terrain("Ds") ), } -- very dirt coast local terrain_to_change = map:get_locations(f.terrain("Ds")) helper.shuffle(terrain_to_change) for i = 1, #terrain_to_change // wesnoth.random(3, 4) do map:set_terrain(terrain_to_change[i], "Ds^Esd") end helper.shuffle(terrain_to_change) for i = 1, #terrain_to_change // 6 do map:set_terrain(terrain_to_change[i], "Ds^Es") end set_terrain { "Dd^Es", f.terrain("Dd"), fraction_rand = "4..6", } set_terrain { "Uue^Es", f.terrain("Uue"), fraction_rand = "2..3", } set_terrain { "Sm^Es", f.terrain("Sm"), fraction_rand = "4..6", } -- 1.12 new forest set_terrain { "*^Ft", f.terrain("*^Fp"), fraction_rand = "6..10", layer = "overlay", } set_terrain { "*^Ftd", f.terrain("H*^Ft"), layer = "overlay", } set_terrain { "*^Fts", f.terrain("*^Ft"), layer = "overlay", } set_terrain { "*^Fts", f.terrain("*^Fmw"), fraction_rand = "4..7", layer = "overlay", } set_terrain { "*^Ft", f.terrain("*^Fms"), fraction_rand = "2..4", layer = "overlay", } local r = wesnoth.random(20) if r == 1 then wct_change_map_water("g") elseif r == 2 then wct_change_map_water("t") end end return function() set_map_name(_"Volcanic") world_conquest_tek_map_noise_classic("Gs^Fp") wct_enemy_castle_expansion() world_conquest_tek_map_repaint_4b() world_conquest_tek_bonus_points("volcanic") wct_map_enemy_themed("dwarf", "Giant Mudcrawler", "ud", "Ur^Vud", 5) end
gpl-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/npcs/Morefie.lua
6
1119
----------------------------------- -- Area: Lower Jeuno -- NPC: Morefie -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MOREFIE_SHOP_DIALOG); stock = {0x340F,1250, -- Silver Earring 0x3490,1250, -- Silver Ring 0x3410,4140} -- Mythril Earring showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
philipyufei/References
Moudle.lua
1
1046
Module = {"PD_Simulation","TD_Simulation","PD_Test","TD_Test"} PD_Simulation = {TFP = "TFPModule.dll",EPD = "EPDModule.dll",E3 = "nullptr",Library = "LibraryModule.dll",Result = "ResultModule.dll","TFP","EPD","E3","Library","Result"} TD_Simulation = {TTD = "TTDModule.dll",ETD = "ETDModule.dll",Library = "LibraryModule.dll", Result = "ResultModule.dll","TTD","ETD","Library","Result"} PD_Test = {General = "SignalModule.dll",ChannelConfig = "ChannelModule.dll",ChannelSwitch = "CSwitchModule.dll", Library = "LibraryModule.dll", FEight = "ForTwoNine.dll",VNA = "VNAModule.dll",DFCalibration = "DFCalibrationModule.dll", "General","ChannelSwitch","Library","ChannelConfig","FEight","VNA","DFCalibration"} TD_Test = {General = "SignalModule.dll",ChannelConfig = "ChannelModule.dll",ChannelSwitch = "CSwitchModule.dll", Library = "LibraryModule.dll", FEight = "ForTwoNine.dll",VNA = "VNAModule.dll",TDCalibration = "TDCalibrationModule.dll", "General","ChannelSwitch","Library","ChannelConfig","FEight","VNA","TDCalibration"}
gpl-3.0
waytim/darkstar
scripts/zones/San_dOria-Jeuno_Airship/npcs/Nigel.lua
30
2316
----------------------------------- -- Area: San d'Oria-Jeuno Airship -- NPC: Nigel -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/San_dOria-Jeuno_Airship/TextIDs"] = nil; require("scripts/zones/San_dOria-Jeuno_Airship/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 3 do vHour = vHour - 6; end local message = WILL_REACH_SANDORIA; if (vHour == -3) then if (vMin >= 10) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -2) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == -1) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == 0) then if (vMin <= 11) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == 1) then vHour = 2; elseif (vHour == 2) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 11 - vMin; else -- WILL_REACH_SANDORIA vMinutes = (vHour * 60) + 10 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_SANDORIA) then message = IN_SANDORIA_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); 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
X-Raym/REAPER-ReaScripts
Text Items and Item Notes/Formatting/X-Raym_Delete font color markup from selected items notes.lua
1
1791
--[[ * ReaScript Name: Delete font color markup from selected items notes * About: Delete font color markup from selected items notes * Instructions: Select an item. Use it. * Author: X-Raym * Author URI: https://www.extremraym.com * Repository: GitHub > X-Raym > REAPER-ReaScripts * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts * Licence: GPL v3 * Forum Thread: Scripts (LUA): Text Items Formatting Actions (various) * Forum Thread URI: http://forum.cockos.com/showthread.php?t=156757 * REAPER: 5.0 pre 15 * Extensions: SWS/S&M 2.7.3 #0 * Version: 1.1 --]] --[[ * Changelog: * v1.1 (2015-07-29) # Better Set Notes * v1.0 (2015-03-06) + Initial Release --]] function fontColor() reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function. -- LOOP THROUGH SELECTED ITEMS selected_items_count = reaper.CountSelectedMediaItems(0) -- INITIALIZE loop through selected items for i = 0, selected_items_count-1 do -- GET ITEMS item = reaper.GetSelectedMediaItem(0, i) -- Get selected item i -- GET NOTES note = reaper.ULT_GetMediaItemNote(item) -- MODIFY NOTES note = note:gsub("<font color=\"#.+\">", "") note = note:gsub("</font>", "") reaper.ULT_SetMediaItemNote(item, note) end -- ENDLOOP through selected items reaper.Undo_EndBlock("Delete font color markup from selected items notes", 0) -- End of the undo block. Leave it at the bottom of your main function. end reaper.PreventUIRefresh(1) -- Prevent UI refreshing. Uncomment it only if the script works. fontColor() -- Execute your main function reaper.PreventUIRefresh(-1) -- Restore UI Refresh. Uncomment it only if the script works. reaper.UpdateArrange() -- Update the arrangement (often needed)
gpl-3.0
waytim/darkstar
scripts/globals/spells/geohelix.lua
26
1688
-------------------------------------- -- Spell: Geohelix -- Deals earth damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); -- calculate raw damage local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); -- get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3); -- get the resisted damage dmg = dmg*resist; -- add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); -- add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); local dot = dmg; -- add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); -- calculate Damage over time dot = target:magicDmgTaken(dot); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); if (dot > 0) then target:addStatusEffect(EFFECT_HELIX,dot,3,duration); end; return dmg; end;
gpl-3.0
behnam98/SmartRobot
plugins/id.lua
355
2795
local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver --local chat_id = "chat#id"..result.id local chat_id = result.id local chatname = result.print_name local text = 'IDs for chat '..chatname ..' ('..chat_id..')\n' ..'There are '..result.members_num..' members' ..'\n---------\n' i = 0 for k,v in pairs(result.members) do i = i+1 text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n" end send_large_msg(receiver, text) end local function username_id(cb_extra, success, result) local receiver = cb_extra.receiver local qusername = cb_extra.qusername local text = 'User '..qusername..' not found in this group!' for k,v in pairs(result.members) do vusername = v.username if vusername == qusername then text = 'ID for username\n'..vusername..' : '..v.id end end send_large_msg(receiver, text) end local function run(msg, matches) local receiver = get_receiver(msg) if matches[1] == "!id" then local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id if is_chat_msg(msg) then text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")" end return text elseif matches[1] == "chat" then -- !ids? (chat) (%d+) if matches[2] and is_sudo(msg) then local chat = 'chat#id'..matches[2] chat_info(chat, returnids, {receiver=receiver}) else if not is_chat_msg(msg) then return "You are not in a group." end local chat = get_receiver(msg) chat_info(chat, returnids, {receiver=receiver}) end else if not is_chat_msg(msg) then return "Only works in group" end local qusername = string.gsub(matches[1], "@", "") local chat = get_receiver(msg) chat_info(chat, username_id, {receiver=receiver, qusername=qusername}) end end return { description = "Know your id or the id of a chat members.", usage = { "!id: Return your ID and the chat id if you are in one.", "!ids chat: Return the IDs of the current chat members.", "!ids chat <chat_id>: Return the IDs of the <chat_id> members.", "!id <username> : Return the id from username given." }, patterns = { "^!id$", "^!ids? (chat) (%d+)$", "^!ids? (chat)$", "^!id (.*)$" }, run = run }
gpl-2.0
waytim/darkstar
scripts/zones/Lower_Jeuno/npcs/_l07.lua
13
1554
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -45.148 0 -47.279 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 4) then player:setVar("cService",5); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 17) then player:setVar("cService",18); end 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
waytim/darkstar
scripts/zones/The_Boyahda_Tree/npcs/Grounds_Tome.lua
30
1095
----------------------------------- -- Area: The Boyahda Tree -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_BOYAHDA_TREE,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,719,720,721,722,723,724,725,726,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,719,720,721,722,723,724,725,726,0,0,GOV_MSG_BOYAHDA_TREE); end;
gpl-3.0
waytim/darkstar
scripts/zones/Bastok_Markets/npcs/Zacc.lua
13
1607
----------------------------------- -- Area: Bastok Markets -- NPC: Zacc -- Type: Quest NPC -- @zone: 235 -- @pos -255.709 -13 -91.379 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK, WISH_UPON_A_STAR) == QUEST_COMPLETED) then -- Quest: Wish Upon a Star - Quest has been completed. player:startEvent(0x0150); elseif (player:getFameLevel(BASTOK) > 4 and player:getQuestStatus(BASTOK, WISH_UPON_A_STAR) == QUEST_AVAILABLE) then -- Quest: Wish Upon a Star - Start quest. player:startEvent(0x0149); else -- Standard dialog player:startEvent(0x0148); 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 == 0x0149) then -- Quest: Wish Upon a Star player:addQuest(BASTOK, WISH_UPON_A_STAR); player:setVar("WishUponAStar_Status", 1); end end;
gpl-3.0
nwhitehead/vida
src/vida.lua
3
9109
-- Requires LuaJIT if type(jit) ~= 'table' then error('This modules requires LuaJIT') end local os = require('os') local ffi = require('ffi') local md5 = require('md5') local path = require('path') local temp = require('temp') local vida = {} -- Optionally update value local function update(old, new) if new ~= nil then return new else return old end end -- Parse bool, no error on nil local function toboolean(val) if val == nil then return nil end return val == 'true' or val == 'True' or val == 'TRUE' end -- Update value with environmental variable value local function update_env(old, name) return update(old, os.getenv(name)) end vida.version = "v0.1.10" vida.useLocalCopy = update_env(true, 'VIDA_READ_CACHE') vida.saveLocalCopy = update_env(true, 'VIDA_WRITE_CACHE') local home_vidacache = '.vidacache' local home = os.getenv('HOME') local libsuffix local objsuffix if ffi.os == 'Linux' or ffi.os == 'OSX' then vida.compiler = update_env(update_env('clang', 'CC'), 'VIDA_COMPILER') vida.compilerFlags = update_env('-fpic -O3 -fvisibility=hidden', 'VIDA_COMPILER_FLAGS') vida.justCompile = '-c' vida.linkerFlags = update_env('-shared', 'VIDA_LINKER_FLAGS') libsuffix = '.so' objsuffix = '.o' if home then home_vidacache = string.format('%s/.vidacache', home) end elseif ffi.os == 'Windows' then vida.compiler = update_env('cl', 'VIDA_COMPILER') vida.compilerFlags = update_env('/nologo /O2', 'VIDA_COMPILER_FLAGS') vida.justCompile = '/c' vida.linkerFlags = update_env('/nologo /link /DLL', 'VIDA_LINKER_FLAGS') libsuffix = '.dll' objsuffix = '.obj' else error('Unknown platform') end vida.cachePath = update_env(home_vidacache, 'VIDA_CACHE_PATH') vida._code_prelude = update_env('', 'VIDA_CODE_PRELUDE') vida._interface_prelude = update_env('', 'VIDA_INTERFACE_PRELUDE') -- Fixed header for C source to simplify exports vida._code_header = [[ #line 0 "vida_header" #ifdef _WIN32 #define EXPORT __declspec(dllexport) #else #define EXPORT __attribute__ ((visibility ("default"))) #endif ]] vida.cdef = ffi.cdef -- Read in a file function read_file(name) local f = io.open(name, 'r') if f == nil then return nil end local txt = f:read('*a') f:close() return txt end -- Check if file exists function file_exists(name) local f = io.open(name, 'r') if f ~= nil then io.close(f) return true end return false end -- Give C header interface function vida.interface(txt, info) local res = { vida = 'interface', code = txt, filename = 'vida_interface', linenum = 1, } if info == true or info == nil then -- Get filename and linenumber of caller -- This helps us give good error messages when compiling -- Add caller filename and line numbers for debugging local caller = debug.getinfo(2) res.filename = caller.short_src res.linenum = caller.currentline end return res end -- Give C source code function vida.code(txt) local res = { vida='code', code=txt, filename = 'vida_code', linenum = 1, } if info == true or info == nil then -- Get filename and linenumber of caller -- This helps us give good error messages when compiling -- Add caller filename and line numbers for debugging local caller = debug.getinfo(2) res.filename = caller.short_src res.linenum = caller.currentline end return res end -- Give interface file function vida.interfacefile(filename) local interface = read_file(filename) if not interface then error('Could not open file ' .. filename .. ' for reading', 2) end return { vida='interface', code=interface, filename = filename, linenum = 1, } end -- Give source code file function vida.codefile(filename) local src = read_file(filename) if not src then error('Could not open file ' .. filename .. ' for reading', 2) end return { vida='code', code=src, filename = filename, linenum = 1, } end -- Add code or interface to common prelude function vida.prelude(...) local args = {...} -- Put together source string local srcs = { vida._code_prelude } local ints = { vida._interface_prelude } for k, v in ipairs(args) do if not type(v) == 'table' then error('Argument ' .. k .. ' to prelude not Vida code or interface', 2) end if v.vida == 'code' then srcs[#srcs + 1] = string.format('#line %d "%s"', v.linenum, v.filename) srcs[#srcs + 1] = v.code elseif v.vida == 'interface' then ints[#ints + 1] = v.code else error('Argument ' .. k .. ' to prelude not Vida code or interface', 2) end end vida._code_prelude = table.concat(srcs, '\n') vida._interface_prelude = table.concat(ints, '\n') end -- Given chunks of C code and interfaces, return working FFI namespace function vida.compile(...) local args = {...} -- Put together source string local srcs = { vida._code_header, vida._code_prelude } local ints = { vida._interface_prelude } for k, v in ipairs(args) do if type(v) == 'string' then -- Assume code local caller = debug.getinfo(2) srcs[#srcs + 1] = string.format('#line %d "%s"', caller.currentline, caller.short_src) srcs[#srcs + 1] = v elseif type(v) ~= 'table' then error('Argument ' .. k .. ' to compile not Vida code or interface', 2) elseif v.vida == 'code' then srcs[#srcs + 1] = string.format('#line %d "%s"', v.linenum, v.filename) srcs[#srcs + 1] = v.code elseif v.vida == 'interface' then ints[#ints + 1] = v.code else error('Argument ' .. k .. ' to compile not Vida code or interface', 2) end end local src = table.concat(srcs, '\n') local interface = table.concat(ints, '\n') -- Interpret interface using FFI -- (Do this first in case there is an error here) if interface ~= '' then ffi.cdef(interface) end local name = md5.hash(src) -- Check for local copy of shared library local locallib = path.join(vida.cachePath, ffi.os .. '-' .. name .. libsuffix) if vida.useLocalCopy then if file_exists(locallib) then return ffi.load(locallib) end end -- If we don't have a compiler, bail out now if not vida.compiler then error('Error loading shared library, compiler disabled', 2) end -- Create names local fname = temp.name() .. name local cname = fname .. '.c' local oname = fname .. objsuffix local libname = fname .. libsuffix local localcname = path.join(vida.cachePath, name .. '.c') -- Write C source contents to .c file local file = io.open(cname, 'w') if not file then error(string.format('Error writing source file %s', cname), 2) end file:write(src) file:close() -- Compile local r if ffi.os == 'Windows' then r = os.execute(string.format('%s %s %s %s /Fo%s >nul', vida.compiler, vida.compilerFlags, vida.justComile, cname, oname)) if r ~= 0 then error('Error during compile', 2) end r = os.execute(string.format('%s %s %s /OUT:%s >nul', vida.compiler, oname, vida.linkerFlags, libname)) if r ~= 0 then error('Error during link', 2) end -- Save a local copy of library and source if vida.saveLocalCopy then os.execute(string.format('mkdir %s >nul 2>nul', vida.cachePath)) -- Ignore errors, likely already exists r = os.execute(string.format('copy %s %s >nul', libname, locallib)) if r ~= 0 then error('Error saving local copy', 2) end r = os.execute(string.format('copy %s %s >nul', cname, localcname)) if r ~= 0 then error('Error saving local copy2', 2) end end else r = os.execute(string.format('%s %s %s %s -o %s', vida.compiler, vida.compilerFlags, vida.justCompile, cname, oname)) if r ~= 0 then error('Error during compile', 2) end -- Link into shared library r = os.execute(string.format('%s %s %s -o %s', vida.compiler, vida.linkerFlags, oname, libname)) if r ~= 0 then error('Error during link', 2) end -- Save a local copy of library and source if vida.saveLocalCopy then r = os.execute(string.format('mkdir -p %s', vida.cachePath)) if r ~= 0 then error('Error creating cache path', 2) end r = os.execute(string.format('cp %s %s', libname, locallib)) if r ~= 0 then error('Error saving local copy', 2) end r = os.execute(string.format('cp %s %s', cname, localcname)) if r ~= 0 then error('Error saving local copy', 2) end end end -- Load the shared library return ffi.load(libname) end return vida
mit
waytim/darkstar
scripts/globals/items/bataquiche.lua
18
1456
----------------------------------------- -- ID: 5168 -- Item: Bataquiche -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 8 -- Agility 1 -- Vitality -2 -- Ranged ATT % 7 -- Ranged ATT Cap 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5168); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 8); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -2); target:addMod(MOD_FOOD_RATTP, 7); target:addMod(MOD_FOOD_RATT_CAP, 15); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 8); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -2); target:delMod(MOD_FOOD_RATTP, 7); target:delMod(MOD_FOOD_RATT_CAP, 15); end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c100000944.lua
2
4425
--Created and coded by Rising Phoenix function c100000944.initial_effect(c) --cannot special summon local e10=Effect.CreateEffect(c) e10:SetType(EFFECT_TYPE_SINGLE) e10:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e10:SetCode(EFFECT_SPSUMMON_CONDITION) e10:SetValue(aux.FALSE) c:RegisterEffect(e10) --lp local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(100000944,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_DELAY) e1:SetTarget(c100000944.htg) e1:SetOperation(c100000944.hop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e2) local e7=e1:Clone() e7:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e7) --synchro limit local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e3:SetValue(c100000944.synlimit) c:RegisterEffect(e3) --synchro effect local e12=Effect.CreateEffect(c) e12:SetCategory(CATEGORY_SPECIAL_SUMMON) e12:SetType(EFFECT_TYPE_QUICK_O) e12:SetCode(EVENT_FREE_CHAIN) e12:SetRange(LOCATION_MZONE) e12:SetCountLimit(1) e12:SetHintTiming(0,0x1c0) e12:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e12:SetTarget(c100000944.sctg) e12:SetOperation(c100000944.scop) c:RegisterEffect(e12) local e14=Effect.CreateEffect(c) e14:SetDescription(aux.Stringid(100000944,0)) e14:SetCategory(CATEGORY_TOGRAVE) e14:SetProperty(EFFECT_FLAG_CARD_TARGET) e14:SetType(EFFECT_TYPE_IGNITION) e14:SetRange(LOCATION_GRAVE) e14:SetCost(c100000944.costex) e14:SetTarget(c100000944.targetex) e14:SetOperation(c100000944.operationex) c:RegisterEffect(e14) end function c100000944.costex(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c100000944.filterex(c) return c:IsCode(100000951) and c:IsAbleToGrave() end function c100000944.targetex(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100000944.filterex,tp,LOCATION_EXTRA,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_EXTRA) end function c100000944.operationex(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c100000944.filterex,tp,LOCATION_EXTRA,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end function c100000944.mfilter(c) return c:IsSetCard(0x114) end function c100000944.sctg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local mg=Duel.GetMatchingGroup(c100000944.mfilter,tp,LOCATION_MZONE,0,nil) return Duel.IsExistingMatchingCard(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,1,nil,nil,mg) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c100000944.scop(e,tp,eg,ep,ev,re,r,rp) local mg=Duel.GetMatchingGroup(c100000944.mfilter,tp,LOCATION_MZONE,0,nil) local g=Duel.GetMatchingGroup(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,nil,nil,mg) if g:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,1,1,nil) Duel.SynchroSummon(tp,sg:GetFirst(),nil,mg) end end function c100000944.synlimit(e,c) if not c then return false end return not c:IsSetCard(0x114) end function c100000944.htg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,100000955,0,0x4011,1000,1000,4,RACE_DRAGON,ATTRIBUTE_LIGHT) end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0) end function c100000944.hop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end if not Duel.IsPlayerCanSpecialSummonMonster(tp,100000955,0,0x4011,1000,1000,4,RACE_DRAGON,ATTRIBUTE_LIGHT) then return end local token=Duel.CreateToken(tp,100000955) Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetValue(c100000944.synlimit) e2:SetReset(RESET_EVENT+0x1fe0000) token:RegisterEffect(e2) end
gpl-3.0
waytim/darkstar
scripts/zones/Abyssea-Tahrongi/npcs/qm18.lua
17
1550
----------------------------------- -- Zone: Abyssea-Tahrongi -- NPC: ??? -- Spawns: Lacovie ----------------------------------- require("scripts/globals/status"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ if (GetMobAction(16961931) == ACTION_NONE) then -- NM not already spawned from this if (player:hasKeyItem(OVERGROWN_MANDRAGORA_FLOWER) and player:hasKeyItem(CHIPPED_SANDWORM_TOOTH)) then player:startEvent(1020, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Ask if player wants to use KIs else player:startEvent(1021, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Do not ask, because player is missing at least 1. end end ]] end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 1020 and option == 1) then SpawnMob(16961931):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:delKeyItem(OVERGROWN_MANDRAGORA_FLOWER); player:delKeyItem(CHIPPED_SANDWORM_TOOTH); end end;
gpl-3.0
waytim/darkstar
scripts/zones/Port_Bastok/npcs/_6k8.lua
13
1400
----------------------------------- -- Area: Port Bastok -- NPC: Door: Departures Exit -- @zone 236 -- @pos -62 1 -8 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then player:startEvent(0x008d); else player:startEvent(0x008e); 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 == 0x008d) then local X = player:getXPos(); if (X >= -58 and X <= -55) then player:delGil(200); end end end;
gpl-3.0
Project-OSRM/osrm-backend
third_party/flatbuffers/lua/flatbuffers/numTypes.lua
6
4437
local m = {} local ba = require("flatbuffers.binaryarray") local bpack = ba.Pack local bunpack = ba.Unpack local type_mt = {} function type_mt:Pack(value) return bpack(self.packFmt, value) end function type_mt:Unpack(buf, pos) return bunpack(self.packFmt, buf, pos) end function type_mt:ValidNumber(n) if not self.min_value and not self.max_value then return true end return self.min_value <= n and n <= self.max_value end function type_mt:EnforceNumber(n) -- duplicate code since the overhead of function calls -- for such a popular method is time consuming if not self.min_value and not self.max_value then return end if self.min_value <= n and n <= self.max_value then return end error("Number is not in the valid range") end function type_mt:EnforceNumberAndPack(n) return bpack(self.packFmt, n) end function type_mt:ConvertType(n, otherType) assert(self.bytewidth == otherType.bytewidth, "Cannot convert between types of different widths") if self == otherType then return n end return otherType:Unpack(self:Pack(n)) end local bool_mt = { bytewidth = 1, min_value = false, max_value = true, lua_type = type(true), name = "bool", packFmt = "<I1", Pack = function(self, value) return value and "1" or "0" end, Unpack = function(self, buf, pos) return buf[pos] == "1" end, ValidNumber = function(self, n) return true end, -- anything is a valid boolean in Lua EnforceNumber = function(self, n) end, -- anything is a valid boolean in Lua EnforceNumberAndPack = function(self, n) return self:Pack(value) end, } local uint8_mt = { bytewidth = 1, min_value = 0, max_value = 2^8-1, lua_type = type(1), name = "uint8", packFmt = "<I1" } local uint16_mt = { bytewidth = 2, min_value = 0, max_value = 2^16-1, lua_type = type(1), name = "uint16", packFmt = "<I2" } local uint32_mt = { bytewidth = 4, min_value = 0, max_value = 2^32-1, lua_type = type(1), name = "uint32", packFmt = "<I4" } local uint64_mt = { bytewidth = 8, min_value = 0, max_value = 2^64-1, lua_type = type(1), name = "uint64", packFmt = "<I8" } local int8_mt = { bytewidth = 1, min_value = -2^7, max_value = 2^7-1, lua_type = type(1), name = "int8", packFmt = "<i1" } local int16_mt = { bytewidth = 2, min_value = -2^15, max_value = 2^15-1, lua_type = type(1), name = "int16", packFmt = "<i2" } local int32_mt = { bytewidth = 4, min_value = -2^31, max_value = 2^31-1, lua_type = type(1), name = "int32", packFmt = "<i4" } local int64_mt = { bytewidth = 8, min_value = -2^63, max_value = 2^63-1, lua_type = type(1), name = "int64", packFmt = "<i8" } local float32_mt = { bytewidth = 4, min_value = nil, max_value = nil, lua_type = type(1.0), name = "float32", packFmt = "<f" } local float64_mt = { bytewidth = 8, min_value = nil, max_value = nil, lua_type = type(1.0), name = "float64", packFmt = "<d" } -- register the base class setmetatable(bool_mt, {__index = type_mt}) setmetatable(uint8_mt, {__index = type_mt}) setmetatable(uint16_mt, {__index = type_mt}) setmetatable(uint32_mt, {__index = type_mt}) setmetatable(uint64_mt, {__index = type_mt}) setmetatable(int8_mt, {__index = type_mt}) setmetatable(int16_mt, {__index = type_mt}) setmetatable(int32_mt, {__index = type_mt}) setmetatable(int64_mt, {__index = type_mt}) setmetatable(float32_mt, {__index = type_mt}) setmetatable(float64_mt, {__index = type_mt}) m.Uint8 = uint8_mt m.Uint16 = uint16_mt m.Uint32 = uint32_mt m.Uint64 = uint64_mt m.Int8 = int8_mt m.Int16 = int16_mt m.Int32 = int32_mt m.Int64 = int64_mt m.Float32 = float32_mt m.Float64 = float64_mt m.UOffsetT = uint32_mt m.VOffsetT = uint16_mt m.SOffsetT = int32_mt local GenerateTypes = function(listOfTypes) for _,t in pairs(listOfTypes) do t.Pack = function(self, value) return bpack(self.packFmt, value) end t.Unpack = function(self, buf, pos) return bunpack(self.packFmt, buf, pos) end end end GenerateTypes(m) -- explicitly execute after GenerateTypes call, as we don't want to define a Pack/Unpack function for it. m.Bool = bool_mt return m
bsd-2-clause
waytim/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Nilerouche.lua
13
1300
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Nilerouche -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NILEROUCHE_SHOP_DIALOG); stock = {0x426d,108, -- Lufaise Fly 0x43e7,2640, -- Clothespole 0x02b0,200, -- Arrowwood Log 0x02b2,7800, -- Elm Log 0x121e,66000, -- Scroll of Banish III 0x0b37,9200} -- Safehold Waystone showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Bhaflau_Thickets/npcs/Runic_Portal.lua
2
1589
----------------------------------- -- Area: Bhaflau Thickets -- NPC: Runic Portal -- Mamook Ja Teleporter Back to Aht Urgan Whitegate -- @pos -211 -11 -818 52 ----------------------------------- package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/besieged"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/zones/Bhaflau_Thickets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(TOAU)== IMMORTAL_SENTRIES and player:getVar("TOAUM2") ==1)then player:startEvent(0x006F); elseif(player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES)then if(hasRunicPortal(player,3) == 1) then player:startEvent(0x006d); else player:startEvent(0x006f); end else player:messageSpecial(RESPONSE); 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(option == 1) then if(csid == 0x006f) then player:addNationTeleport(AHTURHGAN,8); end toChamberOfPassage(player); end end;
gpl-3.0
waytim/darkstar
scripts/zones/Selbina/npcs/Graegham.lua
13
1145
----------------------------------- -- Area: Selbina -- NPC: Graegham -- Guild Merchant NPC: Fishing Guild -- @pos -12.423 -7.287 8.665 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Selbina/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(5182,3,18,5)) then player:showText(npc,FISHING_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
waytim/darkstar
scripts/zones/Qufim_Island/npcs/Giant_Footprint.lua
13
1039
----------------------------------- -- Area: Qufim Island -- NPC: Giant Footprint -- Involved in quest: Regaining Trust -- @pos 501 -11 354 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Qufim_Island/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(GIGANTIC_FOOTPRINT); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("updateRESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("finishRESULT: %u",option); end;
gpl-3.0
alecxvs/UTChat
utchat/client/formats/shadow.lua
1
1074
--UText Shadow Format-- --[[ Shadow Effect - type = "Shadow" - startpos = <number> - endpos = <number> *Custom Parameter* * shadow = args[1-4] X Offset = -1 (number), Y Offset = -1 (number), Alpha = 255 (number), Scale = 1 (number) ]]-- Events:Subscribe( "ModulesLoad", function() class 'Shadow' -- Shadow Effect Init function Shadow:__init( startpos, endpos, params ) Format.__init(self, startpos, endpos) local xoffset, yoffset, alpha, scale = table.unpack(params) self.xoffset = xoffset or -1 self.yoffset = yoffset or -1 self.alpha = alpha or 255 self.scale = scale or 1 self.colormult = colormult or 0 end -- Shadow Effect Render function Shadow:Render( block ) local scolor = block.color * self.colormult scolor.a = self.alpha*(block.alpha*(block.parent.color.a*(block.parent.alpha/255)/255)/255) Render:DrawText( block.position - Vector2( self.xoffset, self.yoffset ), block.text, scolor, block.textsize, block.scale * self.scale ) end UText.RegisterFormat( Shadow, "shadow" ) end)
mit
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Ordelles_Caves/npcs/Stalagmite.lua
2
2354
----------------------------------- -- Area: Ordelles Caves -- NPC: Stalagmite -- Involved In Quest: Sharpening the Sword -- @zone 193 -- @pos -51 0 3 ----------------------------------- package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Ordelles_Caves/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getVar("sharpeningTheSwordCS") == 3) then NMDespawned = GetMobAction(17568134) == 0; spawnTime = player:getVar("Polevik_Spawned"); canSpawn = (os.time() - spawnTime) > 30; PolevikKilled = player:getVar("PolevikKilled"); if(PolevikKilled == 1) then if((os.time() - player:getVar("Polevik_Timer") < 30) or (NMDespawned and (os.time() - spawnTime) < 30)) then player:addKeyItem(ORDELLE_WHETSTONE); player:messageSpecial(KEYITEM_OBTAINED,ORDELLE_WHETSTONE); player:setVar("PolevikKilled",0); player:setVar("Polevik_Spawned",0); player:setVar("Polevik_Timer",0); player:setVar("sharpeningTheSwordCS",4) elseif(NMDespawned) then SpawnMob(17568134,168):updateEnmity(player); -- Despawn after 3 minutes (-12 seconds for despawn delay). player:setVar("PolevikKilled",0); player:setVar("Polevik_Spawned",os.time()+180); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end elseif(canSpawn) then SpawnMob(17568134,168):updateEnmity(player); -- Despawn after 3 minutes (-12 seconds for despawn delay). player:setVar("Polevik_Spawned",os.time()+180); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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
waytim/darkstar
scripts/globals/items/piece_of_cascade_candy.lua
18
1175
----------------------------------------- -- ID: 5942 -- Item: Piece of Cascade Candy -- Food Effect: 30Min, All Races ----------------------------------------- -- Mind +4 -- Charisma +4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5942); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MND, 4); target:addMod(MOD_CHR, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MND, 4); target:delMod(MOD_CHR, 4); end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c80106548.lua
2
3980
--The Fourth Panticle of Serenity function c80106548.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_HANDES+CATEGORY_DRAW) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,80106548) e1:SetTarget(c80106548.drtg) e1:SetOperation(c80106548.drop) c:RegisterEffect(e1) --self destroy local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_SELF_DESTROY) e2:SetCondition(c80106548.sdcon) c:RegisterEffect(e2) --disable spsummon local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetRange(LOCATION_MZONE) e3:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetTargetRange(0,1) e3:SetCondition(c80106548.desrepcon) e3:SetTarget(c80106548.disspsum) c:RegisterEffect(e3) --spsummon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(80106548,0)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_TO_GRAVE) e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e4:SetCondition(c80106548.spcon) e4:SetTarget(c80106548.sptg) e4:SetOperation(c80106548.spop) c:RegisterEffect(e4) end function c80106548.drtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,2) and Duel.IsPlayerCanDraw(1-tp,2) end Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,PLAYER_ALL,2) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,PLAYER_ALL,2) end function c80106548.drop(e,tp,eg,ep,ev,re,r,rp) local h1=Duel.Draw(tp,2,REASON_EFFECT) local h2=Duel.Draw(1-tp,2,REASON_EFFECT) if h1>0 or h2>0 then Duel.BreakEffect() end if h1>0 then Duel.ShuffleHand(tp) Duel.DiscardHand(tp,aux.TRUE,2,2,REASON_EFFECT+REASON_DISCARD) end if h2>0 then Duel.ShuffleHand(1-tp) Duel.DiscardHand(1-tp,aux.TRUE,2,2,REASON_EFFECT+REASON_DISCARD) end end function c80106548.sdfilter(c) return not c:IsFaceup() or not c:IsSetCard(0xca00) end function c80106548.sdcon(e) return Duel.IsExistingMatchingCard(c80106548.sdfilter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end function c80106548.cfilter(c) return c:IsType(TYPE_MONSTER) end function c80106548.desrepcon(e) local tp=e:GetHandlerPlayer() return Duel.GetFieldGroupCount(tp,LOCATION_EXTRA,0)==0 and not Duel.IsExistingMatchingCard(c80106548.cfilter,tp,LOCATION_GRAVE,0,1,nil) and Duel.IsExistingMatchingCard(c80106548.cfilter,tp,0,LOCATION_GRAVE,1,nil) end function c80106548.disspsum(e,c) return c:IsAttribute(ATTRIBUTE_DARK+ATTRIBUTE_LIGHT) end function c80106548.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsReason(REASON_EFFECT) and e:GetHandler():IsPreviousLocation(LOCATION_HAND) and not e:GetHandler():IsReason(REASON_RETURN) end function c80106548.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,80106548,0,0xca00,7,2100,2100,RACE_FAIRY,ATTRIBUTE_DARK) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c80106548.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.IsPlayerCanSpecialSummonMonster(tp,80106548,0,0xca00,7,2100,2100,RACE_FAIRY,ATTRIBUTE_DARK) then c:SetStatus(STATUS_NO_LEVEL,false) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CHANGE_TYPE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetValue(TYPE_EFFECT+TYPE_MONSTER) e1:SetReset(RESET_EVENT+0x47c0000) c:RegisterEffect(e1,true) Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP) local e7=Effect.CreateEffect(c) e7:SetType(EFFECT_TYPE_SINGLE) e7:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e7:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e7:SetReset(RESET_EVENT+0x47e0000) e7:SetValue(LOCATION_DECKBOT) c:RegisterEffect(e7,true) end end
gpl-3.0
omaralahmad/RESANDA
bot/utils.lua
14
16238
--Begin Utils.lua By #BeyondTeam :) function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "data/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end 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 scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end function gp_type(chat_id) local gp_type = "pv" local id = tostring(chat_id) if id:match("^-100") then gp_type = "channel" elseif id:match("-") then gp_type = "chat" end return gp_type end function is_reply(msg) local var = false if msg.reply_to_message_id_ ~= 0 then -- reply message id is not 0 var = true end return var end function is_supergroup(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-100') then --supergroups and channels start with -100 if not msg.is_post_ then return true end else return false end end function is_channel(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-100') then -- Start with -100 (like channels and supergroups) if msg.is_post_ then -- message is a channel post return true else return false end end end function is_group(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-100') then --not start with -100 (normal groups does not have -100 in first) return false elseif chat_id:match('^-') then return true else return false end end function is_private(msg) chat_id = tostring(msg.to.id) if chat_id:match('^-') then --private chat does not start with - return false else return true end end function check_markdown(text) --markdown escape ( when you need to escape markdown , use it like : check_markdown('your text') str = text if str:match('_') then output = str:gsub('_',[[\_]]) elseif str:match('*') then output = str:gsub('*','\\*') elseif str:match('`') then output = str:gsub('`','\\`') else output = str end return output end function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['owners'] then if data[tostring(msg.to.id)]['owners'][tostring(msg.from.id)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == msg.from.id then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin(msg) local var = false local user = msg.from.id for v,user in pairs(_config.admins) do if user[1] == msg.from.id then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end --Check if user is the mod of that group or not function is_mod(msg) local var = false local data = load_data(_config.moderation.data) local usert = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['mods'] then if data[tostring(msg.to.id)]['mods'][tostring(msg.from.id)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['owners'] then if data[tostring(msg.to.id)]['owners'][tostring(msg.from.id)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == msg.from.id then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_sudo1(user_id) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end function is_owner1(chat_id, user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id if data[tostring(chat_id)] then if data[tostring(chat_id)]['owners'] then if data[tostring(chat_id)]['owners'][tostring(user)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == user_id then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end function is_admin1(user_id) local var = false local user = user_id for v,user in pairs(_config.admins) do if user[1] == user_id then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_mod1(chat_id, user_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(chat_id)] then if data[tostring(chat_id)]['mods'] then if data[tostring(chat_id)]['mods'][tostring(usert)] then var = true end end end if data[tostring(chat_id)] then if data[tostring(chat_id)]['owners'] then if data[tostring(chat_id)]['owners'][tostring(usert)] then var = true end end end for v,user in pairs(_config.admins) do if user[1] == user_id then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = '*This plugin requires privileged user*' local receiver = msg.chat_id_ tdcli.sendMessage(msg.chat_id_, "", 0, result, 0, "md") return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function is_banned(user_id, chat_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(chat_id)] then if data[tostring(chat_id)]['banned'] then if data[tostring(chat_id)]['banned'][tostring(user_id)] then var = true end end end return var end function is_silent_user(user_id, chat_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(chat_id)] then if data[tostring(chat_id)]['is_silent_users'] then if data[tostring(chat_id)]['is_silent_users'][tostring(user_id)] then var = true end end end return var end function is_gbanned(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local gban_users = 'gban_users' if data[tostring(gban_users)] then if data[tostring(gban_users)][tostring(user)] then var = true end end return var end function is_filter(msg, text) local var = false local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['filterlist'] then for k,v in pairs(data[tostring(msg.to.id)]['filterlist']) do if string.find(string.lower(text), string.lower(k)) then var = true end end end return var end function kick_user(user_id, chat_id) if not tonumber(user_id) then return false end tdcli.changeChatMemberStatus(chat_id, user_id, 'Kicked', dl_cb, nil) end function del_msg(chat_id, message_ids) local msgid = {[0] = message_ids} tdcli.deleteMessages(chat_id, msgid, dl_cb, nil) end function file_dl(file_id) tdcli.downloadFile(file_id, dl_cb, nil) end function banned_list(chat_id) local hash = "gp_lang:"..chat_id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end -- determine if table is empty if next(data[tostring(chat_id)]['banned']) == nil then --fix way if not lang then return "_No_ *banned* _users in this group_" else return "*هیچ کاربری از این گروه محروم نشده*" end end if not lang then message = '*List of banned users :*\n' else message = '_لیست کاربران محروم شده از گروه :_\n' end for k,v in pairs(data[tostring(chat_id)]['banned']) do message = message ..i.. '- '..check_markdown(v)..' [' ..k.. '] \n' i = i + 1 end return message end function silent_users_list(chat_id) local hash = "gp_lang:"..chat_id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end -- determine if table is empty if next(data[tostring(chat_id)]['is_silent_users']) == nil then --fix way if not lang then return "_No_ *silent* _users in this group_" else return "*لیست کاربران سایلنت شده خالی است*" end end if not lang then message = '*List of silent users :*\n' else message = '_لیست کاربران سایلنت شده :_\n' end for k,v in pairs(data[tostring(chat_id)]['is_silent_users']) do message = message ..i.. '- '..check_markdown(v)..' [' ..k.. '] \n' i = i + 1 end return message end function gbanned_list(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data['gban_users'] then data['gban_users'] = {} save_data(_config.moderation.data, data) end if next(data['gban_users']) == nil then --fix way if not lang then return "_No_ *globally banned* _users available_" else return "*هیچ کاربری از گروه های ربات محروم نشده*" end end if not lang then message = '*List of globally banned users :*\n' else message = '_لیست کاربران محروم شده از گروه های ربات :_\n' end for k,v in pairs(data['gban_users']) do message = message ..i.. '- '..check_markdown(v)..' [' ..k.. '] \n' i = i + 1 end return message end function filter_list(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.chat_id_)]['filterlist'] then data[tostring(msg.chat_id_)]['filterlist'] = {} save_data(_config.moderation.data, data) end if not data[tostring(msg.chat_id_)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end -- determine if table is empty if next(data[tostring(msg.chat_id_)]['filterlist']) == nil then --fix way if not lang then return "*Filtered words list* _is empty_" else return "_لیست کلمات فیلتر شده خالی است_" end end if not data[tostring(msg.chat_id_)]['filterlist'] then data[tostring(msg.chat_id_)]['filterlist'] = {} save_data(_config.moderation.data, data) end if not lang then filterlist = '*List of filtered words :*\n' else filterlist = '_لیست کلمات فیلتر شده :_\n' end local i = 1 for k,v in pairs(data[tostring(msg.chat_id_)]['filterlist']) do filterlist = filterlist..'*'..i..'* - _'..check_markdown(k)..'_\n' i = i + 1 end return filterlist end
gpl-3.0
dmccuskey/dmc-sockets
examples/dmc-sockets-basic/dmc_corona/dmc_sockets/ssl_params.lua
16
4809
--====================================================================-- -- dmc_corona/dmc_sockets/ssl_params.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2014-2015 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- --== DMC Lua Library : Sockets SSL Params --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.2.0" --====================================================================-- --== Imports local Objects = require 'lib.dmc_lua.lua_objects' local Utils = require 'lib.dmc_lua.lua_utils' -- Check imports -- TODO: work on this assert( Objects, "lua_error: requires lua_objects" ) if checkModule then checkModule( Objects, '1.1.2' ) end --====================================================================-- --== Setup, Constants -- none --====================================================================-- --== SSL Params Class --====================================================================-- local SSLParams = newClass( nil, { name="SSL Params" } ) --== Class Constants ==-- SSLParams.__version = VERSION -- Modes SSLParams.CLIENT = 'client' SSLParams.MODES = { SSLParams.CLIENT, } -- secure protocols SSLParams.TLS_V1 = 'tlsv1' SSLParams.SSL_V3 = 'sslv3' SSLParams.PROTOCOLS = { SSLParams.TLS_V1, SSLParams.SSL_V3 } -- options SSLParams.ALL = 'all' SSLParams.OPTIONS = { SSLParams.ALL } -- verify options SSLParams.NONE = 'none' SSLParams.PEER = 'peer' SSLParams.VERIFY_OPTS = { SSLParams.NONE, SSLParams.PEER } function SSLParams:__new__( params ) -- print( "SSLParams:__new__", params ) params = params or {} --==-- if self.is_class then return end assert( type(params)=='table', "SSLParams: incorrect parameter type" ) -- save args self._mode = self.CLIENT self._options = self.ALL self._protocol = self.TLS_V1 self._verify = self.NONE if params then self:update( params ) end end function SSLParams.__setters:mode( value ) -- print( "SSLParams.__setters:mode", value ) assert( Utils.propertyIn( self.MODES, value ), "unknown mode" ) --==-- self._mode = value end function SSLParams.__getters:mode( ) -- print( "SSLParams.__getters:mode" ) return self._mode end function SSLParams.__setters:options( value ) -- print( "SSLParams.__setters:options", value ) assert( Utils.propertyIn( self.OPTIONS, value ), "unknown option" ) --==-- self._options = value end function SSLParams.__getters:options( ) -- print( "SSLParams.__getters:options" ) return self._options end function SSLParams.__setters:protocol( value ) -- print( "SSLParams.__setters:protocol", value ) assert( Utils.propertyIn( self.PROTOCOLS, value ), "unknown protocol" ) --==-- self._protocol = value end function SSLParams.__getters:protocol( ) -- print( "SSLParams.__getters:protocol" ) return self._protocol end function SSLParams.__setters:verify( value ) -- print( "SSLParams.__setters:verify", value ) assert( Utils.propertyIn( self.VERIFY_OPTS, value ), "unknown verify" ) --==-- self._verify = value end function SSLParams.__getters:verify( ) -- print( "SSLParams.__getters:verify" ) return self._verify end function SSLParams:update( options ) -- print( "SSLParams:update", options ) assert( type(options)=='table', "bad value for update" ) --==-- if options.mode then self.mode = options.mode end if options.options then self.options = options.options end if options.protocol then self.protocol = options.protocol end if options.verify then self.verify = options.verify end end return SSLParams
mit
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/spells/gain-chr.lua
2
2309
-------------------------------------- -- Spell: Gain-CHR -- Boosts targets CHR stat -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) enchanceSkill = caster:getSkillLevel(34); duration = 300; if(enchanceSkill <309)then power = 5 elseif(enchanceSkill >=309 and enchanceSkill <=319)then power = 6 elseif(enchanceSkill >=320 and enchanceSkill <=329)then power = 7 elseif(enchanceSkill >=330 and enchanceSkill <=339)then power = 8 elseif(enchanceSkill >=340 and enchanceSkill <=349)then power = 9 elseif(enchanceSkill >=350 and enchanceSkill <=359)then power = 10 elseif(enchanceSkill >=360 and enchanceSkill <=369)then power = 11 elseif(enchanceSkill >=370 and enchanceSkill <=379)then power = 12 elseif(enchanceSkill >=380 and enchanceSkill <=389)then power = 13 elseif(enchanceSkill >=390 and enchanceSkill <=399)then power = 14 elseif(enchanceSkill >=400 and enchanceSkill <=409)then power = 15 elseif(enchanceSkill >=410 and enchanceSkill <=419)then power = 16 elseif(enchanceSkill >=420 and enchanceSkill <=429)then power = 17 elseif(enchanceSkill >=430 and enchanceSkill <=439)then power = 18 elseif(enchanceSkill >=440 and enchanceSkill <=449)then power = 19 elseif(enchanceSkill >=450 and enchanceSkill <=459)then power = 20 elseif(enchanceSkill >=460 and enchanceSkill <=469)then power = 21 elseif(enchanceSkill >=470 and enchanceSkill <=479)then power = 22 elseif(enchanceSkill >=480 and enchanceSkill <=489)then power = 23 elseif(enchanceSkill >=480 and enchanceSkill <=499)then power = 24 else power = 25 end if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end if(target:hasStatusEffect(EFFECT_CHR_DOWN) == true) then target:delStatusEffect(EFFECT_CHR_DOWN); else target:addStatusEffect(EFFECT_CHR_BOOST,power,0,duration); end end;
gpl-3.0
waytim/darkstar
scripts/globals/spells/cura_ii.lua
36
4121
----------------------------------------- -- Spell: Cura -- Restores hp in area of effect. Self target only -- From what I understand, Cura's base potency is the same as Cure II's. -- With Afflatus Misery Bonus, it can be as potent as a Curaga III -- Modeled after our cure_ii.lua, which was modeled after the below reference -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) if (caster:getID() ~= target:getID()) then return MSGBASIC_CANNOT_PERFORM_TARG; else return 0; end; end; function onSpellCast(caster,target,spell) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 60; if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster); divisor = 1; constant = 20; if (power > 170) then divisor = 35.6666; constant = 87.62; elseif (power > 110) then divisor = 2; constant = 47.5; end else power = getCurePower(caster); if (power < 70) then divisor = 1; constant = 60; basepower = 40; elseif (power < 125) then divisor = 5.5; constant = 90; basepower = 70; elseif (power < 200) then divisor = 7.5; constant = 100; basepower = 125; elseif (power < 400) then divisor = 10; constant = 110; basepower = 200; elseif (power < 700) then divisor = 20; constant = 130; basepower = 400; else divisor = 999999; constant = 145; basepower = 0; end end if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCure(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end --Apply Afflatus Misery Bonus to Final Result if (caster:hasStatusEffect(EFFECT_AFFLATUS_MISERY)) then if (caster:getID() == target:getID()) then -- Let's use a local var to hold the power of Misery so the boost is applied to all targets, caster:setLocalVar("Misery_Power", caster:getMod(MOD_AFFLATUS_MISERY)); end; local misery = caster:getLocalVar("Misery_Power"); --THIS IS LARELY SEMI-EDUCATED GUESSWORK. THERE IS NOT A --LOT OF CONCRETE INFO OUT THERE ON CURA THAT I COULD FIND --Not very much documentation for Cura II known at all. --As with Cura, the Afflatus Misery bonus can boost this spell up --to roughly the level of a Curaga 3. For Cura I vs Curaga II, --this is document at ~175HP, 15HP less than the cap of 190HP. So --for Cura II, i'll go with 15 less than the cap of Curaga III (390): 375 --So with lack of available formula documentation, I'll go with that. --printf("BEFORE AFFLATUS MISERY BONUS: %d", basecure); basecure = basecure + misery; if (basecure > 375) then basecure = 375; end --printf("AFTER AFFLATUS MISERY BONUS: %d", basecure); --Afflatus Misery Mod Gets Used Up caster:setMod(MOD_AFFLATUS_MISERY, 0); end final = getCureFinal(caster,spell,basecure,minCure,false); final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; target:addHP(final); target:wakeUp(); --Enmity for Cura is fixed, so its CE/VE is set in the SQL and not calculated with updateEnmityFromCure spell:setMsg(367); return final; end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c100000790.lua
2
2475
--Created and coded by Rising Phoenix function c100000790.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_TOHAND) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c100000790.spcon) e1:SetTarget(c100000790.target) e1:SetOperation(c100000790.activate) c:RegisterEffect(e1) end function c100000790.cfilter(c) return c:IsSetCard(0x118) and c:IsAbleToDeckAsCost() and c:IsCode(100000793) end function c100000790.cfilter2(c) return c:IsSetCard(0x118) and c:IsAbleToDeckAsCost() and c:IsCode(100000794) end function c100000790.cfilter3(c) return c:IsSetCard(0x118) and c:IsAbleToDeckAsCost() and c:IsCode(100000799) end function c100000790.spcon(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100000790.cfilter,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD,0,1,nil) and Duel.IsExistingMatchingCard(c100000790.cfilter2,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD,0,1,nil) and Duel.IsExistingMatchingCard(c100000790.cfilter3,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectMatchingCard(tp,c100000790.cfilter,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD,0,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g1=Duel.SelectMatchingCard(tp,c100000790.cfilter2,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD,0,1,1,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g2=Duel.SelectMatchingCard(tp,c100000790.cfilter3,tp,LOCATION_HAND+LOCATION_GRAVE+LOCATION_ONFIELD,0,1,1,nil) g:Merge(g1) g:Merge(g2) Duel.SendtoDeck(g,nil,2,REASON_COST) end function c100000790.filter(c,e,tp) return c:IsCode(100000789) and c:IsCanBeSpecialSummoned(e,0,tp,true,false) end function c100000790.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c100000790.filter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_EXTRA) end function c100000790.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c100000790.filter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp) if g:GetCount()>0 then end Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP) end
gpl-3.0
tst2005/lunamark
lunamark/writer/xml.lua
3
1505
-- (c) 2009-2011 John MacFarlane. Released under MIT license. -- See the file LICENSE in the source for details. --- Generic XML writer for lunamark. -- It extends [lunamark.writer.generic] and is extended by -- [lunamark.writer.html] and [lunamark.writer.docbook]. local M = {} local generic = require("lunamark.writer.generic") local util = require("lunamark.util") --- Returns a new XML writer. -- For a list of fields, see [lunamark.writer.generic]. function M.new(options) local options = options or {} local Xml = generic.new(options) Xml.container = "section" -- {1,2} means: a second level header inside a first-level local header_level_stack = {} function Xml.start_section(level) header_level_stack[#header_level_stack + 1] = level return "<" .. Xml.container .. ">" end function Xml.stop_section(level) local len = #header_level_stack if len == 0 then return "" else local last = header_level_stack[len] local res = {} while last >= level do header_level_stack[len] = nil table.insert(res, "</" .. Xml.container .. ">") len = len - 1 last = (len > 0 and header_level_stack[len]) or 0 end return table.concat(res, Xml.containersep) end end Xml.linebreak = "<linebreak />" local escape = util.escaper { ["<" ] = "&lt;", [">" ] = "&gt;", ["&" ] = "&amp;", ["\"" ] = "&quot;", ["'" ] = "&#39;" } Xml.string = escape return Xml end return M
mit
TheOnePharaoh/YGOPro-Custom-Cards
script/c20912240.lua
2
1970
--klein function c20912240.initial_effect(c) --lv gain local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(20912240,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetCondition(c20912240.condition) e1:SetTarget(c20912240.target) e1:SetOperation(c20912240.operation) c:RegisterEffect(e1) --synchro limit local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e2:SetValue(c20912240.synlimit) c:RegisterEffect(e2) end function c20912240.condition(e) return e:GetHandler():GetEquipCount()>0 end function c20912240.filter(c) return c:IsFaceup() and c:IsSetCard(0xd0a2) end function c20912240.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c20912240.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c20912240.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) local g=Duel.SelectTarget(tp,c20912240.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) local tc=g:GetFirst() local op=0 if tc:GetLevel()==1 then op=Duel.SelectOption(tp,aux.Stringid(20912240,1),aux.Stringid(20912240,2)) else op=Duel.SelectOption(tp,aux.Stringid(20912240,1),aux.Stringid(20912240,2)) end e:SetLabel(op) end function c20912240.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_UPDATE_LEVEL) e1:SetReset(RESET_EVENT+0x1fe0000) if e:GetLabel()==0 then e1:SetValue(1) else e1:SetValue(3) end tc:RegisterEffect(e1) end end function c89258906.synlimit(e,c) if not c then return false end return not c:IsRace(RACE_WARRIOR) end
gpl-3.0
waytim/darkstar
scripts/zones/Cloister_of_Storms/bcnms/trial_by_lightning.lua
30
2230
----------------------------------- -- Area: Cloister of Storms -- BCNM: Trial by Lightning ----------------------------------- package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Cloister_of_Storms/TextIDs"); ----------------------------------- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); trialLightning = player:getQuestStatus(OTHER_AREAS,TRIAL_BY_LIGHTNING) if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (trialLightning == QUEST_COMPLETED) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:delKeyItem(TUNING_FORK_OF_LIGHTNING); player:addKeyItem(WHISPER_OF_STORMS); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_STORMS); end end;
gpl-3.0
wanmaple/MWFrameworkForCocosLua
frameworks/runtime-src/Framework/lua/auto/api/MWJsonObject.lua
1
5572
-------------------------------- -- @module MWJsonObject -- @extend MWObject -- @parent_module mw -------------------------------- -- Get pairs count of json.<br> -- return Return the count of key-value pairs. -- @function [parent=#MWJsonObject] count -- @param self -- @return unsigned int#unsigned int ret (return value: unsigned int) -------------------------------- -- Get json array of the specified key.<br> -- param key Key to consult.<br> -- return Return json array of key. -- @function [parent=#MWJsonObject] getJsonArray -- @param self -- @param #string key -- @return MWJsonArray#MWJsonArray ret (return value: mw.MWJsonArray) -------------------------------- -- Return boolean of the specified key.<br> -- param key Key to consult.<br> -- return Return boolean value of key. -- @function [parent=#MWJsonObject] getBoolean -- @param self -- @param #string key -- @return bool#bool ret (return value: bool) -------------------------------- -- Add new boolean value to json.<br> -- param key Key to insert.<br> -- param value Boolean value to add. -- @function [parent=#MWJsonObject] putBoolean -- @param self -- @param #string key -- @param #bool value -------------------------------- -- Return string of the specified key.<br> -- param key Key to consult.<br> -- return Return string value of key. -- @function [parent=#MWJsonObject] getString -- @param self -- @param #string key -- @return char#char ret (return value: char) -------------------------------- -- Return number of the specified key.<br> -- param key Key to consult.<br> -- return Return number value of key. -- @function [parent=#MWJsonObject] getNumber -- @param self -- @param #string key -- @return double#double ret (return value: double) -------------------------------- -- Add new json array to json.<br> -- param key Key to insert.<br> -- param value Json array to add. -- @function [parent=#MWJsonObject] putJsonArray -- @param self -- @param #string key -- @param #mw.MWJsonArray value -------------------------------- -- Add new json object to json.<br> -- param key Key to insert.<br> -- param value Json object to add. -- @function [parent=#MWJsonObject] putJsonObject -- @param self -- @param #string key -- @param #mw.MWJsonObject value -------------------------------- -- Clear json. -- @function [parent=#MWJsonObject] clear -- @param self -------------------------------- -- Convert to lua string.<br> -- return Return lua version of json string. -- @function [parent=#MWJsonObject] toLuaString -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Add new number value to json.<br> -- param key Key to insert.<br> -- param value Number value to add. -- @function [parent=#MWJsonObject] putNumber -- @param self -- @param #string key -- @param #double value -------------------------------- -- Remove value of the specified key.<br> -- param key Key to remove. -- @function [parent=#MWJsonObject] remove -- @param self -- @param #string key -------------------------------- -- Add new string value to json.<br> -- param key Key to insert.<br> -- param value String value to add. -- @function [parent=#MWJsonObject] putString -- @param self -- @param #string key -- @param #string value -------------------------------- -- Get json object of the specified key.<br> -- param key Key to consult.<br> -- return Return json object of key. -- @function [parent=#MWJsonObject] getJsonObject -- @param self -- @param #string key -- @return MWJsonObject#MWJsonObject ret (return value: mw.MWJsonObject) -------------------------------- -- Convert to pretty string.<br> -- return Return pretty version of json string. -- @function [parent=#MWJsonObject] toPrettyString -- @param self -- @return string#string ret (return value: string) -------------------------------- -- Figure out whether json has the specified key.<br> -- param key Key to consult.<br> -- return Whether the key exists. -- @function [parent=#MWJsonObject] hasKey -- @param self -- @param #string key -- @return bool#bool ret (return value: bool) -------------------------------- -- Get any object of the specified key.<br> -- param key Key to consult.<br> -- return Return object of key. -- @function [parent=#MWJsonObject] getObject -- @param self -- @param #string key -- @return MWObject#MWObject ret (return value: mw.MWObject) -------------------------------- -- Create a json object from json file.<br> -- param jsonPath Json file path.<br> -- return Return a new json object. -- @function [parent=#MWJsonObject] createWithFile -- @param self -- @param #string jsonPath -- @return MWJsonObject#MWJsonObject ret (return value: mw.MWJsonObject) -------------------------------- -- -- @function [parent=#MWJsonObject] create -- @param self -- @return MWJsonObject#MWJsonObject ret (return value: mw.MWJsonObject) -------------------------------- -- Create a json object through string.<br> -- param jsonStr Json string.<br> -- return Return a new json object. -- @function [parent=#MWJsonObject] createWithString -- @param self -- @param #string jsonStr -- @return MWJsonObject#MWJsonObject ret (return value: mw.MWJsonObject) -------------------------------- -- Convert to json string.<br> -- return Return json string format. -- @function [parent=#MWJsonObject] toString -- @param self -- @return string#string ret (return value: string) return nil
apache-2.0
waytim/darkstar
scripts/zones/Southern_San_dOria/npcs/Coderiant.lua
13
1465
----------------------------------- -- Area: Southern San d'Oria -- NPC: Coderiant -- General Info NPC -- @zone 230 -- @pos -111 -2 33 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x247); 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
TheOnePharaoh/YGOPro-Custom-Cards
script/c100000812.lua
2
4204
--Created and coded by Rising Phoenix function c100000812.initial_effect(c) --lp local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(100000812,0)) e1:SetCategory(CATEGORY_RECOVER) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_DELAY) e1:SetTarget(c100000812.htg) e1:SetOperation(c100000812.hop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e2) local e3=e1:Clone() e3:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e3) --spsummon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(100000812,0)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_SUMMON_SUCCESS) e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e4:SetCountLimit(1,100000812) e4:SetTarget(c100000812.sptg) e4:SetOperation(c100000812.spop) c:RegisterEffect(e4) local e5=e4:Clone() e5:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e5) local e6=e4:Clone() e6:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e6) --no damage local e7=Effect.CreateEffect(c) e7:SetType(EFFECT_TYPE_FIELD) e7:SetCode(EFFECT_CHANGE_DAMAGE) e7:SetRange(LOCATION_MZONE) e7:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e7:SetTargetRange(1,0) e7:SetValue(c100000812.damval) c:RegisterEffect(e7) local e8=e7:Clone() e8:SetCode(EFFECT_NO_EFFECT_DAMAGE) c:RegisterEffect(e8) --avoid local e9=Effect.CreateEffect(c) e9:SetType(EFFECT_TYPE_SINGLE) e9:SetCode(EFFECT_AVOID_BATTLE_DAMAGE) e9:SetValue(1) c:RegisterEffect(e9) --synchro limit local e10=Effect.CreateEffect(c) e10:SetType(EFFECT_TYPE_SINGLE) e10:SetCode(EFFECT_CANNOT_BE_XYZ_MATERIAL) e10:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e10:SetValue(c100000812.synlimit) c:RegisterEffect(e10) --damage local e11=Effect.CreateEffect(c) e11:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e11:SetDescription(aux.Stringid(100000812,1)) e11:SetCategory(CATEGORY_DAMAGE) e11:SetCode(EVENT_PHASE+PHASE_STANDBY) e11:SetRange(LOCATION_MZONE) e11:SetCountLimit(1) e11:SetCondition(c100000812.damcon) e11:SetTarget(c100000812.damtg) e11:SetOperation(c100000812.damop) c:RegisterEffect(e11) end function c100000812.htg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,1000) end function c100000812.hop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Recover(p,d,REASON_EFFECT) end function c100000812.filter(c,e,tp) return c:IsSetCard(0x10A) and c:GetLevel()==4 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c100000812.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c100000812.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c100000812.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c100000812.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c100000812.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then end Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end function c100000812.damval(e,re,val,r,rp,rc) if bit.band(r,REASON_EFFECT)~=0 and rp~=e:GetOwnerPlayer() then return 0 else return val end end function c100000812.synlimit(e,c) if not c then return false end return not c:IsSetCard(0x10A) end function c100000812.damcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c100000812.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(tp) Duel.SetTargetParam(1000) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,0,0,tp,1000) end function c100000812.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end
gpl-3.0
niegenug/wesnoth
data/ai/micro_ais/cas/ca_forest_animals_tusker_attack.lua
26
2575
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local function get_tuskers(cfg) local tuskers = AH.get_units_with_moves { side = wesnoth.current.side, type = cfg.tusker_type } return tuskers end local function get_adjacent_enemies(cfg) local adjacent_enemies = wesnoth.get_units { { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } }, { "filter_adjacent", { side = wesnoth.current.side, type = cfg.tusklet_type } } } return adjacent_enemies end local ca_forest_animals_tusker_attack = {} function ca_forest_animals_tusker_attack:evaluation(ai, cfg) -- Check whether there is an enemy next to a tusklet and attack it ("protective parents" AI) if (not cfg.tusker_type) or (not cfg.tusklet_type) then return 0 end if (not get_tuskers(cfg)[1]) then return 0 end if (not get_adjacent_enemies(cfg)[1]) then return 0 end return cfg.ca_score end function ca_forest_animals_tusker_attack:execution(ai, cfg) local tuskers = get_tuskers(cfg) local adjacent_enemies = get_adjacent_enemies(cfg) -- Find the closest enemy to any tusker local min_dist, attacker, target = 9e99 for _,tusker in ipairs(tuskers) do for _,enemy in ipairs(adjacent_enemies) do local dist = H.distance_between(tusker.x, tusker.y, enemy.x, enemy.y) if (dist < min_dist) then min_dist, attacker, target = dist, tusker, enemy end end end -- The tusker moves as close to enemy as possible -- Closeness to tusklets is secondary criterion local adj_tusklets = wesnoth.get_units { side = wesnoth.current.side, type = cfg.tusklet_type, { "filter_adjacent", { id = target.id } } } local best_hex = AH.find_best_move(attacker, function(x, y) local rating = - H.distance_between(x, y, target.x, target.y) for _,tusklet in ipairs(adj_tusklets) do if (H.distance_between(x, y, tusklet.x, tusklet.y) == 1) then rating = rating + 0.1 end end return rating end) AH.movefull_stopunit(ai, attacker, best_hex) if (not attacker) or (not attacker.valid) then return end if (not target) or (not target.valid) then return end local dist = H.distance_between(attacker.x, attacker.y, target.x, target.y) if (dist == 1) then AH.checked_attack(ai, attacker, target) else AH.checked_stopunit_attacks(ai, attacker) end end return ca_forest_animals_tusker_attack
gpl-2.0
steven-jackson/PersonalLoot
libs/LibBabble-Inventory-3.0/LibStub/tests/test2.lua
100
1112
debugstack = debug.traceback strmatch = string.match loadfile("../LibStub.lua")() for major, library in LibStub:IterateLibraries() do -- check that MyLib doesn't exist yet, by iterating through all the libraries assert(major ~= "MyLib") end assert(not LibStub:GetLibrary("MyLib", true)) -- check that MyLib doesn't exist yet by direct checking assert(not pcall(LibStub.GetLibrary, LibStub, "MyLib")) -- don't silently fail, thus it should raise an error. local lib = LibStub:NewLibrary("MyLib", 1) -- create the lib assert(lib) -- check it exists assert(rawequal(LibStub:GetLibrary("MyLib"), lib)) -- verify that :GetLibrary("MyLib") properly equals the lib reference assert(LibStub:NewLibrary("MyLib", 2)) -- create a new version local count=0 for major, library in LibStub:IterateLibraries() do -- check that MyLib exists somewhere in the libraries, by iterating through all the libraries if major == "MyLib" then -- we found it! count = count +1 assert(rawequal(library, lib)) -- verify that the references are equal end end assert(count == 1) -- verify that we actually found it, and only once
gpl-3.0
TienHP/Aquaria
files/scripts/maps/node_energytemple01door.lua
6
1879
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) node_setCursorActivation(me, false) local orbHolder = node_getNearestEntity(me) local energyOrb = entity_getNearestEntity(orbHolder, "EnergyOrb") if energyOrb ~= 0 and orbHolder ~= 0 then entity_setPosition(energyOrb, entity_x(orbHolder), entity_y(orbHolder)) entity_setState(energyOrb, STATE_CHARGED) else --debugLog("NO ORB") end local door = node_getNearestEntity(me, "EnergyDoor") if door ~= 0 then --debugLog("setting door to open") entity_setState(door, STATE_OPENED) end end function activate(me) --[[ if getFlag(FLAG_ENERGYTEMPLE01DOOR)==0 then local energyOrb = node_getNearestEntity(me, "EnergyOrb") msg ("HERE") if energyOrb ~= 0 then msg("ENERGY ORB OUT") setFlag(FLAG_ENERGYTEMPLE01DOOR, entity_getID(energyOrb)) local door = node_getNearestEntity(me, "EnergyDoor") if door ~= 0 then entity_setState(door, STATE_OPEN) end else msg("NO ENERGY ORB") end end ]]-- end function update(me, dt) end
gpl-2.0
waytim/darkstar
scripts/globals/abilities/ninja_roll.lua
19
2510
----------------------------------- -- Ability: Ninja Roll -- Enhances evasion for party members within area of effect -- Optimal Job: Ninja -- Lucky Number: 4 -- Unlucky Number: 8 -- Jobs: -- Corsair Level 8 -- -- Die Roll |With NIN -- -------- ---------- -- 1 |+4 -- 2 |+6 -- 3 |+8 -- 4 |+25 -- 5 |+10 -- 6 |+12 -- 7 |+14 -- 8 |+2 -- 9 |+17 -- 10 |+20 -- 11 |+30 -- Bust |-10 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/ability"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = EFFECT_NINJA_ROLL ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; elseif atMaxCorsairBusts(player) then return MSGBASIC_CANNOT_PERFORM,0; else return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(caster,target,ability,action) if (caster:getID() == target:getID()) then corsairSetup(caster, ability, action, EFFECT_NINJA_ROLL, JOBS.NIN); end local total = caster:getLocalVar("corsairRollTotal") return applyRoll(caster,target,ability,action,total) end; function applyRoll(caster,target,ability,action,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {4, 5, 5, 14, 6, 7, 9, 2, 10, 11, 18, 6} local effectpower = effectpowers[total]; if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then effectpower = effectpower + 6 end if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_NINJA_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_EVA) == false) then ability:setMsg(422); elseif total > 11 then ability:setMsg(426); end return total; end
gpl-3.0
waytim/darkstar
scripts/globals/mobskills/Dragon_Breath.lua
34
1375
--------------------------------------------- -- Dragon Breath -- -- Description: Deals Fire damage to enemies within a fan-shaped area. -- Type: Breath -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown cone -- Notes: Used only by Fafnir, Nidhogg, Cynoprosopi, and Wyrm. Because of the high damage output from Fafnir/Nidhogg/Wyrm, it is usually avoided by -- standing on (or near) the wyrm's two front feet. Cynoprosopi's breath attack is much less painful. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/utils"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (target:isBehind(mob, 48) == true) then return 1; elseif (mob:AnimationSub() ~= 0) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local dmgmod = MobBreathMove(mob, target, 0.2, 1.25, ELE_FIRE, 1400); local angle = mob:getAngle(target); angle = mob:getRotPos() - angle; dmgmod = dmgmod * ((128-math.abs(angle))/128); dmgmod = utils.clamp(dmgmod, 50, 1600); local dmg = MobFinalAdjustments(dmgmod,mob,skill,target,MOBSKILL_BREATH,MOBPARAM_FIRE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
chrox/koreader
frontend/ui/wikipedia.lua
3
2599
local JSON = require("json") local DEBUG = require("dbg") --[[ -- Query wikipedia using Wikimedia Web API. -- http://en.wikipedia.org/w/api.php?action=query&prop=extracts&format=json&exintro=&explaintext=&redirects=&titles=hello --]] local Wikipedia = { wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_params = { action = "query", prop = "extracts", format = "json", exintro = "", explaintext = "", redirects = "", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain) local socket = require('socket') local url = require('socket.url') local http = require('socket.http') local https = require('ssl.https') local ltn12 = require('ltn12') local request, sink = {}, {} local query = "" self.wiki_params.exintro = intro and "" or nil self.wiki_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_params) do query = query .. k .. '=' .. v .. '&' end local parsed = url.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. url.escape(text) -- HTTP request request['url'] = url.build(parsed) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) DEBUG("request", request) http.TIMEOUT, https.TIMEOUT = 10, 10 local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) -- raise error message when network is unavailable if headers == nil then error("Network is unreachable") end if status ~= "HTTP/1.1 200 OK" then DEBUG("HTTP status not okay:", status) return end local content = table.concat(sink) if content ~= "" and string.sub(content, 1,1) == "{" then local ok, result = pcall(JSON.decode, content) if ok and result then DEBUG("wiki result", result) return result else DEBUG("error:", result) end else DEBUG("not JSON:", content) end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result then local query = result.query if query then return query.pages end end end return Wikipedia
agpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/bird_egg.lua
3
1083
----------------------------------------- -- ID: 4570 -- Item: Bird Egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 6 -- Magic 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4570); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 6); target:addMod(MOD_MP, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 6); target:delMod(MOD_MP, 6); end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c19007855.lua
2
4774
--Mechquipped Death Knight function c19007855.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,3,2) c:EnableReviveLimit() --atk local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e1:SetRange(LOCATION_MZONE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(c19007855.atkval) c:RegisterEffect(e1) --Disable local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_BATTLED) e2:SetCondition(c19007855.dscon) e2:SetOperation(c19007855.disop) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(19007855,0)) e3:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetCountLimit(1) e3:SetRange(LOCATION_MZONE) e3:SetCost(c19007855.cost) e3:SetTarget(c19007855.target) e3:SetOperation(c19007855.operation) c:RegisterEffect(e3) --special summon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(19007855,1)) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetType(EFFECT_TYPE_QUICK_O) e4:SetCode(EVENT_FREE_CHAIN) e4:SetHintTiming(0,TIMING_END_PHASE) e4:SetRange(LOCATION_MZONE) e4:SetCondition(c19007855.spcon) e4:SetCost(c19007855.spcost) e4:SetTarget(c19007855.sptg) e4:SetOperation(c19007855.spop) c:RegisterEffect(e4) end function c19007855.atkfilter(c) return c:IsFaceup() and c:IsSetCard(0xda3791) or c:IsSetCard(0xda3790) or c:IsCode(15914410) or c:IsCode(41309158) end function c19007855.atkval(e,c) return Duel.GetMatchingGroupCount(c19007855.atkfilter,c:GetControler(),LOCATION_MZONE,0,nil)*200 end function c19007855.dscon(e) return e:GetHandler():GetOverlayCount()~=0 end function c19007855.disop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local bc=c:GetBattleTarget() if bc and bc:IsStatus(STATUS_BATTLE_DESTROYED) and bc:IsType(TYPE_FLIP) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_DISABLE) e1:SetReset(RESET_EVENT+0x17a0000) bc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_DISABLE_EFFECT) e2:SetReset(RESET_EVENT+0x17a0000) bc:RegisterEffect(e2) end end function c19007855.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c19007855.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end if e:GetHandler():IsDefensePos() then Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,500) end end function c19007855.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end if Duel.Damage(1-tp,500,REASON_EFFECT)~=0 and Duel.IsExistingTarget(Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,nil)then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) then Duel.Destroy(tc,REASON_EFFECT) end end end function c19007855.spcon(e) return e:GetHandler():GetOverlayCount()==0 end function c19007855.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToExtraAsCost() end Duel.SendtoDeck(e:GetHandler(),nil,0,REASON_COST) end function c19007855.spfilter1(c,e,tp) return c:IsType(TYPE_MONSTER) and c:IsSetCard(0xda3791) or c:IsSetCard(0xda3790) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c19007855.spfilter2,tp,LOCATION_DECK,0,1,nil,e,tp,c:GetCode()) end function c19007855.spfilter2(c,e,tp,code) return c:IsType(TYPE_MONSTER) and c:IsSetCard(0xda3791) or c:IsSetCard(0xda3790) and not c:IsCode(code) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c19007855.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c19007855.spfilter1,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK) end function c19007855.spop(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsPlayerAffectedByEffect(tp,59822133) and Duel.GetLocationCount(tp,LOCATION_MZONE)>1 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g1=Duel.SelectMatchingCard(tp,c19007855.spfilter1,tp,LOCATION_DECK,0,1,1,nil,e,tp) if g1:GetCount()<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g2=Duel.SelectMatchingCard(tp,c19007855.spfilter2,tp,LOCATION_DECK,0,1,1,nil,e,tp,g1:GetFirst():GetCode()) g1:Merge(g2) Duel.SpecialSummon(g1,0,tp,tp,false,false,POS_FACEUP_ATTACK) end end
gpl-3.0
waytim/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Louxiard.lua
15
2494
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Louxiard -- @zone 80 -- @pos -93 -4 49 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then local mask = player:getVar("GiftsOfGriffonPlumes"); if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,1)) then player:startEvent(0x01A) -- Gifts of Griffon Trade end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCampaignAllegiance() > 0 and player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_AVAILABLE) then player:startEvent(0x015); -- Gifts of Griffon Quest Start elseif (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 0) then player:startEvent(0x016); -- Gifts of Griffon Stage 2 Cutscene elseif (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 1) then player:startEvent(0x027); -- Gifts of Griffon Stage 2 Dialogue else player:startEvent(0x025); -- Default Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x015) then player:addQuest(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON); -- Gifts of Griffon Quest Start elseif (csid == 0x016) then player:setVar("GiftsOfGriffonProg",1); -- Gifts of Griffon Stage 2 elseif (csid == 0x01A) then player:tradeComplete(); local mask = player:getVar("GiftsOfGriffonPlumes"); player:setMaskBit(mask,"GiftsOfGriffonPlumes",1,true); end end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c91536870.lua
2
1160
--Vocaloid Bruno and Clara function c91536870.initial_effect(c) c:SetUniqueOnField(1,0,91536870) --special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCondition(c91536870.spcon) c:RegisterEffect(e1) --nontuner local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_NONTUNER) c:RegisterEffect(e2) --ATK modify local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetRange(LOCATION_MZONE) e3:SetTargetRange(LOCATION_MZONE,0) e3:SetCode(EFFECT_UPDATE_ATTACK) e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x0dac402)) e3:SetValue(200) c:RegisterEffect(e3) end function c91536870.cfilter(tc) return tc and tc:IsFaceup() end function c91536870.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and (c91536870.cfilter(Duel.GetFieldCard(tp,LOCATION_SZONE,5)) or c91536870.cfilter(Duel.GetFieldCard(1-tp,LOCATION_SZONE,5))) end
gpl-3.0
waytim/darkstar
scripts/commands/checkvar.lua
38
1130
--------------------------------------------------------------------------------------------------- -- func: @checkvar <varType> <varName> -- desc: checks player or server variable and returns result value. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "ss" }; function onTrigger(player, varType, varName) if (varType == nil or varName == nil) then player:PrintToPlayer("Incorrect command syntax or missing paramters."); player:PrintToPlayer("@checkvar <player name or server> <variable name>"); return; end if (varType == "server") then player:PrintToPlayer(string.format("Server Variable '%s' : %u ", varName, GetServerVariable(varName))); else local targ = GetPlayerByName(varType); if (targ ~= nil) then player:PrintToPlayer(string.format("Player '%s' variable '%s' : %u ", varType, varName, targ:getVar(varName))); else player:PrintToPlayer(string.format( "Player named '%s' not found!", varType)); end end end
gpl-3.0
vashstorm/thrift
lib/lua/TBinaryProtocol.lua
90
6141
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you 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. -- require 'TProtocol' require 'libluabpack' require 'libluabitwise' TBinaryProtocol = __TObject.new(TProtocolBase, { __type = 'TBinaryProtocol', VERSION_MASK = -65536, -- 0xffff0000 VERSION_1 = -2147418112, -- 0x80010000 TYPE_MASK = 0x000000ff, strictRead = false, strictWrite = true }) function TBinaryProtocol:writeMessageBegin(name, ttype, seqid) if self.strictWrite then self:writeI32(libluabitwise.bor(TBinaryProtocol.VERSION_1, ttype)) self:writeString(name) self:writeI32(seqid) else self:writeString(name) self:writeByte(ttype) self:writeI32(seqid) end end function TBinaryProtocol:writeMessageEnd() end function TBinaryProtocol:writeStructBegin(name) end function TBinaryProtocol:writeStructEnd() end function TBinaryProtocol:writeFieldBegin(name, ttype, id) self:writeByte(ttype) self:writeI16(id) end function TBinaryProtocol:writeFieldEnd() end function TBinaryProtocol:writeFieldStop() self:writeByte(TType.STOP); end function TBinaryProtocol:writeMapBegin(ktype, vtype, size) self:writeByte(ktype) self:writeByte(vtype) self:writeI32(size) end function TBinaryProtocol:writeMapEnd() end function TBinaryProtocol:writeListBegin(etype, size) self:writeByte(etype) self:writeI32(size) end function TBinaryProtocol:writeListEnd() end function TBinaryProtocol:writeSetBegin(etype, size) self:writeByte(etype) self:writeI32(size) end function TBinaryProtocol:writeSetEnd() end function TBinaryProtocol:writeBool(bool) if bool then self:writeByte(1) else self:writeByte(0) end end function TBinaryProtocol:writeByte(byte) local buff = libluabpack.bpack('c', byte) self.trans:write(buff) end function TBinaryProtocol:writeI16(i16) local buff = libluabpack.bpack('s', i16) self.trans:write(buff) end function TBinaryProtocol:writeI32(i32) local buff = libluabpack.bpack('i', i32) self.trans:write(buff) end function TBinaryProtocol:writeI64(i64) local buff = libluabpack.bpack('l', i64) self.trans:write(buff) end function TBinaryProtocol:writeDouble(dub) local buff = libluabpack.bpack('d', dub) self.trans:write(buff) end function TBinaryProtocol:writeString(str) -- Should be utf-8 self:writeI32(string.len(str)) self.trans:write(str) end function TBinaryProtocol:readMessageBegin() local sz, ttype, name, seqid = self:readI32() if sz < 0 then local version = libluabitwise.band(sz, TBinaryProtocol.VERSION_MASK) if version ~= TBinaryProtocol.VERSION_1 then terror(TProtocolException:new{ message = 'Bad version in readMessageBegin: ' .. sz }) end ttype = libluabitwise.band(sz, TBinaryProtocol.TYPE_MASK) name = self:readString() seqid = self:readI32() else if self.strictRead then terror(TProtocolException:new{message = 'No protocol version header'}) end name = self.trans:readAll(sz) ttype = self:readByte() seqid = self:readI32() end return name, ttype, seqid end function TBinaryProtocol:readMessageEnd() end function TBinaryProtocol:readStructBegin() return nil end function TBinaryProtocol:readStructEnd() end function TBinaryProtocol:readFieldBegin() local ttype = self:readByte() if ttype == TType.STOP then return nil, ttype, 0 end local id = self:readI16() return nil, ttype, id end function TBinaryProtocol:readFieldEnd() end function TBinaryProtocol:readMapBegin() local ktype = self:readByte() local vtype = self:readByte() local size = self:readI32() return ktype, vtype, size end function TBinaryProtocol:readMapEnd() end function TBinaryProtocol:readListBegin() local etype = self:readByte() local size = self:readI32() return etype, size end function TBinaryProtocol:readListEnd() end function TBinaryProtocol:readSetBegin() local etype = self:readByte() local size = self:readI32() return etype, size end function TBinaryProtocol:readSetEnd() end function TBinaryProtocol:readBool() local byte = self:readByte() if byte == 0 then return false end return true end function TBinaryProtocol:readByte() local buff = self.trans:readAll(1) local val = libluabpack.bunpack('c', buff) return val end function TBinaryProtocol:readI16() local buff = self.trans:readAll(2) local val = libluabpack.bunpack('s', buff) return val end function TBinaryProtocol:readI32() local buff = self.trans:readAll(4) local val = libluabpack.bunpack('i', buff) return val end function TBinaryProtocol:readI64() local buff = self.trans:readAll(8) local val = libluabpack.bunpack('l', buff) return val end function TBinaryProtocol:readDouble() local buff = self.trans:readAll(8) local val = libluabpack.bunpack('d', buff) return val end function TBinaryProtocol:readString() local len = self:readI32() local str = self.trans:readAll(len) return str end TBinaryProtocolFactory = TProtocolFactory:new{ __type = 'TBinaryProtocolFactory', strictRead = false } function TBinaryProtocolFactory:getProtocol(trans) -- TODO Enforce that this must be a transport class (ie not a bool) if not trans then terror(TProtocolException:new{ message = 'Must supply a transport to ' .. ttype(self) }) end return TBinaryProtocol:new{ trans = trans, strictRead = self.strictRead, strictWrite = true } end
apache-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/weaponskills/retribution.lua
4
1502
----------------------------------- -- Retribution -- Staff weapon skill -- Skill Level: 230 -- Delivers a single-hit attack. Damage varies with TP. -- In order to obtain Retribution, the quest Blood and Glory must be completed. -- Despite the appearance of throwing the staff, this is not a long-range Weapon Skill like Mistral Axe. -- The range only extends the usual 1 yalm beyond meleeing range. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget, Soil Gorget & Aqua Gorget. -- Aligned with the Shadow Belt, Soil Belt & Aqua Belt. -- Element: None -- Modifiers: STR:30% ; MND:50% -- 100%TP 200%TP 300%TP -- 2.00 2.50 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 2; params.ftp200 = 2.5; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.5; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
waytim/darkstar
scripts/zones/Kazham/npcs/Mitti_Haplihza.lua
15
1054
----------------------------------- -- Area: Kazham -- NPC: Mitti Haplihza -- 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(0x00B8); -- scent from Blue Rafflesias else player:startEvent(0x005E); 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
wanmaple/MWFrameworkForCocosLua
frameworks/runtime-src/Framework/lua/auto/api/MWZipData.lua
1
3007
-------------------------------- -- @module MWZipData -- @extend MWObject -- @parent_module mw -------------------------------- -- Get the total raw data of the compressed file.<br> -- param compressedFile Compressed file path.<br> -- password The compressed password if required. -- @function [parent=#MWZipData] getCompressedFileData -- @param self -- @param #string compressedFile -- @return MWBinaryData#MWBinaryData ret (return value: mw.MWBinaryData) -------------------------------- -- Compress new file into the zip.<br> -- param name The compressed file name.<br> -- param fileData The data to compress.<br> -- param Add a password if desired.<br> -- param level Compressed level 0-9. -- @function [parent=#MWZipData] zipNewFile -- @param self -- @param #string name -- @param #mw.MWBinaryData fileData -- @param #int level -- @return bool#bool ret (return value: bool) -------------------------------- -- Prepare to unzip from the zip.<br> -- note You have to call this before using "getCompressedFileData", otherwise you will failed to get the correct data. -- @function [parent=#MWZipData] beginUnzip -- @param self -------------------------------- -- Stop to do unzip operations.<br> -- note Don't forget to end after all unzip operations are done, otherwise you will failed to do other operations after that. -- @function [parent=#MWZipData] endUnzip -- @param self -------------------------------- -- Prepare to zip new file to the zip.<br> -- note You have to call this before using "zipNewFile", otherwise you will failed to add the data to the zip. -- @function [parent=#MWZipData] beginZip -- @param self -------------------------------- -- Stop to do zip operations.<br> -- note Don't forget to end after all zip operations are done, otherwise you will failed to do other operations after that. -- @function [parent=#MWZipData] endZip -- @param self -------------------------------- -- Wrapper the zip data from the file and password if required.<br> -- param filePath The zip file path.<br> -- param password Zip password. -- @function [parent=#MWZipData] createWithExistingFile -- @param self -- @param #string filePath -- @param #string password -- @return MWZipData#MWZipData ret (return value: mw.MWZipData) -------------------------------- -- Create an empty zip.<br> -- param filePath The zip file path to create.<br> -- param password Zip password. -- @function [parent=#MWZipData] createWithNewFile -- @param self -- @param #string filePath -- @param #string password -- @return MWZipData#MWZipData ret (return value: mw.MWZipData) -------------------------------- -- Wrapper the zip data from raw data.<br> -- param rawData The zip file data.<br> -- param password Zip password. -- @function [parent=#MWZipData] createWithBinaryData -- @param self -- @param #mw.MWBinaryData rawData -- @param #string password -- @return MWZipData#MWZipData ret (return value: mw.MWZipData) return nil
apache-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/danceshroom.lua
3
1099
----------------------------------------- -- ID: 4375 -- Item: danceshroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -5 -- Dexterity 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4375); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -5); target:addMod(MOD_DEX, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -5); target:delMod(MOD_DEX, 3); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Western_Altepa_Desert/npcs/Sapphire_Column.lua
2
1659
----------------------------------- -- Area: Western Altepa Desert -- NPC: Sapphire Column -- Mechanism for Altepa Gate -- @pos -499 10 224 125 ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Ruby = GetNPCByID(17289740):getAnimation(); Topaz = GetNPCByID(17289741):getAnimation(); Emerald = GetNPCByID(17289742):getAnimation(); Sapphire = GetNPCByID(17289743):getAnimation(); if(Sapphire ~= 8) then GetNPCByID(17289743):setAnimation(8); end if(Emerald == 8 and Ruby == 8 and Topaz == 8) then rand = math.random(15,30); timeDoor = rand * 60; -- Add timer for the door GetNPCByID(17289739):openDoor(timeDoor); -- Add same timer for the 4 columns GetNPCByID(17289740):openDoor(timeDoor); GetNPCByID(17289741):openDoor(timeDoor); GetNPCByID(17289742):openDoor(timeDoor); GetNPCByID(17289743):openDoor(timeDoor); 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
X-Raym/REAPER-ReaScripts
Items Properties/X-Raym_Set selected items active take sources offline.lua
1
1877
--[[ * ReaScript Name: Set selected items active take sources offline * Author: X-Raym * Author URI: https://www.extremraym.com * Repository: GitHub > X-Raym > REAPER-ReaScripts * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts * Forum Thread: Online / Offline takes * Forum Thread URI: https://forum.cockos.com/showthread.php?p=2154446#post2154446 * Licence: GPL v3 * REAPER: 5.0 * Version: 1.0 --]] --[[ * Changelog: * v1.0 (2019-07-06) + Initial release --]] -- USER CONFIG AREA ----------------------------------------------------------- console = false -- true/false: display debug messages in the console ------------------------------------------------------- END OF USER CONFIG AREA -- UTILITIES ------------------------------------------------------------- local reaper = reaper -- Display a message in the console for debugging function Msg(value) if console then reaper.ShowConsoleMsg(tostring(value) .. "\n") end end --------------------------------------------------------- END OF UTILITIES -- Main function function Main() for i = 0, count_selected_items - 1 do local item = reaper.GetSelectedMediaItem( 0, i ) local active_take = reaper.GetActiveTake( item ) if active_take then local src = reaper.GetMediaItemTake_Source( active_take ) reaper.CF_SetMediaSourceOnline( src, false ) end end end -- INIT -- See if there is items selected count_selected_items = reaper.CountSelectedMediaItems(0) if count_selected_items > 0 then reaper.PreventUIRefresh(1) reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function. Main() reaper.Undo_EndBlock("Set selected items active take sources offline", -1) -- End of the undo block. Leave it at the bottom of your main function. reaper.UpdateArrange() reaper.PreventUIRefresh(-1) end
gpl-3.0
waytim/darkstar
scripts/globals/effects/aftermath_lv1.lua
30
1130
----------------------------------- -- -- EFFECT_AFTERMATH_LV1 -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); if (effect:getSubPower() == 1) then target:addMod(MOD_ACC,power); elseif (effect:getSubPower() == 2) then target:addMod(MOD_MACC,power) elseif (effect:getSubPower() == 3) then target:addMod(MOD_RACC,power) end end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); if (effect:getSubPower() == 1) then target:delMod(MOD_ACC,power); elseif (effect:getSubPower() == 2) then target:delMod(MOD_MACC,power) elseif (effect:getSubPower() == 3) then target:delMod(MOD_RACC,power) end end;
gpl-3.0
narner/Soundpipe
modules/data/randi.lua
2
1462
sptbl["randi"] = { files = { module = "randi.c", header = "randi.h", example = "ex_randi.c", }, func = { create = "sp_randi_create", destroy = "sp_randi_destroy", init = "sp_randi_init", compute = "sp_randi_compute", }, params = { optional = { { name = "min", type = "SPFLOAT", description = "Minimum value", default = 0 }, { name = "max", type = "SPFLOAT", description ="Maximum value", default = 1 }, { name = "cps", type = "SPFLOAT", description ="Frequency to change values.", default = 3 }, { name = "mode", type = "SPFLOAT", description = "Randi mode (not yet implemented yet.)", default = 0, irate = true }, } }, modtype = "module", description = [[Line segments between random values within a range]], ninputs = 0, noutputs = 1, inputs = { { name = "dummy", description = "This doesn't do anything." }, }, outputs = { { name = "out", description = "Signal out." }, } }
mit
TienHP/Aquaria
files/scripts/entities/_unused/minicrab.lua
6
3466
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- K I N G C R A B -- ================================================================================================ -- ================================================================================================ -- L O C A L V A R I A B L E S -- ================================================================================================ v.fireDelay = 2 -- ================================================================================================ -- FUNCTIONS -- ================================================================================================ function init() setupBasicEntity( "kingcrab-head", -- texture 20, -- health 2, -- manaballamount 2, -- exp 1, -- money 64, -- collideRadius (for hitting entities + spells) STATE_IDLE, -- initState 256, -- sprite width 256, -- sprite height 1, -- particle "explosion" type, maps to particleEffects.txt -1 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 4000 -- updateCull -1: disabled, default: 4000 ) --entity_offset(0, 128) -- entity_initPart(partName, partTexture, partPosition, partFlipH, partFlipV, -- partOffsetInterpolateTo, partOffsetInterpolateTime entity_initPart( "ClawLeft", "kingcrab-claw", -64, -48, 0, 1, 0) entity_initPart( "ClawRight", "kingcrab-claw", 64, -48, 0, 0, 0) entity_initPart("LegsLeft", "kingcrab-leg", -64, 48, 0, 1, 0) entity_initPart("LegsRight", "kingcrab-leg", 64, 48, 0, 0, 0) entity_partRotate("ClawLeft", -32, 0.5, -1, 1, 1); entity_partRotate("ClawRight", 32, 0.5, -1, 1, 1); entity_partRotate("LegsLeft", 16, 0.25, -1, 1, 1); entity_partRotate("LegsRight", -16, 0.25, -1, 1, 1); entity_scale(0.5, 0.5) entity_clampToSurface() end function update(dt) -- dt, pixelsPerSecond, climbHeight, outfromwall entity_moveAlongSurface(dt, 100, 6, 54) --64 (32) entity_rotateToSurfaceNormal(0.1) if not(entity_hasTarget()) then entity_findTarget(1200) else if entity_isTargetInRange(64) then entity_pushTarget(500) end if v.fireDelay > 0 then v.fireDelay = v.fireDelay - dt if v.fireDelay < 0 then -- FIXME: obsolete function -- dmg, mxspd, homing, numsegs, out --entity_fireAtTarget(1, 1000, 200, 3, 64) v.fireDelay = 5 end end end end function enterState() if entity_getState()==STATE_IDLE then end end function exitState() end function hitSurface() end
gpl-2.0
ld-test/zipwriter
utils/mkarch.lua
3
2280
local IS_WINDOWS = package.config:sub(1,1) == '\\' local ZipWriter = require "ZipWriter" local PATH = require "path" local TEXT_EXT = {".lua", ".txt", ".c", ".cpp", ".h", ".hpp", ".pas", ".cxx", ".me"} local function isin(s, t) local s = s:lower() for _, v in ipairs(t) do if s == v then return true end end end local function make_file_desc(path) local fullpath = PATH.fullpath(path) local desc = {} desc.isfile = PATH.isfile(fullpath) desc.isdir = PATH.isdir(fullpath) if not (desc.isfile or desc.isdir) then error('file not found :' .. path .. ' (' .. fullpath .. ')') end desc.mtime = PATH.mtime(fullpath) desc.ctime = PATH.ctime(fullpath) desc.atime = PATH.atime(fullpath) local ext = desc.isfile and PATH.extension(fullpath) desc.istext = ext and isin(ext, TEXT_EXT) desc.exattrib = PATH.fileattrib and PATH.fileattrib(fullpath) return desc end local function file_reader(path, chunk_size) local desc = assert(make_file_desc(path)) local f = desc.isfile and assert(io.open(path, 'rb')) chunk_size = chunk_size or 4096 return desc, desc.isfile and function() local chunk = f:read(chunk_size) if chunk then return chunk end f:close() end end local function file_writer(path) local f = assert(io.open(path, 'wb+')) return function(chunk) if not chunk then return f:close() end f:write(chunk) end ,function(...) return f:seek(...) end end io.stdout:setvbuf'no' local oFile = assert(arg[1]) local mask = arg[2] or "*.*" local mask = PATH.fullpath(mask) local base = PATH.dirname(mask) if PATH.extension(oFile):lower() ~= '.zip' then oFile = oFile .. '.zip' end local files = {} PATH.each(mask, function(fullpath) local relpath = string.sub(fullpath, #base + 1) table.insert(files,{fullpath, relpath}) end,{recurse=true;skipdirs=true}) writer = ZipWriter.new{ level = ZipWriter.COMPRESSION_LEVEL.DEFAULT; zip64 = false; utf8 = false; } writer:open_writer(file_writer(oFile)) for _, t in ipairs(files) do local fullpath,fileName = t[1],t[2] io.write("Add : " .. fileName .. ' (' .. fullpath .. ')') writer:write(fileName, file_reader(fullpath)) io.write(' OK!\n') end writer:close()
mit
Sertex-Team/sPhone
src/init.lua
3
4702
os.oldPullEvent = os.pullEvent os.pullEvent = os.pullEventRaw local function crash(err) if not sPhone then sPhone = { devMode = false, } end term.setCursorBlink(false) term.setBackgroundColor(colors.white) term.clear() term.setCursorPos(1,1) term.setTextColor(colors.black) if not err then err = "Undefined Error" end print("sPhone got an error :(\n") term.setTextColor(colors.red) print(err) term.setTextColor(colors.black) print("") if sPhone.version then print("sPhone "..sPhone.version) end print("Computer ID: "..os.getComputerID()) if _CC_VERSION then print("CC Version: ".._CC_VERSION) print("MC Version: ".._MC_VERSION) elseif _HOST then print("Host: ".._HOST) else print("CC Version: Under 1.74") print("MC Version: Undefined") term.setTextColor(colors.red) print("Update CC to 1.74 or higher") term.setTextColor(colors.black) end print("LUA Version: ".._VERSION) if _LUAJ_VERSION then print("LUAJ Version: ".._LUAJ_VERSION) end print("Contact sPhone devs:") print("GitHub: SertexTeam/sPhone") print("Thanks for using sPhone") print("Press any key") repeat sleep(0) until os.pullEvent("key") if not sPhone.devMode then _G.term = nil end term.setBackgroundColor(colors.black) term.clear() term.setCursorPos(1,1) sleep(0.1) shell.run("/rom/programs/shell") end local function recovery() term.setBackgroundColor(colors.white) term.setTextColor(colors.black) term.clear() term.setCursorPos(1,1) print("sPhone Recovery") print("[1] Hard Reset") print("[2] Update sPhone") print("[3] Reset User Config") print("[4] Continue Booting") print("[5] Boot in safe mode") while true do local _, k = os.pullEvent("key") if k == 2 then term.setBackgroundColor(colors.black) term.setTextColor(colors.white) for k, v in pairs(fs.list("/")) do if not fs.isReadOnly(v) then if fs.isDir(v) then shell.setDir(v) for k, v in pairs(fs.list("/"..v)) do fs.delete(v) print("Removed "..shell.dir().."/"..v) end shell.setDir(shell.resolve("..")) end fs.delete(v) print("Removed "..v) end end print("Installing sPhone...") sleep(0.5) setfenv(loadstring(http.get("https://raw.githubusercontent.com/SertexTeam/sPhone/master/src/installer.lua").readAll()),getfenv())() elseif k == 3 then setfenv(loadstring(http.get("https://raw.githubusercontent.com/SertexTeam/sPhone/master/src/installer.lua").readAll()),getfenv())() elseif k == 4 then fs.delete("/.sPhone/config") fs.delete("/.sPhone/cache") fs.delete("/.sPhone/apps/spk") fs.delete("/.sPhone/autorun") os.reboot() elseif k == 5 then safemode = false break elseif k == 6 then safemode = true break end end end term.setBackgroundColor(colors.white) term.setCursorPos(1,1) term.clear() term.setTextColor(colors.black) print("Sertex") if fs.exists("/.sPhone/interfaces/bootImage") then local bootImage = paintutils.loadImage("/.sPhone/interfaces/bootImage") paintutils.drawImage(bootImage, 11,7) else print("Missing bootImage") end local w, h = term.getSize() term.setBackgroundColor(colors.white) term.setTextColor(colors.black) term.setCursorPos(1,h) write("Press ALT to recovery mode") local bootTimer = os.startTimer(1) while true do local e,k = os.pullEvent() if e == "key" and k == 56 then recovery() break elseif e == "timer" and k == bootTimer then safemode = false break end end if not fs.exists("/.sPhone/sPhone") then printError("sPhone not installed") shell.run("/.sPhone/init -u") return end local runningOnStartup term.setBackgroundColor(colors.black) term.clear() term.setCursorPos(1,1) term.setTextColor(colors.white) if sPhone then printError("sPhone already started") return end if not pocket or not term.isColor() then printError("Computer not supported: use an Advanced Pocket Computer or an Advanced Wireless Pocket Computer") return end local tArgs = {...} local argData = { ["-u"] = false, ["-s"] = false, } if #tArgs > 0 then while #tArgs > 0 do local tArgs = table.remove(tArgs, 1) if argData[tArgs] ~= nil then argData[tArgs] = true end end end if argData["-u"] then print("Getting installer...") setfenv(loadstring(http.get("https://raw.githubusercontent.com/SertexTeam/sPhone/master/src/installer.lua").readAll()),getfenv())() end os.pullEvent = os.oldPullEvent local ok, err = pcall(function() setfenv(loadfile("/.sPhone/sPhone"), setmetatable({ crash = crash, safemode = safemode, }, {__index = getfenv()}))() end) if not ok then crash(err) end _G.term = nil -- The OS ends here - This string force to crash the pda to shutdown
mit
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Aht_Urhgan_Whitegate/npcs/Malfud.lua
2
1217
----------------------------------- -- Area: Aht Urhfan Whitegate -- NPC: Malfud -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); 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:showText(npc,MALFUD_SHOP_DIALOG); stock = {0x03A8,16, -- Rock Salt 0x0272,255, -- Black Pepper 0x0279,16, -- Olive Oil 0x1124,44, -- Eggplant 0x1126,40, -- Mithran Tomato 0x08A5,12} -- Pine Nuts showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
forcecore/OpenRA
mods/d2k/maps/ordos-02b/ordos02b-AI.lua
20
2890
--[[ Copyright 2007-2017 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] IdlingUnits = { } AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(9) }, normal = { DateTime.Seconds(2), DateTime.Seconds(7) }, hard = { DateTime.Seconds(1), DateTime.Seconds(5) } } HarkonnenInfantryTypes = { "light_inf" } AttackOnGoing = false HoldProduction = false HarvesterKilled = true IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end SetupAttackGroup = function() local units = { } for i = 0, AttackGroupSize[Map.LobbyOption("difficulty")], 1 do if #IdlingUnits == 0 then return units end local number = Utils.RandomInteger(1, #IdlingUnits + 1) if IdlingUnits[number] and not IdlingUnits[number].IsDead then units[i] = IdlingUnits[number] table.remove(IdlingUnits, number) end end return units end SendAttack = function() if Attacking then return end Attacking = true HoldProduction = true local units = SetupAttackGroup() Utils.Do(units, function(unit) IdleHunt(unit) end) Trigger.OnAllRemovedFromWorld(units, function() Attacking = false HoldProduction = false end) end DefendActor = function(unit) Trigger.OnDamaged(unit, function(self, attacker) if AttackOnGoing then return end AttackOnGoing = true local Guards = SetupAttackGroup() if #Guards <= 0 then AttackOnGoing = false return end Utils.Do(Guards, function(unit) if not self.IsDead then unit.AttackMove(self.Location) end IdleHunt(unit) end) Trigger.OnAllRemovedFromWorld(Guards, function() AttackOnGoing = false end) end) end InitAIUnits = function() Utils.Do(HarkonnenBase, function(actor) DefendActor(actor) Trigger.OnDamaged(actor, function(building) if building.Health < building.MaxHealth * 3/4 then building.StartBuildingRepairs() end end) end) end ProduceInfantry = function() if HBarracks.IsDead then return end if HoldProduction then Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry) return end local delay = Utils.RandomInteger(AttackDelays[Map.LobbyOption("difficulty")][1], AttackDelays[Map.LobbyOption("difficulty")][2] + 1) local toBuild = { Utils.Random(HarkonnenInfantryTypes) } harkonnen.Build(toBuild, function(unit) IdlingUnits[#IdlingUnits + 1] = unit[1] Trigger.AfterDelay(delay, ProduceInfantry) if #IdlingUnits >= (AttackGroupSize[Map.LobbyOption("difficulty")] * 2.5) then SendAttack() end end) end ActivateAI = function() InitAIUnits() ProduceInfantry() end
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Alphollon_C_Meriard.lua
4
3095
----------------------------------- -- Area: Northern San d'Oria -- NPC: Alphollon C Meriard -- Type: Purifies cursed items with their corresponding abjurations. -- @zone: 231 -- @pos 98.108 -1 137.999 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:getItemCount() == 2) then -- abjuration, item, item -1, reward, reward +1 abjuList = {1314,1344,1345,13934,13935, 1315,1346,1347,14387,14388, 1316,1348,1349,14821,14822, 1317,1350,1351,14303,14304, 1318,1352,1353,14184,14185, 1319,1354,1355,12429,13924, 1320,1356,1357,12557,14371, 1321,1358,1359,12685,14816, 1322,1360,1361,12813,14296, 1323,1362,1363,12941,14175, 1324,1364,1365,13876,13877, 1325,1366,1367,13787,13788, 1326,1368,1369,14006,14007, 1327,1370,1371,14247,14248, 1328,1372,1373,14123,14124, 1329,1374,1375,12421,13911, 1330,1376,1377,12549,14370, 1331,1378,1379,12677,14061, 1332,1380,1381,12805,14283, 1333,1382,1383,12933,14163, 1334,1384,1385,13908,13909, 1335,1386,1387,14367,14368, 1336,1388,1389,14058,14059, 1337,1390,1391,14280,14281, 1338,1392,1393,14160,14161, 1339,1394,1395,13927,13928, 1340,1396,1397,14378,14379, 1341,1398,1399,14076,14077, 1342,1400,1401,14308,14309, 1343,1402,1403,14180,14181, 2429,2439,2440,16113,16114, 2430,2441,2442,14573,14574, 2431,2443,2444,14995,14996, 2432,2445,2446,15655,15656, 2433,2447,2448,15740,15741, 2434,2449,2450,16115,16116, 2435,2451,2452,14575,14576, 2436,2453,2454,14997,14998, 2437,2455,2456,15657,15658, 2438,2457,2458,15742,15743}; item = 0; reward = 0; for i = 1,table.getn(abjuList),5 do if(trade:hasItemQty(abjuList[i],1)) then if(trade:hasItemQty(abjuList[i + 1],1)) then item = abjuList[i + 1]; reward = abjuList[i + 3]; elseif(trade:hasItemQty(abjuList[i + 2],1)) then item = abjuList[i + 2]; reward = abjuList[i + 4]; end break; end end if (reward ~= 0) then --Trade pair for a nice reward. player:startEvent(0x02d0,item,reward); player:setVar("reward",reward); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02cf); 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 == 0x02d0 and player:getVar("reward") ~= 0) then reward = player:getVar("reward"); player:tradeComplete(); player:addItem(reward); player:messageSpecial(ITEM_OBTAINED,reward); player:setVar("reward",0); end end;
gpl-3.0
TienHP/Aquaria
files/scripts/maps/_unused/node_energyboss_done.lua
6
1348
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end v.naija = 0 function init(me) node_setCursorActivation(me, false) v.naija = getNaija() -- kill the boss if he shouldn't be there anymore if getStory() > 8 then debugLog("killing boss?") local energyBoss = getEntity("EnergyBoss") if energyBoss ~= 0 then entity_delete(energyBoss) end end end function activate(me) end function update(me, dt) if getStory() <= 8 then if node_isEntityIn(me, v.naija) then setStory(9) end end end
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c1013043.lua
2
2952
--Fiend's Hand (Pendulum) function c1013043.initial_effect(c) --Pendulum Set aux.EnablePendulumAttribute(c) --[[ aux.AddPendulumProcedure(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1)]]-- --Destroy local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DESTROY+CATEGORY_REMOVE) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetRange(LOCATION_PZONE) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCountLimit(1,1013043) e1:SetTarget(c1013043.target) e1:SetOperation(c1013043.activate) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_DESTROY+CATEGORY_REMOVE) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) e2:SetRange(LOCATION_PZONE) e2:SetCountLimit(1,1013043) e2:SetTarget(c1013043.target) e2:SetOperation(c1013043.activate) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetCategory(CATEGORY_DESTROY+CATEGORY_REMOVE) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_SPSUMMON_SUCCESS) e3:SetRange(LOCATION_PZONE) e3:SetCountLimit(1,1013043) e3:SetTarget(c1013043.target2) e3:SetOperation(c1013043.activate2) c:RegisterEffect(e3) end function c1013043.filter(c,tp,ep) return c:IsLocation(LOCATION_MZONE) and c:IsFaceup() and c:GetAttack()>=2000 and ep~=tp and c:IsDestructable() and c:IsAbleToRemove() end function c1013043.target(e,tp,eg,ep,ev,re,r,rp,chk) local tc=eg:GetFirst() if chk==0 then return c1013043.filter(tc,tp,ep) end Duel.SetTargetCard(eg) Duel.SetOperationInfo(0,CATEGORY_DESTROY,tc,1,0,0) Duel.SetOperationInfo(0,CATEGORY_REMOVE,tc,1,0,0) end function c1013043.activate(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=eg:GetFirst() if tc and tc:IsRelateToEffect(e) and c:IsRelateToEffect(e) and tc:IsFaceup() and tc:GetAttack()>=2000 and Duel.Destroy(c,REASON_EFFECT)>0 then Duel.Destroy(tc,REASON_EFFECT,LOCATION_REMOVED) end end function c1013043.filter2(c,tp) return c:IsLocation(LOCATION_MZONE) and c:IsFaceup() and c:GetAttack()>=2000 and c:GetSummonPlayer()~=tp and c:IsDestructable() and c:IsAbleToRemove() end function c1013043.target2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c1013043.filter2,1,nil,tp) end local g=eg:Filter(c1013043.filter2,nil,tp) Duel.SetTargetCard(eg) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0) end function c1013043.filter3(c,e,tp) return c:IsFaceup() and c:GetAttack()>=2000 and c:GetSummonPlayer()~=tp and c:IsRelateToEffect(e) and c:IsLocation(LOCATION_MZONE) and c:IsDestructable() end function c1013043.activate2(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local g=eg:Filter(c1013043.filter3,nil,e,tp) if g:GetCount()>0 and c:IsRelateToEffect(e) and Duel.Destroy(c,REASON_EFFECT) then Duel.Destroy(g,REASON_EFFECT,LOCATION_REMOVED) end end
gpl-3.0
X-Raym/REAPER-ReaScripts
MIDI Editor/X-Raym_Export active take in MIDI editor as CSV of notes and velocity.lua
1
2543
--[[ * ReaScript Name: Export active take in MIDI editor as CSV of notes and velocity * About: Designed for my MIDI CSV as notes sequence JSFX. * Author: X-Raym * Author URI: https://www.extremraym.com * Links: Forum Thread http://forum.cockos.com/showthread.php?t=181105 * Licence: GPL v3 * REAPER: 5.0 * Version: 2.0 --]] --[[ * Changelog: * v2.0 (2017-09-26) # Change CSV separator from . to , This is not compatible with v1 workflow + Added channel infos + Prevent muted notes to be exported * v1.0.1 (2017-09-26) # Fix MacOS folder creation issue * v1.0 (2016-09-19) + Initial Release --]] local reaper = reaper notes_array = {} function Main( take ) retval, notes, ccs, sysex = reaper.MIDI_CountEvts( take ) -- GET SELECTED NOTES (from 0 index) for k = 0, notes - 1 do local retval, sel, muted, startppq, endppq, chan, pitch, vel = reaper.MIDI_GetNote( take, k ) if not muted then notes_array[k+1] = {} notes_array[k+1].pitch = pitch notes_array[k+1].vel = vel notes_array[k+1].chan = chan end end end function export() -- OS BASED SEPARATOR if reaper.GetOS() == "Win32" or reaper.GetOS() == "Win64" then slash = "\\" else slash = "/" end resource = reaper.GetResourcePath() file_name = reaper.GetTakeName( take ) dir_name = resource .. slash .. "Data" .. slash .. "MIDI Sequences" reaper.RecursiveCreateDirectory(dir_name, 0) file = dir_name .. slash .. file_name .. ".txt" -- CREATE THE FILE f = io.open(file, "w") io.output(f) --Msg(file) for i, note in ipairs(notes_array) do f:write( tostring( note.pitch .. "," .. note.vel .. "," .. note.chan ) ) if i == #notes_array then break end f:write("\n") end f:close() -- never forget to close the file Msg("File exported: " .. file) end function Msg(g) reaper.ShowConsoleMsg(tostring(g).."\n") end ------------------------------- -- INIT ------------------------------- midi_editor = reaper.MIDIEditor_GetActive() if not midi_editor then return end take = reaper.MIDIEditor_GetTake( midi_editor ) if take then reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function. Main( take ) -- Execute your main function export() reaper.Undo_EndBlock("Export active take in MIDI editor as CSV of notes and velocity", 0) -- End of the undo block. Leave it at the bottom of your main function. reaper.UpdateArrange() -- Update the arrangement (often needed) end -- ENDIF Take is MIDI
gpl-3.0
waytim/darkstar
scripts/zones/Beaucedine_Glacier_[S]/npcs/Watchful_Pixie.lua
13
1073
----------------------------------- -- Area: Beaucedine Glacier (S) -- NPC: Watchful Pixie -- Type: Quest NPC -- @zone: 136 -- @pos -56.000 -1.3 -392.000 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0fa2); 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
TheOnePharaoh/YGOPro-Custom-Cards
script/c59821133.lua
2
1331
--Action Card - Guardian Angel function c59821133.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_FREE_CHAIN) e1:SetHintTiming(TIMING_DAMAGE_STEP) e1:SetCondition(c59821133.condition) e1:SetOperation(c59821133.activate) c:RegisterEffect(e1) --act in hand local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_QP_ACT_IN_NTPHAND) e2:SetCondition(c59821133.handcon) c:RegisterEffect(e2) end function c59821133.handcon(e) return tp~=Duel.GetTurnPlayer() end function c59821133.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated() end function c59821133.activate(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_AVOID_BATTLE_DAMAGE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetValue(1) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetReset(RESET_PHASE+PHASE_END) e2:SetValue(1) Duel.RegisterEffect(e2,tp) end
gpl-3.0
zorfmorf/loveprojects
graph/main.lua
1
3945
require "node" nodeamount = 10 -- can never be < 3 noderotate = math.pi / 32 xshift= love.graphics.getWidth() / 2 yshift = love.graphics.getHeight() / 2 -- rotate node1 around node2 by the given angle (in radians) function rotateNode(node1, node2, angle) local c = math.cos(angle) local s = math.sin(angle) --translate to origin local x = node2.x - node1.x local y = node2.y - node1.y local xn = x * c - y * s local yn = x * s + y * c xn = xn + node1.x yn = yn + node1.y node2.x = xn node2.y = yn end function love.load() math.randomseed(os.time()) nodes = {} nodesNew = {} -- first generate a couple of random circles for i = 1,nodeamount do local node = Node:new() node.id = i -- so we can recreate the order later node.radius = math.random(5, 150) node.x = 1000 node.y = 1000 nodes[i] = node end -- sort by radius table.sort(nodes, function(x,y) return x.radius > y.radius end ) -- now try to position them correctly -- lets start with the first three, its easy for them -- first one in center of screen nodes[1].x = 0 nodes[1].y = 0 nodesNew[1] = nodes[1] --second one is to the right nodes[2].x = nodes[1].x + nodes[1].radius + nodes[2].radius nodes[2].y = nodes[1].y nodesNew[2] = nodes[2] -- calculate angle between node[1] and node[3] local b = nodes[1].radius + nodes[3].radius local c = nodes[1].radius + nodes[2].radius local a = nodes[2].radius + nodes[3].radius local angle = math.acos((b * b + c * c - a * a) / (2 * b * c)) -- now assume node[3] is at node[2]'s position and rotate it around node[1] nodes[3].x = nodes[1].x + nodes[1].radius + nodes[3].radius nodes[3].y = nodes[1].y rotateNode(nodes[1], nodes[3], angle) nodesNew[3] = nodes[3] -- Base triangle finished. Now to the interesting part --add every remaining node for i=4,4 do --#nodes do -- first find node after which to insert it local index = 1 --first move right until we find a node with lower index while nodesNew[index].id > nodes[i].id and index < #nodesNew do index = index + 1 end -- now move right until on the right side is a node with higher index while index + 1 <= #nodesNew and nodesNew[index + 1].id < nodes[i].id do index = index + 1 end --insert node at current position (after index) table.insert(nodesNew, index + 1, nodes[i]) --rotate left node local leftIndex = index - 1 if leftIndex <= 0 then leftIndex = #nodesNew end rotateNode(nodesNew[leftIndex], nodesNew[index], -noderotate) --rotate right node local right = index + 2 if right > #nodesNew then right = right - #nodesNew end local rightright = right + 1 if rightright > #nodesNew then rightright = rightright - #nodesNew end rotateNode(nodesNew[rightright], nodesNew[right], noderotate) --now adjust new nodes position end end function love.draw() love.graphics.translate(xshift, yshift) love.graphics.setColor(255, 255, 255, 255) for i,node in pairs(nodesNew) do love.graphics.circle("fill", node.x, node.y, node.radius, 60) end love.graphics.setColor(150, 150, 250, 255) for i,node in pairs(nodesNew) do local target = nil if i == table.getn(nodesNew) then target = nodes[1] else target = nodes[i+1] end love.graphics.line(node.x, node.y, target.x, target.y) end end
apache-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c78330006.lua
2
1148
--AB myrdon function c78330006.initial_effect(c) --spsummon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(78330006,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetRange(LOCATION_REMOVED) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCondition(c78330006.spcon) e1:SetCost(c78330006.spcost) e1:SetTarget(c78330006.sptg) e1:SetOperation(c78330006.spop) c:RegisterEffect(e1) end function c78330006.spcon(e,tp,eg,ep,ev,re,r,rp) local tc=eg:GetFirst() return tc:IsControler(tp) and tc:IsRace(RACE_INSECT) end function c78330006.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckLPCost(tp,400) end Duel.PayLPCost(tp,400) end function c78330006.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c78330006.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) then Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end
gpl-3.0
waytim/darkstar
scripts/globals/weaponskills/shijin_spiral.lua
10
1804
----------------------------------- -- Shijin Spiral -- Hand-to-Hand weapon skill -- Skill Level: N/A -- Delivers a fivefold attack that Plagues the target. Chance of inflicting Plague varies with TP. -- In order to obtain Shijin Spiral, the quest Martial Mastery must be completed. -- Aligned with the Flame Gorget, Light Gorget & Aqua Gorget. -- Aligned with the Flame Belt, Light Belt & Aqua Belt. -- Element: None -- Modifiers: DEX: 73~85% -- 100%TP 200%TP 300%TP -- 1.0625 1.0625 1.0625 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 5; params.ftp100 = 1.0625; params.ftp200 = 1.0625; params.ftp300 = 1.0625; params.str_wsc = 0.0; params.dex_wsc = 0.85 + (player:getMerit(MERIT_SHIJIN_SPIRAL) / 100); params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1.05; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary); if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.7 + (player:getMerit(MERIT_SHIJIN_SPIRAL) / 100); end if (damage > 0) then local duration = (tp/1000) + 4; if (target:hasStatusEffect(EFFECT_PLAGUE) == false) then target:addStatusEffect(EFFECT_PLAGUE, 5, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c12310711.lua
2
3449
--Lifehunt Scythe --lua script by SGJin function c12310711.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c12310711.target) e1:SetOperation(c12310711.operation) c:RegisterEffect(e1) --ATK up local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_EQUIP) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetValue(800) c:RegisterEffect(e2) --Self bleed effect local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e4:SetCode(EVENT_PHASE+PHASE_STANDBY) e4:SetRange(LOCATION_SZONE) e4:SetCountLimit(1) e4:SetOperation(c12310711.mtop) c:RegisterEffect(e4) local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(12310711,0)) e4:SetCategory(CATEGORY_TOHAND) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e4:SetRange(LOCATION_SZONE) e4:SetCode(EVENT_BATTLE_DESTROYING) e4:SetCondition(c12310711.thcon) e4:SetTarget(c12310711.thtg) e4:SetOperation(c12310711.thop) c:RegisterEffect(e4) --Equip limit local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_EQUIP_LIMIT) e5:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e5:SetValue(c12310711.eqlimit) c:RegisterEffect(e5) end function c12310711.eqlimit(e,c) return c:IsRace(RACE_WARRIOR) or c:IsRace(RACE_SPELLCASTER) end function c12310711.filter(c) return c:IsFaceup() and c:IsRace(RACE_WARRIOR) or c:IsRace(RACE_SPELLCASTER) end function c12310711.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c12310711.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c12310711.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) Duel.SelectTarget(tp,c12310711.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0) end function c12310711.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.Equip(tp,e:GetHandler(),tc) end end function c12310711.mtop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if Duel.GetTurnPlayer()~=tp then return end if c:GetEquipTarget():IsCode(12310707) then return else if Duel.GetLP(tp)>1200 and Duel.SelectYesNo(tp,aux.Stringid(82432018,0)) then Duel.PayLPCost(tp,1200) else Duel.Destroy(e:GetHandler(),REASON_RULE) end end end function c12310711.thcon(e,tp,eg,ep,ev,re,r,rp) return eg:GetFirst()==e:GetHandler():GetEquipTarget() end function c12310711.filter2(c) local code=c:GetCode() return (code==12310712 or code==12310713 or code==12310730) and c:IsAbleToHand() and not c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c12310711.thtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c12310711.filter2,tp,LOCATION_DECK+LOCATION_GRAVE,LOCATION_GRAVE,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE) end function c12310711.thop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c12310711.filter2,tp,LOCATION_DECK+LOCATION_GRAVE,LOCATION_GRAVE,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,tp,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Kristen.lua
4
1042
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Kristen -- Type: Standard NPC -- @zone: 94 -- @pos: 2.195 -2 60.296 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0194); 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
chrox/koreader
frontend/ui/widget/confirmbox.lua
4
3321
local InputContainer = require("ui/widget/container/inputcontainer") local CenterContainer = require("ui/widget/container/centercontainer") local FrameContainer = require("ui/widget/container/framecontainer") local HorizontalGroup = require("ui/widget/horizontalgroup") local VerticalGroup = require("ui/widget/verticalgroup") local ImageWidget = require("ui/widget/imagewidget") local TextBoxWidget = require("ui/widget/textboxwidget") local HorizontalSpan = require("ui/widget/horizontalspan") local ButtonTable = require("ui/widget/buttontable") local GestureRange = require("ui/gesturerange") local UIManager = require("ui/uimanager") local Device = require("device") local Geom = require("ui/geometry") local Input = require("device").input local Screen = require("device").screen local Font = require("ui/font") local DEBUG = require("dbg") local _ = require("gettext") local Blitbuffer = require("ffi/blitbuffer") -- screen --[[ Widget that shows a message and OK/Cancel buttons ]] local ConfirmBox = InputContainer:new{ modal = true, text = _("no text"), face = Font:getFace("infofont", 25), ok_text = _("OK"), cancel_text = _("Cancel"), ok_callback = function() end, cancel_callback = function() end, margin = 5, padding = 5, } function ConfirmBox:init() local content = HorizontalGroup:new{ align = "center", ImageWidget:new{ file = "resources/info-i.png" }, HorizontalSpan:new{ width = 10 }, TextBoxWidget:new{ text = self.text, face = self.face, width = Screen:getWidth()*2/3, } } local button_table = ButtonTable:new{ width = content:getSize().w, button_font_face = "cfont", button_font_size = 20, buttons = { { { text = self.cancel_text, callback = function() self.cancel_callback() UIManager:close(self) end, }, { text = self.ok_text, callback = function() self.ok_callback() UIManager:close(self) end, }, }, }, zero_sep = true, show_parent = self, } self[1] = CenterContainer:new{ dimen = Screen:getSize(), FrameContainer:new{ background = Blitbuffer.COLOR_WHITE, margin = self.margin, padding = self.padding, VerticalGroup:new{ align = "left", content, button_table, } } } end function ConfirmBox:onShow() UIManager:setDirty(self, function() return "ui", self[1][1].dimen end) end function ConfirmBox:onCloseWidget() UIManager:setDirty(nil, function() return "partial", self[1][1].dimen end) end function ConfirmBox:onClose() UIManager:close(self) return true end function ConfirmBox:onSelect() DEBUG("selected:", self.selected.x) if self.selected.x == 1 then self:ok_callback() else self:cancel_callback() end UIManager:close(self) return true end return ConfirmBox
agpl-3.0
LuaDist2/prosody
core/portmanager.lua
2
7940
local config = require "core.configmanager"; local certmanager = require "core.certmanager"; local server = require "net.server"; local socket = require "socket"; local log = require "util.logger".init("portmanager"); local multitable = require "util.multitable"; local set = require "util.set"; local table = table; local setmetatable, rawset, rawget = setmetatable, rawset, rawget; local type, tonumber, tostring, ipairs = type, tonumber, tostring, ipairs; local prosody = prosody; local fire_event = prosody.events.fire_event; module "portmanager"; --- Config local default_interfaces = { }; local default_local_interfaces = { }; if config.get("*", "use_ipv4") ~= false then table.insert(default_interfaces, "*"); table.insert(default_local_interfaces, "127.0.0.1"); end if socket.tcp6 and config.get("*", "use_ipv6") ~= false then table.insert(default_interfaces, "::"); table.insert(default_local_interfaces, "::1"); end local default_mode = config.get("*", "network_default_read_size") or 4096; --- Private state -- service_name -> { service_info, ... } local services = setmetatable({}, { __index = function (t, k) rawset(t, k, {}); return rawget(t, k); end }); -- service_name, interface (string), port (number) local active_services = multitable.new(); --- Private helpers local function error_to_friendly_message(service_name, port, err) --luacheck: ignore 212/service_name local friendly_message = err; if err:match(" in use") then -- FIXME: Use service_name here if port == 5222 or port == 5223 or port == 5269 then friendly_message = "check that Prosody or another XMPP server is " .."not already running and using this port"; elseif port == 80 or port == 81 then friendly_message = "check that a HTTP server is not already using " .."this port"; elseif port == 5280 then friendly_message = "check that Prosody or a BOSH connection manager " .."is not already running"; else friendly_message = "this port is in use by another application"; end elseif err:match("permission") then friendly_message = "Prosody does not have sufficient privileges to use this port"; end return friendly_message; end prosody.events.add_handler("item-added/net-provider", function (event) local item = event.item; register_service(item.name, item); end); prosody.events.add_handler("item-removed/net-provider", function (event) local item = event.item; unregister_service(item.name, item); end); --- Public API function activate(service_name) local service_info = services[service_name][1]; if not service_info then return nil, "Unknown service: "..service_name; end local listener = service_info.listener; local config_prefix = (service_info.config_prefix or service_name).."_"; if config_prefix == "_" then config_prefix = ""; end local bind_interfaces = config.get("*", config_prefix.."interfaces") or config.get("*", config_prefix.."interface") -- COMPAT w/pre-0.9 or (service_info.private and (config.get("*", "local_interfaces") or default_local_interfaces)) or config.get("*", "interfaces") or config.get("*", "interface") -- COMPAT w/pre-0.9 or listener.default_interface -- COMPAT w/pre0.9 or default_interfaces bind_interfaces = set.new(type(bind_interfaces)~="table" and {bind_interfaces} or bind_interfaces); local bind_ports = config.get("*", config_prefix.."ports") or service_info.default_ports or {service_info.default_port or listener.default_port -- COMPAT w/pre-0.9 } bind_ports = set.new(type(bind_ports) ~= "table" and { bind_ports } or bind_ports ); local mode, ssl = listener.default_mode or default_mode; local hooked_ports = {}; for interface in bind_interfaces do for port in bind_ports do local port_number = tonumber(port); if not port_number then log("error", "Invalid port number specified for service '%s': %s", service_info.name, tostring(port)); elseif #active_services:search(nil, interface, port_number) > 0 then log("error", "Multiple services configured to listen on the same port ([%s]:%d): %s, %s", interface, port, active_services:search(nil, interface, port)[1][1].service.name or "<unnamed>", service_name or "<unnamed>"); else local err; -- Create SSL context for this service/port if service_info.encryption == "ssl" then local global_ssl_config = config.get("*", "ssl") or {}; local prefix_ssl_config = config.get("*", config_prefix.."ssl") or global_ssl_config; ssl, err = certmanager.create_context(service_info.name.." port "..port, "server", service_info.ssl_config or {}, prefix_ssl_config[interface], prefix_ssl_config[port], prefix_ssl_config, global_ssl_config[interface], global_ssl_config[port]); if not ssl then log("error", "Error binding encrypted port for %s: %s", service_info.name, error_to_friendly_message(service_name, port_number, err) or "unknown error"); end end if not err then -- Start listening on interface+port local handler, err = server.addserver(interface, port_number, listener, mode, ssl); if not handler then log("error", "Failed to open server port %d on %s, %s", port_number, interface, error_to_friendly_message(service_name, port_number, err)); else table.insert(hooked_ports, "["..interface.."]:"..port_number); log("debug", "Added listening service %s to [%s]:%d", service_name, interface, port_number); active_services:add(service_name, interface, port_number, { server = handler; service = service_info; }); end end end end end log("info", "Activated service '%s' on %s", service_name, #hooked_ports == 0 and "no ports" or table.concat(hooked_ports, ", ")); return true; end function deactivate(service_name, service_info) for name, interface, port, n, active_service --luacheck: ignore 213/name 213/n in active_services:iter(service_name or service_info and service_info.name, nil, nil, nil) do if service_info == nil or active_service.service == service_info then close(interface, port); end end log("info", "Deactivated service '%s'", service_name or service_info.name); end function register_service(service_name, service_info) table.insert(services[service_name], service_info); if not active_services:get(service_name) then log("debug", "No active service for %s, activating...", service_name); local ok, err = activate(service_name); if not ok then log("error", "Failed to activate service '%s': %s", service_name, err or "unknown error"); end end fire_event("service-added", { name = service_name, service = service_info }); return true; end function unregister_service(service_name, service_info) log("debug", "Unregistering service: %s", service_name); local service_info_list = services[service_name]; for i, service in ipairs(service_info_list) do if service == service_info then table.remove(service_info_list, i); end end deactivate(nil, service_info); if #service_info_list > 0 then -- Other services registered with this name activate(service_name); -- Re-activate with the next available one end fire_event("service-removed", { name = service_name, service = service_info }); end function close(interface, port) local service, service_server = get_service_at(interface, port); if not service then return false, "port-not-open"; end service_server:close(); active_services:remove(service.name, interface, port); log("debug", "Removed listening service %s from [%s]:%d", service.name, interface, port); return true; end function get_service_at(interface, port) local data = active_services:search(nil, interface, port)[1][1]; return data.service, data.server; end function get_service(service_name) return (services[service_name] or {})[1]; end function get_active_services() return active_services; end function get_registered_services() return services; end return _M;
mit
TheOnePharaoh/YGOPro-Custom-Cards
script/c55438790.lua
1
2860
--T.M. Librarian function c55438790.initial_effect(c) --option local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(55438790,0)) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetCost(c55438790.tgcost) e1:SetTarget(c55438790.tgtg) e1:SetOperation(c55438790.tgop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --special summon local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(55438790,3)) e3:SetCategory(CATEGORY_SPECIAL_SUMMON) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_REMOVE) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e3:SetCountLimit(1,55438790) e3:SetTarget(c55438790.sptg) e3:SetOperation(c55438790.spop) c:RegisterEffect(e3) --synthetic tuner local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e4:SetCode(EFFECT_ADD_TYPE) e4:SetRange(LOCATION_HAND+LOCATION_MZONE+LOCATION_GRAVE) e4:SetValue(TYPE_NORMAL) c:RegisterEffect(e4) --add setcode local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e5:SetCode(EFFECT_ADD_SETCODE) e5:SetValue(0xd71) c:RegisterEffect(e5) end function c55438790.filter(c) return c:GetLevel()>0 and c:IsRace(RACE_FAIRY) and not c:IsCode(55438790) and c:IsAbleToRemoveAsCost() end function c55438790.tgcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c55438790.filter,tp,LOCATION_DECK,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c55438790.filter,tp,LOCATION_DECK,0,1,1,nil) Duel.Remove(g,POS_FACEUP,REASON_COST) e:SetLabelObject(g:GetFirst()) end function c55438790.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local opt=Duel.SelectOption(tp,aux.Stringid(55438790,1),aux.Stringid(55438790,2)) e:SetLabel(opt) end function c55438790.tgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local lv=e:GetLabelObject():GetLevel() if c:IsRelateToEffect(e) and c:IsFaceup() then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_LEVEL) if e:GetLabel()==0 then e1:SetValue(lv) else e1:SetValue(-lv) end e1:SetReset(RESET_EVENT+0x1ff0000) c:RegisterEffect(e1) end end function c55438790.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c55438790.spop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP_DEFENSE) end end
gpl-3.0
delram/seedup2
bot/utils.lua
646
23489
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() JSON = (loadfile "./libs/dkjson.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end --Check if this chat is realm or not function is_realm(msg) local var = false local realms = 'realms' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(realms)] then if data[tostring(realms)][tostring(msg.to.id)] then var = true end return var end end --Check if this chat is a group or not function is_group(msg) local var = false local groups = 'groups' local data = load_data(_config.moderation.data) local chat = msg.to.id if data[tostring(groups)] then if data[tostring(groups)][tostring(msg.to.id)] then var = true end return var end end function savelog(group, logtxt) local text = (os.date("[ %c ]=> "..logtxt.."\n \n")) local file = io.open("./groups/logs/"..group.."log.txt", "a") file:write(text) file:close() end function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end --Check if user is the owner of that group or not function is_owner(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_owner2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is admin or not function is_admin(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_admin2(user_id) local var = false local data = load_data(_config.moderation.data) local user = user_id local admins = 'admins' if data[tostring(admins)] then if data[tostring(admins)][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == user_id then var = true end end return var end --Check if user is the mod of that group or not function is_momod(msg) local var = false local data = load_data(_config.moderation.data) local user = msg.from.id if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['moderators'] then if data[tostring(msg.to.id)]['moderators'][tostring(user)] then var = true end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['set_owner'] then if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then var = true end end end if data['admins'] then if data['admins'][tostring(user)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end function is_momod2(user_id, group_id) local var = false local data = load_data(_config.moderation.data) local usert = user_id if data[tostring(group_id)] then if data[tostring(group_id)]['moderators'] then if data[tostring(group_id)]['moderators'][tostring(usert)] then var = true end end end if data[tostring(group_id)] then if data[tostring(group_id)]['set_owner'] then if data[tostring(group_id)]['set_owner'] == tostring(user_id) then var = true end end end if data['admins'] then if data['admins'][tostring(user_id)] then var = true end end for v,user in pairs(_config.sudo_users) do if user == usert then var = true end end return var end -- Returns the name of the sender function kick_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_owner2(user_id, chat_id) then -- Ignore admins return end local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end -- Ban function ban_user(user_id, chat_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'banned:'..chat_id redis:sadd(hash, user_id) -- Kick from chat kick_user(user_id, chat_id) end -- Global ban function banall_user(user_id) if tonumber(user_id) == tonumber(our_id) then -- Ignore bot return end if is_admin2(user_id) then -- Ignore admins return end -- Save to redis local hash = 'gbanned' redis:sadd(hash, user_id) end -- Global unban function unbanall_user(user_id) --Save on redis local hash = 'gbanned' redis:srem(hash, user_id) end -- Check if user_id is banned in chat_id or not function is_banned(user_id, chat_id) --Save on redis local hash = 'banned:'..chat_id local banned = redis:sismember(hash, user_id) return banned or false end -- Check if user_id is globally banned or not function is_gbanned(user_id) --Save on redis local hash = 'gbanned' local banned = redis:sismember(hash, user_id) return banned or false end -- Returns chat_id ban list function ban_list(chat_id) local hash = 'banned:'..chat_id local list = redis:smembers(hash) local text = "Ban list !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- Returns globally ban list function banall_list() local hash = 'gbanned' local list = redis:smembers(hash) local text = "global bans !\n\n" for k,v in pairs(list) do text = text..k.." - "..v.." \n" end return text end -- /id by reply function get_message_callback_id(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id send_large_msg(chat, result.from.id) else return 'Use This in Your Groups' end end -- kick by reply for mods and owner function Kick_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end -- Kick by reply for admins function Kick_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't kick myself" end if is_admin2(result.from.id) then -- Ignore admins return end chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) else return 'Use This in Your Groups' end end --Ban by reply for admins function ban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin return "you can't kick mods,owner and admins" end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Ban by reply for admins function ban_by_reply_admins(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't ban myself" end if is_admin2(result.from.id) then -- Ignore admins return end ban_user(result.from.id, result.to.id) send_large_msg(chat, "User "..result.from.id.." Banned") else return 'Use This in Your Groups' end end -- Unban by reply function unban_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't unban myself" end send_large_msg(chat, "User "..result.from.id.." Unbanned") -- Save on redis local hash = 'banned:'..result.to.id redis:srem(hash, result.from.id) else return 'Use This in Your Groups' end end function banall_by_reply(extra, success, result) if result.to.type == 'chat' then local chat = 'chat#id'..result.to.id if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot return "I won't banall myself" end if is_admin2(result.from.id) then -- Ignore admins return end local name = user_print_name(result.from) banall_user(result.from.id) chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false) send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered") else return 'Use This in Your Groups' end end
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c100000945.lua
2
4424
--Created and coded by Rising Phoenix function c100000945.initial_effect(c) --cannot special summon local e10=Effect.CreateEffect(c) e10:SetType(EFFECT_TYPE_SINGLE) e10:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e10:SetCode(EFFECT_SPSUMMON_CONDITION) e10:SetValue(aux.FALSE) c:RegisterEffect(e10) --lp local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(100000945,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_DELAY) e1:SetTarget(c100000945.htg) e1:SetOperation(c100000945.hop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e2) local e7=e1:Clone() e7:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e7) --synchro limit local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e3:SetValue(c100000945.synlimit) c:RegisterEffect(e3) --synchro effect local e12=Effect.CreateEffect(c) e12:SetCategory(CATEGORY_SPECIAL_SUMMON) e12:SetType(EFFECT_TYPE_QUICK_O) e12:SetCode(EVENT_FREE_CHAIN) e12:SetRange(LOCATION_MZONE) e12:SetCountLimit(1) e12:SetHintTiming(0,0x1c0) e12:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e12:SetTarget(c100000945.sctg) e12:SetOperation(c100000945.scop) c:RegisterEffect(e12) local e14=Effect.CreateEffect(c) e14:SetDescription(aux.Stringid(100000945,0)) e14:SetCategory(CATEGORY_TOGRAVE) e14:SetProperty(EFFECT_FLAG_CARD_TARGET) e14:SetType(EFFECT_TYPE_IGNITION) e14:SetRange(LOCATION_GRAVE) e14:SetCost(c100000945.costex) e14:SetTarget(c100000945.targetex) e14:SetOperation(c100000945.operationex) c:RegisterEffect(e14) end function c100000945.costex(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c100000945.filterex(c) return c:IsCode(100000948) and c:IsAbleToGrave() end function c100000945.targetex(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c100000945.filterex,tp,LOCATION_EXTRA,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_EXTRA) end function c100000945.operationex(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c100000945.filterex,tp,LOCATION_EXTRA,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end function c100000945.mfilter(c) return c:IsSetCard(0x114) end function c100000945.sctg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then local mg=Duel.GetMatchingGroup(c100000945.mfilter,tp,LOCATION_MZONE,0,nil) return Duel.IsExistingMatchingCard(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,1,nil,nil,mg) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) end function c100000945.scop(e,tp,eg,ep,ev,re,r,rp) local mg=Duel.GetMatchingGroup(c100000945.mfilter,tp,LOCATION_MZONE,0,nil) local g=Duel.GetMatchingGroup(Card.IsSynchroSummonable,tp,LOCATION_EXTRA,0,nil,nil,mg) if g:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:Select(tp,1,1,nil) Duel.SynchroSummon(tp,sg:GetFirst(),nil,mg) end end function c100000945.synlimit(e,c) if not c then return false end return not c:IsSetCard(0x114) end function c100000945.htg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsPlayerCanSpecialSummonMonster(tp,100000955,0,0x4011,1000,1000,4,RACE_DRAGON,ATTRIBUTE_LIGHT) end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0) end function c100000945.hop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end if not Duel.IsPlayerCanSpecialSummonMonster(tp,100000955,0,0x4011,1000,1000,4,RACE_DRAGON,ATTRIBUTE_LIGHT) then return end local token=Duel.CreateToken(tp,100000955) Duel.SpecialSummon(token,0,tp,tp,false,false,POS_FACEUP) local e2=Effect.CreateEffect(e:GetHandler()) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetValue(c100000945.synlimit) e2:SetReset(RESET_EVENT+0x1fe0000) token:RegisterEffect(e2) end
gpl-3.0
DevPGSV/telegram-bot
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
waytim/darkstar
scripts/globals/items/prime_angler_stewpot.lua
18
2000
----------------------------------------- -- ID: 5612 -- Item: Prime Angler Stewpot -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% -- MP +15 -- Dexterity 2 -- Agility 1 -- Mind 1 -- HP Recovered while healing 7 -- MP Recovered while healing 2 -- Accuracy 15% Cap 30 -- Ranged Accuracy 15% Cap 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,14400,5612); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_MP, 15); target:addMod(MOD_DEX, 2); target:addMod(MOD_AGI, 1); target:addMod(MOD_MND, 1); target:addMod(MOD_HPHEAL, 7); target:addMod(MOD_MPHEAL, 2); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 30); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_MP, 15); target:delMod(MOD_DEX, 2); target:delMod(MOD_AGI, 1); target:delMod(MOD_MND, 1); target:delMod(MOD_HPHEAL, 7); target:delMod(MOD_MPHEAL, 2); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 30); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 30); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Ranpi-Monpi.lua
4
1049
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Ranpi-Monpi -- Type: Standard NPC -- @zone: 94 -- @pos: -115.452 -3 43.389 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0075); 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
CaptainPRICE/wire
lua/entities/gmod_wire_expression2/core/find.lua
1
31750
E2Lib.RegisterExtension("find", true, "Allows an E2 to search for entities matching a filter.") local function table_IsEmpty(t) return not next(t) end local filterList = E2Lib.filterList local function replace_match(a,b) return string.match( string.Replace(a,"-","__"), string.Replace(b,"-","__") ) end -- -- some generic filter criteria -- -- local function filter_all() return true end local function filter_none() return false end local forbidden_classes = { /* ["info_apc_missile_hint"] = true, ["info_camera_link"] = true, ["info_constraint_anchor"] = true, ["info_hint"] = true, ["info_intermission"] = true, ["info_ladder_dismount"] = true, ["info_landmark"] = true, ["info_lighting"] = true, ["info_mass_center"] = true, ["info_no_dynamic_shadow"] = true, ["info_node"] = true, ["info_node_air"] = true, ["info_node_air_hint"] = true, ["info_node_climb"] = true, ["info_node_hint"] = true, ["info_node_link"] = true, ["info_node_link_controller"] = true, ["info_npc_spawn_destination"] = true, ["info_null"] = true, ["info_overlay"] = true, ["info_particle_system"] = true, ["info_projecteddecal"] = true, ["info_snipertarget"] = true, ["info_target"] = true, ["info_target_gunshipcrash"] = true, ["info_teleport_destination"] = true, ["info_teleporter_countdown"] = true, */ ["info_player_allies"] = true, ["info_player_axis"] = true, ["info_player_combine"] = true, ["info_player_counterterrorist"] = true, ["info_player_deathmatch"] = true, ["info_player_logo"] = true, ["info_player_rebel"] = true, ["info_player_start"] = true, ["info_player_terrorist"] = true, ["info_player_blu"] = true, ["info_player_red"] = true, ["prop_dynamic"] = true, ["physgun_beam"] = true, ["player_manager"] = true, ["predicted_viewmodel"] = true, ["gmod_ghost"] = true, } local function filter_default(self) local chip = self.entity return function(ent) if forbidden_classes[ent:GetClass()] then return false end if ent == chip then return false end return true end end -- -- some filter criterion generators -- -- -- Generates a filter that filters out everything not in a lookup table. local function filter_in_lookup(lookup) if table_IsEmpty(lookup) then return filter_none end return function(ent) return lookup[ent] end end -- Generates a filter that filters out everything in a lookup table. local function filter_not_in_lookup(lookup) if table_IsEmpty(lookup) then return filter_all end return function(ent) return not lookup[ent] end end -- Generates a filter that filters out everything not in a lookup table. local function filter_function_result_in_lookup(lookup, func) if table_IsEmpty(lookup) then return filter_none end return function(ent) return lookup[func(ent)] end end -- Generates a filter that filters out everything in a lookup table. local function filter_function_result_not_in_lookup(lookup, func) if table_IsEmpty(lookup) then return filter_all end return function(ent) return not lookup[func(ent)] end end -- checks if binary_predicate(func(ent), key) matches for any of the keys in the lookup table. Returns false if it does. local function filter_binary_predicate_match_none(lookup, func, binary_predicate) if table_IsEmpty(lookup) then return filter_all end return function(a) a = func(a) for b,_ in pairs(lookup) do if binary_predicate(a, b) then return false end end return true end end -- checks if binary_predicate(func(ent), key) matches for any of the keys in the lookup table. Returns true if it does. local function filter_binary_predicate_match_one(lookup, func, binary_predicate) if table_IsEmpty(lookup) then return filter_none end return function(a) a = func(a) for b,_ in pairs(lookup) do if binary_predicate(a, b) then return true end end return false end end -- -- filter criterion combiners -- -- local _filter_and = { [0] = function() return filter_all end, function(f1) return f1 end, function(f1,f2) return function(v) return f1(v) and f2(v) end end, function(f1,f2,f3) return function(v) return f1(v) and f2(v) and f3(v) end end, function(f1,f2,f3,f4) return function(v) return f1(v) and f2(v) and f3(v) and f4(v) end end, function(f1,f2,f3,f4,f5) return function(v) return f1(v) and f2(v) and f3(v) and f4(v) and f5(v) end end, function(f1,f2,f3,f4,f5,f6) return function(v) return f1(v) and f2(v) and f3(v) and f4(v) and f5(v) and f6(v) end end, function(f1,f2,f3,f4,f5,f6,f7) return function(v) return f1(v) and f2(v) and f3(v) and f4(v) and f5(v) and f6(v) and f7(v) end end, } -- Usage: filter = filter_and(filter1, filter2, filter3) local function filter_and(...) local args = {...} -- filter out all filter_all entries filterList(args, function(f) if f == filter_none then args = { filter_none } -- If a filter_none is in the list, we can discard all other filters. end return f ~= filter_all end) local combiner = _filter_and[#args] if not combiner then return nil end -- TODO: write generic combiner return combiner(unpack(args)) end local _filter_or = { [0] = function() return filter_none end, function(f1) return f1 end, function(f1,f2) return function(v) return f1(v) or f2(v) end end, function(f1,f2,f3) return function(v) return f1(v) or f2(v) or f3(v) end end, function(f1,f2,f3,f4) return function(v) return f1(v) or f2(v) or f3(v) or f4(v) end end, function(f1,f2,f3,f4,f5) return function(v) return f1(v) or f2(v) or f3(v) or f4(v) or f5(v) end end, function(f1,f2,f3,f4,f5,f6) return function(v) return f1(v) or f2(v) or f3(v) or f4(v) or f5(v) or f6(v) end end, function(f1,f2,f3,f4,f5,f6,f7) return function(v) return f1(v) or f2(v) or f3(v) or f4(v) or f5(v) or f6(v) or f7(v) end end, } -- Usage: filter = filter_or(filter1, filter2, filter3) local function filter_or(...) local args = {...} -- filter out all filter_none entries filterList(args, function(f) if f == filter_all then args = { filter_all } -- If a filter_all is in the list, we can discard all other filters. end return f ~= filter_none end) local combiner = _filter_or[#args] if not combiner then return nil end -- TODO: write generic combiner return combiner(unpack(args)) end local function invalidate_filters(self) -- Update the filters the next time they are used. self.data.findfilter = nil end -- This function should be called after the black- or whitelists have changed. local function update_filters(self) -- Do not update again until the filters are invalidated the next time. local find = self.data.find --------------------- -- blacklist -- --------------------- -- blacklist for single entities local bl_entity_filter = filter_not_in_lookup(find.bl_entity) -- blacklist for a player's props local bl_owner_filter = filter_function_result_not_in_lookup(find.bl_owner, function(ent) return getOwner(self,ent) end) -- blacklist for models local bl_model_filter = filter_binary_predicate_match_none(find.bl_model, function(ent) return string.lower(ent:GetModel() or "") end, replace_match) -- blacklist for classes local bl_class_filter = filter_binary_predicate_match_none(find.bl_class, function(ent) return string.lower(ent:GetClass()) end, replace_match) -- combine all blacklist filters (done further down) --local filter_blacklist = filter_and(bl_entity_filter, bl_owner_filter, bl_model_filter, bl_class_filter) --------------------- -- whitelist -- --------------------- local filter_whitelist = filter_all -- if not all whitelists are empty, use the whitelists. local whiteListInUse = not (table_IsEmpty(find.wl_entity) and table_IsEmpty(find.wl_owner) and table_IsEmpty(find.wl_model) and table_IsEmpty(find.wl_class)) if whiteListInUse then -- blacklist for single entities local wl_entity_filter = filter_in_lookup(find.wl_entity) -- blacklist for a player's props local wl_owner_filter = filter_function_result_in_lookup(find.wl_owner, function(ent) return getOwner(self,ent) end) -- blacklist for models local wl_model_filter = filter_binary_predicate_match_one(find.wl_model, function(ent) return string.lower(ent:GetModel() or "") end, replace_match) -- blacklist for classes local wl_class_filter = filter_binary_predicate_match_one(find.wl_class, function(ent) return string.lower(ent:GetClass()) end, replace_match) -- combine all whitelist filters filter_whitelist = filter_or(wl_entity_filter, wl_owner_filter, wl_model_filter, wl_class_filter) end --------------------- -- finally combine all filters --self.data.findfilter = filter_and(find.filter_default, filter_blacklist, filter_whitelist) self.data.findfilter = filter_and(find.filter_default, bl_entity_filter, bl_owner_filter, bl_model_filter, bl_class_filter, filter_whitelist) end local function applyFindList(self, findlist) local findfilter = self.data.findfilter if not findfilter then update_filters(self) findfilter = self.data.findfilter end filterList(findlist, findfilter) self.data.findlist = findlist return #findlist end --[[************************************************************************]]-- local _findrate = CreateConVar("wire_expression2_find_rate", 0.05,{FCVAR_ARCHIVE,FCVAR_NOTIFY}) local _maxfinds = CreateConVar("wire_expression2_find_max",10,{FCVAR_ARCHIVE,FCVAR_NOTIFY}) local function findrate() return _findrate:GetFloat() end local function maxfinds() return _maxfinds:GetInt() end local chiplist = {} registerCallback("construct", function(self) self.data.find = { filter_default = filter_default(self), bl_entity = {}, bl_owner = {}, bl_model = {}, bl_class = {}, wl_entity = {}, wl_owner = {}, wl_model = {}, wl_class = {}, } invalidate_filters(self) self.data.findnext = 0 self.data.findlist = {} self.data.findcount = maxfinds() chiplist[self.data] = true end) registerCallback("destruct", function(self) chiplist[self.data] = nil end) hook.Add("EntityRemoved", "wire_expression2_find_EntityRemoved", function(ent) for chip,_ in pairs(chiplist) do local find = chip.find find.bl_entity[ent] = nil find.bl_owner[ent] = nil find.wl_entity[ent] = nil find.wl_owner[ent] = nil filterList(chip.findlist, function(v) return ent ~= v end) end end) --[[************************************************************************]]-- function query_blocked(self, update) if (update) then if (self.data.findcount > 0) then self.data.findcount = self.data.findcount - 1 return false else return true end end return (self.data.findcount < 1) end -- Adds to the available find calls local delay = 0 local function addcount() if (delay > CurTime()) then return end delay = CurTime() + findrate() for v,_ in pairs( chiplist ) do if (v and v.findcount and v.findcount < maxfinds()) then v.findcount = v.findcount + 1 end end end hook.Add("Think","Wire_Expression2_Find_AddCount",addcount) __e2setcost(2) --- Returns the minimum delay between entity find events on a chip e2function number findUpdateRate() return findrate() end -- Returns the maximum number of finds per E2 e2function number findMax() return maxfinds() end -- Returns the remaining available find calls e2function number findCount() return self.data.findcount end --[[ This function wasn't used --- Returns the minimum delay between entity find events per player e2 function number findPlayerUpdateRate() return wire_exp2_playerFindRate:GetFloat() end ]] --- Returns 1 if find functions can be used, 0 otherwise. e2function number findCanQuery() return query_blocked(self) and 0 or 1 end --[[************************************************************************]]-- __e2setcost(30) --- Finds entities in a sphere around V with a radius of N, returns the number found after filtering e2function number findInSphere(vector center, radius) if query_blocked(self, 1) then return 0 end center = Vector(center[1], center[2], center[3]) return applyFindList(self,ents.FindInSphere(center, radius)) end --- Like findInSphere but with a [[http://mathworld.wolfram.com/SphericalCone.html Spherical cone]], arguments are for position, direction, length, and degrees (works now) e2function number findInCone(vector position, vector direction, length, degrees) if query_blocked(self, 4) then return 0 end position = Vector(position[1], position[2], position[3]) direction = Vector(direction[1], direction[2], direction[3]):GetNormalized() local findlist = ents.FindInSphere(position, length) local cosDegrees = math.cos(math.rad(degrees)) local Dot = direction.Dot -- update filter and apply it, together with the cone filter. This is an optimization over applying the two filters in separate passes if not self.data.findfilter then update_filters(self) end filterList(findlist, filter_and( self.data.findfilter, function(ent) return Dot(direction, (ent:GetPos() - position):GetNormalized()) > cosDegrees end )) self.data.findlist = findlist return #findlist end --- Like findInSphere but with a globally aligned box, the arguments are the diagonal corners of the box e2function number findInBox(vector min, vector max) if query_blocked(self, 1) then return 0 end min = Vector(min[1], min[2], min[3]) max = Vector(max[1], max[2], max[3]) return applyFindList(self, ents.FindInBox(min, max)) end --- Find all entities with the given name e2function number findByName(string name) if query_blocked(self, 1) then return 0 end return applyFindList(self, ents.FindByName(name)) end --- Find all entities with the given model e2function number findByModel(string model) if query_blocked(self, 1) then return 0 end return applyFindList(self, ents.FindByModel(model)) end --- Find all entities with the given class e2function number findByClass(string class) if query_blocked(self, 1) then return 0 end return applyFindList(self, ents.FindByClass(class)) end --[[************************************************************************]]-- local function findPlayer(name) name = string.lower(name) return filterList(player.GetAll(), function(ent) return string.find(string.lower(ent:GetName()), name,1,true) end)[1] end --- Returns the player with the given name, this is an exception to the rule e2function entity findPlayerByName(string name) if query_blocked(self, 1) then return nil end return findPlayer(name) end --[[************************************************************************]]-- __e2setcost(10) --- Exclude all entities from <arr> from future finds e2function void findExcludeEntities(array arr) local bl_entity = self.data.find.bl_entity local IsValid = IsValid for _,ent in ipairs(arr) do if not IsValid(ent) then return end bl_entity[ent] = true end invalidate_filters(self) end --- Exclude <ent> from future finds e2function void findExcludeEntity(entity ent) if not IsValid(ent) then return end self.data.find.bl_entity[ent] = true invalidate_filters(self) end --- Exclude this player from future finds (put it on the entity blacklist) e2function void findExcludePlayer(entity ply) = e2function void findExcludeEntity(entity ent) --- Exclude this player from future finds (put it on the entity blacklist) e2function void findExcludePlayer(string name) local ply = findPlayer(name) if not ply then return end self.data.find.bl_entity[ply] = true invalidate_filters(self) end --- Exclude entities owned by this player from future finds e2function void findExcludePlayerProps(entity ply) if not IsValid(ply) then return end self.data.find.bl_owner[ply] = true invalidate_filters(self) end --- Exclude entities owned by this player from future finds e2function void findExcludePlayerProps(string name) local ply = findPlayer(name) if not ply then return end e2_findExcludePlayerProps_e(self, { nil, { function() return ply end } }) end --- Exclude entities with this model (or partial model name) from future finds e2function void findExcludeModel(string model) self.data.find.bl_model[string.lower(model)] = true invalidate_filters(self) end --- Exclude entities with this class (or partial class name) from future finds e2function void findExcludeClass(string class) self.data.find.bl_class[string.lower(class)] = true invalidate_filters(self) end --[[************************************************************************]]-- --- Remove all entities from <arr> from the blacklist e2function void findAllowEntities(array arr) local bl_entity = self.data.find.bl_entity local IsValid = IsValid for _,ent in ipairs(arr) do if not IsValid(ent) then return end bl_entity[ent] = nil end invalidate_filters(self) end --- Remove <ent> from the blacklist e2function void findAllowEntity(entity ent) if not IsValid(ent) then return end self.data.find.bl_entity[ent] = nil invalidate_filters(self) end --- Remove this player from the entity blacklist e2function void findAllowPlayer(entity ply) = e2function void findAllowEntity(entity ent) --- Remove this player from the entity blacklist e2function void findAllowPlayer(string name) local ply = findPlayer(name) if not ply then return end self.data.find.bl_entity[ply] = nil invalidate_filters(self) end --- Remove entities owned by this player from the blacklist e2function void findAllowPlayerProps(entity ply) if not IsValid(ply) then return end self.data.find.bl_owner[ply] = nil invalidate_filters(self) end --- Remove entities owned by this player from the blacklist e2function void findAllowPlayerProps(string name) local ply = findPlayer(name) if not ply then return end e2_findAllowPlayerProps_e(self, { nil, { function() return ply end } }) end --- Remove entities with this model (or partial model name) from the blacklist e2function void findAllowModel(string model) self.data.find.bl_model[string.lower(model)] = nil invalidate_filters(self) end --- Remove entities with this class (or partial class name) from the blacklist e2function void findAllowClass(string class) self.data.find.bl_class[string.lower(class)] = nil invalidate_filters(self) end --[[************************************************************************]]-- --- Include all entities from <arr> in future finds, and remove others not in the whitelist e2function void findIncludeEntities(array arr) local wl_entity = self.data.find.wl_entity local IsValid = IsValid for _,ent in ipairs(arr) do if not IsValid(ent) then return end wl_entity[ent] = true end invalidate_filters(self) end --- Include <ent> in future finds, and remove others not in the whitelist e2function void findIncludeEntity(entity ent) if not IsValid(ent) then return end self.data.find.wl_entity[ent] = true invalidate_filters(self) end --- Include this player in future finds, and remove other entities not in the entity whitelist e2function void findIncludePlayer(entity ply) = e2function void findIncludeEntity(entity ent) --- Include this player in future finds, and remove other entities not in the entity whitelist e2function void findIncludePlayer(string name) local ply = findPlayer(name) if not ply then return end self.data.find.wl_entity[ply] = true invalidate_filters(self) end --- Include entities owned by this player from future finds, and remove others not in the whitelist e2function void findIncludePlayerProps(entity ply) if not IsValid(ply) then return end self.data.find.wl_owner[ply] = true invalidate_filters(self) end --- Include entities owned by this player from future finds, and remove others not in the whitelist e2function void findIncludePlayerProps(string name) local ply = findPlayer(name) if not ply then return end e2_findIncludePlayerProps_e(self, { nil, { function() return ply end } }) end --- Include entities with this model (or partial model name) in future finds, and remove others not in the whitelist e2function void findIncludeModel(string model) self.data.find.wl_model[string.lower(model)] = true invalidate_filters(self) end --- Include entities with this class (or partial class name) in future finds, and remove others not in the whitelist e2function void findIncludeClass(string class) self.data.find.wl_class[string.lower(class)] = true invalidate_filters(self) end --[[************************************************************************]]-- --- Remove all entities from <arr> from the whitelist e2function void findDisallowEntities(array arr) local wl_entity = self.data.find.wl_entity local IsValid = IsValid for _,ent in ipairs(arr) do if not IsValid(ent) then return end wl_entity[ent] = nil end invalidate_filters(self) end --- Remove <ent> from the whitelist e2function void findDisallowEntity(entity ent) if not IsValid(ent) then return end self.data.find.wl_entity[ent] = nil invalidate_filters(self) end --- Remove this player from the entity whitelist e2function void findDisallowPlayer(entity ply) = e2function void findDisallowEntity(entity ent) --- Remove this player from the entity whitelist e2function void findDisallowPlayer(string name) local ply = findPlayer(name) if not ply then return end self.data.find.wl_entity[ply] = nil invalidate_filters(self) end --- Remove entities owned by this player from the whitelist e2function void findDisallowPlayerProps(entity ply) if not IsValid(ply) then return end self.data.find.wl_owner[ply] = nil invalidate_filters(self) end --- Remove entities owned by this player from the whitelist e2function void findDisallowPlayerProps(string name) local ply = findPlayer(name) if not ply then return end e2_findDisallowPlayerProps_e(self, { nil, { function() return ply end } }) end --- Remove entities with this model (or partial model name) from the whitelist e2function void findDisallowModel(string model) self.data.find.wl_model[string.lower(model)] = nil invalidate_filters(self) end --- Remove entities with this class (or partial class name) from the whitelist e2function void findDisallowClass(string class) self.data.find.wl_class[string.lower(class)] = nil invalidate_filters(self) end --[[************************************************************************]]-- --- Clear all entries from the entire blacklist e2function void findClearBlackList() local find = self.data.find find.bl_entity = {} find.bl_owner = {} find.bl_model = {} find.bl_class = {} invalidate_filters(self) end --- Clear all entries from the entity blacklist e2function void findClearBlackEntityList() self.data.find.bl_entity = {} invalidate_filters(self) end --- Clear all entries from the prop owner blacklist e2function void findClearBlackPlayerPropList() self.data.find.bl_owner = {} invalidate_filters(self) end --- Clear all entries from the model blacklist e2function void findClearBlackModelList() self.data.find.bl_model = {} invalidate_filters(self) end --- Clear all entries from the class blacklist e2function void findClearBlackClassList() self.data.find.bl_class = {} invalidate_filters(self) end --- Clear all entries from the entire whitelist e2function void findClearWhiteList() local find = self.data.find find.wl_entity = {} find.wl_owner = {} find.wl_model = {} find.wl_class = {} invalidate_filters(self) end --- Clear all entries from the player whitelist e2function void findClearWhiteEntityList() self.data.find.wl_entity = {} invalidate_filters(self) end --- Clear all entries from the prop owner whitelist e2function void findClearWhitePlayerPropList() self.data.find.wl_owner = {} invalidate_filters(self) end --- Clear all entries from the model whitelist e2function void findClearWhiteModelList() self.data.find.wl_model = {} invalidate_filters(self) end --- Clear all entries from the class whitelist e2function void findClearWhiteClassList() self.data.find.wl_class = {} invalidate_filters(self) end --[[************************************************************************]]-- __e2setcost(2) --- Returns the indexed entity from the previous find event (valid parameters are 1 to the number of entities found) e2function entity findResult(index) return self.data.findlist[index] end --- Returns the closest entity to the given point from the previous find event e2function entity findClosest(vector position) local closest = nil local dist = math.huge self.prf = self.prf + #self.data.findlist * 10 for _,ent in pairs(self.data.findlist) do if IsValid(ent) then local pos = ent:GetPos() local xd, yd, zd = pos.x-position[1], pos.y-position[2], pos.z-position[3] local curdist = xd*xd + yd*yd + zd*zd if curdist < dist then closest = ent dist = curdist end end end return closest end --- Formats the query as an array, R:entity(Index) to get a entity, R:string to get a description including the name and entity id. e2function array findToArray() local tmp = {} for k,v in ipairs(self.data.findlist) do tmp[k] = v end self.prf = self.prf + #tmp / 3 return tmp end --- Equivalent to findResult(1) e2function entity find() return self.data.findlist[1] end --[[************************************************************************]]-- __e2setcost(10) --- Sorts the entities from the last find event, index 1 is the closest to point V, returns the number of entities in the list e2function number findSortByDistance(vector position) position = Vector(position[1], position[2], position[3]) local Distance = position.Distance local IsValid = IsValid local findlist = self.data.findlist self.prf = self.prf + #findlist * 12 table.sort(findlist, function(a, b) if not IsValid(a) then return false end -- !(invalid < b) <=> (b <= invalid) if not IsValid(b) then return true end -- (valid < invalid) return Distance(position, a:GetPos()) < Distance(position, b:GetPos()) end) return #findlist end --[[************************************************************************]]-- __e2setcost(5) local function applyClip(self, filter) local findlist = self.data.findlist self.prf = self.prf + #findlist * 5 filterList(findlist, filter) return #findlist end --- Filters the list of entities by removing all entities that are NOT of this class e2function number findClipToClass(string class) class = string.lower(class) return applyClip(self, function(ent) if !IsValid(ent) then return false end return replace_match(string.lower(ent:GetClass()), class) end) end --- Filters the list of entities by removing all entities that are of this class e2function number findClipFromClass(string class) return applyClip(self, function(ent) if !IsValid(ent) then return false end return not replace_match(string.lower(ent:GetClass()), class) end) end --- Filters the list of entities by removing all entities that do NOT have this model e2function number findClipToModel(string model) return applyClip(self, function(ent) if !IsValid(ent) then return false end return replace_match(string.lower(ent:GetModel() or ""), model) end) end --- Filters the list of entities by removing all entities that do have this model e2function number findClipFromModel(string model) return applyClip(self, function(ent) if !IsValid(ent) then return false end return not replace_match(string.lower(ent:GetModel() or ""), model) end) end --- Filters the list of entities by removing all entities that do NOT have this name e2function number findClipToName(string name) return applyClip(self, function(ent) if !IsValid(ent) then return false end return replace_match(string.lower(ent:GetName()), name) end) end --- Filters the list of entities by removing all entities that do have this name e2function number findClipFromName(string name) return applyClip(self, function(ent) if !IsValid(ent) then return false end return not replace_match(string.lower(ent:GetName()), name) end) end --- Filters the list of entities by removing all entities NOT within the specified sphere (center, radius) e2function number findClipToSphere(vector center, radius) center = Vector(center[1], center[2], center[3]) return applyClip(self, function(ent) if !IsValid(ent) then return false end return center:Distance(ent:GetPos()) <= radius end) end --- Filters the list of entities by removing all entities within the specified sphere (center, radius) e2function number findClipFromSphere(vector center, radius) center = Vector(center[1], center[2], center[3]) return applyClip(self, function(ent) if !IsValid(ent) then return false end return center:Distance(ent:GetPos()) > radius end) end --- Filters the list of entities by removing all entities NOT on the positive side of the defined plane. (Plane origin, vector perpendicular to the plane) You can define any convex hull using this. e2function number findClipToRegion(vector origin, vector perpendicular) origin = Vector(origin[1], origin[2], origin[3]) perpendicular = Vector(perpendicular[1], perpendicular[2], perpendicular[3]) local perpdot = perpendicular:Dot(origin) return applyClip(self, function(ent) if !IsValid(ent) then return false end return perpdot < perpendicular:Dot(ent:GetPos()) end) end -- inrange used in findClip*Box (below) local function inrange( vec1, vecmin, vecmax ) if (vec1.x < vecmin.x) then return false end if (vec1.y < vecmin.y) then return false end if (vec1.z < vecmin.z) then return false end if (vec1.x > vecmax.x) then return false end if (vec1.y > vecmax.y) then return false end if (vec1.z > vecmax.z) then return false end return true end -- If vecmin is greater than vecmax, flip it local function sanitize( vecmin, vecmax ) for I=1, 3 do if (vecmin[I] > vecmax[I]) then local temp = vecmin[I] vecmin[I] = vecmax[I] vecmax[I] = temp end end return vecmin, vecmax end -- Filters the list of entities by removing all entities within the specified box e2function number findClipFromBox( vector min, vector max ) min, max = sanitize( min, max ) min = Vector(min[1], min[2], min[3]) max = Vector(max[1], max[2], max[3]) return applyClip( self, function(ent) return !inrange(ent:GetPos(),min,max) end) end -- Filters the list of entities by removing all entities not within the specified box e2function number findClipToBox( vector min, vector max ) min, max = sanitize( min, max ) min = Vector(min[1], min[2], min[3]) max = Vector(max[1], max[2], max[3]) return applyClip( self, function(ent) return inrange(ent:GetPos(),min,max) end) end -- Filters the list of entities by removing all entities equal to this entity e2function number findClipFromEntity( entity ent ) if !IsValid( ent ) then return -1 end return applyClip( self, function( ent2 ) if !IsValid(ent2) then return false end return ent != ent2 end) end -- Filters the list of entities by removing all entities equal to one of these entities e2function number findClipFromEntities( array entities ) local lookup = {} self.prf = self.prf + #entities / 3 for k,v in ipairs( entities ) do lookup[v] = true end return applyClip( self, function( ent ) if !IsValid(ent) then return false end return !lookup[ent] end) end -- Filters the list of entities by removing all entities not equal to this entity e2function number findClipToEntity( entity ent ) if !IsValid( ent ) then return -1 end return applyClip( self, function( ent2 ) if !IsValid(ent2) then return false end return ent == ent2 end) end -- Filters the list of entities by removing all entities not equal to one of these entities e2function number findClipToEntities( array entities ) local lookup = {} self.prf = self.prf + #entities / 3 for k,v in ipairs( entities ) do lookup[v] = true end return applyClip( self, function( ent ) if !IsValid(ent) then return false end return lookup[ent] end) end
apache-2.0
X-Raym/REAPER-ReaScripts
MIDI Editor/X-Raym_Mute selected notes in open MIDI take randomly.lua
1
2924
--[[ * ReaScript Name: Mute selected notes in open MIDI take randomly * Instructions: Open a MIDI take in MIDI Editor. Select Notes. Run. * Author: X-Raym * Author URI: https://www.extremraym.com * Repository: GitHub > X-Raym > REAPER-ReaScripts * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts * Licence: GPL v3 * REAPER: 5.0 pre 15 * Version: 1.0 --]] --[[ * Changelog: * v1.0 (2015-06-12) + Initial Release --]] -- USER AREA ----------- -- strength_percent = 0.5 -- END OF USER AREA ---- -- INIT note_sel = 0 init_notes = {} t = {} -- SHUFFLE TABLE FUNCTION -- from Tutorial: How to Shuffle Table Items by Rob Miracle -- https://coronalabs.com/blog/2014/09/30/tutorial-how-to-shuffle-table-items/ math.randomseed( os.time() ) local function ShuffleTable( t ) local rand = math.random local iterations = #t local w for z = iterations, 2, -1 do w = rand(z) t[z], t[w] = t[w], t[z] end end function main() reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function. take = reaper.MIDIEditor_GetTake(reaper.MIDIEditor_GetActive()) if take ~= nil then retval, notes, ccs, sysex = reaper.MIDI_CountEvts(take) -- GET SELECTED NOTES (from 0 index) for k = 0, notes-1 do retval, sel, muted, startppqposOut, endppqposOut, chan, pitch, vel = reaper.MIDI_GetNote(take, k) if sel == true then note_sel = note_sel + 1 init_notes[note_sel] = k end end defaultvals_csv = note_sel retval, retvals_csv = reaper.GetUserInputs("Mute Selected Notes Randomly", 1, "Number of Notes to Mute?", defaultvals_csv) if retval then -- if user complete the fields notes_selection = tonumber(retvals_csv) -- SHUFFLE TABLE ShuffleTable( init_notes ) -- MUTE RANDOMLY -- if percentage is needed --notes_selection = math.floor(notes * strength_percent) for j = 1, note_sel do if j <= notes_selection then retval, sel, muted, startppqposOut, endppqposOut, chan, pitch, vel = reaper.MIDI_GetNote(take, init_notes[j]) reaper.MIDI_SetNote(take, init_notes[j], true, true, startppqposOut, endppqposOut, chan, pitch, vel) else -- this allow to execute the action several times. Else, all notes end to be muted. retval, sel, muted, startppqposOut, endppqposOut, chan, pitch, vel = reaper.MIDI_GetNote(take, init_notes[j]) reaper.MIDI_SetNote(take, init_notes[j], false, false, startppqposOut, endppqposOut, chan, pitch, vel) end end end end -- ENFIF Take is MIDI reaper.Undo_EndBlock("Mute selected note in open MIDI take randomly", 0) -- End of the undo block. Leave it at the bottom of your main function. end main() -- Execute your main function reaper.UpdateArrange() -- Update the arrangement (often needed)
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Dynamis-Jeuno/mobs/Goblin_Statue.lua
2
4691
----------------------------------- -- Area: Dynamis Jeuno -- NPC: Goblin Statue -- Map1 Position: http://images3.wikia.nocookie.net/__cb20090312005127/ffxi/images/b/bb/Jeu1.jpg -- Map2 Position: http://images4.wikia.nocookie.net/__cb20090312005155/ffxi/images/3/31/Jeu2.jpg -- Vanguard Position: http://faranim.livejournal.com/39860.html ----------------------------------- package.loaded["scripts/zones/Dynamis-Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Jeuno/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local spawnList = jeunoList; for nb = 1, table.getn(spawnList), 2 do if(mob:getID() == spawnList[nb]) then for nbi = 1, table.getn(spawnList[nb + 1]), 1 do if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end local mobNBR = spawnList[nb + 1][nbi]; if(mobNBR <= 20) then if(mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY) local DynaMob = getDynaMob(target,mobNBR,1); --printf("Goblin Statue => mob %u \n",DynaMob); if(DynaMob ~= nil) then -- Spawn Mob SpawnMob(DynaMob):updateEnmity(target); GetMobByID(DynaMob):setPos(X,Y,Z); GetMobByID(DynaMob):setSpawn(X,Y,Z); -- Spawn Pet for BST, DRG, and SMN if(mobNBR == 9 or mobNBR == 15) then SpawnMob(DynaMob + 1):updateEnmity(target); GetMobByID(DynaMob + 1):setPos(X,Y,Z); GetMobByID(DynaMob + 1):setSpawn(X,Y,Z); end end elseif(mobNBR > 20) then SpawnMob(mobNBR):updateEnmity(target); local MJob = GetMobByID(mobNBR):getMainJob(); if(MJob == 9 or MJob == 15) then -- Spawn Pet for BST, DRG, and SMN SpawnMob(mobNBR + 1):updateEnmity(target); GetMobByID(mobNBR + 1):setPos(X,Y,Z); GetMobByID(mobNBR + 1):setSpawn(X,Y,Z); end end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) mobID = mob:getID(); -- HP Bonus: 005 011 016 023 026 031 040 057 063 065 068 077 079 080 082 083 084 093 102 119 | 123 126 128 if(mobID == 17547534 or mobID == 17547540 or mobID == 17547545 or mobID == 17547552 or mobID == 17547555 or mobID == 17547560 or mobID == 17547569 or mobID == 17547586 or mobID == 17547592 or mobID == 17547594 or mobID == 17547597 or mobID == 17547606 or mobID == 17547608 or mobID == 17547609 or mobID == 17547612 or mobID == 17547613 or mobID == 17547622 or mobID == 17547631 or mobID == 17547647 or mobID == 17547651 or mobID == 17547654 or mobID == 17547656) then killer:restoreHP(3000); killer:messageBasic(024,(killer:getMaxHP()-killer:getHP())); -- MP Bonus: 009 012 017 024 025 030 039 044 056 062 064 067 076 078 081 082 085 094 095 101 118 | 122 127 129 150 elseif(mobID == 17547538 or mobID == 17547541 or mobID == 17547546 or mobID == 17547553 or mobID == 17547554 or mobID == 17547559 or mobID == 17547568 or mobID == 17547573 or mobID == 17547585 or mobID == 17547591 or mobID == 17547593 or mobID == 17547596 or mobID == 17547605 or mobID == 17547607 or mobID == 17547610 or mobID == 17547611 or mobID == 17547614 or mobID == 17547623 or mobID == 17547624 or mobID == 17547630 or mobID == 17547646 or mobID == 17547650 or mobID == 17547655 or mobID == 17547657 or mobID == 17547678) then killer:restoreMP(3000); killer:messageBasic(025,(killer:getMaxMP()-killer:getMP())); end -- Spawn 089-097 when statue 044 is defeated if(mobID == 17547573) then for nbx = 17547618, 17547626, 1 do SpawnMob(nbx); end end -- Spawn 114-120 when statue 064 is defeated if(mobID == 17547593) then for nbx = 17547642, 17547648, 1 do SpawnMob(nbx); end end -- Spawn 098-100 when statue 073 074 075 are defeated if((mobID == 17547602 or mobID == 17547603 or mobID == 17547604) and GetMobAction(17547602) == 0 and GetMobAction(17547603) == 0 and GetMobAction(17547604) == 0) then SpawnMob(17547627); -- 098 SpawnMob(17547628); -- 099 SpawnMob(17547629); -- 100 end -- Spawn 101-112 when statue 098 099 100 are defeated if((mobID == 17547627 or mobID == 17547628 or mobID == 17547629) and GetMobAction(17547627) == 0 and GetMobAction(17547628) == 0 and GetMobAction(17547629) == 0) then for nbx = 17547630, 17547641, 1 do SpawnMob(nbx); end end end;
gpl-3.0
db260179/openwrt-bpi-r1-luci
applications/luci-app-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua
68
2351
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local ast = require("luci.asterisk") -- -- SIP trunk info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Trunk Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Trunk %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "trunks") ) end return form -- -- SIP trunk config -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Trunk") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "peer", qualify = "yes", } back = peer:option(DummyValue, "_overview", "Back to trunk overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks") sipdomain = peer:option(Value, "host", "SIP Domain") sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy") outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port") register = peer:option(Flag, "register", "Register with peer") register.enabled = "yes" register.disabled = "no" regext = peer:option(Value, "registerextension", "Extension to register (optional)") regext:depends({register="1"}) didval = peer:option(ListValue, "_did", "Number of assigned DID numbers") didval:value("", "(none)") for i=1,24 do didval:value(i) end dialplan = peer:option(ListValue, "context", "Dialplan Context") dialplan:value(arg[1] .. "_inbound", "(default)") cbimap.uci:foreach("asterisk", "dialplan", function(s) dialplan:value(s['.name']) end) return cbimap end
apache-2.0
waytim/darkstar
scripts/globals/spells/huton_san.lua
21
1271
----------------------------------------- -- Spell: Huton: San -- Deals wind damage to an enemy and lowers its resistance against ice. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_HUTON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_HUTON_EFFECT); -- T1 mag atk if(caster:getMerit(MERIT_HUTON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_HUTON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_HUTON_SAN) - 5; end local dmg = doNinjutsuNuke(134,1.5,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_ICERES); return dmg; end;
gpl-3.0
Contatta/prosody-modules
mod_mam/mamprefsxml.lib.lua
36
1467
-- XEP-0313: Message Archive Management for Prosody -- Copyright (C) 2011-2013 Kim Alvefur -- -- This file is MIT/X11 licensed. local st = require"util.stanza"; local xmlns_mam = "urn:xmpp:mam:0"; local global_default_policy = module:get_option("default_archive_policy", false); local default_attrs = { always = true, [true] = "always", never = false, [false] = "never", roster = "roster", } local function tostanza(prefs) local default = prefs[false]; default = default ~= nil and default_attrs[default] or global_default_policy; local prefstanza = st.stanza("prefs", { xmlns = xmlns_mam, default = default }); local always = st.stanza("always"); local never = st.stanza("never"); for jid, choice in pairs(prefs) do if jid then (choice and always or never):tag("jid"):text(jid):up(); end end prefstanza:add_child(always):add_child(never); return prefstanza; end local function fromstanza(prefstanza) local prefs = {}; local default = prefstanza.attr.default; if default then prefs[false] = default_attrs[default]; end local always = prefstanza:get_child("always"); if always then for rule in always:childtags("jid") do local jid = rule:get_text(); prefs[jid] = true; end end local never = prefstanza:get_child("never"); if never then for rule in never:childtags("jid") do local jid = rule:get_text(); prefs[jid] = false; end end return prefs; end return { tostanza = tostanza; fromstanza = fromstanza; }
mit
waytim/darkstar
scripts/globals/items/cheese_sandwich_+1.lua
18
1186
----------------------------------------- -- ID: 5687 -- Item: cheese_sandwich_+1 -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 10 -- Agility 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5687); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_AGI, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_AGI, 2); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/wild_melon.lua
3
1088
----------------------------------------- -- ID: 4597 -- Item: wild_melon -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -6 -- Intelligence 4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4597); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -6); target:addMod(MOD_INT, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -6); target:delMod(MOD_INT, 4); end;
gpl-3.0
waytim/darkstar
scripts/zones/Riverne-Site_A01/npcs/_0u1.lua
13
1347
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x6); else player:messageSpecial(SD_VERY_SMALL); end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/persikos.lua
3
1086
----------------------------------------- -- ID: 4274 -- Item: persikos -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -7 -- Intelligence 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4274); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -7); target:addMod(MOD_INT, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -7); target:delMod(MOD_INT, 5); end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c77777848.lua
2
1784
--Mystic Fauna Owl function c77777848.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(77777848,0)) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCondition(c77777848.spcon) c:RegisterEffect(e1) --search on shuffle local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(77777848,1)) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP) e3:SetCountLimit(1,77777848) e3:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE) e3:SetCode(EVENT_TO_DECK) e3:SetTarget(c77777848.tg) e3:SetOperation(c77777848.op) c:RegisterEffect(e3) end function c77777848.filter2(c) return c:IsSetCard(0x40a) and c:IsType(TYPE_MONSTER)and c:IsAbleToHand() and not c:IsCode(77777848) end function c77777848.tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c77777848.filter2,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) and re:GetOwner():IsSetCard(0x40a)end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE) end function c77777848.op(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c77777848.filter2,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c77777848.filter(c) return c:IsRace(RACE_BEAST)and (c:IsLevelBelow(2) or c:IsRankBelow(2))and c:IsFaceup() end function c77777848.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c77777848.filter,tp,LOCATION_MZONE,0,1,nil) end
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c44559815.lua
2
5870
--Zhong Kui, Descendant of the Nirvana function c44559815.initial_effect(c) c:SetUniqueOnField(1,0,44559815) --special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_HAND) e1:SetCondition(c44559815.spcon) e1:SetOperation(c44559815.spop) c:RegisterEffect(e1) --spsummon local e2=Effect.CreateEffect(c) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCountLimit(1,44559815) e2:SetTarget(c44559815.target) e2:SetOperation(c44559815.operation) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e3) local e4=e2:Clone() e4:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e4) --negate local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(44559815,0)) e5:SetCategory(CATEGORY_DISABLE_SUMMON+CATEGORY_DESTROY+CATEGORY_DRAW) e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O) e5:SetCode(EVENT_SUMMON) e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e5:SetRange(LOCATION_MZONE) e5:SetCountLimit(1) e5:SetCondition(c44559815.negcon) e5:SetTarget(c44559815.negtg) e5:SetOperation(c44559815.negop) c:RegisterEffect(e5) --tograve local e6=Effect.CreateEffect(c) e6:SetDescription(aux.Stringid(44559815,1)) e6:SetCategory(CATEGORY_TOGRAVE) e6:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_SINGLE) e6:SetCode(EVENT_BATTLE_DESTROYING) e6:SetCondition(c44559815.tgcon) e6:SetTarget(c44559815.tgtg) e6:SetOperation(c44559815.tgop) c:RegisterEffect(e6) --token local e7=Effect.CreateEffect(c) e7:SetDescription(aux.Stringid(44559815,2)) e7:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN) e7:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e7:SetCode(EVENT_TO_GRAVE) e7:SetCondition(c44559815.tokcon) e7:SetTarget(c44559815.toktg) e7:SetOperation(c44559815.tokop) c:RegisterEffect(e7) end function c44559815.spfilter(c) return c:IsFaceup() and c:IsSetCard(0x2016) or c:IsSetCard(0x2017) and not c:IsCode(44559815) and c:IsAbleToGraveAsCost() end function c44559815.spcon(e,c) if c==nil then return true end return Duel.IsExistingMatchingCard(c44559815.spfilter,c:GetControler(),LOCATION_MZONE,0,3,nil) end function c44559815.spop(e,tp,eg,ep,ev,re,r,rp,c) local g=Duel.SelectMatchingCard(tp,c44559815.spfilter,tp,LOCATION_MZONE,0,3,3,nil) Duel.SendtoGrave(g,REASON_COST) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetValue(2500) e1:SetReset(RESET_EVENT+0xff0000) c:RegisterEffect(e1) end function c44559815.specfilter(c,e,tp) return c:IsType(TYPE_MONSTER) and c:IsSetCard(0x2016) and c:GetCode()~=44559815 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c44559815.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c44559815.specfilter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE+LOCATION_HAND) end function c44559815.operation(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c44559815.specfilter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function c44559815.negcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentChain()==0 end function c44559815.negtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,eg,eg:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c44559815.negop(e,tp,eg,ep,ev,re,r,rp) Duel.NegateSummon(eg) Duel.Destroy(eg,REASON_EFFECT) Duel.Draw(tp,1,REASON_EFFECT) end function c44559815.tgcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsRelateToBattle() and c:GetBattleTarget():IsType(TYPE_MONSTER) end function c44559815.tgfilter(c) return c:IsSetCard(0x2016) or c:IsCode(44559811) and not c:IsCode(44559815) and c:IsAbleToGrave() end function c44559815.tgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c44559815.tgfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK) end function c44559815.tgop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c44559815.tgfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoGrave(g,REASON_EFFECT) end end function c44559815.tokcon(e,tp,eg,ep,ev,re,r,rp) return bit.band(e:GetHandler():GetPreviousLocation(),LOCATION_ONFIELD)>0 end function c44559815.toktg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,2,0,0) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,0,0) end function c44559815.tokop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end if not Duel.IsPlayerCanSpecialSummonMonster(tp,44559816,0,0x2016,0,0,2,RACE_BEASTWARRIOR,ATTRIBUTE_DARK) then return end for i=1,2 do local token=Duel.CreateToken(tp,44559815+i) Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP_DEFENSE) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(1) token:RegisterEffect(e1,true) end Duel.SpecialSummonComplete() end
gpl-3.0
waytim/darkstar
scripts/zones/Chamber_of_Oracles/npcs/Pedestal_of_Earth.lua
13
2385
----------------------------------- -- Area: Chamber of Oracles -- NPC: Pedestal of Earth -- Involved in Zilart Mission 7 -- @pos 199 -2 36 168 ------------------------------------- package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Chamber_of_Oracles/TextIDs"); ------------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ZilartStatus = player:getVar("ZilartStatus"); if (player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then if (player:hasKeyItem(EARTH_FRAGMENT)) then player:delKeyItem(EARTH_FRAGMENT); player:setVar("ZilartStatus",ZilartStatus + 4); player:messageSpecial(YOU_PLACE_THE,EARTH_FRAGMENT); if (ZilartStatus == 255) then player:startEvent(0x0001); end elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted. player:startEvent(0x0001); else player:messageSpecial(IS_SET_IN_THE_PEDESTAL,EARTH_FRAGMENT); end elseif (player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES)) then player:messageSpecial(HAS_LOST_ITS_POWER,EARTH_FRAGMENT); else player:messageSpecial(PLACED_INTO_THE_PEDESTAL); 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 == 0x0001) then player:addTitle(LIGHTWEAVER); player:setVar("ZilartStatus",0); player:addKeyItem(PRISMATIC_FRAGMENT); player:messageSpecial(KEYITEM_OBTAINED,PRISMATIC_FRAGMENT); player:completeMission(ZILART,THE_CHAMBER_OF_ORACLES); player:addMission(ZILART,RETURN_TO_DELKFUTTS_TOWER); end end;
gpl-3.0
TienHP/Aquaria
files/scripts/entities/nauplius.lua
12
6551
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria 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; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end -- ================================================================================================ -- N A U P L I U S -- ================================================================================================ -- ================================================================================================ -- S T A T E S -- ================================================================================================ local MOVE_STATE_UP = 0 local MOVE_STATE_DOWN = 1 -- ================================================================================================ -- L O C A L V A R I A B L E S -- ================================================================================================ v.blupTimer = 0 v.dirTimer = 0 v.blupTime = 3.0 v.fireDelay = 2 v.moveTimer = 0 v.maxShots = 3 v.lastShot = v.maxShots -- ================================================================================================ -- F U N C T I O N S -- ================================================================================================ v.sz = 1.0 v.dir = 0 v.moveState = 0 v.moveTimer = 0 v.velx = 0 v.soundDelay = 0 v.dir = ORIENT_UP local function doIdleScale(me) entity_scale(me, 1.0*v.sz, 0.80*v.sz, v.blupTime, -1, 1, 1) end function init(me) setupBasicEntity( me, "nauplius", -- texture 4, -- health 2, -- manaballamount 2, -- exp 10, -- money 32, -- collideRadius (for hitting entities + spells) STATE_IDLE, -- initState 128, -- sprite width 128, -- sprite height 1, -- particle "explosion" type, 0 = none 0, -- 0/1 hit other entities off/on (uses collideRadius) 4000, -- updateCull -1: disabled, default: 4000 1 ) entity_setEntityType(me, ET_ENEMY) entity_setDeathParticleEffect(me, "PurpleExplode") entity_setDropChance(me, 5) entity_setEatType(me, EAT_FILE, "Jelly") entity_initHair(me, 40, 5, 30, "nauplius-tentacles") entity_scale(me, 0.75*v.sz, 1*v.sz) doIdleScale(me) entity_exertHairForce(me, 0, 400, 1) entity_setState(me, STATE_IDLE) end function update(me, dt) dt = dt * 1.5 if avatar_isBursting() or entity_getRiding(getNaija())~=0 then local e = entity_getRiding(getNaija()) if entity_touchAvatarDamage(me, 32, 0, 400) then if e~=0 then local x,y = entity_getVectorToEntity(me, e) x,y = vector_setLength(x, y, 500) entity_addVel(e, x, y) end local len = 500 local x,y = entity_getVectorToEntity(getNaija(), me) x,y = vector_setLength(x, y, len) entity_push(me, x, y, 0.2, len, 0) entity_sound(me, "JellyBlup", 800) end else if entity_touchAvatarDamage(me, 32, 0, 1000) then entity_sound(me, "JellyBlup", 800) end end entity_handleShotCollisions(me) v.sx,v.sy = entity_getScale(me) -- Quick HACK to handle getting bumped out of the water. --achurch if not entity_isUnderWater(me) then v.moveState = MOVE_STATE_DOWN v.moveTimer = 5 + math.random(200)/100.0 + math.random(3) entity_setMaxSpeed(me, 500) entity_setMaxSpeedLerp(me, 1, 0) entity_addVel(me, 0, 500*dt) entity_updateMovement(me, dt) entity_setHairHeadPosition(me, entity_x(me), entity_y(me)) entity_updateHair(me, dt) return elseif not entity_isState(me, STATE_PUSH) then entity_setMaxSpeed(me, 50) end v.moveTimer = v.moveTimer - dt if v.moveTimer < 0 then if v.moveState == MOVE_STATE_DOWN then v.moveState = MOVE_STATE_UP v.fireDelay = 0.5 entity_setMaxSpeedLerp(me, 1.5, 0.2) entity_scale(me, 0.80, 1, 1, 1, 1) v.moveTimer = 3 + math.random(200)/100.0 entity_sound(me, "JellyBlup") elseif v.moveState == MOVE_STATE_UP then v.moveState = MOVE_STATE_DOWN doIdleScale(me) entity_setMaxSpeedLerp(me, 1, 1) v.moveTimer = math.random(4) + math.random(200)/100.0 end end if v.moveState == MOVE_STATE_UP then if v.dir == ORIENT_UP then entity_addVel(me, 0, -4000*dt) if isObstructed(entity_x(me), entity_y(me)-40) then v.dir = ORIENT_DOWN end elseif v.dir == ORIENT_DOWN then entity_addVel(me, 0, 4000*dt) if isObstructed(entity_x(me), entity_y(me)+40) then v.dir = ORIENT_UP end end --entity_rotateToVel(me, 1) if not(entity_hasTarget(me)) then entity_findTarget(me, 1200) else if v.fireDelay > 0 then v.fireDelay = v.fireDelay - dt if v.fireDelay < 0 then spawnParticleEffect("ArmaShot", entity_x(me), entity_y(me) - 80) local s = createShot("Raspberry", me, entity_getTarget(me), entity_x(me), entity_y(me) - 20) shot_setAimVector(s, entity_getNormal(me)) shot_setOut(s, 64) if v.lastShot <= 1 then v.fireDelay = 4 v.lastShot = v.maxShots else v.fireDelay = 0.5 v.lastShot = v.lastShot - 1 end end end end elseif v.moveState == MOVE_STATE_DOWN then entity_addVel(me, 0, 50*dt) --entity_rotateTo(me, 0, 3) entity_exertHairForce(me, 0, 200, dt*0.6, -1) end entity_doEntityAvoidance(me, dt, 32, 1.0) entity_doCollisionAvoidance(me, 1.0, 8, 1.0) entity_updateCurrents(me, dt) entity_updateMovement(me, dt) entity_setHairHeadPosition(me, entity_x(me), entity_y(me)) entity_updateHair(me, dt) end function hitSurface(me) end function dieNormal(me) end function enterState(me) if entity_isState(me, STATE_IDLE) then entity_setMaxSpeed(me, 50) elseif entity_isState(me, STATE_DEAD) then end end function damage(me, attacker, bone, damageType, dmg) if entity_isName(attacker, "Nauplius") then return false end if damageType == DT_AVATAR_BITE then entity_changeHealth(me, -dmg) end return true end function exitState(me) end
gpl-2.0
CaptainPRICE/wire
lua/entities/gmod_wire_light.lua
10
7999
AddCSLuaFile() DEFINE_BASECLASS( "base_wire_entity" ) ENT.PrintName = "Wire Light" ENT.RenderGroup = RENDERGROUP_BOTH ENT.WireDebugName = "Light" function ENT:SetupDataTables() self:NetworkVar( "Bool", 0, "Glow" ) self:NetworkVar( "Float", 0, "Brightness" ) self:NetworkVar( "Float", 1, "Size" ) self:NetworkVar( "Int", 0, "R" ) self:NetworkVar( "Int", 1, "G" ) self:NetworkVar( "Int", 2, "B" ) end if CLIENT then local matLight = Material( "sprites/light_ignorez" ) local matBeam = Material( "effects/lamp_beam" ) function ENT:Initialize() self.PixVis = util.GetPixelVisibleHandle() --[[ This is some unused value which is used to activate the wire overlay. We're not using it because we are using NetworkVars instead, since wire overlays only update when you look at them, and we want to update the sprite colors whenever the wire input changes. ]] self:SetOverlayData({}) end function ENT:GetMyColor() return Color( self:GetR(), self:GetG(), self:GetB(), 255 ) end function ENT:DrawTranslucent() local up = self:GetAngles():Up() local LightPos = self:GetPos() render.SetMaterial( matLight ) local ViewNormal = self:GetPos() - EyePos() local Distance = ViewNormal:Length() ViewNormal:Normalize() local Visible = util.PixelVisible( LightPos, 4, self.PixVis ) if not Visible or Visible < 0.1 then return end local c = self:GetMyColor() if self:GetModel() == "models/maxofs2d/light_tubular.mdl" then render.DrawSprite( LightPos - up * 2, 8, 8, Color(255, 255, 255, 255), Visible ) render.DrawSprite( LightPos - up * 4, 8, 8, Color(255, 255, 255, 255), Visible ) render.DrawSprite( LightPos - up * 6, 8, 8, Color(255, 255, 255, 255), Visible ) render.DrawSprite( LightPos - up * 5, 128, 128, c, Visible ) else render.DrawSprite( self:LocalToWorld( self:OBBCenter() ), 128, 128, c, Visible ) end end local wire_light_block = CreateClientConVar("wire_light_block", 0, false, false) function ENT:Think() if self:GetGlow() and not wire_light_block:GetBool() then local dlight = DynamicLight(self:EntIndex()) if dlight then dlight.Pos = self:GetPos() local c = self:GetMyColor() dlight.r = c.r dlight.g = c.g dlight.b = c.b dlight.Brightness = self:GetBrightness() dlight.Decay = self:GetSize() * 5 dlight.Size = self:GetSize() dlight.DieTime = CurTime() + 1 end end end local color_box_size = 64 function ENT:GetWorldTipBodySize() -- text local w_total,h_total = surface.GetTextSize( "Color:\n255,255,255,255" ) -- Color box width w_total = math.max(w_total,color_box_size) -- Color box height h_total = h_total + 18 + color_box_size + 18/2 return w_total, h_total end local white = Color(255,255,255,255) local black = Color(0,0,0,255) local function drawColorBox( color, x, y ) surface.SetDrawColor( color ) surface.DrawRect( x, y, color_box_size, color_box_size ) local size = color_box_size surface.SetDrawColor( black ) surface.DrawLine( x, y, x + size, y ) surface.DrawLine( x + size, y, x + size, y + size ) surface.DrawLine( x + size, y + size, x, y + size ) surface.DrawLine( x, y + size, x, y ) end function ENT:DrawWorldTipBody( pos ) -- get color local color = self:GetMyColor() -- text local color_text = string.format("Color:\n%d,%d,%d",color.r,color.g,color.b) local w,h = surface.GetTextSize( color_text ) draw.DrawText( color_text, "GModWorldtip", pos.center.x, pos.min.y + pos.edgesize, white, TEXT_ALIGN_CENTER ) -- color box drawColorBox( color, pos.center.x - color_box_size / 2, pos.min.y + pos.edgesize * 1.5 + h ) end return -- No more client end -- Server function ENT:Initialize() self:PhysicsInit( SOLID_VPHYSICS ) self:SetMoveType( MOVETYPE_VPHYSICS ) self:SetSolid( SOLID_VPHYSICS ) self.Inputs = WireLib.CreateInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]"}) end function ENT:Directional( On ) if On then if IsValid( self.DirectionalComponent ) then return end local flashlight = ents.Create( "env_projectedtexture" ) flashlight:SetParent( self ) -- The local positions are the offsets from parent.. flashlight:SetLocalPos( Vector( 0, 0, 0 ) ) flashlight:SetLocalAngles( Angle( -90, 0, 0 ) ) if self:GetModel() == "models/maxofs2d/light_tubular.mdl" then flashlight:SetLocalAngles( Angle( 90, 0, 0 ) ) end -- Looks like only one flashlight can have shadows enabled! flashlight:SetKeyValue( "enableshadows", 1 ) flashlight:SetKeyValue( "farz", 1024 ) flashlight:SetKeyValue( "nearz", 12 ) flashlight:SetKeyValue( "lightfov", 90 ) local c = self:GetColor() local b = self.brightness flashlight:SetKeyValue( "lightcolor", Format( "%i %i %i 255", c.r * b, c.g * b, c.b * b ) ) flashlight:Spawn() flashlight:Input( "SpotlightTexture", NULL, NULL, "effects/flashlight001" ) self.DirectionalComponent = flashlight elseif IsValid( self.DirectionalComponent ) then self.DirectionalComponent:Remove() self.DirectionalComponent = nil end end function ENT:Radiant( On ) if On then if IsValid( self.RadiantComponent ) then self.RadiantComponent:Fire( "TurnOn", "", "0" ) else local dynlight = ents.Create( "light_dynamic" ) dynlight:SetPos( self:GetPos() ) local dynlightpos = dynlight:GetPos() + Vector( 0, 0, 10 ) dynlight:SetPos( dynlightpos ) dynlight:SetKeyValue( "_light", Format( "%i %i %i 255", self.R, self.G, self.B ) ) dynlight:SetKeyValue( "style", 0 ) dynlight:SetKeyValue( "distance", 255 ) dynlight:SetKeyValue( "brightness", 5 ) dynlight:SetParent( self ) dynlight:Spawn() self.RadiantComponent = dynlight end elseif IsValid( self.RadiantComponent ) then self.RadiantComponent:Fire( "TurnOff", "", "0" ) end end function ENT:UpdateLight() self:SetR( self.R ) self:SetG( self.G ) self:SetB( self.B ) if IsValid( self.DirectionalComponent ) then self.DirectionalComponent:SetKeyValue( "lightcolor", Format( "%i %i %i 255", self.R * self.brightness, self.G * self.brightness, self.B * self.brightness ) ) end if IsValid( self.RadiantComponent ) then self.RadiantComponent:SetKeyValue( "_light", Format( "%i %i %i 255", self.R, self.G, self.B ) ) end end function ENT:TriggerInput(iname, value) if (iname == "Red") then self.R = math.Clamp(value,0,255) elseif (iname == "Green") then self.G = math.Clamp(value,0,255) elseif (iname == "Blue") then self.B = math.Clamp(value,0,255) elseif (iname == "RGB") then self.R, self.G, self.B = math.Clamp(value[1],0,255), math.Clamp(value[2],0,255), math.Clamp(value[3],0,255) elseif (iname == "GlowBrightness") then if not game.SinglePlayer() then value = math.Clamp( value, 0, 10 ) end self.brightness = value self:SetBrightness( value ) elseif (iname == "GlowSize") then if not game.SinglePlayer() then value = math.Clamp( value, 0, 1024 ) end self.size = value self:SetSize( value ) end self:UpdateLight() end function ENT:Setup(directional, radiant, glow, brightness, size, r, g, b) self.directional = directional or false self.radiant = radiant or false self.glow = glow or false self.brightness = brightness or 2 self.size = size or 256 self.R = r or 255 self.G = g or 255 self.B = b or 255 if not game.SinglePlayer() then self.brightness = math.Clamp( self.brightness, 0, 10 ) self.size = math.Clamp( self.size, 0, 1024 ) end self:Directional( self.directional ) self:Radiant( self.radiant ) self:SetGlow( self.glow ) self:SetBrightness( self.brightness ) self:SetSize( self.size ) if self.glow then WireLib.AdjustInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]", "GlowBrightness", "GlowSize"}) else WireLib.AdjustInputs(self, {"Red", "Green", "Blue", "RGB [VECTOR]"}) end self:UpdateLight() end duplicator.RegisterEntityClass("gmod_wire_light", WireLib.MakeWireEnt, "Data", "directional", "radiant", "glow", "brightness", "size", "R", "G", "B")
apache-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Yhoator_Jungle/npcs/Emila_RK.lua
4
2897
----------------------------------- -- Area: Yhoator Jungle -- NPC: Emila, R.K. -- Border Conquest Guards -- @pos -84.113 -0.449 224.902 124 ----------------------------------- package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Yhoator_Jungle/TextIDs"); guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border region = ELSHIMOUPLANDS; csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/spells/gravity.lua
4
1282
----------------------------------------- -- Spell: Gravity ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) -- Pull base stats. dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); bonus = AffinityBonus(caster,spell); power = 50; -- 50% reduction -- Duration, including resistance. Unconfirmed. duration = 120 * applyResistance(caster,spell,target,dINT,35,bonus); if(100 * math.random() >= target:getMod(MOD_GRAVITYRES)) then if(duration >= 30) then --Do it! target:delStatusEffect(EFFECT_WEIGHT); target:addStatusEffect(EFFECT_WEIGHT,power,0,duration); spell:setMsg(236); else -- if(spell:isAOE() == false) then -- spell:setMsg(85); -- else spell:setMsg(284); -- end end else -- if(spell:isAOE() == false) then -- spell:setMsg(85); -- else spell:setMsg(284); -- end end return EFFECT_WEIGHT; end;
gpl-3.0
waytim/darkstar
scripts/zones/North_Gustaberg/npcs/Stone_Monument.lua
13
1276
----------------------------------- -- Area: North Gustaberg -- NPC: Stone Monument -- Involved in quest "An Explorer's Footsteps" -- @pos -199.635 96.106 505.624 106 ----------------------------------- package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil; ----------------------------------- require("scripts/zones/North_Gustaberg/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",0x00020); 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
amostalong/SSFS
Assets/LuaFramework/ToLua/Lua/UnityEngine/Quaternion.lua
7
13664
-------------------------------------------------------------------------------- -- Copyright (c) 2015 , 蒙占志(topameng) topameng@gmail.com -- All rights reserved. -- Use, modification and distribution are subject to the "MIT License" -------------------------------------------------------------------------------- local math = math local sin = math.sin local cos = math.cos local acos = math.acos local asin = math.asin local sqrt = math.sqrt local min = math.min local max = math.max local sign = math.sign local atan2 = math.atan2 local clamp = Mathf.Clamp local abs = math.abs local setmetatable = setmetatable local getmetatable = getmetatable local rawget = rawget local rawset = rawset local Vector3 = Vector3 local rad2Deg = Mathf.Rad2Deg local halfDegToRad = 0.5 * Mathf.Deg2Rad local _forward = Vector3.forward local _up = Vector3.up local _next = { 2, 3, 1 } local Quaternion = {} local get = tolua.initget(Quaternion) Quaternion.__index = function(t, k) local var = rawget(Quaternion, k) if var == nil then var = rawget(get, k) if var ~= nil then return var(t) end end return var end Quaternion.__newindex = function(t, name, k) if name == "eulerAngles" then t:SetEuler(k) else rawset(t, name, k) end end function Quaternion.New(x, y, z, w) local quat = {x = x or 0, y = y or 0, z = z or 0, w = w or 0} setmetatable(quat, Quaternion) return quat end local _new = Quaternion.New Quaternion.__call = function(t, x, y, z, w) return _new(x, y, z, w) end function Quaternion:Set(x,y,z,w) self.x = x or 0 self.y = y or 0 self.z = z or 0 self.w = w or 0 end function Quaternion:Clone() return _new(self.x, self.y, self.z, self.w) end function Quaternion:Get() return self.x, self.y, self.z, self.w end function Quaternion.Dot(a, b) return a.x * b.x + a.y * b.y + a.z * b.z + a.w * b.w end function Quaternion.Angle(a, b) local dot = Quaternion.Dot(a, b) if dot < 0 then dot = -dot end return acos(min(dot, 1)) * 2 * 57.29578 end function Quaternion.AngleAxis(angle, axis) local normAxis = axis:Normalize() angle = angle * halfDegToRad local s = sin(angle) local w = cos(angle) local x = normAxis.x * s local y = normAxis.y * s local z = normAxis.z * s return _new(x,y,z,w) end function Quaternion.Equals(a, b) return a.x == b.x and a.y == b.y and a.z == b.z and a.w == b.w end function Quaternion.Euler(x, y, z) local quat = _new() quat:SetEuler(x,y,z) return quat end function Quaternion:SetEuler(x, y, z) if y == nil and z == nil then y = x.y z = x.z x = x.x end x = x * halfDegToRad y = y * halfDegToRad z = z * halfDegToRad local sinX = sin(x) local cosX = cos(x) local sinY = sin(y) local cosY = cos(y) local sinZ = sin(z) local cosZ = cos(z) self.w = cosY * cosX * cosZ + sinY * sinX * sinZ self.x = cosY * sinX * cosZ + sinY * cosX * sinZ self.y = sinY * cosX * cosZ - cosY * sinX * sinZ self.z = cosY * cosX * sinZ - sinY * sinX * cosZ return self end function Quaternion:Normalize() local quat = self:Clone() quat:SetNormalize() return quat end function Quaternion:SetNormalize() local n = self.x * self.x + self.y * self.y + self.z * self.z + self.w * self.w if n ~= 1 and n > 0 then n = 1 / sqrt(n) self.x = self.x * n self.y = self.y * n self.z = self.z * n self.w = self.w * n end end --产生一个新的从from到to的四元数 function Quaternion.FromToRotation(from, to) local quat = Quaternion.New() quat:SetFromToRotation(from, to) return quat end --设置当前四元数为 from 到 to的旋转, 注意from和to同 forward平行会同unity不一致 function Quaternion:SetFromToRotation1(from, to) local v0 = from:Normalize() local v1 = to:Normalize() local d = Vector3.Dot(v0, v1) if d > -1 + 1e-6 then local s = sqrt((1+d) * 2) local invs = 1 / s local c = Vector3.Cross(v0, v1) * invs self:Set(c.x, c.y, c.z, s * 0.5) elseif d > 1 - 1e-6 then return _new(0, 0, 0, 1) else local axis = Vector3.Cross(Vector3.right, v0) if axis:SqrMagnitude() < 1e-6 then axis = Vector3.Cross(Vector3.forward, v0) end self:Set(axis.x, axis.y, axis.z, 0) return self end return self end local function MatrixToQuaternion(rot, quat) local trace = rot[1][1] + rot[2][2] + rot[3][3] if trace > 0 then local s = sqrt(trace + 1) quat.w = 0.5 * s s = 0.5 / s quat.x = (rot[3][2] - rot[2][3]) * s quat.y = (rot[1][3] - rot[3][1]) * s quat.z = (rot[2][1] - rot[1][2]) * s--]] quat:SetNormalize() else local i = 1 local q = {0, 0, 0} if rot[2][2] > rot[1][1] then i = 2 end if rot[3][3] > rot[i][i] then i = 3 end local j = _next[i] local k = _next[j] local t = rot[i][i] - rot[j][j] - rot[k][k] + 1 local s = 0.5 / sqrt(t) q[i] = s * t local w = (rot[k][j] - rot[j][k]) * s q[j] = (rot[j][i] + rot[i][j]) * s q[k] = (rot[k][i] + rot[i][k]) * s quat:Set(q[1], q[2], q[3], w) quat:SetNormalize() end end function Quaternion:SetFromToRotation(from, to) from = from:Normalize() to = to:Normalize() local e = Vector3.Dot(from, to) if e > 1 - 1e-6 then self:Set(0, 0, 0, 1) elseif e < -1 + 1e-6 then local left = {0, from.z, from.y} local mag = left[2] * left[2] + left[3] * left[3] --+ left[1] * left[1] = 0 if mag < 1e-6 then left[1] = -from.z left[2] = 0 left[3] = from.x mag = left[1] * left[1] + left[3] * left[3] end local invlen = 1/sqrt(mag) left[1] = left[1] * invlen left[2] = left[2] * invlen left[3] = left[3] * invlen local up = {0, 0, 0} up[1] = left[2] * from.z - left[3] * from.y up[2] = left[3] * from.x - left[1] * from.z up[3] = left[1] * from.y - left[2] * from.x local fxx = -from.x * from.x local fyy = -from.y * from.y local fzz = -from.z * from.z local fxy = -from.x * from.y local fxz = -from.x * from.z local fyz = -from.y * from.z local uxx = up[1] * up[1] local uyy = up[2] * up[2] local uzz = up[3] * up[3] local uxy = up[1] * up[2] local uxz = up[1] * up[3] local uyz = up[2] * up[3] local lxx = -left[1] * left[1] local lyy = -left[2] * left[2] local lzz = -left[3] * left[3] local lxy = -left[1] * left[2] local lxz = -left[1] * left[3] local lyz = -left[2] * left[3] local rot = { {fxx + uxx + lxx, fxy + uxy + lxy, fxz + uxz + lxz}, {fxy + uxy + lxy, fyy + uyy + lyy, fyz + uyz + lyz}, {fxz + uxz + lxz, fyz + uyz + lyz, fzz + uzz + lzz}, } MatrixToQuaternion(rot, self) else local v = Vector3.Cross(from, to) local h = (1 - e) / Vector3.Dot(v, v) local hx = h * v.x local hz = h * v.z local hxy = hx * v.y local hxz = hx * v.z local hyz = hz * v.y local rot = { {e + hx*v.x, hxy - v.z, hxz + v.y}, {hxy + v.z, e + h*v.y*v.y, hyz-v.x}, {hxz - v.y, hyz + v.x, e + hz*v.z}, } MatrixToQuaternion(rot, self) end end function Quaternion:Inverse() local quat = Quaternion.New() quat.x = -self.x quat.y = -self.y quat.z = -self.z quat.w = self.w return quat end function Quaternion.Lerp(q1, q2, t) t = clamp(t, 0, 1) local q = _new() if Quaternion.Dot(q1, q2) < 0 then q.x = q1.x + t * (-q2.x -q1.x) q.y = q1.y + t * (-q2.y -q1.y) q.z = q1.z + t * (-q2.z -q1.z) q.w = q1.w + t * (-q2.w -q1.w) else q.x = q1.x + (q2.x - q1.x) * t q.y = q1.y + (q2.y - q1.y) * t q.z = q1.z + (q2.z - q1.z) * t q.w = q1.w + (q2.w - q1.w) * t end q:SetNormalize() return q end function Quaternion.LookRotation(forward, up) local mag = forward:Magnitude() if mag < 1e-6 then error("error input forward to Quaternion.LookRotation" + tostring(forward)) return nil end forward = forward / mag up = up or _up local right = Vector3.Cross(up, forward) right:SetNormalize() up = Vector3.Cross(forward, right) right = Vector3.Cross(up, forward) --[[ local quat = _new(0,0,0,1) local rot = { {right.x, up.x, forward.x}, {right.y, up.y, forward.y}, {right.z, up.z, forward.z}, } MatrixToQuaternion(rot, quat) return quat--]] local t = right.x + up.y + forward.z if t > 0 then local x, y, z, w t = t + 1 local s = 0.5 / sqrt(t) w = s * t x = (up.z - forward.y) * s y = (forward.x - right.z) * s z = (right.y - up.x) * s local ret = _new(x, y, z, w) ret:SetNormalize() return ret else local rot = { {right.x, up.x, forward.x}, {right.y, up.y, forward.y}, {right.z, up.z, forward.z}, } local q = {0, 0, 0} local i = 1 if up.y > right.x then i = 2 end if forward.z > rot[i][i] then i = 3 end local j = _next[i] local k = _next[j] local t = rot[i][i] - rot[j][j] - rot[k][k] + 1 local s = 0.5 / sqrt(t) q[i] = s * t local w = (rot[k][j] - rot[j][k]) * s q[j] = (rot[j][i] + rot[i][j]) * s q[k] = (rot[k][i] + rot[i][k]) * s local ret = _new(q[1], q[2], q[3], w) ret:SetNormalize() return ret end end function Quaternion:SetIdentity() self.x = 0 self.y = 0 self.z = 0 self.w = 1 end local function UnclampedSlerp(from, to, t) local cosAngle = Quaternion.Dot(from, to) if cosAngle < 0 then cosAngle = -cosAngle to = Quaternion.New(-to.x, -to.y, -to.z, -to.w) end local t1, t2 if cosAngle < 0.95 then local angle = acos(cosAngle) local sinAngle = sin(angle) local invSinAngle = 1 / sinAngle t1 = sin((1 - t) * angle) * invSinAngle t2 = sin(t * angle) * invSinAngle local quat = _new(from.x * t1 + to.x * t2, from.y * t1 + to.y * t2, from.z * t1 + to.z * t2, from.w * t1 + to.w * t2) return quat else return Quaternion.Lerp(from, to, t) end end function Quaternion.Slerp(from, to, t) t = clamp(t, 0, 1) return UnclampedSlerp(from, to, t) end function Quaternion.RotateTowards(from, to, maxDegreesDelta) local angle = Quaternion.Angle(from, to) if angle == 0 then return to end local t = min(1, maxDegreesDelta / angle) return UnclampedSlerp(from, to, t) end local function Approximately(f0, f1) return abs(f0 - f1) < 1e-6 end function Quaternion:ToAngleAxis() local angle = 2 * acos(self.w) if Approximately(angle, 0) then return angle * 57.29578, Vector3.New(1, 0, 0) end local div = 1 / sqrt(1 - sqrt(self.w)) return angle * 57.29578, Vector3.New(self.x * div, self.y * div, self.z * div) end local pi = Mathf.PI local half_pi = pi * 0.5 local two_pi = 2 * pi local negativeFlip = -0.0001 local positiveFlip = two_pi - 0.0001 local function SanitizeEuler(euler) if euler.x < negativeFlip then euler.x = euler.x + two_pi elseif euler.x > positiveFlip then euler.x = euler.x - two_pi end if euler.y < negativeFlip then euler.y = euler.y + two_pi elseif euler.y > positiveFlip then euler.y = euler.y - two_pi end if euler.z < negativeFlip then euler.z = euler.z + two_pi elseif euler.z > positiveFlip then euler.z = euler.z + two_pi end end --from http://www.geometrictools.com/Documentation/EulerAngles.pdf --Order of rotations: YXZ function Quaternion:ToEulerAngles() local x = self.x local y = self.y local z = self.z local w = self.w local check = 2 * (y * z - w * x) if check < 0.999 then if check > -0.999 then local v = Vector3.New( -asin(check), atan2(2 * (x * z + w * y), 1 - 2 * (x * x + y * y)), atan2(2 * (x * y + w * z), 1 - 2 * (x * x + z * z))) SanitizeEuler(v) v:Mul(rad2Deg) return v else local v = Vector3.New(half_pi, atan2(2 * (x * y - w * z), 1 - 2 * (y * y + z * z)), 0) SanitizeEuler(v) v:Mul(rad2Deg) return v end else local v = Vector3.New(-half_pi, atan2(-2 * (x * y - w * z), 1 - 2 * (y * y + z * z)), 0) SanitizeEuler(v) v:Mul(rad2Deg) return v end end function Quaternion:Forward() return self:MulVec3(_forward) end function Quaternion.MulVec3(self, point) local vec = Vector3.New() local num = self.x * 2 local num2 = self.y * 2 local num3 = self.z * 2 local num4 = self.x * num local num5 = self.y * num2 local num6 = self.z * num3 local num7 = self.x * num2 local num8 = self.x * num3 local num9 = self.y * num3 local num10 = self.w * num local num11 = self.w * num2 local num12 = self.w * num3 vec.x = (((1 - (num5 + num6)) * point.x) + ((num7 - num12) * point.y)) + ((num8 + num11) * point.z) vec.y = (((num7 + num12) * point.x) + ((1 - (num4 + num6)) * point.y)) + ((num9 - num10) * point.z) vec.z = (((num8 - num11) * point.x) + ((num9 + num10) * point.y)) + ((1 - (num4 + num5)) * point.z) return vec end Quaternion.__mul = function(lhs, rhs) if Quaternion == getmetatable(rhs) then return Quaternion.New((((lhs.w * rhs.x) + (lhs.x * rhs.w)) + (lhs.y * rhs.z)) - (lhs.z * rhs.y), (((lhs.w * rhs.y) + (lhs.y * rhs.w)) + (lhs.z * rhs.x)) - (lhs.x * rhs.z), (((lhs.w * rhs.z) + (lhs.z * rhs.w)) + (lhs.x * rhs.y)) - (lhs.y * rhs.x), (((lhs.w * rhs.w) - (lhs.x * rhs.x)) - (lhs.y * rhs.y)) - (lhs.z * rhs.z)) elseif Vector3 == getmetatable(rhs) then return lhs:MulVec3(rhs) end end Quaternion.__unm = function(q) return Quaternion.New(-q.x, -q.y, -q.z, -q.w) end Quaternion.__eq = function(lhs,rhs) return Quaternion.Dot(lhs, rhs) > 0.999999 end Quaternion.__tostring = function(self) return "["..self.x..","..self.y..","..self.z..","..self.w.."]" end get.identity = function() return _new(0, 0, 0, 1) end get.eulerAngles = Quaternion.ToEulerAngles UnityEngine.Quaternion = Quaternion setmetatable(Quaternion, Quaternion) return Quaternion
mit
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/rolanberry.lua
3
1088
----------------------------------------- -- ID: 4365 -- Item: rolanberry -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility -4 -- Intelligence 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4365); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, -4); target:addMod(MOD_INT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, -4); target:delMod(MOD_INT, 2); end;
gpl-3.0