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 |
|---|---|---|---|---|---|
waytim/darkstar | scripts/zones/GM_Home/npcs/Trader.lua | 32 | 1090 | -----------------------------------
-- Area: GM Home
-- NPC: Trader
-- Type: Debug NPC for testing trades.
-----------------------------------
package.loaded["scripts/zones/GM_Home/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/GM_Home/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(4096,1) and trade:getItemCount() == 1) then
player:startEvent(126);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(127);
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/Bastok_Mines/npcs/Deadly_Spider.lua | 3 | 1414 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Deadly Spider
-- Involved in Quest: Stamp Hunt
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT);
stampCount = player:getVar("StampHunt_Event");
checkStamp = testflag(tonumber(stampCount),0x2);
if (StampHunt == 1 and checkStamp == false) then
player:setVar("StampHunt_Event",stampCount+0x2);
player:startEvent(0x0056);
else
player:startEvent(0x0011);
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 |
GregSatre/nn | ParallelCriterion.lua | 18 | 1309 | local ParallelCriterion, parent = torch.class('nn.ParallelCriterion', 'nn.Criterion')
function ParallelCriterion:__init(repeatTarget)
parent.__init(self)
self.criterions = {}
self.weights = {}
self.gradInput = {}
self.repeatTarget = repeatTarget
end
function ParallelCriterion:add(criterion, weight)
weight = weight or 1
table.insert(self.criterions, criterion)
table.insert(self.weights, weight)
return self
end
function ParallelCriterion:updateOutput(input, target)
self.output = 0
for i,criterion in ipairs(self.criterions) do
local target = self.repeatTarget and target or target[i]
self.output = self.output + self.weights[i]*criterion:updateOutput(input[i],target)
end
return self.output
end
function ParallelCriterion:updateGradInput(input, target)
self.gradInput = nn.utils.recursiveResizeAs(self.gradInput, input)
nn.utils.recursiveFill(self.gradInput, 0)
for i,criterion in ipairs(self.criterions) do
local target = self.repeatTarget and target or target[i]
nn.utils.recursiveAdd(self.gradInput[i], self.weights[i], criterion:updateGradInput(input[i], target))
end
return self.gradInput
end
function ParallelCriterion:type(type, tensorCache)
self.gradInput = {}
return parent.type(self, type, tensorCache)
end
| bsd-3-clause |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99980340.lua | 1 | 2296 | --HN - Leanbox
function c99980340.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--Mill
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c99980340.millcon)
e2:SetTarget(c99980340.milltg)
e2:SetOperation(c99980340.millop)
c:RegisterEffect(e2)
--To Hand
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetCondition(c99980340.thcon)
e3:SetTarget(c99980340.thtg)
e3:SetOperation(c99980340.thop)
c:RegisterEffect(e3)
end
function c99980340.millfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x998) and c:IsControler(tp) and c:GetSummonType()==SUMMON_TYPE_XYZ
end
function c99980340.millcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c99980340.millfilter,1,nil,tp) and rp==tp
end
function c99980340.milltg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDiscardDeck(1-tp,1) end
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DECKDES,nil,0,1-tp,1)
end
function c99980340.millop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.DiscardDeck(p,d,REASON_EFFECT)
end
function c99980340.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY)
end
function c99980340.thfilter(c)
return c:IsSetCard(0x998) and c:IsLevelBelow(4) and c:IsAbleToHand()
end
function c99980340.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c99980340.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c99980340.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c99980340.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end | gpl-3.0 |
LuaDist2/prosody | core/storagemanager.lua | 2 | 4872 |
local type, pairs = type, pairs;
local setmetatable = setmetatable;
local config = require "core.configmanager";
local datamanager = require "util.datamanager";
local modulemanager = require "core.modulemanager";
local multitable = require "util.multitable";
local hosts = hosts;
local log = require "util.logger".init("storagemanager");
local prosody = prosody;
module("storagemanager")
local olddm = {}; -- maintain old datamanager, for backwards compatibility
for k,v in pairs(datamanager) do olddm[k] = v; end
_M.olddm = olddm;
local null_storage_method = function () return false, "no data storage active"; end
local null_storage_driver = setmetatable(
{
name = "null",
open = function (self) return self; end
}, {
__index = function (self, method) --luacheck: ignore 212
return null_storage_method;
end
}
);
local stores_available = multitable.new();
function initialize_host(host)
local host_session = hosts[host];
host_session.events.add_handler("item-added/storage-provider", function (event)
local item = event.item;
stores_available:set(host, item.name, item);
end);
host_session.events.add_handler("item-removed/storage-provider", function (event)
local item = event.item;
stores_available:set(host, item.name, nil);
end);
end
prosody.events.add_handler("host-activated", initialize_host, 101);
function load_driver(host, driver_name)
if driver_name == "null" then
return null_storage_driver;
end
local driver = stores_available:get(host, driver_name);
if driver then return driver; end
local ok, err = modulemanager.load(host, "storage_"..driver_name);
if not ok then
log("error", "Failed to load storage driver plugin %s on %s: %s", driver_name, host, err);
end
return stores_available:get(host, driver_name);
end
function get_driver(host, store)
local storage = config.get(host, "storage");
local driver_name;
local option_type = type(storage);
if option_type == "string" then
driver_name = storage;
elseif option_type == "table" then
driver_name = storage[store];
end
if not driver_name then
driver_name = config.get(host, "default_storage") or "internal";
end
local driver = load_driver(host, driver_name);
if not driver then
log("warn", "Falling back to null driver for %s storage on %s", store, host);
driver_name = "null";
driver = null_storage_driver;
end
return driver, driver_name;
end
local map_shim_mt = {
__index = {
get = function(self, username, key)
local ret, err = self.keyval_store:get(username);
if ret == nil then return nil, err end
return ret[key];
end;
set = function(self, username, key, data)
local current, err = self.keyval_store:get(username);
if current == nil then
if err then
return nil, err;
else
current = {};
end
end
current[key] = data;
return self.keyval_store:set(username, current);
end;
};
}
local function create_map_shim(host, store)
local keyval_store, err = open(host, store, "keyval");
if keyval_store == nil then return nil, err end
return setmetatable({
keyval_store = keyval_store;
}, map_shim_mt);
end
function open(host, store, typ)
local driver, driver_name = get_driver(host, store);
local ret, err = driver:open(store, typ);
if not ret then
if err == "unsupported-store" then
if typ == "map" then -- Use shim on top of keyval store
log("debug", "map storage driver unavailable, using shim on top of keyval store.");
return create_map_shim(host, store);
end
log("debug", "Storage driver %s does not support store %s (%s), falling back to null driver",
driver_name, store, typ or "<nil>");
ret = null_storage_driver;
err = nil;
end
end
return ret, err;
end
function purge(user, host)
local storage = config.get(host, "storage");
if type(storage) == "table" then
-- multiple storage backends in use that we need to purge
local purged = {};
for store, driver in pairs(storage) do
if not purged[driver] then
purged[driver] = get_driver(host, store):purge(user);
end
end
end
get_driver(host):purge(user); -- and the default driver
olddm.purge(user, host); -- COMPAT list stores, like offline messages end up in the old datamanager
return true;
end
function datamanager.load(username, host, datastore)
return open(host, datastore):get(username);
end
function datamanager.store(username, host, datastore, data)
return open(host, datastore):set(username, data);
end
function datamanager.users(host, datastore, typ)
local driver = open(host, datastore, typ);
if not driver.users then
return function() log("warn", "storage driver %s does not support listing users", driver.name) end
end
return driver:users();
end
function datamanager.stores(username, host, typ)
return get_driver(host):stores(username, typ);
end
function datamanager.purge(username, host)
return purge(username, host);
end
return _M;
| mit |
deepmind/classic | classic/Class.lua | 2 | 17772 | local classic = assert(classic, 'metaclass should not be required directly')
-- Argument checking: check that self was correctly passed.
local function checkSelf(self, name)
if type(self) ~= 'table' then
error(name .. "() must be called on a class. Did you forget the colon?", 3)
end
end
-- Argument checking: check that a string argument was correctly passed.
local function checkStringArg(str, name)
if type(str) ~= 'string' then
error(name .. "() expects a string argument, but got "
.. tostring(type(str)) .. ".", 3)
end
end
local Class = {}
--[[ Creates a new Class object.
This should not be called by user code directly - use `classic.class()` instead.
Arguments:
* `name` - Lua string containing the desired name of the class.
* `parent` - a classic class (optional).
Returns: a new classic class.
]]
function Class:_init(name, parent)
local methods = {}
local requiredMethods = {}
local finalMethods = {}
local classAttributes = {}
local staticMethods = {}
setmetatable(classAttributes, {
__newindex = function(tbl, attributeName, attributeValue)
if attributeName == 'static' then
error("Defining a class attribute called 'static' in " .. name
.. " is forbidden because it causes ambiguity.", 2)
end
if rawget(staticMethods, attributeName) then
error("A naming conflict was detected in " .. name
.. ": you are trying to set a class attribute '"
.. attributeName .. " that has the same name as an existing "
.. "static method.", 2)
end
if rawget(Class, attributeName) then
error("A naming conflict was detected in " .. name
.. ": you are trying to set a class attribute '"
.. attributeName .. " that has the same name as one of the "
.. " methods that are available on all class objects. This is "
.. "forbidden because it causes ambiguity when you try to"
.. " call it", 2)
end
rawset(tbl, attributeName, attributeValue)
end
})
setmetatable(staticMethods, {
__newindex = function(tbl, method, definition)
if method == 'static' then
error("Defining a static method called 'static' in " .. name
.. " is forbidden because it causes ambiguity.", 2)
end
if rawget(classAttributes, method) then
error("A naming conflict was detected in " .. name
.. ": you are trying to define a static method '" .. method
.. "' that has the same name as an existing class attribute.",
2)
end
if rawget(Class, method) then
error("A naming conflict was detected in " .. name
.. ": you are trying to define a static method '" .. method
.. "' that has the same name as one of the methods that are "
.. "available on all class objects. This is forbidden because "
.. "it causes ambiguity when you try to call it.", 2)
end
rawset(tbl, method, definition)
end
})
rawset(self, '_name', name)
rawset(self, '_parent', parent)
rawset(self, '_methods', methods)
rawset(self, '_classAttributes', classAttributes)
rawset(self, '_requiredMethods', requiredMethods)
rawset(self, '_finalMethods', finalMethods)
rawset(self, 'static', staticMethods)
-- Apply inheritance if necessary.
if parent ~= nil then
-- Copy instance methods from parent to the new class.
for name, func in pairs(rawget(parent, '_methods')) do
if methods[name] == nil then
methods[name] = func
end
end
-- Inherit any 'mustHave' settings.
for _, methodName in ipairs(rawget(parent, '_requiredMethods')) do
table.insert(requiredMethods, methodName)
end
-- Inherit any 'final' settings.
for methodName, _ in pairs(rawget(parent, '_finalMethods')) do
finalMethods[methodName] = true
end
end
-- These methods are callable on all classic objects. We implement them for
-- this class here.
local Object = {
class = function(obj) return self end,
classIs = function(obj, otherKlass)
return self == otherKlass
end,
}
setmetatable(methods, {__index = Object})
end
--[[ Returns the name of the class.
Arguments: none.
Returns:
1. Lua string.
]]
function Class:name()
return self._name
end
--[[ Returns the parent of the class.
Arguments: none.
Returns: classic.Class, or nil if there is no parent
]]
function Class:parent()
return self._parent
end
--[[ Checks whether a given object is of precisely this class's type.
This does not traverse the inheritance tree at all.
Arguments:
* `obj` - an instance of a classic class.
Returns: boolean; true if the object is an instance of this particular class.
]]
function Class:isClassOf(x)
return self == x:class()
end
--[[ Checks whether a given class is an ancestor of this class in the
inheritance tree.
Arguments:
* `class` - a classic class.
Returns: boolean; true if self is a subtype of the given class.
]]
function Class:isSubclassOf(klass)
if self == klass then
return true
end
local parent = rawget(self, '_parent')
if parent then
return parent:isSubclassOf(klass)
end
return false
end
--[[ Returns a table giving access to the parent's methods.
For convenience, rather than calling super(), you will probably want to use the
local MyClass, super = classic.class("MyClass")
shortcut.
Parent methods can then be called like so:
super.myMethod(self, opts)
**Note the need to pass in the instance of the object, 'self', explicitly!**
However, if you wanted to do it the long way, you could do:
MyClass:super().myMethod(self, opts)
Arguments: none.
Returns:
* a Lua table. Indexing into the table with a valid parent method name will
return the corresponding function. Indexing with invalid names
or assigning to the table will throw an error.
]]
function Class:super()
local parent = self._parent
if not parent then
error(table.concat{"super() called, but ",
self:name(), " has no parent!"}, 2)
end
local parentProxy = {}
for name, method in pairs(parent._methods) do
parentProxy[name] = function(arg1, ...)
if arg1 == parentProxy then
error("Misuse of Super object! Do not call it with a colon. " ..
"Correct way: Super." .. name .. "(self, ...)", 2)
end
return method(arg1, ...)
end
end
setmetatable(parentProxy, {
__index = function(tbl, key)
error(table.concat{
"Trying to call method '", key, "' via super(), but the parent ",
"class (", parent:name(), ") has no such method."}, 2)
end,
__newindex = function(tbl, key, value)
error(table.concat{"Trying to assign to a value via super(),",
" but this is not allowed!"}, 2)
end,
})
return parentProxy
end
--[[ Returns a Lua string which corresponds uniquely to the content of the class
definition - i.e. the actual bytecode of the methods therein.
This may be useful for serialization.
Arguments: none.
Returns: Lua string; as described above.
]]
function Class:hash()
local hashes = {}
for k, v in pairs(self) do
local hash
if type(v) == 'function' then
table.insert(hashes, k .. string.dump(v))
else
table.insert(hashes, k .. v)
end
end
return table.concat(hashes)
end
--[[ To be used during class definition: indicates that neither this class, nor
any subclass of it, may be instantiated - unless a method with the given name
has been defined.
Simply, this is useful if you want to specify that certain methods are left to
be implemented by subclasses, and should not be omitted.
Arguments:
* `methodName` - Lua string containing a valid method name.
Returns: none.
]]
function Class:mustHave(methodName)
checkSelf(self, 'mustHave')
checkStringArg(methodName, 'mustHave')
local requiredMethods = rawget(self, '_requiredMethods')
table.insert(requiredMethods, methodName)
end
--[[ Marks a method as 'final'.
This can be used during class definition to indicate that a particular method
should *not* be overridden by subclasses, or in classes that include this class
as a mixin.
Any subsequent attempt to do so will trigger an error.
Arguments:
* `methodName` - Lua string containing a valid method name.
Returns: none.
]]
function Class:final(methodName)
checkSelf(self, 'final')
checkStringArg(methodName, 'final')
local methods = rawget(self, '_methods')
if methods[methodName] == nil then
error("attempted to mark method '" .. methodName ..
"' as final, but no method of that name has been declared yet.", 2)
end
local finalMethods = rawget(self, '_finalMethods')
finalMethods[methodName] = true
end
--[[ Checks whether a given method name is marked as 'final'.
Arguments:
* `methodName` - Lua string containing a valid method name.
Returns: boolean; true if the method name is final, and false otherwise.
]]
function Class:methodIsFinal(methodName)
checkSelf(self, 'methodIsFinal')
checkStringArg(methodName, 'methodIsFinal')
local finalMethods = rawget(self, '_finalMethods')
return finalMethods[methodName] ~= nil
end
--[[ Returns a table of methods for this class (excluding private methods).
This can be used to iterate over all methods of a class, or to call a method of
the class on some other object, for example.
Arguments: none.
Returns: Lua table, mapping from method name to function.
]]
function Class:methods()
checkSelf(self, 'methods')
local methods = {}
for name, func in pairs(self._methods) do
if type(func) == 'function' and string.sub(name, 1, 1) ~= "_"
and Class[name] == nil then
methods[name] = func
end
end
return methods
end
--[[ Returns a table of methods for this class, including private methods.
This can be used to iterate over all methods of a class, or to call a method of
the class on some other object, for example.
Arguments: none.
Returns: Lua table, mapping from method name to function.
]]
function Class:allMethods()
checkSelf(self, 'methods')
local methods = {}
for name, func in pairs(self._methods) do
if type(func) == 'function' and Class[name] == nil then
methods[name] = func
end
end
return methods
end
--[[ Creates an object; an instance of this class.
Generally you'd want to call this the short way:
local obj = MyClass(opts)
But if you really wanted to, you could equivalently do:
local obj = MyClass:instantiate(opts)
This will call the constructor (_init) if one has been defined.
Note that the details of this object's metatable and internals depend on whether
Torch compatibility mode is enabled! In general, these internals may be subject
to change, and you should aim not to rely on them.
Arguments:
* `...` - any arguments to be passed to the constructor.
Returns: a new object, whose type is this class.
]]
function Class:instantiate(...)
checkSelf(self, 'instantiate')
assert(self ~= nil, "badly formed constructor call")
local parent = rawget(self, '_parent')
local methods = rawget(self, '_methods')
local requiredMethods = rawget(self, '_requiredMethods')
for _, methodName in ipairs(requiredMethods) do
if methods[methodName] == nil then
error("You cannot instantiate " .. self._name
.. " since " .. methodName .. "() is marked as"
.. " *mustHave*, yet has not been implemented.")
end
end
local obj = classic._createObject(self)
local constructor = methods._init
if constructor ~= nil then
constructor(obj, ...)
end
return obj
end
--[[ Adds the contents of the given class to this class's definition.
This is less commonly used, but provides a way of reusing functionality via a
with a weaker relationship than inheritance. This is akin to mixins, or traits,
in other languages.
Arguments:
* `class` - another classic class to include.
Returns: none.
]]
function Class:include(klass)
if type(klass) == 'string' then
klass = classic.getClass(klass)
end
assert(klass ~= nil, "invalid class include")
-- Methods provided by the mixin are copied to the including class.
local methods = rawget(self, '_methods')
local otherMethods = rawget(klass, '_methods')
for name, func in pairs(otherMethods) do
if methods[name] ~= nil then
error("method conflict: trying to include " .. name .. "() from "
.. klass:name() .. ", but a method of that name already exists.", 2)
end
methods[name] = func
end
-- Methods required by the mixin are also required by the including class.
local requiredMethods = rawget(self, '_requiredMethods')
local otherRequiredMethods = rawget(klass, '_requiredMethods')
for _, name in pairs(otherRequiredMethods) do
table.insert(requiredMethods, name)
end
-- Methods marked final should also be final in the including class.
local finalMethods = rawget(self, '_finalMethods')
local otherFinalMethods = rawget(klass, '_finalMethods')
for name, _ in pairs(otherFinalMethods) do
finalMethods[name] = true
end
end
--[[ Checks whether the class is abstract.
In other words, does it have any methods marked 'mustHave' that are not
implemented.
Arguments: none.
Returns: boolean; true if abstract, false if not.
]]
function Class:abstract()
local methods = rawget(self, '_methods')
local requiredMethods = rawget(self, '_requiredMethods')
for _, methodName in ipairs(requiredMethods) do
if methods[methodName] == nil then
return true
end
end
return false
end
local Metaclass = {}
--[[ This provides the shortcut whereby we can instantiate MyClass by calling it
as if it were a function:
local instance = MyClass()
]]
function Metaclass.__call(self, ...)
return self:instantiate(...)
end
--[[ This handles looking things up in the class object. There are several types
of data that live in the class. We store them separately so that they don't get
mixed up, but this means that we need to look in several places to find a value.
]]
function Metaclass.__index(self, name)
-- If looking for the 'static' table that is used for defining static methods,
-- return that.
local static = rawget(self, 'static')
if name == 'static' then
return static
end
-- If looking for a static method, return that.
local staticMethod = rawget(static, name)
if staticMethod then
return staticMethod
end
-- If looking for a class attribute, return that.
local classAttributes = rawget(self, '_classAttributes')
if classAttributes[name] ~= nil then
return classAttributes[name]
end
-- If looking for one of the global class methods, return that.
if Class[name] ~= nil then
return Class[name]
end
error(tostring(name)
.. " is neither a static method, a class attribute, nor a global class "
.. "method.", 2)
end
--[[ This handles defining new things in the class. Things defined directly on
the class must either be class attributes, or instance methods. Static methods
must be defined through the 'static' table and so do not come through this
function.
]]
function Metaclass.__newindex(self, name, value)
-- If it's not a function, it's a class attribute.
if type(value) ~= 'function' then
rawget(self, '_classAttributes')[name] = value
classic._notify(classic.events.CLASS_SET_ATTRIBUTE, self, name, value)
end
-- Otherwise, we're defining an instance method (the normal case).
-- We have a check for the constructor name, because it's easy to accidentally
-- define the constructor with the wrong name and get confused, otherwise.
if name == '__init' or name == 'init' then
error("did you mean _init?")
end
-- Check that we're not trying to override a final method.
local parent = rawget(self, '_parent')
local methods = rawget(self, '_methods')
if (parent and parent:methodIsFinal(name)) or
(self:methodIsFinal(name) and rawget(methods, name) ~= nil) then
error("Attempted to define method '" .. name .. "' in class '" ..
self._name .. "', but '" .. name .. "' is marked as final.", 2)
end
rawset(methods, name, value)
classic._notify(classic.events.CLASS_DEFINE_METHOD, self, name, value)
end
--[[ String representation of the class object. ]]
function Metaclass.__tostring(self)
return table.concat{"classic.class<",
tostring(rawget(self, '_name')), ">"}
end
--[[ This is a flag marking the object as being a classic class object, which
can then later be used for checking whether or not something is one. ]]
Metaclass.classicClass = true
--[[ We can create a new class object by calling
local MyClass = Class(name, parent)
But users should create classes via classic.class().
]]
setmetatable(Class, {
__call = function(self, options)
local name = options.name
if name == nil then
error("Missing option when creating class: 'name'.", 3)
end
if type(name) ~= 'string' then
error("Expected class name to be a string.", 3)
end
local parent = options.parent
-- Parent classes may be specified either by passing a class object
-- directly, or by passing the name of a class as a string.
if parent ~= nil and type(parent) == 'string' then
parent = classic.getClass(parent)
end
if parent ~= nil then
if not classic.isClass(parent) then
error("parent is not a class", 3)
end
end
local klass = {}
setmetatable(klass, Metaclass)
Class._init(klass, name, parent or nil)
classic._notify(classic.events.CLASS_INIT, name)
return klass
end
})
return Class
| bsd-3-clause |
TheOnePharaoh/YGOPro-Custom-Cards | script/c100000876.lua | 2 | 1663 | --Created and coded by Rising Phoenix
function c100000876.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCountLimit(1,100000876+EFFECT_COUNT_CODE_OATH)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e1:SetTarget(c100000876.target)
e1:SetOperation(c100000876.activate)
e1:SetCondition(c100000876.condition2)
c:RegisterEffect(e1)
end
function c100000876.filter(c,e,tp)
return c:IsCode(100000868) and c:IsCanBeSpecialSummoned(e,0,tp,true,false)
end
function c100000876.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c100000876.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,LOCATION_REMOVED)
end
function c100000876.activate(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,c100000876.filter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
if g:GetCount()>0 then end
Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP)
end
function c100000876.spfilter1(c)
return (c:IsSetCard(0x10E) and c:IsType(TYPE_MONSTER))
end
function c100000876.spfilter2(c)
return c:IsCode(100000868)
end
function c100000876.condition2(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c100000876.spfilter1,tp,LOCATION_REMOVED,0,5,nil)
and Duel.IsExistingMatchingCard(c100000876.spfilter2,tp,LOCATION_REMOVED,0,1,nil)
end | gpl-3.0 |
waytim/darkstar | scripts/globals/spells/bluemagic/radiant_breath.lua | 25 | 2259 | -----------------------------------------
-- Spell: Radiant Breath
-- Deals light damage to enemies within a fan-shaped area of effect originating from the caster. Additional effect: Slow and Silence.
-- Spell cost: 116 MP
-- Monster Type: Wyverns
-- Spell Type: Magical (Light)
-- Blue Magic Points: 4
-- Stat Bonus: CHR+1, HP+5
-- Level: 54
-- Casting Time: 5.25 seconds
-- Recast Time: 33.75 seconds
-- Magic Bursts on: Transfixion, Fusion, Light
-- Combos: None
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
local multi = 2.90;
if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then
multi = multi + 0.50;
end
params.multiplier = multi;
params.tMultiplier = 1.5;
params.duppercap = 69;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.3;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0);
if (damage > 0 and resist > 0.3) then
local typeEffect = EFFECT_SLOW;
target:delStatusEffect(typeEffect);
target:addStatusEffect(typeEffect,35,0,getBlueEffectDuration(caster,resist,typeEffect));
end
if (damage > 0 and resist > 0.3) then
local typeEffect = EFFECT_SILENCE;
target:delStatusEffect(typeEffect);
target:addStatusEffect(typeEffect,25,0,getBlueEffectDuration(caster,resist,typeEffect));
end
return damage;
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/gain-agi.lua | 2 | 2309 | --------------------------------------
-- Spell: Gain-AGI
-- Boosts targets AGI 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_AGI_DOWN) == true) then
target:delStatusEffect(EFFECT_AGI_DOWN);
else
target:addStatusEffect(EFFECT_AGI_BOOST,power,0,duration);
end
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Temple_of_Uggalepih/npcs/Stone_Picture_Frame.lua | 27 | 3762 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Stone Picture Frame
-- Notes: Opens door to Den of Rancor using Painbrush of Souls
-- @pos -52.239 -2.089 10.000 159
-----------------------------------
package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Temple_of_Uggalepih/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local X = player:getXPos();
local Z = player:getZPos();
local DoorToRancor = 17428989;
if (X < -60) then
if (Z < -6) then -- SW frame
if (player:hasKeyItem(FINAL_FANTASY)) then
player:startEvent(0x0032,FINAL_FANTASY);
else
player:messageSpecial(PAINTBRUSH_OFFSET + 31); -- This is a frame for a painting.
end
elseif (Z < 5) then
player:messageSpecial(PAINTBRUSH_OFFSET + 14); -- It is a picture of an old mage carrying a staff.
else
player:messageSpecial(PAINTBRUSH_OFFSET + 13); -- It is a picture of a small group of three men and women.
end
else
if (Z <-5) then -- SE picture
player:messageSpecial(PAINTBRUSH_OFFSET + 12); -- It is a painting of a beautiful landscape.
elseif (Z > -5 and Z < 5) then
if (GetNPCByID(DoorToRancor):getAnimation() == 8) then
player:messageSpecial(PAINTBRUSH_OFFSET + 23,PAINTBRUSH_OF_SOULS); -- The <KEY_ITEM> begins to twitch. The canvas is graced with the image from your soul.
elseif (player:hasKeyItem(PAINTBRUSH_OF_SOULS) and X >= -53.2 and Z <= 0.1 and Z >= -0.1) then -- has paintbrush of souls + close enough
player:messageSpecial(PAINTBRUSH_OFFSET + 17,PAINTBRUSH_OF_SOULS);
player:setVar("started_painting",os.time());
player:startEvent(0x003C,PAINTBRUSH_OF_SOULS);
elseif (player:hasKeyItem(PAINTBRUSH_OF_SOULS)) then
player:messageSpecial(PAINTBRUSH_OFFSET + 15,PAINTBRUSH_OF_SOULS);
else
player:messageSpecial(PAINTBRUSH_OFFSET, PAINTBRUSH_OF_SOULS); -- When the paintbrush of souls projects the deepest, darkest corner of your soul...
end
else
player:messageSpecial(PAINTBRUSH_OFFSET + 11); -- It is a painting of a sublime-looking woman.
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);
local DoorToRancor = 17428989;
if (csid == 0x0032) then
-- Soon !
elseif (csid == 0x003C) then
time_elapsed = os.time() - player:getVar("started_painting");
if (time_elapsed >= 30) then
player:messageSpecial(PAINTBRUSH_OFFSET + 22); -- You succeeded in projecting the image in your soul to the blank canvas. The door to the Rancor Den has opened!<Prompt>
GetNPCByID(DoorToRancor):openDoor(45); -- Open the door to Den of Rancor for 45 sec
else
player:messageSpecial(PAINTBRUSH_OFFSET + 21); -- You were unable to fill the canvas with an image from your soul.
end
player:setVar("started_painting",0);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Castle_Oztroja/npcs/Kaa_Toru_the_Just.lua | 13 | 1656 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Kaa Toru the Just
-- Type: Mission NPC [ Windurst Mission 6-2 NPC ]~
-- @pos -100.188 -62.125 145.422 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") == 2) then
player:startEvent(0x002d,0,200);
else
player:startEvent(0x002e);
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 == 0x002d) then
player:delKeyItem(HOLY_ONES_INVITATION);
player:addKeyItem(HOLY_ONES_OATH);
player:messageSpecial(KEYITEM_OBTAINED,HOLY_ONES_OATH);
player:addItem(13134); -- Ashura Necklace
player:messageSpecial(ITEM_OBTAINED,13134);
player:setVar("MissionStatus",3);
end
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/rock_crusher.lua | 4 | 1173 | -----------------------------------
-- Rock Crusher
-- Staff weapon skill
-- Skill Level: 40
-- Delivers an earth elemental attack. Damage varies with TP.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: Earth
-- Modifiers: STR:20% ; INT:20%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; 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;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
waytim/darkstar | scripts/zones/Silver_Sea_Remnants/Zone.lua | 17 | 1080 | -----------------------------------
--
-- Zone: Silver_Sea_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Silver_Sea_Remnants/TextIDs"] = nil;
require("scripts/zones/Silver_Sea_Remnants/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Northern_San_dOria/npcs/Esqualea.lua | 13 | 1411 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Esqualea
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_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(0x029e);
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/Bibiki_Bay/npcs/Fheli_Lapatzuo.lua | 5 | 1081 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Fheli Lapatzuo
-- Type: Manaclipper
-- @zone: 4
-- @pos: 488.793 -4.003 709.473
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bibiki_Bay/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0012);
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/Windurst_Woods/npcs/Mheca_Khetashipah.lua | 13 | 1061 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Mheca Khetashipah
-- Type: Standard NPC
-- @zone: 241
-- @pos 66.881 -6.249 185.752
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01aa);
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/c20912223.lua | 1 | 2399 | --The Indestructable Sword Bekatowa
function c20912223.initial_effect(c)
c:SetUniqueOnField(1,0,20912223)
aux.AddEquipProcedure(c,0,aux.FilterBoolFunction(Card.IsRace,RACE_WARRIOR))
--Untargetable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e2:SetValue(c20912223.tglimit)
c:RegisterEffect(e2)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c20912223.eqlimit)
c:RegisterEffect(e3)
--equip
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(20912223,0))
e4:SetCategory(CATEGORY_EQUIP)
e4:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c20912223.eqcon)
e4:SetCost(c20912223.eqcost)
e4:SetTarget(c20912223.eqtg)
e4:SetOperation(c20912223.operation)
c:RegisterEffect(e4)
end
function c20912223.eqlimit(e,c)
return c:IsRace(RACE_WARRIOR)
end
function c20912223.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() and c:CheckUniqueOnField(tp) then
Duel.Equip(tp,c,tc)
end
end
function c20912223.tglimit(e,re,rp)
return rp~=e:GetHandlerPlayer() and re:IsActiveType(TYPE_MONSTER)
end
function c20912223.eqcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousLocation(LOCATION_ONFIELD) and c:IsPreviousPosition(POS_FACEUP) and c:IsReason(REASON_DESTROY) and c:CheckUniqueOnField(tp)
end
function c20912223.eqcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,500) end
Duel.PayLPCost(tp,500)
end
function c20912223.eqfilter2(c)
return c:IsFaceup() and c:IsSetCard(0xd0a2)
end
function c20912223.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c20912223.eqfilter2(chkc) end
if chk==0 then return e:GetHandler():IsRelateToEffect(e) and Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c20912223.eqfilter2,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c20912223.eqfilter2,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Rabao/npcs/Brave_Wolf.lua | 6 | 1434 | -----------------------------------
-- Area: Rabao
-- NPC: Brave Wolf
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Rabao/TextIDs"] = nil;
require("scripts/zones/Rabao/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,BRAVEWOLF_SHOP_DIALOG);
stock = {0x300D,31201, --Buckler
0x300E,60260, --Darksteel Buckler
0x369B,24373, --Silver Bangles
0x310A,66066, --Banded Mail
0x318A,35285, --Mufflers
0x320A,52552, --Breeches
0x328A,32382, --Sollerets
0x3141,9423, --Black Tunic
0x31C1,4395, --White Mitts
0x3241,6279, --Black Slacks
0x32C1,4084, --Sandals
0x3122,28654, --Padded Armor
0x31A2,15724, --Iron Mittens
0x3224,23063, --Iron Subligar
0x32A2,14327} --Leggins
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 |
waytim/darkstar | scripts/zones/Windurst_Waters/npcs/Furakku-Norakku.lua | 25 | 4882 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Furakku-Norakku
-- Involved in Quests: Early Bird Catches the Bookworm, Chasing Tales, Class Reunion
-- @pos -19 -5 101 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local bookwormStatus = player:getQuestStatus(WINDURST,EARLY_BIRD_CATCHES_THE_BOOKWORM);
local chasingStatus = player:getQuestStatus(WINDURST,CHASING_TALES);
local bookNotifications = player:hasKeyItem(OVERDUE_BOOK_NOTIFICATIONS);
local ClassReunion = player:getQuestStatus(WINDURST,CLASS_REUNION);
local ClassReunionProgress = player:getVar("ClassReunionProgress");
local talk2 = player:getVar("ClassReunion_TalkedToFurakku");
if (bookwormStatus == QUEST_ACCEPTED and bookNotifications == false) then
player:startEvent(0x0185); -- During Quest "Early Bird Catches the Bookworm" 1
elseif (bookwormStatus == QUEST_ACCEPTED and bookNotifications and player:getVar("EARLY_BIRD_TRACK_BOOK") == 0) then
player:startEvent(0x0186); -- During Quest "Early Bird Catches the Bookworm" 2
elseif (bookwormStatus == QUEST_ACCEPTED and player:getVar("EARLY_BIRD_TRACK_BOOK") == 1) then
player:startEvent(0x018d); -- During Quest "Early Bird Catches the Bookworm" 3
elseif (bookwormStatus == QUEST_ACCEPTED and player:getVar("EARLY_BIRD_TRACK_BOOK") >= 2) then
player:startEvent(0x0190); -- Finish Quest "Early Bird Catches the Bookworm"
elseif (bookwormStatus == QUEST_COMPLETED and player:needToZone()) then
player:startEvent(0x0191); -- Standard dialog before player zone
elseif (chasingStatus == QUEST_ACCEPTED and player:hasKeyItem(OVERDUE_BOOK_NOTIFICATION) == false) then
player:startEvent(0x0194,0,126); -- During Quest "Chasing Tales", tells you the book "A Song of Love" is overdue
elseif (player:hasKeyItem(OVERDUE_BOOK_NOTIFICATION) and player:hasKeyItem(A_SONG_OF_LOVE) == false) then
player:startEvent(0x0195,0,126);
elseif (player:getVar("CHASING_TALES_TRACK_BOOK") == 1 and player:hasKeyItem(A_SONG_OF_LOVE) == false) then
player:startEvent(0x0199);
elseif (player:hasKeyItem(A_SONG_OF_LOVE)) then
player:startEvent(0x019a);
elseif (chasingStatus == QUEST_COMPLETED and player:needToZone() == true) then
player:startEvent(0x019b);
-----------------------------------------------------------------
-- Class Reunion
elseif (ClassReunion == 1 and ClassReunionProgress >= 3 and talk2 ~= 1) then
player:startEvent(0x0330); -- he tells you about Uran-Mafran
-----------------------------------------------------------------
else
player:startEvent(0x0173);
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 == 0x0185) then
player:addKeyItem(OVERDUE_BOOK_NOTIFICATIONS);
player:messageSpecial(KEYITEM_OBTAINED,OVERDUE_BOOK_NOTIFICATIONS);
elseif (csid == 0x0190) then
player:needToZone(true);
player:addTitle(SAVIOR_OF_KNOWLEDGE);
player:addGil(GIL_RATE*1500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500);
player:setVar("EARLY_BIRD_TRACK_BOOK",0);
player:addFame(WINDURST,120);
player:completeQuest(WINDURST,EARLY_BIRD_CATCHES_THE_BOOKWORM);
elseif (csid == 0x0194) then
player:addKeyItem(OVERDUE_BOOK_NOTIFICATION);
player:messageSpecial(KEYITEM_OBTAINED,OVERDUE_BOOK_NOTIFICATION);
elseif (csid == 0x019a) then
player:needToZone(true);
player:addGil(GIL_RATE*2800);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*2800);
player:addTitle(SAVIOR_OF_KNOWLEDGE);
player:delKeyItem(OVERDUE_BOOK_NOTIFICATION);
player:delKeyItem(A_SONG_OF_LOVE);
player:setVar("CHASING_TALES_TRACK_BOOK",0);
player:addFame(WINDURST,120);
player:completeQuest(WINDURST,CHASING_TALES);
elseif (csid == 0x0330) then
player:setVar("ClassReunion_TalkedToFurakku",1);
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Northern_San_dOria/npcs/Boncort.lua | 4 | 1921 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Boncort
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED)then
if(trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeBoncort") == 0)then
player:messageSpecial(11932);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeBoncort",1);
player:messageSpecial(FLYER_ACCEPTED);
trade:complete();
elseif(player:getVar("tradeBoncort") ==1)then
player:messageSpecial(11936);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,BONCORT_SHOP_DIALOG);
stock = {0x1159,837,1, --Grape Juice
0x1104,180,2, --White Bread
0x111c,198,2, --Smoked Salmon
0x1147,270,2, --Apple Juice
0x110c,108,3, --Black Bread
0x1118,108,3, --Meat Jerky
0x119d,10,3, --Distilled Water
0x138F,163,3} --Scroll of Sword Madrigal
showNationShop(player, SANDORIA, 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 |
hacker44-h44/spammer | plugins/anti-flood.lua | 281 | 2422 | local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds
local TIME_CHECK = 5
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if msg.to.type ~= 'chat' then
return 'Anti-flood works only on channels'
else
local chat = msg.to.id
local hash = 'anti-flood:enabled:'..chat
if matches[1] == 'enable' then
redis:set(hash, true)
return 'Anti-flood enabled on chat'
end
if matches[1] == 'disable' then
redis:del(hash)
return 'Anti-flood disabled on chat'
end
end
end
local function pre_process (msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
local hash_enable = 'anti-flood:enabled:'..msg.to.id
local enabled = redis:get(hash_enable)
if enabled then
print('anti-flood enabled')
-- Check flood
if msg.from.type == 'user' then
-- Increase the number of messages from the user on the chat
local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
local receiver = get_receiver(msg)
local user = msg.from.id
local text = 'User '..user..' is flooding'
local chat = msg.to.id
send_msg(receiver, text, ok_cb, nil)
if msg.to.type ~= 'chat' then
print("Flood in not a chat group!")
elseif user == tostring(our_id) then
print('I won\'t kick myself')
elseif is_sudo(msg) then
print('I won\'t kick an admin!')
else
-- Ban user
-- TODO: Check on this plugin bans
local bhash = 'banned:'..msg.to.id..':'..msg.from.id
redis:set(bhash, true)
kick_user(user, chat)
end
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
return msg
end
return {
description = 'Plugin to kick flooders from group.',
usage = {},
patterns = {
'^!antiflood (enable)$',
'^!antiflood (disable)$'
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters/Zone.lua | 2 | 2723 | -----------------------------------
--
-- Zone: Windurst_Waters (238)
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/globals/server");
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
-- Check if we are on Windurst Mission 1-3
zone:registerRegion(1, 23,-12,-208, 31,-8,-197);
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
-- FIRST LOGIN (START CS)
if (prevZone == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x213;
end
player:setPos(-40,-5,80,64);
player:setHomePoint();
end
-- MOG HOUSE EXIT
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
position = math.random(1,5) + 157;
player:setPos(position,-5,-62,192);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
if(player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("MEMORIES_OF_A_MAIDEN_Status")==1)then --COP MEMORIES_OF_A_MAIDEN--3-3B: Windurst Route
player:setVar("MEMORIES_OF_A_MAIDEN_Status",2);
cs = 0x0367;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
[1] = function (x) -- Windurst Mission 1-3, final cutscene with Leepe-Hoppe
-- If we're on Windurst Mission 1-3
if(player:getCurrentMission(WINDURST) == THE_PRICE_OF_PEACE and player:getVar("MissionStatus") == 2) then
player:startEvent(0x0092);
end
end,
}
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x213) then
player:messageSpecial(ITEM_OBTAINED,0x218);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif(csid == 0x0092) then -- Returned from Giddeus, Windurst 1-3
player:setVar("MissionStatus",3);
player:setVar("ghoo_talk",0);
player:setVar("laa_talk",0);
end
end;
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99199028.lua | 2 | 4885 | --The Future Gear Kid
function c99199028.initial_effect(c)
--pendulum summon
aux.EnablePendulumAttribute(c)
--splimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_PZONE)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e2:SetTargetRange(1,0)
e2:SetTarget(c99199028.splimit)
e2:SetCondition(c99199028.splimcon)
c:RegisterEffect(e2)
--special summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(99199028,0))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_HAND)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e3:SetCountLimit(1,99199028)
e3:SetTarget(c99199028.sptg)
e3:SetOperation(c99199028.spop)
c:RegisterEffect(e3)
--special summon2
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(99199028,1))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e4:SetCode(EVENT_SPSUMMON_SUCCESS)
e4:SetTarget(c99199028.target)
e4:SetOperation(c99199028.operation)
c:RegisterEffect(e4)
--destroy and set
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_DESTROY)
e5:SetProperty(EFFECT_FLAG_CARD_TARGET)
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_PZONE)
e5:SetCountLimit(1)
e5:SetTarget(c99199028.destg)
e5:SetOperation(c99199028.desop)
c:RegisterEffect(e5)
end
function c99199028.splimit(e,c,sump,sumtype,sumpos,targetp)
if c:IsSetCard(0xff15) then return false end
return bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
function c99199028.splimcon(e)
return not e:GetHandler():IsForbidden()
end
function c99199028.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local g=Group.CreateGroup()
for i=0,4 do
local tc=Duel.GetFieldCard(tp,LOCATION_MZONE,i)
if tc and tc:IsFaceup() and tc:IsSetCard(0xff15) and tc:IsType(TYPE_XYZ) then
g:Merge(tc:GetOverlayGroup())
end
end
if g:GetCount()==0 then return false end
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 c99199028.spop(e,tp,eg,ep,ev,re,r,rp)
local g=Group.CreateGroup()
for i=0,4 do
local tc=Duel.GetFieldCard(tp,LOCATION_MZONE,i)
if tc and tc:IsFaceup() and tc:IsSetCard(0xff15) and tc:IsType(TYPE_XYZ) then
g:Merge(tc:GetOverlayGroup())
end
end
if g:GetCount()==0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVEXYZ)
local sg=g:Select(tp,1,1,nil)
Duel.SendtoGrave(sg,REASON_EFFECT)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
function c99199028.specfilter(c,e,tp)
return c:IsCode(99199028) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c99199028.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c99199028.specfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c99199028.operation(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
local g=Duel.GetMatchingGroup(c99199028.specfilter,tp,LOCATION_DECK,0,nil,e,tp)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
end
tc=g:GetNext()
if ft>1 and tc and Duel.SelectYesNo(tp,aux.Stringid(99199028,2)) then
Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP)
end
Duel.SpecialSummonComplete()
end
function c99199028.desfilter(c)
return c:IsFaceup() and c:IsDestructable()
end
function c99199028.setfilter(c)
return c:IsSetCard(0xff15) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsSSetable()
end
function c99199028.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(tp) and c99199028.desfilter(chkc) and chkc~=e:GetHandler() end
if chk==0 then return Duel.IsExistingTarget(c99199028.desfilter,tp,LOCATION_ONFIELD,0,1,e:GetHandler())
and Duel.IsExistingMatchingCard(c99199028.setfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c99199028.desfilter,tp,LOCATION_ONFIELD,0,1,1,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c99199028.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SET)
local g=Duel.SelectMatchingCard(tp,c99199028.setfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SSet(tp,g:GetFirst())
Duel.ConfirmCards(1-tp,g)
end
end
end | gpl-3.0 |
thisishmed/butler | plugins/invite.lua | 12 | 4020 | do
local function invite_user(chat_id, user_id, type_id)
if is_banned(user_id, chat_id) then
return send_large_msg('chat#id'..chat_id, 'Invitation canceled.\n'
..'ID'..user_id..' is (super)banned.')
end
chat_add_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, false)
end
local function resolve_username(extra, success, result)
if success == 1 then
invite_user('chat#id'..extra.msg.to.id, 'user#id'..result.id, ok_cb, false)
else
return send_large_msg('chat#id'..extra.msg.to.id, 'Failed to invite '
..string.gsub(extra.msg.text, '!invite ', '')
..' into this group.\nPlease check if username is correct.')
end
end
local function action_by_reply(extra, success, result)
invite_user(result.to.id, result.from.id, ok_cb, false)
end
local function run(msg, matches)
if is_chat_msg(msg) and is_sudo(msg) then
if msg.reply_id and msg.text == "!invite" then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
end
if string.match(matches[1], '^%d+$') then
invite_user(msg.to.id, matches[1], ok_cb, false)
elseif string.match(matches[1], '^@.+$') then
msgr = res_user(string.gsub(matches[1], '@', ''), resolve_username, {msg=msg})
elseif string.match(matches[1], '.*$') then
-- This one is tricky. Big chance are, you need an initial interaction with <print_name>.
chat_add_user('chat#id'..msg.to.id, string.gsub(matches[1], ' ', '_'), ok_cb, false)
end
else
return 'Sudo only =))'
end
end
return {
description = 'Invite other user to the chat group.',
usage = {
moderator = {
-- Need space in front of this, so bot won't consider it as a command
' !invite : If type by replying, bot will then inviting the replied user.',
' !invite <user_id> : Invite by their user_id.',
' !invite @<user_name> : Invite by their @<user_name>.',
' !invite <print_name> : Invite by their print_name.'
},
},
patterns = {
'^[!/]invite$',
'^[!/]invite (.*)$',
'^[!/]invite (%d+)$'
},
run = run,
moderated = true
}
end
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
galek/crown | 3rdparty/luajit/src/jit/dump.lua | 5 | 20214 | ----------------------------------------------------------------------------
-- LuaJIT compiler dump module.
--
-- Copyright (C) 2005-2021 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module can be used to debug the JIT compiler itself. It dumps the
-- code representations and structures used in various compiler stages.
--
-- Example usage:
--
-- luajit -jdump -e "local x=0; for i=1,1e6 do x=x+i end; print(x)"
-- luajit -jdump=im -e "for i=1,1000 do for j=1,1000 do end end" | less -R
-- luajit -jdump=is myapp.lua | less -R
-- luajit -jdump=-b myapp.lua
-- luajit -jdump=+aH,myapp.html myapp.lua
-- luajit -jdump=ixT,myapp.dump myapp.lua
--
-- The first argument specifies the dump mode. The second argument gives
-- the output file name. Default output is to stdout, unless the environment
-- variable LUAJIT_DUMPFILE is set. The file is overwritten every time the
-- module is started.
--
-- Different features can be turned on or off with the dump mode. If the
-- mode starts with a '+', the following features are added to the default
-- set of features; a '-' removes them. Otherwise the features are replaced.
--
-- The following dump features are available (* marks the default):
--
-- * t Print a line for each started, ended or aborted trace (see also -jv).
-- * b Dump the traced bytecode.
-- * i Dump the IR (intermediate representation).
-- r Augment the IR with register/stack slots.
-- s Dump the snapshot map.
-- * m Dump the generated machine code.
-- x Print each taken trace exit.
-- X Print each taken trace exit and the contents of all registers.
-- a Print the IR of aborted traces, too.
--
-- The output format can be set with the following characters:
--
-- T Plain text output.
-- A ANSI-colored text output
-- H Colorized HTML + CSS output.
--
-- The default output format is plain text. It's set to ANSI-colored text
-- if the COLORTERM variable is set. Note: this is independent of any output
-- redirection, which is actually considered a feature.
--
-- You probably want to use less -R to enjoy viewing ANSI-colored text from
-- a pipe or a file. Add this to your ~/.bashrc: export LESS="-R"
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, funcbc = jutil.funcinfo, jutil.funcbc
local traceinfo, traceir, tracek = jutil.traceinfo, jutil.traceir, jutil.tracek
local tracemc, tracesnap = jutil.tracemc, jutil.tracesnap
local traceexitstub, ircalladdr = jutil.traceexitstub, jutil.ircalladdr
local bit = require("bit")
local band, shr, tohex = bit.band, bit.rshift, bit.tohex
local sub, gsub, format = string.sub, string.gsub, string.format
local byte, rep = string.byte, string.rep
local type, tostring = type, tostring
local stdout, stderr = io.stdout, io.stderr
-- Load other modules on-demand.
local bcline, disass
-- Active flag, output file handle and dump mode.
local active, out, dumpmode
------------------------------------------------------------------------------
local symtabmt = { __index = false }
local symtab = {}
local nexitsym = 0
-- Fill nested symbol table with per-trace exit stub addresses.
local function fillsymtab_tr(tr, nexit)
local t = {}
symtabmt.__index = t
if jit.arch:sub(1, 4) == "mips" then
t[traceexitstub(tr, 0)] = "exit"
return
end
for i=0,nexit-1 do
local addr = traceexitstub(tr, i)
if addr < 0 then addr = addr + 2^32 end
t[addr] = tostring(i)
end
local addr = traceexitstub(tr, nexit)
if addr then t[addr] = "stack_check" end
end
-- Fill symbol table with trace exit stub addresses.
local function fillsymtab(tr, nexit)
local t = symtab
if nexitsym == 0 then
local ircall = vmdef.ircall
for i=0,#ircall do
local addr = ircalladdr(i)
if addr ~= 0 then
if addr < 0 then addr = addr + 2^32 end
t[addr] = ircall[i]
end
end
end
if nexitsym == 1000000 then -- Per-trace exit stubs.
fillsymtab_tr(tr, nexit)
elseif nexit > nexitsym then -- Shared exit stubs.
for i=nexitsym,nexit-1 do
local addr = traceexitstub(i)
if addr == nil then -- Fall back to per-trace exit stubs.
fillsymtab_tr(tr, nexit)
setmetatable(symtab, symtabmt)
nexit = 1000000
break
end
if addr < 0 then addr = addr + 2^32 end
t[addr] = tostring(i)
end
nexitsym = nexit
end
return t
end
local function dumpwrite(s)
out:write(s)
end
-- Disassemble machine code.
local function dump_mcode(tr)
local info = traceinfo(tr)
if not info then return end
local mcode, addr, loop = tracemc(tr)
if not mcode then return end
if not disass then disass = require("jit.dis_"..jit.arch) end
if addr < 0 then addr = addr + 2^32 end
out:write("---- TRACE ", tr, " mcode ", #mcode, "\n")
local ctx = disass.create(mcode, addr, dumpwrite)
ctx.hexdump = 0
ctx.symtab = fillsymtab(tr, info.nexit)
if loop ~= 0 then
symtab[addr+loop] = "LOOP"
ctx:disass(0, loop)
out:write("->LOOP:\n")
ctx:disass(loop, #mcode-loop)
symtab[addr+loop] = nil
else
ctx:disass(0, #mcode)
end
end
------------------------------------------------------------------------------
local irtype_text = {
[0] = "nil",
"fal",
"tru",
"lud",
"str",
"p32",
"thr",
"pro",
"fun",
"p64",
"cdt",
"tab",
"udt",
"flt",
"num",
"i8 ",
"u8 ",
"i16",
"u16",
"int",
"u32",
"i64",
"u64",
"sfp",
}
local colortype_ansi = {
[0] = "%s",
"%s",
"%s",
"\027[36m%s\027[m",
"\027[32m%s\027[m",
"%s",
"\027[1m%s\027[m",
"%s",
"\027[1m%s\027[m",
"%s",
"\027[33m%s\027[m",
"\027[31m%s\027[m",
"\027[36m%s\027[m",
"\027[34m%s\027[m",
"\027[34m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
"\027[35m%s\027[m",
}
local function colorize_text(s)
return s
end
local function colorize_ansi(s, t)
return format(colortype_ansi[t], s)
end
local irtype_ansi = setmetatable({},
{ __index = function(tab, t)
local s = colorize_ansi(irtype_text[t], t); tab[t] = s; return s; end })
local html_escape = { ["<"] = "<", [">"] = ">", ["&"] = "&", }
local function colorize_html(s, t)
s = gsub(s, "[<>&]", html_escape)
return format('<span class="irt_%s">%s</span>', irtype_text[t], s)
end
local irtype_html = setmetatable({},
{ __index = function(tab, t)
local s = colorize_html(irtype_text[t], t); tab[t] = s; return s; end })
local header_html = [[
<style type="text/css">
background { background: #ffffff; color: #000000; }
pre.ljdump {
font-size: 10pt;
background: #f0f4ff;
color: #000000;
border: 1px solid #bfcfff;
padding: 0.5em;
margin-left: 2em;
margin-right: 2em;
}
span.irt_str { color: #00a000; }
span.irt_thr, span.irt_fun { color: #404040; font-weight: bold; }
span.irt_tab { color: #c00000; }
span.irt_udt, span.irt_lud { color: #00c0c0; }
span.irt_num { color: #4040c0; }
span.irt_int, span.irt_i8, span.irt_u8, span.irt_i16, span.irt_u16 { color: #b040b0; }
</style>
]]
local colorize, irtype
-- Lookup tables to convert some literals into names.
local litname = {
["SLOAD "] = setmetatable({}, { __index = function(t, mode)
local s = ""
if band(mode, 1) ~= 0 then s = s.."P" end
if band(mode, 2) ~= 0 then s = s.."F" end
if band(mode, 4) ~= 0 then s = s.."T" end
if band(mode, 8) ~= 0 then s = s.."C" end
if band(mode, 16) ~= 0 then s = s.."R" end
if band(mode, 32) ~= 0 then s = s.."I" end
t[mode] = s
return s
end}),
["XLOAD "] = { [0] = "", "R", "V", "RV", "U", "RU", "VU", "RVU", },
["CONV "] = setmetatable({}, { __index = function(t, mode)
local s = irtype[band(mode, 31)]
s = irtype[band(shr(mode, 5), 31)].."."..s
if band(mode, 0x800) ~= 0 then s = s.." sext" end
local c = shr(mode, 14)
if c == 2 then s = s.." index" elseif c == 3 then s = s.." check" end
t[mode] = s
return s
end}),
["FLOAD "] = vmdef.irfield,
["FREF "] = vmdef.irfield,
["FPMATH"] = vmdef.irfpm,
["BUFHDR"] = { [0] = "RESET", "APPEND" },
["TOSTR "] = { [0] = "INT", "NUM", "CHAR" },
}
local function ctlsub(c)
if c == "\n" then return "\\n"
elseif c == "\r" then return "\\r"
elseif c == "\t" then return "\\t"
else return format("\\%03d", byte(c))
end
end
local function fmtfunc(func, pc)
local fi = funcinfo(func, pc)
if fi.loc then
return fi.loc
elseif fi.ffid then
return vmdef.ffnames[fi.ffid]
elseif fi.addr then
return format("C:%x", fi.addr)
else
return "(?)"
end
end
local function formatk(tr, idx, sn)
local k, t, slot = tracek(tr, idx)
local tn = type(k)
local s
if tn == "number" then
if t < 12 then
s = k == 0 and "NULL" or format("[0x%08x]", k)
elseif band(sn or 0, 0x30000) ~= 0 then
s = band(sn, 0x20000) ~= 0 and "contpc" or "ftsz"
elseif k == 2^52+2^51 then
s = "bias"
else
s = format(0 < k and k < 0x1p-1026 and "%+a" or "%+.14g", k)
end
elseif tn == "string" then
s = format(#k > 20 and '"%.20s"~' or '"%s"', gsub(k, "%c", ctlsub))
elseif tn == "function" then
s = fmtfunc(k)
elseif tn == "table" then
s = format("{%p}", k)
elseif tn == "userdata" then
if t == 12 then
s = format("userdata:%p", k)
else
s = format("[%p]", k)
if s == "[NULL]" then s = "NULL" end
end
elseif t == 21 then -- int64_t
s = sub(tostring(k), 1, -3)
if sub(s, 1, 1) ~= "-" then s = "+"..s end
elseif sn == 0x1057fff then -- SNAP(1, SNAP_FRAME | SNAP_NORESTORE, REF_NIL)
return "----" -- Special case for LJ_FR2 slot 1.
else
s = tostring(k) -- For primitives.
end
s = colorize(format("%-4s", s), t)
if slot then
s = format("%s @%d", s, slot)
end
return s
end
local function printsnap(tr, snap)
local n = 2
for s=0,snap[1]-1 do
local sn = snap[n]
if shr(sn, 24) == s then
n = n + 1
local ref = band(sn, 0xffff) - 0x8000 -- REF_BIAS
if ref < 0 then
out:write(formatk(tr, ref, sn))
elseif band(sn, 0x80000) ~= 0 then -- SNAP_SOFTFPNUM
out:write(colorize(format("%04d/%04d", ref, ref+1), 14))
else
local m, ot, op1, op2 = traceir(tr, ref)
out:write(colorize(format("%04d", ref), band(ot, 31)))
end
out:write(band(sn, 0x10000) == 0 and " " or "|") -- SNAP_FRAME
else
out:write("---- ")
end
end
out:write("]\n")
end
-- Dump snapshots (not interleaved with IR).
local function dump_snap(tr)
out:write("---- TRACE ", tr, " snapshots\n")
for i=0,1000000000 do
local snap = tracesnap(tr, i)
if not snap then break end
out:write(format("#%-3d %04d [ ", i, snap[0]))
printsnap(tr, snap)
end
end
-- Return a register name or stack slot for a rid/sp location.
local function ridsp_name(ridsp, ins)
if not disass then disass = require("jit.dis_"..jit.arch) end
local rid, slot = band(ridsp, 0xff), shr(ridsp, 8)
if rid == 253 or rid == 254 then
return (slot == 0 or slot == 255) and " {sink" or format(" {%04d", ins-slot)
end
if ridsp > 255 then return format("[%x]", slot*4) end
if rid < 128 then return disass.regname(rid) end
return ""
end
-- Dump CALL* function ref and return optional ctype.
local function dumpcallfunc(tr, ins)
local ctype
if ins > 0 then
local m, ot, op1, op2 = traceir(tr, ins)
if band(ot, 31) == 0 then -- nil type means CARG(func, ctype).
ins = op1
ctype = formatk(tr, op2)
end
end
if ins < 0 then
out:write(format("[0x%x](", tonumber((tracek(tr, ins)))))
else
out:write(format("%04d (", ins))
end
return ctype
end
-- Recursively gather CALL* args and dump them.
local function dumpcallargs(tr, ins)
if ins < 0 then
out:write(formatk(tr, ins))
else
local m, ot, op1, op2 = traceir(tr, ins)
local oidx = 6*shr(ot, 8)
local op = sub(vmdef.irnames, oidx+1, oidx+6)
if op == "CARG " then
dumpcallargs(tr, op1)
if op2 < 0 then
out:write(" ", formatk(tr, op2))
else
out:write(" ", format("%04d", op2))
end
else
out:write(format("%04d", ins))
end
end
end
-- Dump IR and interleaved snapshots.
local function dump_ir(tr, dumpsnap, dumpreg)
local info = traceinfo(tr)
if not info then return end
local nins = info.nins
out:write("---- TRACE ", tr, " IR\n")
local irnames = vmdef.irnames
local snapref = 65536
local snap, snapno
if dumpsnap then
snap = tracesnap(tr, 0)
snapref = snap[0]
snapno = 0
end
for ins=1,nins do
if ins >= snapref then
if dumpreg then
out:write(format(".... SNAP #%-3d [ ", snapno))
else
out:write(format(".... SNAP #%-3d [ ", snapno))
end
printsnap(tr, snap)
snapno = snapno + 1
snap = tracesnap(tr, snapno)
snapref = snap and snap[0] or 65536
end
local m, ot, op1, op2, ridsp = traceir(tr, ins)
local oidx, t = 6*shr(ot, 8), band(ot, 31)
local op = sub(irnames, oidx+1, oidx+6)
if op == "LOOP " then
if dumpreg then
out:write(format("%04d ------------ LOOP ------------\n", ins))
else
out:write(format("%04d ------ LOOP ------------\n", ins))
end
elseif op ~= "NOP " and op ~= "CARG " and
(dumpreg or op ~= "RENAME") then
local rid = band(ridsp, 255)
if dumpreg then
out:write(format("%04d %-6s", ins, ridsp_name(ridsp, ins)))
else
out:write(format("%04d ", ins))
end
out:write(format("%s%s %s %s ",
(rid == 254 or rid == 253) and "}" or
(band(ot, 128) == 0 and " " or ">"),
band(ot, 64) == 0 and " " or "+",
irtype[t], op))
local m1, m2 = band(m, 3), band(m, 3*4)
if sub(op, 1, 4) == "CALL" then
local ctype
if m2 == 1*4 then -- op2 == IRMlit
out:write(format("%-10s (", vmdef.ircall[op2]))
else
ctype = dumpcallfunc(tr, op2)
end
if op1 ~= -1 then dumpcallargs(tr, op1) end
out:write(")")
if ctype then out:write(" ctype ", ctype) end
elseif op == "CNEW " and op2 == -1 then
out:write(formatk(tr, op1))
elseif m1 ~= 3 then -- op1 != IRMnone
if op1 < 0 then
out:write(formatk(tr, op1))
else
out:write(format(m1 == 0 and "%04d" or "#%-3d", op1))
end
if m2 ~= 3*4 then -- op2 != IRMnone
if m2 == 1*4 then -- op2 == IRMlit
local litn = litname[op]
if litn and litn[op2] then
out:write(" ", litn[op2])
elseif op == "UREFO " or op == "UREFC " then
out:write(format(" #%-3d", shr(op2, 8)))
else
out:write(format(" #%-3d", op2))
end
elseif op2 < 0 then
out:write(" ", formatk(tr, op2))
else
out:write(format(" %04d", op2))
end
end
end
out:write("\n")
end
end
if snap then
if dumpreg then
out:write(format(".... SNAP #%-3d [ ", snapno))
else
out:write(format(".... SNAP #%-3d [ ", snapno))
end
printsnap(tr, snap)
end
end
------------------------------------------------------------------------------
local recprefix = ""
local recdepth = 0
-- Format trace error message.
local function fmterr(err, info)
if type(err) == "number" then
if type(info) == "function" then info = fmtfunc(info) end
err = format(vmdef.traceerr[err], info)
end
return err
end
-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
if what == "stop" or (what == "abort" and dumpmode.a) then
if dumpmode.i then dump_ir(tr, dumpmode.s, dumpmode.r and what == "stop")
elseif dumpmode.s then dump_snap(tr) end
if dumpmode.m then dump_mcode(tr) end
end
if what == "start" then
if dumpmode.H then out:write('<pre class="ljdump">\n') end
out:write("---- TRACE ", tr, " ", what)
if otr then out:write(" ", otr, "/", oex == -1 and "stitch" or oex) end
out:write(" ", fmtfunc(func, pc), "\n")
elseif what == "stop" or what == "abort" then
out:write("---- TRACE ", tr, " ", what)
if what == "abort" then
out:write(" ", fmtfunc(func, pc), " -- ", fmterr(otr, oex), "\n")
else
local info = traceinfo(tr)
local link, ltype = info.link, info.linktype
if link == tr or link == 0 then
out:write(" -> ", ltype, "\n")
elseif ltype == "root" then
out:write(" -> ", link, "\n")
else
out:write(" -> ", link, " ", ltype, "\n")
end
end
if dumpmode.H then out:write("</pre>\n\n") else out:write("\n") end
else
if what == "flush" then symtab, nexitsym = {}, 0 end
out:write("---- TRACE ", what, "\n\n")
end
out:flush()
end
-- Dump recorded bytecode.
local function dump_record(tr, func, pc, depth)
if depth ~= recdepth then
recdepth = depth
recprefix = rep(" .", depth)
end
local line
if pc >= 0 then
line = bcline(func, pc, recprefix)
if dumpmode.H then line = gsub(line, "[<>&]", html_escape) end
else
line = "0000 "..recprefix.." FUNCC \n"
end
if pc <= 0 then
out:write(sub(line, 1, -2), " ; ", fmtfunc(func), "\n")
else
out:write(line)
end
if pc >= 0 and band(funcbc(func, pc), 0xff) < 16 then -- ORDER BC
out:write(bcline(func, pc+1, recprefix)) -- Write JMP for cond.
end
end
------------------------------------------------------------------------------
local gpr64 = jit.arch:match("64")
local fprmips32 = jit.arch == "mips" or jit.arch == "mipsel"
-- Dump taken trace exits.
local function dump_texit(tr, ex, ngpr, nfpr, ...)
out:write("---- TRACE ", tr, " exit ", ex, "\n")
if dumpmode.X then
local regs = {...}
if gpr64 then
for i=1,ngpr do
out:write(format(" %016x", regs[i]))
if i % 4 == 0 then out:write("\n") end
end
else
for i=1,ngpr do
out:write(" ", tohex(regs[i]))
if i % 8 == 0 then out:write("\n") end
end
end
if fprmips32 then
for i=1,nfpr,2 do
out:write(format(" %+17.14g", regs[ngpr+i]))
if i % 8 == 7 then out:write("\n") end
end
else
for i=1,nfpr do
out:write(format(" %+17.14g", regs[ngpr+i]))
if i % 4 == 0 then out:write("\n") end
end
end
end
end
------------------------------------------------------------------------------
-- Detach dump handlers.
local function dumpoff()
if active then
active = false
jit.attach(dump_texit)
jit.attach(dump_record)
jit.attach(dump_trace)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach dump handlers.
local function dumpon(opt, outfile)
if active then dumpoff() end
local term = os.getenv("TERM")
local colormode = (term and term:match("color") or os.getenv("COLORTERM")) and "A" or "T"
if opt then
opt = gsub(opt, "[TAH]", function(mode) colormode = mode; return ""; end)
end
local m = { t=true, b=true, i=true, m=true, }
if opt and opt ~= "" then
local o = sub(opt, 1, 1)
if o ~= "+" and o ~= "-" then m = {} end
for i=1,#opt do m[sub(opt, i, i)] = (o ~= "-") end
end
dumpmode = m
if m.t or m.b or m.i or m.s or m.m then
jit.attach(dump_trace, "trace")
end
if m.b then
jit.attach(dump_record, "record")
if not bcline then bcline = require("jit.bc").line end
end
if m.x or m.X then
jit.attach(dump_texit, "texit")
end
if not outfile then outfile = os.getenv("LUAJIT_DUMPFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stdout
end
m[colormode] = true
if colormode == "A" then
colorize = colorize_ansi
irtype = irtype_ansi
elseif colormode == "H" then
colorize = colorize_html
irtype = irtype_html
out:write(header_html)
else
colorize = colorize_text
irtype = irtype_text
end
active = true
end
-- Public module functions.
return {
on = dumpon,
off = dumpoff,
start = dumpon -- For -j command line option.
}
| mit |
TheOnePharaoh/YGOPro-Custom-Cards | script/c100000831.lua | 2 | 2868 | --Created and coded by Rising Phoenix
function c100000831.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(100000831,0))
e1:SetCategory(CATEGORY_TODECK)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLED)
e1:SetCondition(c100000831.retcon)
e1:SetTarget(c100000831.rettg)
e1:SetOperation(c100000831.retop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(100000831,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BATTLE_DESTROYED)
e2:SetTarget(c100000831.target)
e2:SetOperation(c100000831.operation)
e2:SetCost(c100000831.spcost)
e2:SetCountLimit(1,100000831)
c:RegisterEffect(e2)
--attack
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetValue(c100000831.atkval)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e4)
end
function c100000831.retcon(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetAttacker()
if tc==e:GetHandler() then tc=Duel.GetAttackTarget() end
if not tc then return false end
e:SetLabelObject(tc)
local lv=tc:GetLevel()
return lv>9 and lv<=12 and not tc:IsStatus(STATUS_BATTLE_DESTROYED)
end
function c100000831.rettg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk ==0 then return e:GetLabelObject():IsAbleToDeck() end
Duel.SetOperationInfo(0,CATEGORY_TODECK,e:GetLabelObject(),0,0,0)
end
function c100000831.retop(e,tp,eg,ep,ev,re,r,rp)
if e:GetLabelObject():IsRelateToBattle() then end
Duel.SendtoDeck(e:GetLabelObject(),nil,REASON_EFFECT,nil)
end
function c100000831.filter(c,e,tp)
return c:IsSetCard(0x10B)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c100000831.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c100000831.filter,tp,LOCATION_DECK+LOCATION_EXTRA,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK+LOCATION_EXTRA)
end
function c100000831.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,c100000831.filter,tp,LOCATION_DECK+LOCATION_EXTRA,0,1,1,nil,e,tp)
if g:GetCount()>0 then end
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
function c100000831.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsAbleToDeckAsCost() end
Duel.SendtoDeck(c,nil,2,REASON_COST)
end
function c100000831.atkval(e,c)
local g=Duel.GetMatchingGroup(Card.IsFaceup,c:GetControler(),LOCATION_MZONE,LOCATION_MZONE,nil)
return g:GetSum(Card.GetLevel)*150
end
| gpl-3.0 |
Em30-tm-lua/Emc | .luarocks/share/lua/5.2/luarocks/repos.lua | 20 | 11978 |
--- Functions for managing the repository on disk.
--module("luarocks.repos", package.seeall)
local repos = {}
package.loaded["luarocks.repos"] = repos
local fs = require("luarocks.fs")
local path = require("luarocks.path")
local cfg = require("luarocks.cfg")
local util = require("luarocks.util")
local dir = require("luarocks.dir")
local manif = require("luarocks.manif")
local deps = require("luarocks.deps")
--- Get all installed versions of a package.
-- @param name string: a package name.
-- @return table or nil: An array of strings listing installed
-- versions of a package, or nil if none is available.
local function get_installed_versions(name)
assert(type(name) == "string")
local dirs = fs.list_dir(path.versions_dir(name))
return (dirs and #dirs > 0) and dirs or nil
end
--- Check if a package exists in a local repository.
-- Version numbers are compared as exact string comparison.
-- @param name string: name of package
-- @param version string: package version in string format
-- @return boolean: true if a package is installed,
-- false otherwise.
function repos.is_installed(name, version)
assert(type(name) == "string")
assert(type(version) == "string")
return fs.is_dir(path.install_dir(name, version))
end
local function recurse_rock_manifest_tree(file_tree, action)
assert(type(file_tree) == "table")
assert(type(action) == "function")
local function do_recurse_rock_manifest_tree(tree, parent_path, parent_module)
for file, sub in pairs(tree) do
if type(sub) == "table" then
local ok, err = do_recurse_rock_manifest_tree(sub, parent_path..file.."/", parent_module..file..".")
if not ok then return nil, err end
else
local ok, err = action(parent_path, parent_module, file)
if not ok then return nil, err end
end
end
return true
end
return do_recurse_rock_manifest_tree(file_tree, "", "")
end
local function store_package_data(result, name, file_tree)
if not file_tree then return end
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local pathname = parent_path..file
result[path.path_to_module(pathname)] = pathname
return true
end
)
end
--- Obtain a list of modules within an installed package.
-- @param package string: The package name; for example "luasocket"
-- @param version string: The exact version number including revision;
-- for example "2.0.1-1".
-- @return table: A table of modules where keys are module identifiers
-- in "foo.bar" format and values are pathnames in architecture-dependent
-- "foo/bar.so" format. If no modules are found or if package or version
-- are invalid, an empty table is returned.
function repos.package_modules(package, version)
assert(type(package) == "string")
assert(type(version) == "string")
local result = {}
local rock_manifest = manif.load_rock_manifest(package, version)
store_package_data(result, package, rock_manifest.lib)
store_package_data(result, package, rock_manifest.lua)
return result
end
--- Obtain a list of command-line scripts within an installed package.
-- @param package string: The package name; for example "luasocket"
-- @param version string: The exact version number including revision;
-- for example "2.0.1-1".
-- @return table: A table of items where keys are command names
-- as strings and values are pathnames in architecture-dependent
-- ".../bin/foo" format. If no modules are found or if package or version
-- are invalid, an empty table is returned.
function repos.package_commands(package, version)
assert(type(package) == "string")
assert(type(version) == "string")
local result = {}
local rock_manifest = manif.load_rock_manifest(package, version)
store_package_data(result, package, rock_manifest.bin)
return result
end
--- Check if a rock contains binary executables.
-- @param name string: name of an installed rock
-- @param version string: version of an installed rock
-- @return boolean: returns true if rock contains platform-specific
-- binary executables, or false if it is a pure-Lua rock.
function repos.has_binaries(name, version)
assert(type(name) == "string")
assert(type(version) == "string")
local rock_manifest = manif.load_rock_manifest(name, version)
if rock_manifest.bin then
for name, md5 in pairs(rock_manifest.bin) do
-- TODO verify that it is the same file. If it isn't, find the actual command.
if fs.is_actual_binary(dir.path(cfg.deploy_bin_dir, name)) then
return true
end
end
end
return false
end
function repos.run_hook(rockspec, hook_name)
assert(type(rockspec) == "table")
assert(type(hook_name) == "string")
local hooks = rockspec.hooks
if not hooks then
return true
end
if cfg.hooks_enabled == false then
return nil, "This rockspec contains hooks, which are blocked by the 'hooks_enabled' setting in your LuaRocks configuration."
end
if not hooks.substituted_variables then
util.variable_substitutions(hooks, rockspec.variables)
hooks.substituted_variables = true
end
local hook = hooks[hook_name]
if hook then
util.printout(hook)
if not fs.execute(hook) then
return nil, "Failed running "..hook_name.." hook."
end
end
return true
end
local function install_binary(source, target, name, version)
assert(type(source) == "string")
assert(type(target) == "string")
if fs.is_lua(source) then
repos.ok, repos.err = fs.wrap_script(source, target, name, version)
else
repos.ok, repos.err = fs.copy_binary(source, target)
end
return repos.ok, repos.err
end
local function resolve_conflict(target, deploy_dir, name, version)
local cname, cversion = manif.find_current_provider(target)
if not cname then
return nil, cversion
end
if name ~= cname or deps.compare_versions(version, cversion) then
local versioned = path.versioned_name(target, deploy_dir, cname, cversion)
local ok, err = fs.make_dir(dir.dir_name(versioned))
if not ok then return nil, err end
fs.move(target, versioned)
return target
else
return path.versioned_name(target, deploy_dir, name, version)
end
end
function repos.should_wrap_bin_scripts(rockspec)
assert(type(rockspec) == "table")
if cfg.wrap_bin_scripts ~= nil then
return cfg.wrap_bin_scripts
end
if rockspec.deploy and rockspec.deploy.wrap_bin_scripts == false then
return false
end
return true
end
function repos.deploy_files(name, version, wrap_bin_scripts)
assert(type(name) == "string")
assert(type(version) == "string")
assert(type(wrap_bin_scripts) == "boolean")
local function deploy_file_tree(file_tree, path_fn, deploy_dir, move_fn)
local source_dir = path_fn(name, version)
if not move_fn then
move_fn = fs.move
end
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local source = dir.path(source_dir, parent_path, file)
local target = dir.path(deploy_dir, parent_path, file)
local ok, err
if fs.exists(target) then
local new_target, err = resolve_conflict(target, deploy_dir, name, version)
if err == "untracked" then
local backup = target
repeat
backup = backup.."~"
until not fs.exists(backup) -- slight race condition here, but shouldn't be a problem.
util.printerr("Warning: "..target.." is not tracked by this installation of LuaRocks. Moving it to "..backup)
fs.move(target, backup)
elseif err then
return nil, err.." Cannot install new version."
else
target = new_target
end
end
ok, err = fs.make_dir(dir.dir_name(target))
if not ok then return nil, err end
ok, err = move_fn(source, target, name, version)
fs.remove_dir_tree_if_empty(dir.dir_name(source))
if not ok then return nil, err end
return true
end
)
end
local rock_manifest = manif.load_rock_manifest(name, version)
local ok, err = true
if rock_manifest.bin then
local move_bin_fn = wrap_bin_scripts and install_binary or fs.copy_binary
ok, err = deploy_file_tree(rock_manifest.bin, path.bin_dir, cfg.deploy_bin_dir, move_bin_fn)
end
if ok and rock_manifest.lua then
ok, err = deploy_file_tree(rock_manifest.lua, path.lua_dir, cfg.deploy_lua_dir)
end
if ok and rock_manifest.lib then
ok, err = deploy_file_tree(rock_manifest.lib, path.lib_dir, cfg.deploy_lib_dir)
end
return ok, err
end
local function delete_suffixed(filename, suffix)
local filenames = { filename }
if suffix and suffix ~= "" then filenames = { filename..suffix, filename } end
for _, name in ipairs(filenames) do
if fs.exists(name) then
fs.delete(name)
if fs.exists(name) then
return nil, "Failed deleting "..name, "fail"
end
return true, name
end
end
return false, "File not found", "not found"
end
--- Delete a package from the local repository.
-- Version numbers are compared as exact string comparison.
-- @param name string: name of package
-- @param version string: package version in string format
-- @param quick boolean: do not try to fix the versioned name
-- of another version that provides the same module that
-- was deleted. This is used during 'purge', as every module
-- will be eventually deleted.
function repos.delete_version(name, version, quick)
assert(type(name) == "string")
assert(type(version) == "string")
local function delete_deployed_file_tree(file_tree, deploy_dir, suffix)
return recurse_rock_manifest_tree(file_tree,
function(parent_path, parent_module, file)
local target = dir.path(deploy_dir, parent_path, file)
local versioned = path.versioned_name(target, deploy_dir, name, version)
local ok, name, err = delete_suffixed(versioned, suffix)
if ok then
fs.remove_dir_tree_if_empty(dir.dir_name(versioned))
return true
end
if err == "fail" then return nil, name end
ok, name, err = delete_suffixed(target, suffix)
if err == "fail" then return nil, name end
if not quick then
local next_name, next_version = manif.find_next_provider(target)
if next_name then
local versioned = path.versioned_name(name, deploy_dir, next_name, next_version)
fs.move(versioned, name)
fs.remove_dir_tree_if_empty(dir.dir_name(versioned))
end
end
fs.remove_dir_tree_if_empty(dir.dir_name(target))
return true
end
)
end
local rock_manifest = manif.load_rock_manifest(name, version)
if not rock_manifest then
return nil, "rock_manifest file not found for "..name.." "..version.." - not a LuaRocks 2 tree?"
end
local ok, err = true
if rock_manifest.bin then
ok, err = delete_deployed_file_tree(rock_manifest.bin, cfg.deploy_bin_dir, cfg.wrapper_suffix)
end
if ok and rock_manifest.lua then
ok, err = delete_deployed_file_tree(rock_manifest.lua, cfg.deploy_lua_dir)
end
if ok and rock_manifest.lib then
ok, err = delete_deployed_file_tree(rock_manifest.lib, cfg.deploy_lib_dir)
end
if err then return nil, err end
fs.delete(path.install_dir(name, version))
if not get_installed_versions(name) then
fs.delete(dir.path(cfg.rocks_dir, name))
end
return true
end
return repos
| gpl-2.0 |
jixianliang/DBProxy | lib/proxy/balance.lua | 41 | 2807 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
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., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
module("proxy.balance", package.seeall)
function idle_failsafe_rw()
local backend_ndx = 0
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local conns = s.pool.users[proxy.connection.client.username]
if conns.cur_idle_connections > 0 and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.state ~= proxy.BACKEND_STATE_OFFLINE and
s.type == proxy.BACKEND_TYPE_RW then
backend_ndx = i
break
end
end
return backend_ndx
end
function idle_ro()
local max_conns = -1
local max_conns_ndx = 0
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local conns = s.pool.users[proxy.connection.client.username]
-- pick a slave which has some idling connections
if s.type == proxy.BACKEND_TYPE_RO and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.state ~= proxy.BACKEND_STATE_OFFLINE and
conns.cur_idle_connections > 0 then
if max_conns == -1 or
s.connected_clients < max_conns then
max_conns = s.connected_clients
max_conns_ndx = i
end
end
end
return max_conns_ndx
end
function cycle_read_ro()
local backends = proxy.global.backends
local rwsplit = proxy.global.config.rwsplit
local max_weight = rwsplit.max_weight
local cur_weight = rwsplit.cur_weight
local next_ndx = rwsplit.next_ndx
local ndx_num = rwsplit.ndx_num
local ndx = 0
for i = 1, ndx_num do --ÿ¸öquery×î¶àÂÖѯndx_num´Î
local s = backends[next_ndx]
if s.type == proxy.BACKEND_TYPE_RO and s.weight >= cur_weight and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.pool.users[proxy.connection.client.username].cur_idle_connections > 0 then ndx = next_ndx end
if next_ndx == ndx_num then --ÂÖѯÍêÁË×îºóÒ»¸öndx£¬È¨Öµ¼õÒ»
cur_weight = cur_weight - 1
if cur_weight == 0 then cur_weight = max_weight end
next_ndx = 1
else --·ñÔòÖ¸Ïòϸöndx
next_ndx = next_ndx + 1
end
if ndx ~= 0 then break end
end
rwsplit.cur_weight = cur_weight
rwsplit.next_ndx = next_ndx
return ndx
end
| gpl-2.0 |
waytim/darkstar | scripts/globals/spells/burn.lua | 17 | 1851 | -----------------------------------------
-- Spell: Burn
-- Deals fire damage that lowers an enemy's intelligence and gradually reduces its HP.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:getStatusEffect(EFFECT_DROWN) ~= nil) then
spell:setMsg(75); -- no effect
else
local dINT = caster:getStat(MOD_INT)-target:getStat(MOD_INT);
local resist = applyResistance(caster,spell,target,dINT,36,0);
if (resist <= 0.125) then
spell:setMsg(85);
else
if (target:getStatusEffect(EFFECT_FROST) ~= nil) then
target:delStatusEffect(EFFECT_FROST);
end;
local sINT = caster:getStat(MOD_INT);
local DOT = getElementalDebuffDOT(sINT);
local effect = target:getStatusEffect(EFFECT_BURN);
local noeffect = false;
if (effect ~= nil) then
if (effect:getPower() >= DOT) then
noeffect = true;
end;
end;
if (noeffect) then
spell:setMsg(75); -- no effect
else
if (effect ~= nil) then
target:delStatusEffect(EFFECT_BURN);
end;
spell:setMsg(237);
local duration = math.floor(ELEMENTAL_DEBUFF_DURATION * resist);
target:addStatusEffect(EFFECT_BURN,DOT, 3, ELEMENTAL_DEBUFF_DURATION,FLAG_ERASBLE);
end;
end;
end;
return EFFECT_BURN;
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Bhaflau_Remnants/Zone.lua | 19 | 1071 | -----------------------------------
--
-- Zone: Bhaflau_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil;
require("scripts/zones/Bhaflau_Remnants/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Yhoator_Jungle/npcs/Logging_Point.lua | 13 | 1068 | -----------------------------------
-- Area: Yhoator Jungle
-- NPC: Logging Point
-----------------------------------
package.loaded["scripts/zones/Yhoator_Jungle/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/logging");
require("scripts/zones/Yhoator_Jungle/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startLogging(player,player:getZoneID(),npc,trade,0x000A);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(LOGGING_IS_POSSIBLE_HERE,1021);
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 |
Guim3/IcGAN | generation/reconstructWithVariations.lua | 1 | 8523 | require 'image'
require 'nn'
optnet = require 'optnet'
disp = require 'display'
torch.setdefaulttensortype('torch.FloatTensor')
-- Load parameters from config file
assert(loadfile("cfg/generateConfig.lua"))(1)
-- one-line argument parser. Parses environment variables to override the defaults
for k,v in pairs(opt) do opt[k] = tonumber(os.getenv(k)) or os.getenv(k) or opt[k] end
local function applyThreshold(Y, th)
-- Takes a matrix Y and thresholds, given th, to -1 and 1
assert(th>=-1 and th<=1, "Error: threshold must be between -1 and 1")
for i=1,Y:size(1) do
for j=1,Y:size(2) do
local val = Y[{{i},{j}}][1][1]
if val > th then
Y[{{i},{j}}] = 1
else
Y[{{i},{j}}] = -1
end
end
end
return Y
end
local function findElementInTable(table, element)
local i = 1
local matchIdx = 0
while i <= #table and matchIdx == 0 do
if torch.any(table[i]:eq(element)) then matchIdx = i end
i = i + 1
end
return matchIdx
end
local function sampleY(outY, dataset, threshold, inY)
local nSamples = outY:size(1)
local ny = outY:size(2)
if string.lower(dataset) == 'celeba' then
local genderIdx = 10 -- This index is obtained from donkey_celebA.
local genderConfidence = 100*inY[{{},{genderIdx}}]
if threshold then
-- Convert Y to binary [-1, 1] vector
inY = applyThreshold(inY, 0)
end
-- Special cases:
-- 1. Male (11 --> 1) or female (11 --> -1): a male will be converted to female and viceversa.
-- 2. Bald (1), bangs (2) and receding_hairline (15): only one can be activated at the same time
-- 3. Black (3), blonde (4), brown (5) and gray (9) hair: only one can be activated at the same time
-- 4. Wavy_Hair (17) and Straight_Hair (18): only one activated at the same time
-- We check if the input real image is male or female..
local genderAttr = torch.ge(inY[{{},{genderIdx}}], 0) -- Stores whether a sample is male (1) or female (0)
local filterList = {}
filterList[1] = torch.IntTensor{1,2,14} -- hairstyle filter
filterList[2] = torch.IntTensor{3,4,5,8}-- hair color filter
filterList[3] = torch.IntTensor{16,17}
print('Row\tGender\tConfidence')
local k = 0 -- Indexs genderAttr, which has a different dimension than outY
for i=1,nSamples do
local j = ((i-1)%ny)+1 -- Indexs outY 2nd dimension (attributes)
if j==1 then
k = k + 1
local val = genderConfidence[{{k}}][1][1]
if genderAttr[k][1] == 1 then print(('%d\tMale\t%d%%'):format(k,val)) else print(('%d\tFemale\t%d%%'):format(k,-val)) end
end
-- Instead of setting all the other positions to -1, use the original Y vector
outY[{{i},{}}] = inY[{{k},{}}]
if j == genderIdx then
if genderAttr[k][1] == 0 then outY[{{i},{j}}] = 1 else outY[{{i},{j}}] = -1 end
else
-- Check if attribute is in filterList
local filterIdx = findElementInTable(filterList, j)
if filterIdx > 0 then
-- Put to -1 incompatible attributes of filterList[filterIdx] except for value 'i'
for idx=1,filterList[filterIdx]:size(1) do
if filterList[filterIdx][idx] ~= j then
outY[{{i},{filterList[filterIdx][idx]}}] = -1
end
end
end
outY[{{i},{j}}] = 1
end
end
else
-- Case of MNIST and other generic datasets with one-hot vectors.
for i=1,nSamples do
outY[{{i},{((i-1)%ny)+1}}] = 1
end
end
end
local function obtainImageSet(X, path, option, extension)
if option == 1 then
-- Load input image X
-- Check string is a path to an image
assert(path:match(extension) ~= nil, "opt.loadPath '"..path.."' is not an image.")
local tmp = image.load(path):float()
tmp = image.scale(tmp, X:size(3), X:size(4))
-- Image dimensions is 3. We need a 4th dimension indicating the number of images.
tmp:resize(1, X:size(2), X:size(3), X:size(4))
X = tmp
elseif option == 2 then
-- Load multiple images given a path
assert(paths.dir(path)~=nil, "opt.loadPath '"..path.."' is not a directory.")
local i = 1
local fileIterator = paths.files(path, extension)
local fileName = fileIterator()
while i <= opt.nImages and fileName ~= nil do
local imPath = path .. '/' .. fileName
local im = image.load(imPath)
X[{{i},{},{},{}}] = image.scale(im, X:size(3), X:size(4))
i = i + 1
fileName = fileIterator()
end
assert(i~=1, "No images have been found in opt.loadPath '"..path.."'")
assert(i-1==opt.nImages, "Only ".. i-1 .." images have been found in opt.loadPath '"..path.."', expected "..opt.nImages..".")
else
error('Option (customInputImage) not recognized.')
end
X:mul(2):add(-1) -- change [0, 1] to [-1, 1]
return X
end
if opt.gpu > 0 then
require 'cunn'
require 'cudnn'
end
if opt.loadOption == 1 then opt.nImages = 1 end
local imgExtension = '.png'
local ny -- Y label length. This depends on the dataset.
if string.lower(opt.dataset) == 'mnist' then ny = 10; imgExtension = '.png'
elseif string.lower(opt.dataset) == 'celeba' then ny = 18; imgExtension = '.jpg'; end
-- Load nets
local generator = torch.load(opt.decNet)
local encZ = torch.load(opt.encZnet)
local encY = torch.load(opt.encYnet)
-- Load to GPU
if opt.gpu > 0 then
cudnn.convert(generator, cudnn)
cudnn.convert(encZ, cudnn)
cudnn.convert(encY, cudnn)
generator:cuda(); encZ:cuda(); encY:cuda()
else
generator:float(); encZ:float(); encY:cuda()
end
generator:evaluate()
encZ:evaluate()
encY:evaluate()
local inputX = torch.Tensor(opt.nImages, opt.loadSize[1], opt.loadSize[2], opt.loadSize[3])
-- Encode Z and Y from a given set of images
inputX = obtainImageSet(inputX, opt.loadPath, opt.loadOption, imgExtension)
if opt.gpu > 0 then inputX = inputX:cuda() end
local Z = encZ:forward(inputX)
local Y = encY:forward(inputX)
Z:resize(Z:size(1), Z:size(2), 1, 1)
inputX = inputX:float() -- No longer needed in GPU
-- a function to setup double-buffering across the network.
-- this drastically reduces the memory needed to generate samples
local sampleInput = {Z[{{1}}], Y[{{1}}]}
optnet.optimizeMemory(generator, sampleInput)
-- At this point, we have Z and Y and we need to expand them.
-- We just need to fix Z on rows and Y on columns
-- These ones are expanded version of Z and Y.
-- They just have more repetitions.
local nOutSamples = opt.nImages*ny
local outZ = torch.Tensor(nOutSamples, opt.nz, 1, 1)
local outY = torch.Tensor(nOutSamples, ny):fill(-1)
if opt.gpu > 0 then outZ = outZ:cuda(); outY = outY:cuda() end
-- Fix Z for every row in generated samples.
-- A row has ny samples. Every i to (i-1)+ny samples outZ will have the same Z.
local j = 1
for i=1,nOutSamples,ny do
outZ[{{i,(i-1)+ny},{},{},{}}] = Z[{{j},{},{},{}}]:expand(ny,opt.nz,1,1)
j = j + 1
end
-- Fix Y for every column in generated samples.
sampleY(outY, opt.dataset, opt.threshold, Y)
-- Final image: 1st columns: original image (inputX)
-- 2nd: reconstructed image (reconstX)
-- 3rd-end: variations on Y (and same Z for each row) (outX)
local reconstX = generator:forward{Z, Y}:clone():float()
local outX = generator:forward{outZ, outY}:float()
local outputImage = torch.cat(inputX[{{1}}],reconstX[{{1}}], 1):cat(outX[{{1,ny}}],1)
for i=2,opt.nImages do
local tmp = torch.cat(inputX[{{i}}],reconstX[{{i}}], 1):cat(outX[{{(i-1)*ny+1,i*ny}}],1)
outputImage = outputImage:cat(tmp, 1)
end
if string.lower(opt.dataset) == 'celeba' then
local str_list = {'bald', 'bangs', 'black hair', 'blond', 'brown', 'eyebrows', 'eyeglasses', 'gray', 'makeup', 'male', 'mouth open', 'mustache', 'pale skin', 'receding hairline', 'smiling', 'straight hair', 'wavy hair', 'hat'}
print('Column order: ')
print("1. Original\n2. Reconstruction")
for i=1,#str_list do
print(("%d. %s"):format(i+2, str_list[i]))
end
end
disp.image(image.toDisplayTensor(outputImage,0,ny+2))
image.save(opt.name .. '.png', image.toDisplayTensor(outputImage,0,ny+2))
print('Done!')
| bsd-3-clause |
waytim/darkstar | scripts/zones/Monastic_Cavern/TextIDs.lua | 22 | 1704 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6384; -- Obtained: <item>.
GIL_OBTAINED = 6385; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7281; -- You unlock the chest!
CHEST_FAIL = 7282; -- Fails to open the chest.
CHEST_TRAP = 7283; -- The chest was trapped!
CHEST_WEAK = 7284; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7285; -- The chest was a mimic!
CHEST_MOOGLE = 7286; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7287; -- The chest was but an illusion...
CHEST_LOCKED = 7288; -- The chest appears to be locked.
-- Other dialog
NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here.
ALTAR = 7260; -- This appears to be an altar.
THE_MAGICITE_GLOWS_OMINOUSLY = 7263; -- The magicite glows ominously.
ORCISH_OVERLORD_ENGAGE = 7293; -- Intruders? Get outs here! We gots us some adventurers!
ORCISH_OVERLORD_DEATH = 7294; -- Gahahahaha... You fell for our trick. I'm not the big boss. He don't need to be troubled by runty little rarabs like you.
ORC_KING_ENGAGE = 7295; -- Ungh? Who are you?So, you've come to kill big boss Bakgodek? I'll crush your scrawny bones myself!
ORC_KING_DEATH = 7296; -- Unghh... Foolish children of Altana. Defeating me won't change anything. There will be others from the north...
-- conquest Base
CONQUEST_BASE = 7045; -- Tallying conquest results...
| gpl-3.0 |
chatid/fend | signalfd.lua | 1 | 3194 | local next = next
local pairs = pairs
local ffi = require "ffi"
local new_file = require "fend.file".wrap
require "fend.common"
include "stdio"
include "string"
include "errno"
include "sys/signalfd"
local sigfiles_map = setmetatable ( { } , { __mode = "k" } )
local signal_cb_table = {
read = function ( file , cbs )
local info = ffi.new ( "struct signalfd_siginfo[1]" )
local r = tonumber ( ffi.C.read ( file:getfd() , info , ffi.sizeof ( info ) ) )
if r == -1 then
local err = ffi.errno ( )
if err == defines.EAGAIN then
return
else
error ( ffi.string ( ffi.C.strerror ( err ) ) )
end
end
assert ( r == ffi.sizeof ( info ) )
local self = sigfiles_map [ file ]
local signum = info[0].ssi_signo
for id , cb in pairs ( self.sigcbs [ signum ] ) do
cb ( info , id )
end
return cbs.read ( file , cbs ) -- Call self until EAGAIN
end ;
close = function ( file , cbs )
error ( "signalfd closed" )
end ;
error = function ( file , cbs )
error ( "signalfd error" )
end ;
edge = true ;
}
local function new ( dispatcher )
local mask = ffi.new ( "sigset_t[1]" )
if ffi.C.sigemptyset ( mask ) == -1 then
error ( ffi.string ( ffi.C.strerror ( ffi.errno ( ) ) ) )
end
local sigfd = ffi.C.signalfd ( -1 , mask , ffi.C.SFD_NONBLOCK )
if sigfd == -1 then
error ( ffi.string ( ffi.C.strerror ( ffi.errno ( ) ) ) )
end
sigfd = new_file ( sigfd )
local self = {
sigfile = sigfd ;
sigmask = mask ;
sigcbs = { } ;
}
sigfiles_map [ sigfd ] = self
dispatcher:add_fd ( sigfd , signal_cb_table )
return self
end
--- Watch for a signal.
-- This function will not block the signal for you; you must do that yourself
-- signum is the signal to watch for
-- cb is the callback to call when a signal arrives; it will receive a `struct signalfd_siginfo[1]` and the watcher's identifier
-- returns an identifier that should be used to delete the signal later
local function add_signal ( dispatcher , signum , cb )
local self = dispatcher.signalfd
local cbs = self.sigcbs [ signum ]
if cbs then
local n = #cbs + 1
cbs [ n ] = cb
return n
else
cbs = { cb }
self.sigcbs [ signum ] = cbs
if ffi.C.sigaddset ( self.sigmask , signum ) == -1 then
error ( ffi.string ( ffi.C.strerror ( ffi.errno ( ) ) ) )
end
if ffi.C.signalfd ( self.sigfile:getfd() , self.sigmask , 0 ) == -1 then
error ( ffi.string ( ffi.C.strerror ( ffi.errno ( ) ) ) )
end
return 1
end
end
--- Stop watching for a signal.
-- signum is the signal to stop watching
-- id is the signal id to stop watching (obtained from add_signal)
local function del_signal ( dispatcher , signum , id )
local self = dispatcher.signalfd
local cbs = self.sigcbs [ signum ]
cbs [ id ] = nil
if next ( cbs ) == nil then -- No callbacks left for this signal; remove it from the watched set
self.sigcbs [ signum ] = nil
if ffi.C.sigdelset ( self.sigmask , signum ) == -1 then
error ( ffi.string ( ffi.C.strerror ( ffi.errno ( ) ) ) )
end
if ffi.C.signalfd ( self.sigfile:getfd() , self.sigmask , 0 ) == -1 then
error ( ffi.string ( ffi.C.strerror ( ffi.errno ( ) ) ) )
end
end
end
return {
new = new ;
add = add_signal ;
del = del_signal ;
}
| mit |
waytim/darkstar | scripts/zones/Zeruhn_Mines/npcs/Grounds_Tome.lua | 30 | 1079 | -----------------------------------
-- Area: Zeruhn Mines
-- 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_ZERUHN_MINES,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,626,627,628,629,630,0,0,0,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,626,627,628,629,630,0,0,0,0,0,GOV_MSG_ZERUHN_MINES);
end;
| gpl-3.0 |
zorfmorf/loveprojects | colonycontrol/src/lib/hump/camera.lua | 47 | 3388 | --[[
Copyright (c) 2010-2013 Matthias Richter
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
Except as contained in this notice, the name(s) of the above copyright holders
shall not be used in advertising or otherwise to promote the sale, use or
other dealings in this Software without prior written authorization.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
]]--
local _PATH = (...):match('^(.*[%./])[^%.%/]+$') or ''
local cos, sin = math.cos, math.sin
local camera = {}
camera.__index = camera
local function new(x,y, zoom, rot)
x,y = x or love.graphics.getWidth()/2, y or love.graphics.getHeight()/2
zoom = zoom or 1
rot = rot or 0
return setmetatable({x = x, y = y, scale = zoom, rot = rot}, camera)
end
function camera:lookAt(x,y)
self.x, self.y = x,y
return self
end
function camera:move(x,y)
self.x, self.y = self.x + x, self.y + y
return self
end
function camera:pos()
return self.x, self.y
end
function camera:rotate(phi)
self.rot = self.rot + phi
return self
end
function camera:rotateTo(phi)
self.rot = phi
return self
end
function camera:zoom(mul)
self.scale = self.scale * mul
return self
end
function camera:zoomTo(zoom)
self.scale = zoom
return self
end
function camera:attach()
local cx,cy = love.graphics.getWidth()/(2*self.scale), love.graphics.getHeight()/(2*self.scale)
love.graphics.push()
love.graphics.scale(self.scale)
love.graphics.translate(cx, cy)
love.graphics.rotate(self.rot)
love.graphics.translate(-self.x, -self.y)
end
function camera:detach()
love.graphics.pop()
end
function camera:draw(func)
self:attach()
func()
self:detach()
end
function camera:cameraCoords(x,y)
-- x,y = ((x,y) - (self.x, self.y)):rotated(self.rot) * self.scale + center
local w,h = love.graphics.getWidth(), love.graphics.getHeight()
local c,s = cos(self.rot), sin(self.rot)
x,y = x - self.x, y - self.y
x,y = c*x - s*y, s*x + c*y
return x*self.scale + w/2, y*self.scale + h/2
end
function camera:worldCoords(x,y)
-- x,y = (((x,y) - center) / self.scale):rotated(-self.rot) + (self.x,self.y)
local w,h = love.graphics.getWidth(), love.graphics.getHeight()
local c,s = cos(-self.rot), sin(-self.rot)
x,y = (x - w/2) / self.scale, (y - h/2) / self.scale
x,y = c*x - s*y, s*x + c*y
return x+self.x, y+self.y
end
function camera:mousepos()
return self:worldCoords(love.mouse.getPosition())
end
-- the module
return setmetatable({new = new},
{__call = function(_, ...) return new(...) end})
| apache-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Xarcabard/npcs/Pelogrant.lua | 2 | 1728 | -----------------------------------
-- Area: Xarcabard
-- NPC: Pelogrant
-- @pos 210 -22 -201 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Xarcabard/TextIDs");
region = VALDEAUNIA;
csid = 0x7ff4;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
owner = GetRegionOwner(region);
arg1 = getArg1(owner,player);
if(owner == player:getNation()) then
nation = 1;
elseif(arg1 < 1792) then
nation = 2;
else
nation = 0;
end
player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP());
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("OPTION: %u",option);
if(option == 1) then
ShowOPVendorShop(player);
elseif(option == 2) then
if (player:delGil(OP_TeleFee(player,region))) then
toHomeNation(player);
end
elseif(option == 6) then
player:delCP(OP_TeleFee(player,region));
toHomeNation(player);
end
end; | gpl-3.0 |
pedrohenriquerls/cocos2d_ruby_binding | frameworks/cocos2d-x/cocos/scripting/lua-bindings/script/extension/DeprecatedExtensionEnum.lua | 40 | 1369 |
_G.kCCControlStepperPartMinus = cc.CONTROL_STEPPER_PART_MINUS
_G.kCCControlStepperPartPlus = cc.CONTROL_STEPPER_PART_PLUS
_G.kCCControlStepperPartNone = cc.CONTROL_STEPPER_PART_NONE
_G.CCControlEventTouchDown = cc.CONTROL_EVENTTYPE_TOUCH_DOWN
_G.CCControlEventTouchDragInside = cc.CONTROL_EVENTTYPE_DRAG_INSIDE
_G.CCControlEventTouchDragOutside = cc.CONTROL_EVENTTYPE_DRAG_OUTSIDE
_G.CCControlEventTouchDragEnter = cc.CONTROL_EVENTTYPE_DRAG_ENTER
_G.CCControlEventTouchDragExit = cc.CONTROL_EVENTTYPE_DRAG_EXIT
_G.CCControlEventTouchUpInside = cc.CONTROL_EVENTTYPE_TOUCH_UP_INSIDE
_G.CCControlEventTouchUpOutside = cc.CONTROL_EVENTTYPE_TOUCH_UP_OUTSIDE
_G.CCControlEventTouchCancel = cc.CONTROL_EVENTTYPE_TOUCH_CANCEL
_G.CCControlEventValueChanged = cc.CONTROL_EVENTTYPE_VALUE_CHANGED
_G.CCControlStateNormal = cc.CONTROL_STATE_NORMAL
_G.CCControlStateHighlighted = cc.CONTROL_STATE_HIGH_LIGHTED
_G.CCControlStateDisabled = cc.CONTROL_STATE_DISABLED
_G.CCControlStateSelected = cc.CONTROL_STATE_SELECTED
_G.kCCScrollViewDirectionHorizontal = cc.SCROLLVIEW_DIRECTION_HORIZONTAL
_G.kCCScrollViewDirectionVertical = cc.SCROLLVIEW_DIRECTION_VERTICAL
_G.kCCTableViewFillTopDown = cc.TABLEVIEW_FILL_TOPDOWN
_G.kCCTableViewFillBottomUp = cc.TABLEVIEW_FILL_BOTTOMUP
| mit |
waytim/darkstar | scripts/globals/abilities/spirit_link.lua | 17 | 2738 | -----------------------------------
-- Ability: Spirit Link
-- Sacrifices own HP to heal Wyvern's HP.
-- Obtained: Dragoon Level 25
-- Recast Time: 1:30
-- Duration: Instant
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getPet() == nil) then
return MSGBASIC_REQUIRES_A_PET,0;
else
if (player:getPet():getHP() == player:getPet():getMaxHP() and player:getMerit(MERIT_EMPATHY) == 0) then
return MSGBASIC_UNABLE_TO_USE_JA,0;
else
return 0,0;
end
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local playerHP = player:getHP();
local drainamount = (math.random(25,35) / 100) * playerHP;
if (player:getPet():getHP() == player:getPet():getMaxHP()) then
drainamount = 0; -- Prevents player HP lose if wyvern is at full HP
end
if (player:hasStatusEffect(EFFECT_STONESKIN)) then
local skin = player:getMod(MOD_STONESKIN);
if (skin >= drainamount) then
if (skin == drainamount) then
player:delStatusEffect(EFFECT_STONESKIN);
else
local effect = player:getStatusEffect(EFFECT_STONESKIN);
effect:setPower(effect:getPower() - drainamount); -- fixes the status effeect so when it ends it uses the new power instead of old
player:delMod(MOD_STONESKIN,drainamount); --removes the amount from the mod
end
else
player:delStatusEffect(EFFECT_STONESKIN);
player:delHP((drainamount-skin));
end
else
player:delHP(drainamount);
end
local pet = player:getPet();
local healPet = drainamount * 2;
local petTP = pet:getTP();
local regenAmount = player:getMainLvl()/3; -- level/3 tic regen
if (player:getEquipID(SLOT_HEAD)==15238) then
healPet = healPet + 15;
end
pet:delStatusEffect(EFFECT_POISON);
pet:delStatusEffect(EFFECT_BLIND);
pet:delStatusEffect(EFFECT_PARALYSIS);
if (math.random(1,2) == 1) then
pet:delStatusEffect(EFFECT_DOOM);
end
if (pet:getHP() < pet:getMaxHP()) then -- sleep is only removed if it heals the wyvern
removeSleepEffects(pet);
end
pet:addHP(healPet); --add the hp to pet
pet:addStatusEffect(EFFECT_REGEN,regenAmount,3,90,0,0,0); -- 90 seconds of regen
player:addTP(petTP/2); --add half pet tp to you
pet:delTP(petTP/2); -- remove half tp from pet
end; | gpl-3.0 |
GregSatre/nn | SpatialFullConvolutionMap.lua | 44 | 1990 | local SpatialFullConvolutionMap, parent = torch.class('nn.SpatialFullConvolutionMap', 'nn.Module')
function SpatialFullConvolutionMap:__init(conMatrix, kW, kH, dW, dH)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.connTable = conMatrix
self.nInputPlane = self.connTable:select(2,1):max()
self.nOutputPlane = self.connTable:select(2,2):max()
self.weight = torch.Tensor(self.connTable:size(1), kH, kW)
self.gradWeight = torch.Tensor(self.connTable:size(1), kH, kW)
self.bias = torch.Tensor(self.nOutputPlane)
self.gradBias = torch.Tensor(self.nOutputPlane)
self:reset()
end
function SpatialFullConvolutionMap:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
else
local ninp = torch.Tensor(self.nOutputPlane):zero()
for i=1,self.connTable:size(1) do ninp[self.connTable[i][2]] = ninp[self.connTable[i][2]]+1 end
for k=1,self.connTable:size(1) do
stdv = 1/math.sqrt(self.kW*self.kH*ninp[self.connTable[k][2]])
self.weight:select(1,k):apply(function() return torch.uniform(-stdv,stdv) end)
end
for k=1,self.bias:size(1) do
stdv = 1/math.sqrt(self.kW*self.kH*ninp[k])
self.bias[k] = torch.uniform(-stdv,stdv)
end
end
end
function SpatialFullConvolutionMap:updateOutput(input)
input.nn.SpatialFullConvolutionMap_updateOutput(self, input)
return self.output
end
function SpatialFullConvolutionMap:updateGradInput(input, gradOutput)
input.nn.SpatialFullConvolutionMap_updateGradInput(self, input, gradOutput)
return self.gradInput
end
function SpatialFullConvolutionMap:accGradParameters(input, gradOutput, scale)
return input.nn.SpatialFullConvolutionMap_accGradParameters(self, input, gradOutput, scale)
end
| bsd-3-clause |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Castle_Oztroja/npcs/_47c.lua | 2 | 1231 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Handle
-- Open trap door or brass door
-- @pos 20 0 -13 151
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
X = player:getXPos();
Z = player:getZPos();
if(X < 21.6 and X > 18 and Z > -15.6 and Z < -12.4) then
if(VanadielDayOfTheYear() % 2 == 0) then
GetNPCByID(17396152):openDoor();
if(player:getCurrentMission(WINDURST) == TO_EACH_HIS_OWN_RIGHT and player:getVar("MissionStatus") == 3) then
player:startEvent(0x002B);
end
else
GetNPCByID(17396151):openDoor();
end
else
player:messageSpecial(0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x002B) then
player:setVar("MissionStatus",4);
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/La_Theine_Plateau/npcs/Tayula.lua | 4 | 1041 | -----------------------------------
-- Area: La Theine Plateau
-- NPC: Tayula
-- Type: Mission
-- @zone: 102
-- @pos: -311.785 50.351 182.063
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0069);
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/Windurst_Woods/npcs/HomePoint#1.lua | 27 | 1278 | -----------------------------------
-- Area: Windurst Woods
-- NPC: HomePoint#1
-- @pos -98.588 0.001 -183.416 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 25);
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 == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
GregSatre/nn | SpatialFullConvolution.lua | 42 | 1589 | local SpatialFullConvolution, parent = torch.class('nn.SpatialFullConvolution','nn.Module')
function SpatialFullConvolution:__init(nInputPlane, nOutputPlane, kW, kH, dW, dH)
parent.__init(self)
dW = dW or 1
dH = dH or 1
self.nInputPlane = nInputPlane
self.nOutputPlane = nOutputPlane
self.kW = kW
self.kH = kH
self.dW = dW
self.dH = dH
self.weight = torch.Tensor(nInputPlane, nOutputPlane, kH, kW)
self.gradWeight = torch.Tensor(nInputPlane, nOutputPlane, kH, kW)
self.bias = torch.Tensor(self.nOutputPlane)
self.gradBias = torch.Tensor(self.nOutputPlane)
self:reset()
end
function SpatialFullConvolution:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
local nInputPlane = self.nInputPlane
local kH = self.kH
local kW = self.kW
stdv = 1/math.sqrt(kW*kH*nInputPlane)
end
self.weight:apply(function()
return torch.uniform(-stdv, stdv)
end)
self.bias:apply(function()
return torch.uniform(-stdv, stdv)
end)
end
function SpatialFullConvolution:updateOutput(input)
return input.nn.SpatialFullConvolution_updateOutput(self, input)
end
function SpatialFullConvolution:updateGradInput(input, gradOutput)
if self.gradInput then
return input.nn.SpatialFullConvolution_updateGradInput(self, input, gradOutput)
end
end
function SpatialFullConvolution:accGradParameters(input, gradOutput, scale)
return input.nn.SpatialFullConvolution_accGradParameters(self, input, gradOutput, scale)
end
| bsd-3-clause |
waytim/darkstar | scripts/globals/spells/chocobo_mazurka.lua | 27 | 1162 | -----------------------------------------
-- Spell: Chocobo Mazurka
-- Gives party members enhanced movement
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local power = 24;
local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
duration = duration * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
duration = duration * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then
spell:setMsg(75);
end
return EFFECT_MAZURKA;
end;
| gpl-3.0 |
unXedDani/Artal | tests/main.lua | 1 | 1342 | local tests = {}
for i, file in ipairs(love.filesystem.getDirectoryItems("cases")) do
if file:match(".lua$") then
local thread = love.thread.newThread("cases/" .. file)
thread:start()
table.insert(
tests,
{
name = file,
thread = thread,
}
)
end
end
local RUNNING, SUCCESS, FAILED = {255, 255, 0}, {0, 255, 0}, {255, 0, 0}
function love.draw()
love.graphics.push()
for i, test in ipairs(tests) do
local color
if test.thread:isRunning() then
color = RUNNING
else
if test.error then
color = FAILED
elseif test.thread:getError() then
color = FAILED
test.error = test.thread:getError()
print("ERROR in " .. test.name .. ":")
print(test.error)
else
color = SUCCESS
end
end
love.graphics.setColor(color)
love.graphics.circle("fill", 10, 10, 6)
love.graphics.translate(20, 0)
end
love.graphics.pop()
local hovered = tests[math.ceil(love.mouse.getX() / 20)]
if hovered then
love.graphics.setColor(255, 255, 255)
love.graphics.print(hovered.name, 10, 30)
if hovered.error then
love.graphics.printf(hovered.error, 10, 50, love.graphics.getWidth() - 20)
end
end
end
function love.keypressed(key)
if key == "escape" then love.event.push "quit" end
end
| mit |
waytim/darkstar | scripts/zones/Windurst_Waters/npcs/Yuli_Yaam.lua | 13 | 1908 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Yuli Yaam
-- Involved In Quest: Wondering Minstrel
-- Working 100%
-- @zone = 238
-- @pos = -61 -4 23
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
wonderingstatus = player:getQuestStatus(WINDURST,WONDERING_MINSTREL);
fame = player:getFameLevel(WINDURST)
if (wonderingstatus <= 1 and fame >= 5) then
player:startEvent(0x027d); -- WONDERING_MINSTREL: Quest Available / Quest Accepted
elseif (wonderingstatus == QUEST_COMPLETED and player:needToZone()) then
player:startEvent(0x0281); -- WONDERING_MINSTREL: Quest After
else
rand = math.random(2);
if (rand == 1) then
player:startEvent(0x0264); -- Standard Conversation 1
else
player:startEvent(0x0265); -- Standard Conversation 2
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 |
CaptainPRICE/wire | lua/entities/gmod_wire_relay.lua | 10 | 4490 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Relay"
ENT.WireDebugName = "Relay"
ENT.Author = "tad2020"
if CLIENT then return end -- No more client
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Value = {} //stores current output value
self.Last = {} //stores last input value for each input
self.Inputs = Wire_CreateInputs(self, { "1A", "2A", "Switch" })
self.Outputs = Wire_CreateOutputs(self, { "A" })
end
function ENT:Setup(keygroup1, keygroup2, keygroup3, keygroup4, keygroup5, keygroupoff, toggle, normclose, poles, throws, nokey)
local outpoles = {"A", "B", "C", "D", "E", "F", "G", "H"} //output names
// Clamp
throws = throws > 10 and 10 or throws
poles = poles > #outpoles and #outpoles or poles
local inputs = {} //wont need this outside setup
self.outputs = {} //need to rebuild output names
self.keygroup1 = keygroup1
self.keygroup2 = keygroup2
self.keygroup3 = keygroup3
self.keygroup4 = keygroup4
self.keygroup5 = keygroup5
self.keygroupoff = keygroupoff
self.toggle = toggle
self.normclose = normclose or 0
self.selinput = normclose or 0
self.poles = poles
self.throws = throws
self.nokey = nokey
//build inputs and putputs, init all nil values
for p=1, self.poles do
self.outputs[p] = outpoles[p]
self.Value[p] = self.Value[p] or 0
for t=1, self.throws do
//inputs[ p * self.poles + t ] = t .. outpoles[p]
table.insert(inputs, ( t .. outpoles[p] ))
self.Last[ t .. outpoles[p] ] = self.Last[ t .. outpoles[p] ] or 0
end
end
//add switch input to end of input list
table.insert(inputs, "Switch")
Wire_AdjustInputs(self, inputs)
Wire_AdjustOutputs(self, self.outputs)
//set the switch to its new normal state
self:Switch( normclose )
if not nokey then
local pl = self:GetPlayer()
if (keygroupoff) then
numpad.OnDown( pl, keygroupoff, "WireRelay_On", self, 0 )
numpad.OnUp( pl, keygroupoff, "WireRelay_Off", self, 0 )
end
if (keygroup1) then
numpad.OnDown( pl, keygroup1, "WireRelay_On", self, 1 )
numpad.OnUp( pl, keygroup1, "WireRelay_Off", self, 1 )
end
if (keygroup2) then
numpad.OnDown( pl, keygroup2, "WireRelay_On", self, 2 )
numpad.OnUp( pl, keygroup2, "WireRelay_Off", self, 2 )
end
if (keygroup3) then
numpad.OnDown( pl, keygroup3, "WireRelay_On", self, 3 )
numpad.OnUp( pl, keygroup3, "WireRelay_Off", self, 3 )
end
if (keygroup4) then
numpad.OnDown( pl, keygroup4, "WireRelay_On", self, 4 )
numpad.OnUp( pl, keygroup4, "WireRelay_Off", self, 4 )
end
if (keygroup5) then
numpad.OnDown( pl, keygroup5, "WireRelay_On", self, 5 )
numpad.OnUp( pl, keygroup5, "WireRelay_Off", self, 5 )
end
end
end
function ENT:TriggerInput(iname, value)
if (iname == "Switch") then
if (math.abs(value) >= 0 && math.abs(value) <= self.throws) then
self:Switch(math.abs(value))
end
elseif (iname) then
self.Last[iname] = value or 0
self:Switch(self.selinput)
end
end
function ENT:Switch( mul )
if (!self:IsValid()) then return false end
self.selinput = mul
for p,v in ipairs(self.outputs) do
self.Value[p] = self.Last[ mul .. v ] or 0
Wire_TriggerOutput(self, v, self.Value[p])
end
self:ShowOutput()
return true
end
function ENT:ShowOutput()
local txt = self.poles .. "P" .. self.throws .. "T "
if (self.selinput == 0) then
txt = txt .. "Sel: off"
else
txt = txt .. "Sel: " .. self.selinput
end
for p,v in ipairs(self.outputs) do
txt = txt .. "\n" .. v .. ": " .. self.Value[p]
end
self:SetOverlayText( txt )
end
function ENT:InputActivate( mul )
if ( self.toggle && self.selinput == mul) then //only toggle for the same key
return self:Switch( self.normclose )
else
return self:Switch( mul )
end
end
function ENT:InputDeactivate( mul )
if ( self.toggle ) then return true end
return self:Switch( self.normclose )
end
local function On( pl, ent, mul )
if (!ent:IsValid()) then return false end
return ent:InputActivate( mul )
end
local function Off( pl, ent, mul )
if (!ent:IsValid()) then return false end
return ent:InputDeactivate( mul )
end
numpad.Register( "WireRelay_On", On )
numpad.Register( "WireRelay_Off", Off )
duplicator.RegisterEntityClass("gmod_wire_relay", WireLib.MakeWireEnt, "Data", "keygroup1", "keygroup2", "keygroup3", "keygroup4", "keygroup5", "keygroupoff", "toggle", "normclose", "poles", "throws", "nokey")
| apache-2.0 |
waytim/darkstar | scripts/zones/Windurst_Woods/npcs/Gioh_Ajihri.lua | 28 | 2994 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Gioh Ajihri
-- Starts & Finishes Repeatable Quest: Twinstone Bonding
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
GiohAijhriSpokenTo = player:getVar("GiohAijhriSpokenTo");
NeedToZone = player:needToZone();
if (GiohAijhriSpokenTo == 1 and NeedToZone == false) then
count = trade:getItemCount();
TwinstoneEarring = trade:hasItemQty(13360,1);
if (TwinstoneEarring == true and count == 1) then
player:startEvent(0x01ea);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
Fame = player:getFameLevel(WINDURST);
if (TwinstoneBonding == QUEST_COMPLETED) then
if (player:needToZone()) then
player:startEvent(0x01eb,0,13360);
else
player:startEvent(0x01e8,0,13360);
end
elseif (TwinstoneBonding == QUEST_ACCEPTED) then
player:startEvent(0x01e8,0,13360);
elseif (TwinstoneBonding == QUEST_AVAILABLE and Fame >= 2) then
player:startEvent(0x01e7,0,13360);
else
player:startEvent(0x01a8);
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 == 0x01e7) then
player:addQuest(WINDURST,TWINSTONE_BONDING);
player:setVar("GiohAijhriSpokenTo",1);
elseif (csid == 0x01ea) then
TwinstoneBonding = player:getQuestStatus(WINDURST,TWINSTONE_BONDING);
player:tradeComplete();
player:needToZone(true);
player:setVar("GiohAijhriSpokenTo",0);
if (TwinstoneBonding == QUEST_ACCEPTED) then
player:completeQuest(WINDURST,TWINSTONE_BONDING);
player:addFame(WINDURST,80);
player:addItem(17154);
player:messageSpecial(ITEM_OBTAINED,17154);
player:addTitle(BOND_FIXER);
else
player:addFame(WINDURST,10);
player:addGil(GIL_RATE*900);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*900);
end
elseif (csid == 0x01e8) then
player:setVar("GiohAijhriSpokenTo",1);
end
end;
| gpl-3.0 |
wanmaple/MWFrameworkForCocosLua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ClippingRectangleNode.lua | 10 | 1311 |
--------------------------------
-- @module ClippingRectangleNode
-- @extend Node
-- @parent_module cc
--------------------------------
--
-- @function [parent=#ClippingRectangleNode] isClippingEnabled
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
--
-- @function [parent=#ClippingRectangleNode] setClippingEnabled
-- @param self
-- @param #bool enabled
--------------------------------
--
-- @function [parent=#ClippingRectangleNode] getClippingRegion
-- @param self
-- @return rect_table#rect_table ret (return value: rect_table)
--------------------------------
--
-- @function [parent=#ClippingRectangleNode] setClippingRegion
-- @param self
-- @param #rect_table clippingRegion
--------------------------------
-- @overload self
-- @overload self, rect_table
-- @function [parent=#ClippingRectangleNode] create
-- @param self
-- @param #rect_table clippingRegion
-- @return ClippingRectangleNode#ClippingRectangleNode ret (return value: cc.ClippingRectangleNode)
--------------------------------
--
-- @function [parent=#ClippingRectangleNode] visit
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table parentTransform
-- @param #unsigned int parentFlags
return nil
| apache-2.0 |
amitshaked/resmatch | src/pipeline/refinement.lua | 1 | 1643 | local M = {}
function M.refine(disp, vols, opt, dataset, sm_skip, sm_terminate, disp_max, conf, t1, t2)
local sm_active = true
if dataset.name == 'kitti' or dataset.name == 'kitti2015' then
local outlier = torch.CudaTensor():resizeAs(disp[2]):zero()
curesmatch.outlier_detection(disp[2], disp[1], outlier, disp_max, conf[1], conf[2], t1, t2)
if sm_active and sm_skip ~= 'occlusion' then
disp[2] = adcensus.interpolate_occlusion(disp[2], outlier)
end
sm_active = sm_active and (sm_terminate ~= 'occlusion')
if sm_active and sm_skip ~= 'mismatch' then
disp[2] = adcensus.interpolate_mismatch(disp[2], outlier)
end
sm_active = sm_active and (sm_terminate ~= 'mismatch')
end
if sm_active and sm_skip ~= 'subpixel_enhancement' then
disp[2] = adcensus.subpixel_enchancement(disp[2], vols[{{1}}], disp_max)
end
sm_active = sm_active and (sm_terminate ~= 'subpixel_enchancement')
if sm_active and sm_skip ~= 'median' then
disp[2] = adcensus.median2d(disp[2], 5)
end
sm_active = sm_active and (sm_terminate ~= 'median')
if sm_active and sm_skip ~= 'bilateral' then
disp[2] = adcensus.mean2d(disp[2], gaussian(opt.blur_sigma):cuda(), opt.blur_t)
end
return disp
end
function gaussian(sigma)
local kr = math.ceil(sigma * 3)
local ks = kr * 2 + 1
local k = torch.Tensor(ks, ks)
for i = 1, ks do
for j = 1, ks do
local y = (i - 1) - kr
local x = (j - 1) - kr
k[{i,j}] = math.exp(-(x * x + y * y) / (2 * sigma * sigma))
end
end
return k
end
return M
| bsd-2-clause |
waytim/darkstar | scripts/zones/Arrapago_Reef/mobs/Medusa.lua | 20 | 1467 | -----------------------------------
-- Area: Arrapago Reef
-- MOB: Medusa
-- @pos -458 -20 458
-- TODO: resists, attack/def boosts
-----------------------------------
require("scripts/globals/titles");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("eeshpp", math.random(5,99)); -- Uses EES randomly during the fight
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob, target)
local mobID = mob:getID();
target:showText(mob, MEDUSA_ENGAGE);
SpawnMob(mobID+1, 180):updateEnmity(target);
SpawnMob(mobID+2, 180):updateEnmity(target);
SpawnMob(mobID+3, 180):updateEnmity(target);
SpawnMob(mobID+4, 180):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local HPP = mob:getHPP();
if (mob:getLocalVar("usedees") == 0) then
if (HPP <= mob:getLocalVar("eeshpp")) then
mob:useMobAbility(1931); -- Eagle Eye Shot
mob:setLocalVar("usedees", 1);
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob, MEDUSA_DEATH);
player:addTitle(GORGONSTONE_SUNDERER);
end;
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c512000063.lua | 2 | 1328 | --サモンクローズ
function c512000063.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DRAW)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c512000063.cost)
e1:SetTarget(c512000063.target)
e1:SetOperation(c512000063.activate)
c:RegisterEffect(e1)
end
function c512000063.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c512000063.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c512000063.activate(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,p)
end
| gpl-3.0 |
TheEggi/FTCCustom | sct/Functions.lua | 1 | 6005 |
--[[----------------------------------------------------------
SCROLLING COMBAT TEXT FUNCTIONS
-----------------------------------------------------------
* Relevant functions for the scrolling combat text component
* Runs during FTC:Initialize()
]]--
FTC.SCT = {}
function FTC.SCT:Initialize()
-- Setup tables
FTC.SCT.In = {}
FTC.SCT.Out = {}
FTC.SCT.Status = {}
-- Save tiny AP gains
FTC.SCT.backAP = 0
-- Create controls
FTC.SCT:Controls()
-- Register init status
FTC.init.SCT = true
end
--[[----------------------------------------------------------
EVENT HANDLERS
]]-----------------------------------------------------------
--[[
* Process new combat events passed from the combat event handler
* Called by FTC.Damage:New() if the damage is approved
]]--
function FTC.SCT:NewSCT( newSCT , context )
-- Get the existing entries
local damages = FTC.SCT[context]
if ( #damages == 0 ) then table.insert( FTC.SCT[context] , newSCT) end
-- Loop through each existing combat entry
local oldest = 1
local isNew = true
for i = 1, #damages do
-- If an identical entry already exists, do a multiplier instead of a new entry
if ( ( damages[i].name == newSCT.name ) and ( damages[i].heal == newSCT.heal ) and ( math.abs( damages[i].ms - newSCT.ms ) < 500 ) ) then
-- If the damage is higher, replace it
if ( newSCT.dam > damages[i].dam ) then
FTC.SCT[context][i] = newSCT
end
-- Increment the multiplier, and bail
FTC.SCT[context][i].multi = FTC.SCT[context][i].multi + 1
isNew = false
break
-- Otherwise flag the oldest entry for recycling
else oldest = FTC.SCT[context][i].ms < FTC.SCT[context][oldest].ms and i or oldest end
end
-- Process new damage entries
if ( isNew ) then
-- If there are fewer than the maximum number of events recorded, insert it directly
if ( #damages < FTC.vars.SCTCount ) then table.insert( FTC.SCT[context] , newSCT)
-- Otherwise, recycle the oldest entry
else FTC.SCT[context][oldest] = newSCT end
end
-- Next, allocate combat entries to controls
for i = 1, FTC.vars.SCTCount do
-- Add the damage to controls
local container = _G["FTC_SCT"..context..i]
if ( FTC.SCT[context][i] ~= nil ) then
container.damage = FTC.SCT[context][i]
-- Purge unused controls
else container.damage = {} end
end
end
--[[----------------------------------------------------------
UPDATING FUNCTIONS
]]-----------------------------------------------------------
--[[
* Updates Scrolling Combat Text for both incoming and outgoing damage
* Runs every frame OnUpdate
]]--
function FTC.SCT:Update(context)
-- Get saved variables
local speed = FTC.vars.SCTSpeed
local num = FTC.vars.SCTCount
-- Get the SCT UI element
local parent = _G["FTC_CombatText"..context]
-- Get the damage table based on context
local damages = FTC.SCT[context]
-- Bail if no damage is present
if ( #damages == 0 ) then return end
-- Get the game time
local gameTime = GetGameTimeMilliseconds()
-- Loop through damage controls, modifying the display
for i = 1 , FTC.vars.SCTCount do
-- Get the control and it's damage value
local container = _G["FTC_SCT"..context..i]
local damage = container.damage
-- If there's damage, proceed
if ( damage.name ~= nil ) then
-- Get the animation duration ( speed = 10 -> 0.5 second, speed = 1 -> 5 seconds )
local lifespan = ( gameTime - damage.ms ) / 1000
local duration = ( 11 - speed ) / 2
-- If the animation has finished, hide the container
if ( lifespan > duration ) then
container:SetHidden( true )
-- Otherwise, we're good to go!
else
-- Get some values
local dam = damage.dam
local name = damage.name
-- Set default appearance
local font = FTC.Fonts.meta(16)
local alpha = 0.8
-- Flag critical hits
if ( damage.crit == true ) then
dam = "*" .. dam .. "*"
font = FTC.Fonts.meta(20)
alpha = 1
end
-- Flag blocked damage
if ( damage.result == ACTION_RESULT_BLOCKED_DAMAGE ) then
dam = "|c990000(" .. dam .. ")|"
-- Flag damage immunity
elseif ( damage.result == ACTION_RESULT_IMMUNE ) then
dam = "|c990000(Immune)|"
-- Dodges
elseif ( damage.result == ACTION_RESULT_DODGED ) then
dam = "|c990000(Dodge)|"
-- Misses
elseif ( damage.result == ACTION_RESULT_MISS ) then
dam = "|c990000(Miss)|"
-- Flag heals
elseif( damage.heal == true ) then
dam = "|c99DD93" .. dam .. "|"
if string.match( damage.name , "Potion" ) then damage.name = "Health Potion" end
-- Magic damage
elseif ( damage.type ~= DAMAGE_TYPE_PHYSICAL ) then
dam = ( context == "Out" ) and "|c336699" .. dam .. "|" or "|c990000" .. dam .. "|"
-- Standard hits
else
dam = ( context == "Out" ) and "|cAA9F83" .. dam .. "|" or "|c990000" .. dam .. "|"
end
-- Maybe add the ability name
if ( FTC.vars.SCTNames ) then
dam = dam .. " " .. name
end
-- Add the multiplier
if ( damage.multi and damage.multi > 1 ) then
dam = dam .. " (x" .. damage.multi .. ")"
end
-- Update the damage
container:SetHidden(false)
container:SetFont( font )
container:SetAlpha( alpha )
container:SetText( dam )
-- Get the starting offsets
local offsetX = container.offsetX
local offsetY = container.offsetY
local height = parent:GetHeight()
local width = parent:GetWidth()
-- Scroll the vertical position
offsetY = offsetY - height * ( lifespan / duration )
-- Horizontal arcing
if ( FTC.vars.SCTPath == 'Arc' ) then
local ease = lifespan / duration
offsetX = 100 * ( ( 4 * ease * ease ) - ( 4 * ease ) + 1 )
offsetX = ( context == "Out" ) and offsetX or -1 * offsetX
end
-- Adjust the position
container:SetAnchor(BOTTOM,parent,BOTTOM,offsetX,offsetY)
end
end
end
end | apache-2.0 |
CaptainPRICE/wire | lua/entities/gmod_wire_eyepod.lua | 9 | 8963 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Eye Pod"
ENT.Purpose = "To control the player's view in a pod and output their mouse movements"
ENT.WireDebugName = "Eye Pod"
if CLIENT then
local enabled = false
local rotate90 = false
local freezePitch = true
local freezeYaw = true
local previousEnabled = false
usermessage.Hook("UpdateEyePodState", function(um)
if not um then return end
local eyeAng = um:ReadAngle()
enabled = um:ReadBool()
rotate90 = um:ReadBool()
freezePitch = um:ReadBool() and eyeAng.p
freezeYaw = um:ReadBool() and eyeAng.y
end)
hook.Add("CreateMove", "WireEyePodEyeControl", function(ucmd)
if enabled then
currentAng = ucmd:GetViewAngles()
if freezePitch then
currentAng.p = freezePitch
end
if freezeYaw then
currentAng.y = freezeYaw
end
currentAng.r = 0
ucmd:SetViewAngles(currentAng)
previousEnabled = true
elseif previousEnabled then
if rotate90 then
ucmd:SetViewAngles(Angle(0,90,0))
else
ucmd:SetViewAngles(Angle(0,0,0))
end
previousEnabled = false
end
end)
return -- No more client
end
-- Server
function ENT:Initialize()
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WORLD)
self:DrawShadow(false)
-- Set wire I/O
self.Inputs = WireLib.CreateSpecialInputs(self, { "Enable", "SetPitch", "SetYaw", "SetViewAngle", "UnfreezePitch", "UnfreezeYaw" }, { "NORMAL", "NORMAL", "NORMAL", "ANGLE", "NORMAL", "NORMAL" })
self.Outputs = WireLib.CreateSpecialOutputs(self, { "X", "Y", "XY" }, { "NORMAL", "NORMAL", "VECTOR2" })
-- Initialize values
self.driver = nil
self.X = 0
self.Y = 0
self.enabled = false
self.pod = nil
self.eyeAng = Angle(0, 0, 0)
self.rotate90 = false
self.DefaultToZero = 1
self.ShowRateOfChange = 0
self.LastUpdateTime = CurTime()
-- clamps
self.ClampXMin = 0
self.ClampXMax = 0
self.ClampYMin = 0
self.ClampYMax = 0
self.ClampX = 0
self.ClampY = 0
self.freezePitch = true
self.freezeYaw = true
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:Wake()
end
end
function ENT:UpdateOverlay()
self:SetOverlayText(
string.format( "Default to Zero: %s\nCumulative: %s\nMin: %s,%s\nMax: %s,%s\n%s\n\nActivated: %s%s",
(self.DefaultToZero == 1) and "Yes" or "No",
(self.ShowRateOfChange == 0) and "Yes" or "No",
self.ClampXMin, self.ClampYMin,
self.ClampXMax, self.ClampYMax,
IsValid( self.pod ) and "Linked to: " .. self.pod:GetModel() or "Not linked",
self.enabled and "Yes" or "No",
(self.enabled == true and IsValid( self.driver )) and "\nIn use by: " .. self.driver:Nick() or ""
)
)
end
function ENT:Setup(DefaultToZero, RateOfChange, ClampXMin, ClampXMax, ClampYMin, ClampYMax, ClampX, ClampY)
self.DefaultToZero = DefaultToZero
self.ShowRateOfChange = RateOfChange
self.ClampXMin = ClampXMin
self.ClampXMax = ClampXMax
self.ClampYMin = ClampYMin
self.ClampYMax = ClampYMax
self.ClampX = ClampX
self.ClampY = ClampY
self:UpdateOverlay()
end
local Rotate90ModelList = {
["models/props_c17/furniturechair001a.mdl"] = true,
["models/airboat.mdl"] = true,
["models/props_c17/chair_office01a.mdl"] = true,
["models/nova/chair_office02.mdl"] = true,
["models/nova/chair_office01.mdl"] = true,
["models/props_combine/breenchair.mdl"] = true,
["models/nova/chair_wood01.mdl"] = true,
["models/nova/airboat_seat.mdl"] = true,
["models/nova/chair_plastic01.mdl"] = true,
["models/nova/jeep_seat.mdl"] = true,
["models/props_phx/carseat.mdl"] = true,
["models/props_phx/carseat2.mdl"] = true,
["models/props_phx/carseat3.mdl"] = true,
["models/buggy.mdl"] = true,
["models/vehicle.mdl"] = true
}
function ENT:PodLink(vehicle)
if not IsValid(vehicle) or not vehicle:IsVehicle() then
if IsValid(self.pod) then
self.pod.AttachedWireEyePod = nil
end
self.pod = nil
self:UpdateOverlay()
return false
end
self.pod = vehicle
self.rotate90 = false
self.eyeAng = Angle(0, 0, 0)
if IsValid(vehicle) and vehicle:IsVehicle() then
if Rotate90ModelList[string.lower(vehicle:GetModel())] then
self.rotate90 = true
self.eyeAng = Angle(0, 90, 0)
end
end
vehicle.AttachedWireEyePod = self
self:UpdateOverlay()
return true
end
function ENT:updateEyePodState(enabled)
umsg.Start("UpdateEyePodState", self.driver)
umsg.Angle(self.eyeAng)
umsg.Bool(enabled)
umsg.Bool(self.rotate90)
umsg.Bool(self.freezePitch)
umsg.Bool(self.freezeYaw)
umsg.End()
end
hook.Add("PlayerEnteredVehicle","gmod_wire_eyepod_entervehicle",function(ply,vehicle)
local eyepod = vehicle.AttachedWireEyePod
if eyepod ~= nil then
if IsValid(eyepod) then
eyepod.driver = vehicle:GetDriver()
eyepod:updateEyePodState(eyepod.enabled)
eyepod:UpdateOverlay()
else
vehicle.AttachedWireEyePod = nil
end
end
end)
hook.Add("PlayerLeaveVehicle","gmod_wire_eyepod_leavevehicle",function(ply,vehicle)
local eyepod = vehicle.AttachedWireEyePod
if eyepod ~= nil then
if IsValid(eyepod) then
eyepod:updateEyePodState(false)
eyepod.driver = nil
if (eyepod.X ~= 0 or eyepod.Y ~= 0) and eyepod.DefaultToZero == 1 then
eyepod.X = 0
eyepod.Y = 0
WireLib.TriggerOutput( eyepod, "X", 0 )
WireLib.TriggerOutput( eyepod, "Y", 0 )
WireLib.TriggerOutput( eyepod, "XY", {0,0} )
end
eyepod:UpdateOverlay()
else
vehicle.AttachedWireEyePod = nil
end
end
end)
function ENT:OnRemove()
if IsValid(self.pod) and self.pod:IsVehicle() then
self.pod.AttachedWireEyePod = nil
end
if IsValid(self.driver) then
self:updateEyePodState(false)
self.driver = nil
end
end
local function AngNorm(Ang)
return (Ang + 180) % 360 - 180
end
local function AngNorm90(Ang)
return (Ang + 90) % 180 - 90
end
function ENT:TriggerInput(iname, value)
-- Change variables to reflect input
if iname == "Enable" then
self.enabled = value ~= 0
if self.enabled == false and self.DefaultToZero == 1 and (self.X ~= 0 or self.Y ~= 0) then
self.X = 0
self.Y = 0
WireLib.TriggerOutput( self, "X", 0 )
WireLib.TriggerOutput( self, "Y", 0 )
WireLib.TriggerOutput( self, "XY", {0,0} )
end
self:UpdateOverlay()
elseif iname == "SetPitch" then
self.eyeAng = Angle(AngNorm90(value), self.eyeAng.y, self.eyeAng.r)
elseif iname == "SetYaw" then
if self.rotate90 == true then
self.eyeAng = Angle(AngNorm90(self.eyeAng.p), AngNorm(value+90), self.eyeAng.r)
else
self.eyeAng = Angle(AngNorm90(self.eyeAng.p), AngNorm(value), self.eyeAng.r)
end
elseif iname == "SetViewAngle" then
if self.rotate90 == true then
self.eyeAng = Angle(AngNorm90(value.p), AngNorm(value.y+90), 0)
else
self.eyeAng = Angle(AngNorm90(value.p), AngNorm(value.y), 0)
end
elseif iname == "UnfreezePitch" then
self.freezePitch = value == 0
elseif iname == "UnfreezeYaw" then
self.freezeYaw = value == 0
end
if IsValid(self.pod) and IsValid(self.driver) then
self:updateEyePodState(self.enabled)
end
end
hook.Add("SetupMove", "WireEyePodMouseControl", function(ply, movedata)
--is the player in a vehicle?
if not ply then return end
if not ply:InVehicle() then return end
local vehicle = ply:GetVehicle()
if not IsValid(vehicle) then return end
--get the EyePod
local eyePod = vehicle.AttachedWireEyePod
--is the vehicle linked to an EyePod?
if not IsValid(eyePod) then return end
if eyePod.enabled then
local cmd = ply:GetCurrentCommand()
local oldX = eyePod.X
local oldY = eyePod.Y
--reset the output so it is not cumualative if you want the rate of change
if eyePod.ShowRateOfChange == 1 then
eyePod.X = 0
eyePod.Y = 0
end
--update the cumualative output
eyePod.X = cmd:GetMouseX()/10 + eyePod.X
eyePod.Y = -cmd:GetMouseY()/10 + eyePod.Y
--clamp the output
if eyePod.ClampX == 1 then
eyePod.X = math.Clamp(eyePod.X, eyePod.ClampXMin, eyePod.ClampXMax)
end
if eyePod.ClampY == 1 then
eyePod.Y = math.Clamp(eyePod.Y, eyePod.ClampYMin, eyePod.ClampYMax)
end
if oldX ~= eyePod.X or oldY ~= eyePod.Y then
-- Update outputs
WireLib.TriggerOutput(eyePod, "X", eyePod.X)
WireLib.TriggerOutput(eyePod, "Y", eyePod.Y)
local XY_Vec = {eyePod.X, eyePod.Y}
WireLib.TriggerOutput(eyePod, "XY", XY_Vec)
end
--reset the mouse
cmd:SetMouseX(0)
cmd:SetMouseY(0)
end
end)
-- Advanced Duplicator Support
function ENT:BuildDupeInfo()
local info = self.BaseClass.BuildDupeInfo(self) or {}
if IsValid(self.pod) then
info.pod = self.pod:EntIndex()
end
return info
end
function ENT:ApplyDupeInfo(ply, ent, info, GetEntByID)
self.BaseClass.ApplyDupeInfo(self, ply, ent, info, GetEntByID)
self:PodLink(GetEntByID(info.pod))
end
duplicator.RegisterEntityClass("gmod_wire_eyepod", WireLib.MakeWireEnt, "Data", "DefaultToZero", "ShowRateOfChange" , "ClampXMin" , "ClampXMax" , "ClampYMin" , "ClampYMax" , "ClampX", "ClampY")
| apache-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/glory_slash.lua | 4 | 1279 | -----------------------------------
-- Glory Slash
-- Sword weapon skill
-- Skill Level: NA
-- Only avaliable during Campaign Battle while weilding Lex Talionis.
-- Delivers and area attacj that deals triple damage. Damage varies with TP. Additional effect Stun.
-- Will stack with Sneak Attack.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: Light
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 3.00 3.50 4.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 = 3; params.ftp200 = 3.5; params.ftp300 = 4;
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.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;
local damage, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, damage;
end
| gpl-3.0 |
Contatta/prosody-modules | mod_watchuntrusted/mod_watchuntrusted.lua | 5 | 2563 | local jid_prep = require "util.jid".prep;
local secure_auth = module:get_option_boolean("s2s_secure_auth", false);
local secure_domains, insecure_domains =
module:get_option_set("s2s_secure_domains", {})._items, module:get_option_set("s2s_insecure_domains", {})._items;
local untrusted_fail_watchers = module:get_option_set("untrusted_fail_watchers", module:get_option("admins", {})) / jid_prep;
local untrusted_fail_notification = module:get_option("untrusted_fail_notification", "Establishing a secure connection from $from_host to $to_host failed. Certificate hash: $sha1. $errors");
local st = require "util.stanza";
local notified_about_already = { };
module:hook_global("s2s-check-certificate", function (event)
local session, host = event.session, event.host;
local conn = session.conn:socket();
local local_host = session.direction == "outgoing" and session.from_host or session.to_host;
if not (local_host == module:get_host()) then return end
module:log("debug", "Checking certificate...");
local must_secure = secure_auth;
if not must_secure and secure_domains[host] then
must_secure = true;
elseif must_secure and insecure_domains[host] then
must_secure = false;
end
if must_secure and (session.cert_chain_status ~= "valid" or session.cert_identity_status ~= "valid") and not notified_about_already[host] then
notified_about_already[host] = os.time();
local _, errors = conn:getpeerverification();
local error_message = "";
for depth, t in pairs(errors or {}) do
if #t > 0 then
error_message = error_message .. "Error with certificate " .. (depth - 1) .. ": " .. table.concat(t, ", ") .. ". ";
end
end
if session.cert_identity_status then
error_message = error_message .. "This certificate is " .. session.cert_identity_status .. " for " .. host .. ".";
end
local replacements = { sha1 = event.cert and event.cert:digest("sha1"), errors = error_message };
local message = st.message{ type = "chat", from = local_host }
:tag("body")
:text(untrusted_fail_notification:gsub("%$([%w_]+)", function (v)
return event[v] or session and session[v] or replacements and replacements[v] or nil;
end));
for jid in untrusted_fail_watchers do
module:log("debug", "Notifying %s", jid);
message.attr.to = jid;
module:send(message);
end
end
end, -0.5);
module:add_timer(14400, function (now)
for host, time in pairs(notified_about_already) do
if time + 86400 > now then
notified_about_already[host] = nil;
end
end
end)
| mit |
tomyun/Gearsystem | platforms/ios/dependencies/SDL-2.0.4-9174/premake/premake4.lua | 9 | 19887 | -- Copyright (C) 1997-2014 Sam Lantinga <slouken@libsdl.org>
--
-- This software is provided 'as-is', without any express or implied
-- warranty. In no event will the authors be held liable for any damages
-- arising from the use of this software.
--
-- Permission is granted to anyone to use this software for any purpose,
-- including commercial applications, and to alter it and redistribute it
-- freely.
--
-- Meta-build system using premake created and maintained by
-- Benjamin Henning <b.henning@digipen.edu>
--[[
premake4.lua
This script sets up the entire premake system. It's responsible for executing
all of the definition scripts for the SDL2 library and the entire test suite,
or demos for the iOS platform. It handles each specific platform and uses the
setup state to generate both the configuration header file needed to build
SDL2 and the premake lua script to generate the target project files.
]]
-- string utility functions
dofile "util/sdl_string.lua"
-- utility file wrapper for some useful functions
dofile "util/sdl_file.lua"
-- system for defining SDL projects
dofile "util/sdl_projects.lua"
-- offers a utility function for finding dependencies specifically on windows
dofile "util/sdl_depends.lua"
-- system for generating a *config.h file used to build the SDL2 library
dofile "util/sdl_gen_config.lua"
-- functions to handle complicated dependency checks using CMake-esque functions
dofile "util/sdl_check_compile.lua"
-- a list of dependency functions for the SDL2 project and any other projects
dofile "util/sdl_dependency_checkers.lua"
-- the following are various options for configuring the meta-build system
newoption {
trigger = "to",
value = "path",
description = "Set the base output directory for the generated and executed lua file."
}
newoption {
trigger = "mingw",
description = "Runs the premake generation script targeted to MinGW."
}
newoption {
trigger = "cygwin",
description = "Runs the premake generation script targeted to Cygwin."
}
newoption {
trigger = "ios",
description = "Runs the premake generation script targeted to iOS."
}
-- determine the localized destination path
local baseLoc = "./"
if _OPTIONS["to"] then
baseLoc = _OPTIONS["to"]:gsub("\\", "/")
end
local deps = SDL_getDependencies()
for _,v in ipairs(deps) do
newoption {
trigger = v:lower(),
description = "Force on the dependency: " .. v
}
end
-- clean action
if _ACTION == "clean" then
-- this is kept the way it is because premake's default method of cleaning the
-- build tree is not very good standalone, whereas the following correctly
-- cleans every build option
print("Cleaning the build environment...")
os.rmdir(baseLoc .. "/SDL2")
os.rmdir(baseLoc .. "/SDL2main")
os.rmdir(baseLoc .. "/SDL2test")
os.rmdir(baseLoc .. "/tests")
os.rmdir(baseLoc .. "/Demos")
os.rmdir(baseLoc .. "/ipch") -- sometimes shows up
os.remove(baseLoc .. "/SDL.sln")
os.remove(baseLoc .. "/SDL.suo")
os.remove(baseLoc .. "/SDL.v11.suo")
os.remove(baseLoc .. "/SDL.sdf")
os.remove(baseLoc .. "/SDL.ncb")
os.remove(baseLoc .. "/SDL-gen.lua")
os.remove(baseLoc .. "/SDL_config_premake.h")
os.remove(baseLoc .. "/Makefile")
os.rmdir(baseLoc .. "/SDL.xcworkspace")
os.exit()
end
-- only run through standard execution if not in help mode
if _OPTIONS["help"] == nil then
-- load all of the project definitions
local results = os.matchfiles("projects/**.lua")
for _,dir in ipairs(results) do
dofile(dir)
end
-- figure out which configuration template to use
local premakeConfigHeader = baseLoc .. "/SDL_config_premake.h"
-- minimal configuration is the default
local premakeTemplateHeader = "./config/SDL_config_minimal.template.h"
if SDL_getos() == "windows" or SDL_getos() == "mingw" then
premakeTemplateHeader = "./config/SDL_config_windows.template.h"
elseif SDL_getos() == "macosx" then
premakeTemplateHeader = "./config/SDL_config_macosx.template.h"
elseif SDL_getos() == "ios" then
premakeTemplateHeader = "./config/SDL_config_iphoneos.template.h"
elseif os.get() == "linux" then
premakeTemplateHeader = "./config/SDL_config_linux.template.h"
elseif SDL_getos() == "cygwin" then
premakeTemplateHeader = "./config/SDL_config_cygwin.template.h"
end
local genFile = baseLoc .. "/SDL-gen.lua"
local file = fileopen(genFile, "wt")
print("Generating " .. genFile .. "...")
-- begin generating the config header file
startGeneration(premakeConfigHeader, premakeTemplateHeader)
-- begin generating the actual premake script
file:print(0, "-- Premake script generated by Simple DirectMedia Layer meta-build script")
file:print(1, 'solution "SDL"')
local platforms = { }
local platformsIndexed = { }
for n,p in pairs(projects) do
if p.platforms and #p.platforms ~= 0 then
for k,v in pairs(p.platforms) do
platforms[v] = true
end
end
end
for n,v in pairs(platforms) do
platformsIndexed[#platformsIndexed + 1] = n
end
file:print(2, implode(platformsIndexed, 'platforms {', '"', '"', ', ', '}'))
file:print(2, 'configurations { "Debug", "Release" }')
for n,p in pairs(projects) do
if p.compat then
local proj = {}
if p.projectLocation ~= nil then
proj.location = p.projectLocation .. "/" .. p.name
else
proj.location = p.name .. "/"
end
proj.includedirs = { path.getrelative(baseLoc,
path.getdirectory(premakeConfigHeader)),
path.getrelative(baseLoc, "../include") }
proj.libdirs = { }
proj.files = { }
local links = { }
local dbgCopyTable = { }
local relCopyTable = { }
-- custom links that shouldn't exist...
-- (these should always happen before dependencies)
if p.customLinks ~= nil then
for k,lnk in pairs(p.customLinks) do
table.insert(links, lnk)
end
end
-- setup project dependencies
local dependencyLocs = { }
if p.projectDependencies ~= nil and #p.projectDependencies ~= 0 then
for k,projname in pairs(p.projectDependencies) do
local depproj = projects[projname]
-- validation that it exists and can be linked to
if depproj ~= nil and (depproj.kind == "SharedLib" or depproj.kind == "StaticLib") then
if depproj.kind == "SharedLib" then
local deplocation = nil
if depproj.projectLocation ~= nil then
deplocation = depproj.projectLocation .. "/" .. p.name
else
deplocation = depproj.name .. "/"
end
table.insert(dependencyLocs, { location = deplocation, name = projname })
else -- static lib
-- we are now dependent on everything the static lib is dependent on
if depproj.customLinks ~= nil then
for k,lnk in pairs(depproj.customLinks) do
table.insert(links, lnk)
end
end
-- also include links from dependencies
for i,d in pairs(depproj.dependencyTree) do
if d.links then
for k,v in pairs(d.links) do
local propPath = v:gsub("\\", "/")
table.insert(links, propPath)
end
end
end
end
-- finally, depend on the project itself
table.insert(links, projname)
elseif depproj == nil then
print("Warning: Missing external dependency for project: ".. p.name ..
". Be sure you setup project dependencies in a logical order.")
else
print("Warning: Cannot link " .. p.name .. " to second project " ..
projname .. " because the second project is not a library.")
end
end
end
-- iterate across all root directories, matching source directories
local dirs = createDirTable(p.sourcedir)
-- but first, handle any files specifically set in the project, rather than
-- its dependencies
-- register c and h files in this directory
if (p.files ~= nil and #p.files ~= 0) or (p.paths ~= nil and #p.paths ~= 0) then
-- handle all lists of files
if p.files ~= nil and #p.files ~= 0 then
for k,filepat in pairs(p.files) do
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat)) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
end
end -- end props files if
-- add all .c/.h files from each path
-- handle all related paths
if p.paths ~= nil and #p.paths ~= 0 then
for j,filepat in ipairs(p.paths) do
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.c")) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.h")) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
-- mac osx
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.m")) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
end
end -- end of props paths if
end -- end of check for files/paths in main project
-- if this project has any configuration flags, add them to the current file
if p.config then
addConfig(p.config)
end
-- now, handle files and paths for dependencies
for i,props in ipairs(p.dependencyTree) do
if props.compat then
-- register c and h files in this directory
-- handle all lists of files
if props.files ~= nil and #props.files ~= 0 then
for k,filepat in pairs(props.files) do
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat)) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
end
end -- end props files if
-- add all .c/.h files from each path
-- handle all related paths
if props.paths ~= nil and #props.paths ~= 0 then
for j,filepat in ipairs(props.paths) do
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.c")) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.h")) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
-- mac osx
for k,f in pairs(os.matchfiles(p.sourcedir .. filepat .. "*.m")) do
table.insert(proj.files, path.getrelative(baseLoc, f))
end
end
end -- end of props paths if
-- if this dependency has any special configuration flags, add 'em
if props.config then
addConfig(props.config)
end -- end of props config if check
end -- end check for compatibility
end -- end of props loop
--local debugConfig = configuration("Debug")
local debugConfig = {}
local releaseConfig = {}
debugConfig.defines = { "USING_PREMAKE_CONFIG_H", "_DEBUG" }
releaseConfig.defines = { "USING_PREMAKE_CONFIG_H", "NDEBUG" }
-- setup per-project defines
if p.defines ~= nil then
for k,def in pairs(p.defines) do
table.insert(debugConfig.defines, def)
table.insert(releaseConfig.defines, def)
end
end
debugConfig.buildoptions = { }
if SDL_getos() == "windows" then
table.insert(debugConfig.buildoptions, "/MDd")
end
debugConfig.linkoptions = { }
releaseConfig.buildoptions = {}
releaseConfig.linkoptions = {}
local baseBuildDir = "/Build"
if os.get() == "windows" then
baseBuildDir = "/Win32"
end
debugConfig.flags = { "Symbols" }
debugConfig.targetdir = proj.location .. baseBuildDir .. "/Debug"
releaseConfig.flags = { "OptimizeSpeed" }
releaseConfig.targetdir = proj.location .. baseBuildDir .. "/Release"
-- setup postbuild options
local dbgPostbuildcommands = { }
local relPostbuildcommands = { }
-- handle copying depended shared libraries to correct folders
if os.get() == "windows" then
for k,deploc in pairs(dependencyLocs) do
table.insert(dbgCopyTable, { src = deploc.location .. baseBuildDir .. "/Debug/" .. deploc.name .. ".dll",
dst = debugConfig.targetdir .. "/" .. deploc.name .. ".dll" })
table.insert(relCopyTable, { src = deploc.location .. baseBuildDir .. "/Release/" .. deploc.name .. ".dll",
dst = releaseConfig.targetdir .. "/" .. deploc.name .. ".dll" })
end
end
if p.copy ~= nil then
for k,file in pairs(p.copy) do
-- the following builds relative paths native to the current system for copying, other
-- than the copy command itself, this is essentially cross-platform for paths
-- all custom copies should be relative to the current working directory
table.insert(dbgCopyTable, { src = path.getrelative(baseLoc, p.sourcedir .. "/" .. file), dst = debugConfig.targetdir .. "/" .. file })
table.insert(relCopyTable, { src = path.getrelative(baseLoc, p.sourcedir .. "/" .. file), dst = releaseConfig.targetdir .. "/" .. file })
end
end
for k,file in pairs(dbgCopyTable) do
-- all copies should be relative to project location, based on platform
local relLocation = "./"
--if os.get() == "windows" then
relLocation = proj.location
--end
local fromPath = "./" .. path.getrelative(relLocation, file.src)
local toPath = "./" .. path.getrelative(relLocation, file.dst)
local toPathParent = path.getdirectory(toPath)
local copyCommand = "cp"
local destCheck = "if [ ! -d \\\"" .. toPathParent .. "\\\" ]; then mkdir -p \\\"" .. toPathParent .. "\\\"; fi"
if SDL_getos() ~= "windows" and fromPath:find("*") ~= nil then
-- to path must be a directory for * copies
toPath = path.getdirectory(toPath)
end
if SDL_getos() == "windows" then
fromPath = path.translate(fromPath, "/"):gsub("/", "\\\\")
toPath = path.translate(toPath, "/"):gsub("/", "\\\\")
toPathParent = path.translate(toPathParent, "/"):gsub("/", "\\\\")
copyCommand = "copy"
destCheck = "if not exist \\\"" .. toPathParent .. "\\\" ( mkdir \\\"" .. toPathParent .. "\\\" )"
else
fromPath = path.translate(fromPath, nil):gsub("\\", "/")
toPath = path.translate(toPath, nil):gsub("\\", "/")
end
-- command will check for destination directory to exist and, if it doesn't,
-- it will make the directory and then copy over any assets
local quotedFromPath = fromPath
if SDL_getos() == "windows" or fromPath:find("*") == nil then
quotedFromPath = '\\"' .. quotedFromPath .. '\\"'
end
table.insert(dbgPostbuildcommands, destCheck)
table.insert(dbgPostbuildcommands,
copyCommand .. " " ..
quotedFromPath .. " \\\"" ..
toPath .. "\\\"")
end
for k,file in pairs(relCopyTable) do
-- all copies should be relative to project location, based on platform
local relLocation = "./"
relLocation = proj.location
local fromPath = "./" .. path.getrelative(relLocation, file.src)
local toPath = "./" .. path.getrelative(relLocation, file.dst)
local toPathParent = path.getdirectory(toPath)
local copyCommand = "cp"
local destCheck = "if [ ! -d \\\"" .. toPathParent .. "\\\" ]; then mkdir -p \\\"" .. toPathParent .. "\\\"; fi"
if SDL_getos() ~= "windows" and fromPath:find("*") ~= nil then
-- to path must be a directory for * copies
toPath = path.getdirectory(toPath)
end
if SDL_getos() == "windows" then
fromPath = path.translate(fromPath, "/"):gsub("/", "\\\\")
toPath = path.translate(toPath, "/"):gsub("/", "\\\\")
toPathParent = path.translate(toPathParent, "/"):gsub("/", "\\\\")
copyCommand = "copy"
destCheck = "if not exist \\\"" .. toPathParent .. "\\\" ( mkdir \\\"" .. toPathParent .. "\\\" )"
else
fromPath = path.translate(fromPath, nil):gsub("\\", "/")
toPath = path.translate(toPath, nil):gsub("\\", "/")
end
-- command will check for destination directory to exist and, if it doesn't,
-- it will make the directory and then copy over any assets
local quotedFromPath = fromPath
if SDL_getos() == "windows" or fromPath:find("*") == nil then
quotedFromPath = '\\"' .. quotedFromPath .. '\\"'
end
table.insert(relPostbuildcommands, destCheck)
table.insert(relPostbuildcommands,
copyCommand .. " " ..
quotedFromPath .. " \\\"" ..
toPath .. "\\\"")
end
debugConfig.postbuildcommands = dbgPostbuildcommands
debugConfig.links = links
releaseConfig.postbuildcommands = relPostbuildcommands
releaseConfig.links = links -- release links?
for i,d in pairs(p.dependencyTree) do
if d.includes then
for k,v in pairs(d.includes) do
local propPath = v:gsub("\\", "/")
proj.includedirs[propPath] = propPath
end
end
if d.libs then
for k,v in pairs(d.libs) do
local propPath = v:gsub("\\", "/")
proj.libdirs[propPath] = propPath
end
end
if d.links then
for k,v in pairs(d.links) do
local propPath = v:gsub("\\", "/")
debugConfig.links[#debugConfig.links + 1] = propPath
end
end
end
if #proj.files > 0 then
file:print(1, 'project "' .. p.name .. '"')
file:print(2, 'targetname "' .. p.name .. '"')
-- note: commented out because I think this hack is unnecessary
--if iOSMode and p.kind == "ConsoleApp" then
-- hack for iOS where we cannot build "tools"/ConsoleApps in
-- Xcode for iOS, so we convert them over to WindowedApps
-- p.kind = "WindowedApp"
--end
file:print(2, 'kind "' .. p.kind .. '"')
file:print(2, 'language "' .. p.language .. '"')
file:print(2, 'location "' .. proj.location .. '"')
file:print(2, 'flags { "NoExceptions" }') -- NoRTTI
file:print(2, 'buildoptions { }')--"/GS-" }')
file:print(2, implode(proj.includedirs, 'includedirs {', '"', '"', ', ', '}'))
file:print(2, implode(proj.libdirs, 'libdirs {', '"', '"', ', ', '}'))
file:print(2, implode(proj.files, 'files {', '"', '"', ', ', '}'))
-- debug configuration
file:print(2, 'configuration "Debug"')
file:print(3, 'targetdir "' .. debugConfig.targetdir .. '"')
-- debug dir is relative to the solution's location
file:print(3, 'debugdir "' .. debugConfig.targetdir .. '"')
file:print(3, implode(debugConfig.defines, 'defines {', '"', '"', ', ', '}'))
file:print(3, implode(debugConfig.links, "links {", '"', '"', ', ', "}"))
if SDL_getos() == "mingw" then
-- static runtime
file:print(3, 'linkoptions { "-lmingw32 -static-libgcc" }')
end
if SDL_getos() == "cygwin" then
file:print(3, 'linkoptions { "-static-libgcc" }')
end
file:print(3, implode(debugConfig.flags, "flags {", '"', '"', ', ', "}"))
file:print(3, implode(debugConfig.postbuildcommands, "postbuildcommands {", '"', '"', ', ', "}"))
-- release configuration
file:print(2, 'configuration "Release"')
file:print(3, 'targetdir "' .. releaseConfig.targetdir .. '"')
-- debug dir is relative to the solution's location
file:print(3, 'debugdir "' .. releaseConfig.targetdir .. '"')
file:print(3, implode(releaseConfig.defines, 'defines {', '"', '"', ', ', '}'))
file:print(3, implode(releaseConfig.links, "links {", '"', '"', ', ', "}"))
if SDL_getos() == "mingw" then
-- static runtime
file:print(3, 'linkoptions { "-lmingw32 -static-libgcc" }')
end
file:print(3, implode(releaseConfig.flags, "flags {", '"', '"', ', ', "}"))
file:print(3, implode(releaseConfig.postbuildcommands, "postbuildcommands {", '"', '"', ', ', "}"))
end -- end check for valid project (files to build)
end -- end compatibility check for projects
end -- end for loop for projects
endGeneration() -- finish generating the config header file
file:close()
-- generation is over, now execute the generated file, setup the premake
-- solution, and let premake execute the action and generate the project files
dofile(genFile)
end -- end check for not being in help mode
| gpl-3.0 |
waytim/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/npcs/_iyb.lua | 13 | 1259 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- NPC: Particle Gate
-- @pos 1 0.1 -320 34
-----------------------------------
package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == A_FATE_DECIDED and player:getVar("PromathiaStatus")==0) then
player:startEvent(0x0002);
else
player:startEvent(0x0038);
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 == 0x0002) then
player:setVar("PromathiaStatus",1);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Port_San_dOria/npcs/Ambleon.lua | 13 | 1061 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Ambleon
-- Type: NPC World Pass Dealer
-- @zone: 232
-- @pos 71.622 -17 -137.134
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02c6);
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/Mount_Zhayolm/npcs/Bapokk.lua | 2 | 1504 | -----------------------------------
-- Area: Mount Zhayolm
-- NPC: Bapokk
-- Handles access to Alzadaal Ruins
-- @pos -20 -6 276 61
-----------------------------------
package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mount_Zhayolm/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver
player:tradeComplete();
player:setPos(-20,-6,0.001); -- using the pos method until the problem below is fixed
-- player:startEvent(0x00A3,0,0,0,0,0,0,0,0); -- << this CS goes black at the end, never fades in
return 1;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Ruins -> Zhayolm
if(player:getZPos() >= 280) then
player:startEvent(0x00A4);
-- Zhayolm -> Ruins
else
player:startEvent(0x00A3,2,2,2,2,2,2,2,2);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x00a3)then
player:startEvent(0x00a6);
end
end; | gpl-3.0 |
TienHP/Aquaria | files/scripts/entities/wisker.lua | 6 | 3979 | -- 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
-- WISKER
-- ================================================================================================
-- L O C A L V A R I A B L E S
-- ================================================================================================
v.fireDelay = 2
v.moveTimer = 0
v.charge = 0
local STATE_CHARGE = 1000
local STATE_DELAY = 1001
v.inited = false
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init(me)
setupBasicEntity(
me,
"", -- texture
6, -- 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
1, -- 0/1 hit other entities off/on (uses collideRadius)
3000 -- updateCull -1: disabled, default: 4000
)
entity_scale(me, 0.75, 0.75)
entity_setDropChance(me, 25)
entity_clampToSurface(me)
entity_setDeathParticleEffect(me, "TinyGreenExplode")
entity_initSkeletal(me, "Wisker")
entity_setState(me, STATE_IDLE)
esetv(me, EV_WALLOUT, 10)
entity_setEatType(me, EAT_FILE, "Wisker")
end
function update(me, dt)
if entity_isState(me, STATE_IDLE) then
entity_moveAlongSurface(me, dt, 140, 6, 30)
entity_rotateToSurfaceNormal(me, 0.1)
-- entity_rotateToSurfaceNormal(0.1)
v.moveTimer = v.moveTimer + dt
if v.moveTimer > 4 then
entity_switchSurfaceDirection(me)
v.moveTimer = 0
end
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
v.fireDelay = 3
entity_setState(me, STATE_CHARGE)
end
end
end
end
if entity_isState(me, STATE_DELAY) then
entity_moveAlongSurface(me, dt, 60, 6, 10)
entity_rotateToSurfaceNormal(me, 0.1)
end
entity_handleShotCollisions(me)
if entity_touchAvatarDamage(me, entity_getCollideRadius(me), 1, 500) then
setPoison(1, 12)
end
end
function enterState(me)
if entity_getState(me)==STATE_IDLE then
entity_animate(me, "waddle", -1)
elseif entity_isState(me, STATE_CHARGE) then
entity_setStateTime(me, entity_animate(me, "charge"))
elseif entity_isState(me, STATE_DELAY) then
entity_animate(me, "idle", -1)
entity_setStateTime(me, 1)
end
end
local function fireShot(me, a)
local s = createShot("WiskerShot", me, entity_getTarget(me))
shot_setAimVector(s, entity_getAimVector(me, a, 1))
shot_setOut(s, 32)
end
function exitState(me)
if entity_isState(me, STATE_CHARGE) then
--entity_doGlint(me, "Particles/PurpleFlare")
entity_sound(me, "SpineFire")
fireShot(me, -45)
fireShot(me, 0)
fireShot(me, 45)
entity_setState(me, STATE_DELAY)
elseif entity_isState(me, STATE_DELAY) then
entity_setState(me, STATE_IDLE)
end
end
function damage(me)
return true
end
function hitSurface(me)
end
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/mobskills/Gate_of_Tartarus.lua | 10 | 1071 | ---------------------------------------------
-- Gate of Tartarus
--
-- Description: Lowers target's attack. Additional effect: Refresh
-- Type: Physical
-- Shadow per hit
-- Range: Melee
---------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------
function OnMobSkillCheck(target,mob,skill)
return 0;
end;
function OnMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2.5;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local duration = 20;
if(mob:getTP() == 300) then
duration = 60;
elseif(mob:getTP() >= 200) then
duration = 40;
end
MobBuffMove(mob, EFFECT_REFRESH, 8, 3, duration);
MobStatusEffectMove(mob, target, EFFECT_ATTACK_DOWN, 20, 0, duration);
target:delHP(dmg);
return dmg;
end; | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c77628934.lua | 1 | 4076 | --Paladin of the Black Art
function c77628934.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcFun2(c,aux.FilterBoolFunction(Card.IsSetCard,0xba003),aux.FilterBoolFunction(Card.IsRace,RACE_ZOMBIE),true)
--spsummon condition
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetCode(EFFECT_SPSUMMON_CONDITION)
e2:SetValue(c77628934.splimit)
c:RegisterEffect(e2)
--fusion summon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_FUSION_SUMMON)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,77628934)
e3:SetCondition(c77628934.fscon)
e3:SetCost(c77628934.fscost)
e3:SetTarget(c77628934.fstg)
e3:SetOperation(c77628934.fsop)
c:RegisterEffect(e3)
end
function c77628934.splimit(e,se,sp,st)
return not e:GetHandler():IsLocation(LOCATION_EXTRA) or bit.band(st,SUMMON_TYPE_FUSION)==SUMMON_TYPE_FUSION
end
function c77628934.grafilter(c)
return c:IsSetCard(0xba003) and c:IsType(TYPE_MONSTER)
end
function c77628934.fscon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c77628934.grafilter,tp,LOCATION_GRAVE,0,5,nil)
end
function c77628934.fscost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,1000) end
Duel.PayLPCost(tp,1000)
end
function c77628934.filter1(c,e)
return c:IsType(TYPE_MONSTER) and c:IsCanBeFusionMaterial() and not c:IsImmuneToEffect(e)
end
function c77628934.filter2(c,e,tp,m,f,chkf)
return c:IsType(TYPE_FUSION) and c:IsSetCard(0xba003) and (not f or f(c))
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_FUSION,tp,false,false) and c:CheckFusionMaterial(m,nil,chkf)
end
function c77628934.fstg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local chkf=Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and PLAYER_NONE or tp
local mg1=Duel.GetMatchingGroup(Card.IsCanBeFusionMaterial,tp,LOCATION_MZONE,0,nil)
local res=Duel.IsExistingMatchingCard(c77628934.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg1,nil,chkf)
if not res then
local ce=Duel.GetChainMaterial(tp)
if ce~=nil then
local fgroup=ce:GetTarget()
local mg2=fgroup(ce,e,tp)
local mf=ce:GetValue()
res=Duel.IsExistingMatchingCard(c77628934.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,mg2,mf,chkf)
end
end
return res
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c77628934.fsop(e,tp,eg,ep,ev,re,r,rp)
local chkf=Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and PLAYER_NONE or tp
local mg1=Duel.GetMatchingGroup(c77628934.filter1,tp,LOCATION_MZONE,0,nil,e)
local sg1=Duel.GetMatchingGroup(c77628934.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg1,nil,chkf)
local mg2=nil
local sg2=nil
local ce=Duel.GetChainMaterial(tp)
if ce~=nil then
local fgroup=ce:GetTarget()
mg2=fgroup(ce,e,tp)
local mf=ce:GetValue()
sg2=Duel.GetMatchingGroup(c77628934.filter2,tp,LOCATION_EXTRA,0,nil,e,tp,mg2,mf,chkf)
end
if sg1:GetCount()>0 or (sg2~=nil and sg2:GetCount()>0) then
local sg=sg1:Clone()
if sg2 then sg:Merge(sg2) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local tg=sg:Select(tp,1,1,nil)
local tc=tg:GetFirst()
if sg1:IsContains(tc) and (sg2==nil or not sg2:IsContains(tc) or not Duel.SelectYesNo(tp,ce:GetDescription())) then
local mat1=Duel.SelectFusionMaterial(tp,tc,mg1,nil,chkf)
tc:SetMaterial(mat1)
Duel.SendtoGrave(mat1,REASON_EFFECT+REASON_MATERIAL+REASON_FUSION)
Duel.BreakEffect()
Duel.SpecialSummon(tc,SUMMON_TYPE_FUSION,tp,tp,false,false,POS_FACEUP)
else
local mat2=Duel.SelectFusionMaterial(tp,tc,mg2,nil,chkf)
local fop=ce:GetOperation()
fop(ce,e,tp,tc,mat2)
end
tc:CompleteProcedure()
else
local cg1=Duel.GetFieldGroup(tp,LOCATION_MZONE,0)
local cg2=Duel.GetFieldGroup(tp,LOCATION_EXTRA,0)
if cg1:GetCount()>1 and cg2:IsExists(Card.IsFacedown,1,nil)
and Duel.IsPlayerCanSpecialSummon(tp) and not Duel.IsPlayerAffectedByEffect(tp,27581098) then
Duel.ConfirmCards(1-tp,cg1)
Duel.ConfirmCards(1-tp,cg2)
Duel.ShuffleHand(tp)
end
end
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c58431894.lua | 2 | 3338 | --Vocaloid Hatsune Miku
function c58431894.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x0dac405),aux.NonTuner(Card.IsRace,RACE_MACHINE),1)
c:EnableReviveLimit()
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(58431894,0))
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c58431894.condition)
e1:SetTarget(c58431894.target)
e1:SetOperation(c58431894.operation)
c:RegisterEffect(e1)
--cannot attack
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_ATTACK)
e2:SetCondition(c58431894.limcon)
c:RegisterEffect(e2)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(58431894,1))
e3:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetRange(LOCATION_GRAVE)
e3:SetCondition(c58431894.spcon)
e3:SetCost(c58431894.spcost)
e3:SetTarget(c58431894.sptg)
e3:SetOperation(c58431894.spop)
c:RegisterEffect(e3)
end
function c58431894.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SYNCHRO
end
function c58431894.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,nil,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
local tc=g:GetFirst()
if tc and tc:IsAbleToRemove() then
Duel.SetOperationInfo(0,CATEGORY_REMOVE,tc,1,0,0)
if tc:IsFaceup() and not tc:IsRace(RACE_MACHINE) then
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,1000)
end
end
end
function c58431894.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
if tc:IsLocation(LOCATION_REMOVED) and tc:IsType(TYPE_MONSTER) and not tc:IsRace(RACE_MACHINE) then
Duel.Damage(1-tp,1000,REASON_EFFECT)
end
end
end
function c58431894.limcon(e)
return not Duel.IsExistingMatchingCard(nil,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,e:GetHandler())
end
function c58431894.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c58431894.cfilter(c)
return c:IsFaceup() and c:GetType()==TYPE_SPELL+TYPE_CONTINUOUS or c:GetType()==TYPE_TRAP+TYPE_CONTINUOUS and c:IsAbleToGraveAsCost()
end
function c58431894.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c58431894.cfilter,tp,LOCATION_SZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c58431894.cfilter,tp,LOCATION_SZONE,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c58431894.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 c58431894.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 |
waytim/darkstar | scripts/globals/weaponskills/skewer.lua | 11 | 1366 | -----------------------------------
-- Skewer
-- Polearm weapon skill
-- Skill Level: 200
-- Delivers a three-hit attack. Chance of params.critical hit varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Light Gorget & Thunder Gorget.
-- Aligned with the Light Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 3;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.5;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c77777831.lua | 2 | 6245 | --Legendary Wyrm Aganos
function c77777831.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetDescription(aux.Stringid(77777831,0))
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--Psummon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e2:SetCode(EVENT_ADJUST)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetRange(LOCATION_PZONE)
e2:SetTargetRange(0,LOCATION_PZONE)
e2:SetOperation(c77777831.psactivate)
c:RegisterEffect(e2)
--opponent splimit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_PZONE)
e3:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e3:SetTargetRange(0,1)
e3:SetCondition(c77777831.psopcon)
e3:SetTarget(c77777831.psoplimit)
c:RegisterEffect(e3)
--Self Destroy
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_PZONE)
e4:SetCategory(CATEGORY_DESTROY)
e4:SetDescription(aux.Stringid(77777831,1))
e4:SetOperation(c77777831.selfDes)
c:RegisterEffect(e4)
--special summon
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetCode(EFFECT_SPSUMMON_PROC)
e5:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e5:SetRange(LOCATION_HAND)
e5:SetCondition(c77777831.spcon)
c:RegisterEffect(e5)
local e6=e5:Clone()
e6:SetRange(LOCATION_EXTRA)
e6:SetCondition(c77777831.spcon2)
c:RegisterEffect(e6)
--pendulum set
local e7=Effect.CreateEffect(c)
e7:SetCategory(CATEGORY_DESTROY)
e7:SetType(EFFECT_TYPE_IGNITION)
e7:SetDescription(aux.Stringid(77777831,2))
e7:SetRange(LOCATION_PZONE)
e7:SetCountLimit(1,77777831)
e7:SetTarget(c77777831.placetg)
e7:SetOperation(c77777831.placeop)
c:RegisterEffect(e7)
end
--If both cards in your PZ are Reverse Pendulums, then your opponent's PS is limited.
--0xb00 == reverse pendulum set code
function c77777831.psopcon(e,c)
local tp=e:GetHandler()
return Duel.GetFieldCard(tp,LOCATION_SZONE,6):IsSetCard(0xb00) and Duel.GetFieldCard(tp,LOCATION_SZONE,7):IsSetCard(0xb00)
end
function c77777831.psoplimit(e,c,sump,sumtype,sumpos,targetp)
local lsc=Duel.GetFieldCard(tp,LOCATION_SZONE,6):GetLeftScale()
local rsc=Duel.GetFieldCard(tp,LOCATION_SZONE,7):GetRightScale()
if rsc>lsc then
return (c:GetLevel()>lsc and c:GetLevel()<rsc) and bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
else
return (c:GetLevel()>rsc and c:GetLevel()<lsc) and bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
end
function c77777831.psactivate(e,tp,eg,ep,ev,re,r,rp)
local tc1=Duel.GetFieldCard(1-tp,LOCATION_SZONE,6)
if tc1 and tc1:GetFlagEffect(77777831)<1 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC_G)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_BOTH_SIDE)
e1:SetRange(LOCATION_PZONE)
e1:SetCountLimit(1,10000000)
e1:SetCondition(c77777831.pendcon)
e1:SetOperation(c77777831.pendop)
e1:SetValue(SUMMON_TYPE_PENDULUM)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc1:RegisterEffect(e1)
tc1:RegisterFlagEffect(77777831,RESET_EVENT+0x1fe0000,0,1)
end
end
function c77777831.spfilter(c)
return c:IsFaceup() and c:IsSetCard(0xb00)
end
function c77777831.pendcon(e,c,og)
if c==nil then return true end
local tp=e:GetOwnerPlayer()
local rpz=Duel.GetFieldCard(1-tp,LOCATION_SZONE,7)
if rpz==nil then return false end
if c:IsSetCard(0xb00) or rpz:IsSetCard(0xb00) then return false end
local lscale=c:GetLeftScale()
local rscale=rpz:GetRightScale()
if lscale>rscale then lscale,rscale=rscale,lscale end
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return false end
if og then
return og:IsExists(aux.PConditionFilter,1,nil,e,tp,lscale,rscale)
and Duel.GetFieldCard(tp,LOCATION_SZONE,6):IsSetCard(0xb00) and Duel.GetFieldCard(tp,LOCATION_SZONE,7):IsSetCard(0xb00)
else
return Duel.IsExistingMatchingCard(aux.PConditionFilter,tp,LOCATION_EXTRA+LOCATION_HAND,0,1,nil,e,tp,lscale,rscale)
and Duel.GetFieldCard(tp,LOCATION_SZONE,6):IsSetCard(0xb00) and Duel.GetFieldCard(tp,LOCATION_SZONE,7):IsSetCard(0xb00)
end
end
function c77777831.pendop(e,tp,eg,ep,ev,re,r,rp,c,sg,og)
local rpz=Duel.GetFieldCard(1-tp,LOCATION_SZONE,7)
local lscale=c:GetLeftScale()
local rscale=rpz:GetRightScale()
if lscale>rscale then lscale,rscale=rscale,lscale end
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if og then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=og:FilterSelect(tp,aux.PConditionFilter,1,ft,nil,e,tp,lscale,rscale)
sg:Merge(g)
else
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,aux.PConditionFilter,tp,LOCATION_EXTRA+LOCATION_HAND,0,1,ft,nil,e,tp,lscale,rscale)
sg:Merge(g)
end
end
function c77777831.selfDes(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.Destroy(e:GetHandler(),REASON_RULE)
end
function c77777831.spcon(e,c)
if c==nil then return true end
return Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,0)==0
and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
end
function c77777831.spcon2(e,c)
if c==nil then return true end
return Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,0)==0
and Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0 and e:GetHandler():IsFaceup()
end
function c77777831.placetg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsDestructable()
and Duel.IsExistingMatchingCard(c77777831.penfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c77777831.placeop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.Destroy(e:GetHandler(),REASON_EFFECT)~=0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD)
local g=Duel.SelectMatchingCard(tp,c77777831.penfilter,tp,LOCATION_DECK,0,1,1,nil)
local tc=g:GetFirst()
if tc then
Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
end
--0x409==Legendary Wyrm setcode
function c77777831.penfilter(c)
return c:IsSetCard(0x409) and c:IsType(TYPE_PENDULUM) and not c:IsCode(77777831) and not c:IsForbidden()
end | gpl-3.0 |
db260179/openwrt-bpi-r1-luci | applications/luci-app-p2pblock/luasrc/model/cbi/luci_fw/p2pblock.lua | 1 | 1515 | -- Copyright 2009 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sys = require "luci.sys"
m = Map("freifunk_p2pblock", translate("P2P-Block"),
translate("P2P-Block is a greylisting mechanism to block various peer-to-peer protocols for non-whitelisted clients."))
s = m:section(NamedSection, "p2pblock", "settings", "Settings")
s.anonymous = true
s.addremove = false
en = s:option(Flag, "_enabled", translate("Enable P2P-Block"))
en.rmempty = false
function en.cfgvalue()
return ( sys.init.enabled("freifunk-p2pblock") and "1" or "0" )
end
function en.write(self, section, val)
if val == "1" then
sys.init.enable("freifunk-p2pblock")
else
sys.init.disable("freifunk-p2pblock")
end
end
s:option(Value, "portrange", translate("Portrange"))
s:option(Value, "blocktime", translate("Block Time"),
translate("seconds"))
s:option(DynamicList, "whitelist", translate("Whitelisted IPs"))
log=s:option(Flag, "logging", translate("Enable/Disable P2P Logging"))
log.enabled="-j LOG --log-prefix"
log.disabled="#"
log.rmempty = false
ipp2p = s:option(MultiValue, "ipp2p", translate("IP-P2P"))
ipp2p.widget = "checkbox"
ipp2p:value("edk", "eDonkey, eMule, Kademlia")
ipp2p:value("kazaa", "KaZaA, FastTrack")
ipp2p:value("gnu", "Gnutella")
ipp2p:value("dc", "Direct Connect")
ipp2p:value("bit", "BitTorrent, extended BT")
ipp2p:value("apple", "AppleJuice")
ipp2p:value("winmx", "WinMX")
ipp2p:value("soul", "SoulSeek")
ipp2p:value("ares", "AresLite")
return m
| apache-2.0 |
onlinetservers/sudo_bots | plugins/plugins.lua | 5 | 6499 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local tmp = '\n\n@BeyondTeam'
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '*|✖️|*>*'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '*|✔|>*'
end
nact = nact+1
end
if not only_enabled or status == '*|✔|>*'then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'.'..status..' '..v..' \n'
end
end
local text = text..'\n\n'..nsum..' *📂plugins installed*\n\n'..nact..' _✔️plugins enabled_\n\n'..nsum-nact..' _❌plugins disabled_'..tmp
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '*|✖️|>*'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '*|✔|>*'
end
nact = nact+1
end
if not only_enabled or status == '*|✔|>*'then
-- get the name
v = string.match (v, "(.*)%.lua")
-- text = text..v..' '..status..'\n'
end
end
local text = text.."\n_🔃All Plugins Reloaded_\n\n"..nact.." *✔️Plugins Enabled*\n"..nsum.." *📂Plugins Installed*\n\n@BeyondTeam"
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return ''..plugin_name..' _is enabled_'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return ''..plugin_name..' _does not exists_'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return ' '..name..' _does not exists_'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return ' '..name..' _not enabled_'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "_Plugin doesn't exists_"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return ' '..plugin..' _disabled on this chat_'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return '_This plugin is not disabled_'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return ' '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if is_sudo(msg) then
if matches[1]:lower() == '!plist' or matches[1]:lower() == '/plist' or matches[1]:lower() == '#plist' then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
end
-- Re-enable a plugin for this chat
if matches[1] == 'pl' then
if matches[2] == '+' and matches[4] == 'chat' then
if is_momod(msg) then
local receiver = msg.chat_id_
local plugin = matches[3]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
end
-- Enable a plugin
if matches[2] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if is_mod(msg) then
local plugin_name = matches[3]
print("enable: "..matches[3])
return enable_plugin(plugin_name)
end
end
-- Disable a plugin on a chat
if matches[2] == '-' and matches[4] == 'chat' then
if is_mod(msg) then
local plugin = matches[3]
local receiver = msg.chat_id_
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
end
-- Disable a plugin
if matches[2] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[3] == 'plugins' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[3])
return disable_plugin(matches[3])
end
end
-- Reload all the plugins!
if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
if matches[1]:lower() == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plug disable [plugin] chat : disable plugin only this chat.",
"!plug enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plist : list all plugins.",
"!pl + [plugin] : enable plugin.",
"!pl - [plugin] : disable plugin.",
"!pl * : reloads all plugins." },
},
patterns = {
"^[!/#]plist$",
"^[!/#](pl) (+) ([%w_%.%-]+)$",
"^[!/#](pl) (-) ([%w_%.%-]+)$",
"^[!/#](pl) (+) ([%w_%.%-]+) (chat)",
"^[!/#](pl) (-) ([%w_%.%-]+) (chat)",
"^!pl? (*)$",
"^[!/](reload)$"
},
run = run
}
end
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Bearclaw_Pinnacle/bcnms/flames_for_the_dead.lua | 2 | 1743 | -----------------------------------
-- Area: Bearclaw_Pinnacle
-- Name: flames_for_the_dead
-- bcnmID : 640
--ennemy: Snoll_Tzar 16801793 16801794 16801795 group 176
-----------------------------------
package.loaded["scripts/zones/Bearclaw_Pinnacle/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Bearclaw_Pinnacle/TextIDs");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function OnBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function OnBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function OnBcnmLeave(player,instance,leavecode)
if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 6) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
player:setVar("COP_Ulmia_s_Path",7);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
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:addExp(1000);
end
end; | gpl-3.0 |
steven-jackson/PersonalLoot | libs/AceGUI-3.0/widgets/AceGUIWidget-Icon.lua | 5 | 3939 | --[[-----------------------------------------------------------------------------
Icon Widget
-------------------------------------------------------------------------------]]
local Type, Version = "Icon", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local select, pairs, print = select, pairs, print
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Button_OnClick(frame, button)
frame.obj:Fire("OnClick", button)
AceGUI:ClearFocus()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetHeight(110)
self:SetWidth(110)
self:SetLabel()
self:SetImage(nil)
self:SetImageSize(64, 64)
self:SetDisabled(false)
end,
-- ["OnRelease"] = nil,
["SetLabel"] = function(self, text)
if text and text ~= "" then
self.label:Show()
self.label:SetText(text)
self:SetHeight(self.image:GetHeight() + 25)
else
self.label:Hide()
self:SetHeight(self.image:GetHeight() + 10)
end
end,
["SetImage"] = function(self, path, ...)
local image = self.image
image:SetTexture(path)
if image:GetTexture() then
local n = select("#", ...)
if n == 4 or n == 8 then
image:SetTexCoord(...)
else
image:SetTexCoord(0, 1, 0, 1)
end
end
end,
["SetImageSize"] = function(self, width, height)
self.image:SetWidth(width)
self.image:SetHeight(height)
--self.frame:SetWidth(width + 30)
if self.label:IsShown() then
self:SetHeight(height + 25)
else
self:SetHeight(height + 10)
end
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.frame:Disable()
self.label:SetTextColor(0.5, 0.5, 0.5)
self.image:SetVertexColor(0.5, 0.5, 0.5, 0.5)
else
self.frame:Enable()
self.label:SetTextColor(1, 1, 1)
self.image:SetVertexColor(1, 1, 1, 1)
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Button", nil, UIParent)
frame:Hide()
frame:EnableMouse(true)
frame:SetScript("OnEnter", Control_OnEnter)
frame:SetScript("OnLeave", Control_OnLeave)
frame:SetScript("OnClick", Button_OnClick)
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontHighlight")
label:SetPoint("BOTTOMLEFT")
label:SetPoint("BOTTOMRIGHT")
label:SetJustifyH("CENTER")
label:SetJustifyV("TOP")
label:SetHeight(18)
local image = frame:CreateTexture(nil, "BACKGROUND")
image:SetWidth(64)
image:SetHeight(64)
image:SetPoint("TOP", 0, -5)
local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
highlight:SetAllPoints(image)
highlight:SetTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight")
highlight:SetTexCoord(0, 1, 0.23, 0.77)
highlight:SetBlendMode("ADD")
local widget = {
label = label,
image = image,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
widget.SetText = function(self, ...) print("AceGUI-3.0-Icon: SetText is deprecated! Use SetLabel instead!"); self:SetLabel(...) end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-3.0 |
waytim/darkstar | scripts/zones/Abyssea-Uleguerand/Zone.lua | 33 | 1487 | -----------------------------------
--
-- Zone: Abyssea - Uleguerand
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-Uleguerand/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Abyssea-Uleguerand/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-238, -40, -520.5, 0);
end
if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED
and player:getVar("1stTimeAyssea") == 0) then
player:setVar("1stTimeAyssea",1);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99990003.lua | 2 | 2753 | --SAO - Kirito SAO
function c99990003.initial_effect(c)
--Special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(99990003,0))
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c99990003.spcon)
c:RegisterEffect(e1)
--Extra attack
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_EXTRA_ATTACK)
e2:SetValue(1)
c:RegisterEffect(e2)
--ATK/DEF
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_ATKCHANGE)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_BATTLE_DESTROYED)
e3:SetRange(LOCATION_MZONE)
e3:SetCondition(c99990003.atkcon)
e3:SetOperation(c99990003.atkop)
c:RegisterEffect(e3)
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_ATKCHANGE)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_BATTLE_DESTROYED)
e4:SetRange(LOCATION_MZONE)
e4:SetCondition(c99990003.atkcon2)
e4:SetOperation(c99990003.atkop)
c:RegisterEffect(e4)
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_ATKCHANGE)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_BATTLE_DESTROYED)
e5:SetRange(LOCATION_MZONE)
e5:SetCondition(c99990003.atkcon3)
e5:SetOperation(c99990003.atkop)
c:RegisterEffect(e5)
end
function c99990003.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.GetFieldGroupCount(c:GetControler(),LOCATION_MZONE,0,nil)==0
end
function c99990003.atkcon(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
return tc:IsReason(REASON_BATTLE) and bc:IsRelateToBattle() and bc:IsControler(tp) and bc:IsSetCard(9999)
end
function c99990003.atkcon2(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
if tc==nil then return false
elseif tc:IsType(TYPE_MONSTER) and bc:IsControler(tp) and bc:IsSetCard(9999) and tc:IsReason(REASON_BATTLE) and bc:IsReason(REASON_BATTLE) then return true end
end
function c99990003.atkcon3(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local bc=tc:GetBattleTarget()
if tc==nil then return false
elseif bc:IsType(TYPE_MONSTER) and tc:IsControler(tp) and tc:IsSetCard(9999) and bc:IsReason(REASON_BATTLE) and tc:IsReason(REASON_BATTLE) then return true end
end
function c99990003.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(100)
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
c:RegisterEffect(e2)
end | gpl-3.0 |
MinFu/luci | applications/luci-app-coovachilli/luasrc/model/cbi/coovachilli_network.lua | 79 | 1459 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local sys = require"luci.sys"
local ip = require "luci.ip"
m = Map("coovachilli")
-- tun
s1 = m:section(TypedSection, "tun")
s1.anonymous = true
s1:option( Flag, "usetap" )
s1:option( Value, "tundev" ).optional = true
s1:option( Value, "txqlen" ).optional = true
net = s1:option( Value, "net" )
for _, route in ipairs(ip.routes({ family = 4, type = 1 })) do
if route.dest:prefix() > 0 and route.dest:prefix() < 32 then
net:value( route.dest:string() )
end
end
s1:option( Value, "dynip" ).optional = true
s1:option( Value, "statip" ).optional = true
s1:option( Value, "dns1" ).optional = true
s1:option( Value, "dns2" ).optional = true
s1:option( Value, "domain" ).optional = true
s1:option( Value, "ipup" ).optional = true
s1:option( Value, "ipdown" ).optional = true
s1:option( Value, "conup" ).optional = true
s1:option( Value, "condown" ).optional = true
-- dhcp config
s2 = m:section(TypedSection, "dhcp")
s2.anonymous = true
dif = s2:option( Value, "dhcpif" )
for _, nif in ipairs(sys.net.devices()) do
if nif ~= "lo" then dif:value(nif) end
end
s2:option( Value, "dhcpmac" ).optional = true
s2:option( Value, "lease" ).optional = true
s2:option( Value, "dhcpstart" ).optional = true
s2:option( Value, "dhcpend" ).optional = true
s2:option( Flag, "eapolenable" )
return m
| apache-2.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c90000079.lua | 2 | 5952 | --Black Flag Gunner
function c90000079.initial_effect(c)
--Pendulum Summon
aux.EnablePendulumAttribute(c)
--Pendulum Limit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_CANNOT_NEGATE)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetRange(LOCATION_PZONE)
e1:SetTargetRange(1,0)
e1:SetTarget(c90000079.tg)
c:RegisterEffect(e1)
--Scale Change
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_PZONE)
e2:SetCountLimit(1)
e2:SetCost(c90000079.cost)
e2:SetOperation(c90000079.operation)
c:RegisterEffect(e2)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetRange(LOCATION_PZONE)
e3:SetCondition(c90000079.condition)
e3:SetTarget(c90000079.target)
e3:SetOperation(c90000079.operation2)
c:RegisterEffect(e3)
--Draw
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(90000079,0))
e4:SetCategory(CATEGORY_DRAW)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e4:SetRange(LOCATION_HAND)
e4:SetCost(c90000079.cost)
e4:SetTarget(c90000079.target2)
e4:SetOperation(c90000079.operation3)
c:RegisterEffect(e4)
--To Hand
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_TOHAND)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e5:SetCode(EVENT_SPSUMMON_SUCCESS)
e5:SetCondition(c90000079.condition2)
e5:SetTarget(c90000079.target3)
e5:SetOperation(c90000079.operation4)
c:RegisterEffect(e5)
--ATK Down
local e6=Effect.CreateEffect(c)
e6:SetCategory(CATEGORY_ATKCHANGE)
e6:SetType(EFFECT_TYPE_QUICK_O)
e6:SetCode(EVENT_FREE_CHAIN)
e6:SetRange(LOCATION_MZONE)
e6:SetCountLimit(1)
e6:SetCondition(c90000079.condition3)
e6:SetTarget(c90000079.target4)
e6:SetOperation(c90000079.operation5)
c:RegisterEffect(e6)
end
function c90000079.tg(e,c,sump,sumtype,sumpos,targetp)
return not c:IsRace(RACE_ZOMBIE) and bit.band(sumtype,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
function c90000079.filter(c)
return c:IsRace(RACE_ZOMBIE) and not c:IsPublic()
end
function c90000079.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c90000079.filter,tp,LOCATION_HAND,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_CONFIRM)
local g=Duel.SelectMatchingCard(tp,c90000079.filter,tp,LOCATION_HAND,0,1,1,nil)
Duel.ConfirmCards(1-tp,g)
Duel.ShuffleHand(tp)
e:SetLabel(g:GetFirst():GetLevel())
end
function c90000079.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LSCALE)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+0x1ff0000)
e:GetHandler():RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_CHANGE_RSCALE)
e:GetHandler():RegisterEffect(e2)
end
function c90000079.filter2(c,tp)
return c:IsControler(tp) and c:GetSummonLocation()==LOCATION_GRAVE
end
function c90000079.condition(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c90000079.filter2,1,nil,1-tp)
end
function c90000079.target(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 c90000079.operation2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
if Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)<=0
and c:IsCanBeSpecialSummoned(e,0,tp,false,false) then
Duel.SendtoGrave(c,REASON_RULE)
end
end
function c90000079.cost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsDiscardable() end
Duel.SendtoGrave(c,REASON_COST+REASON_DISCARD)
end
function c90000079.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,2) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(2)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,2)
end
function c90000079.operation3(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
Duel.BreakEffect()
if Duel.DiscardHand(tp,Card.IsRace,1,1,REASON_EFFECT+REASON_DISCARD,nil,RACE_ZOMBIE)~=0 then
Duel.ConfirmCards(1-p,tg)
Duel.ShuffleHand(p)
else
Duel.SetLP(tp,math.ceil(Duel.GetLP(tp)/2))
end
end
function c90000079.condition2(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_PENDULUM
end
function c90000079.filter3(c)
return c:IsType(TYPE_EQUIP) and c:IsAbleToHand()
end
function c90000079.target3(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c90000079.filter3,tp,LOCATION_GRAVE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_GRAVE)
end
function c90000079.operation4(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c90000079.filter3,tp,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 c90000079.condition3(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer() and (Duel.GetCurrentPhase()>=PHASE_BATTLE_START and Duel.GetCurrentPhase()<=PHASE_BATTLE)
end
function c90000079.target4(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end
end
function c90000079.operation5(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-1000)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
end | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/bowl_of_delicious_puls.lua | 3 | 1208 | -----------------------------------------
-- ID: 4533
-- Item: Bowl of Delicious Puls
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity -1
-- Vitality 3
-- Health Regen While Healing 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,14400,4533);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -1);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_HPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -1);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_HPHEAL, 5);
end;
| gpl-3.0 |
hacker44-h44/spammer | plugins/stats.lua | 458 | 4098 | -- Saves the number of messages from a user
-- Can check the number of messages with !stats
do
local NUM_MSG_MAX = 5
local TIME_CHECK = 4 -- seconds
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
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ('..user_id..')'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end | gpl-2.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c344000038.lua | 2 | 1375 | function c344000038.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCodeFun(c,344000023,aux.FilterBoolFunction(Card.IsRace,RACE_MACHINE),2,false,false)
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(344000038,0))
e3:SetCategory(CATEGORY_DESTROY)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetCost(c344000038.descost)
e3:SetTarget(c344000038.destg)
e3:SetOperation(c344000038.desop)
c:RegisterEffect(e3)
end
function c344000038.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,Card.IsDiscardable,1,1,REASON_COST+REASON_DISCARD)
end
function c344000038.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsDestructable() end
if chk==0 then return Duel.IsExistingTarget(Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,nil) end
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,g:GetCount(),0,0)
end
function c344000038.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-3.0 |
TienHP/Aquaria | files/scripts/entities/_unused/lumitebreeder.lua | 6 | 3488 | -- 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
-- L U M I T E
-- ================================================================================================
-- entity specific
local STATE_STUNNED = 1000
local STATE_GRABBED = 1001
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init()
setupBasicEntity(
"Lumite", -- texture
3, -- health
0, -- manaballamount
1, -- exp
0, -- money
16, -- collideRadius (only used if hit entities is on)
STATE_IDLE, -- initState
32, -- sprite width
32, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
5000, -- updateCull -1: disabled, default: 4000
2 -- layer 0: below avatar, 1: above avatar, 2: dark layer
)
entity_initPart("Glow", "lumite-glow", 0, 0, 1)
entity_partWidthHeight("Glow", 900, 900)
entity_partBlendType("Glow", 1)
end
function update(dt)
if entity_getState()==STATE_IDLE then
if not entity_hasTarget() then
entity_findTarget(800)
--entity_partAlpha("Glow", -1, 0, 0.1)
else
if not entity_isTargetInRange(300) then
entity_moveTowardsTarget(dt, 1000)
else
entity_moveTowardsTarget(dt, -1500)
end
--[[
dist = entity_getDistanceToTarget()
totalDist = 600
if dist > totalDist then
entity_partAlpha("Glow", -1, 0.1)
else
entity_partAlpha("Glow", -1, ((totalDist-dist)/totalDist)*0.5+0.1)
end
]]--
end
entity_doSpellAvoidance(dt, 200, 0.5)
entity_doCollisionAvoidance(dt, 5, 1)
entity_doEntityAvoidance(dt, 64, 0.5)
entity_updateMovement(dt)
if entity_getHealth() == 1 then
entity_setState(STATE_STUNNED)
end
entity_rotateToVel(0.1)
elseif entity_getState()==STATE_STUNNED then
entity_doFriction(dt, 400)
if entity_isTargetInRange(64) then
entity_setState(STATE_GRABBED)
end
end
end
function enterState()
if entity_getState()==STATE_IDLE then
entity_setMaxSpeed(500)
elseif entity_getState()==STATE_DEAD then
entity_partAlpha("Glow", -1, 0, 0.1)
elseif entity_getState()==STATE_GRABBED then
pickupItem("Lumite", 1)
--msg1("Naija: Got one!")
entity_partAlpha("Glow", -1, 0, 0.1)
entity_delete()
if getItem("Lumite")>=2 and getFlag("Q2")==0 and getFlag("Q2-intro")>0 then
setFlag("Q2", 1)
conversation("Q2-collectedLumites")
end
end
end
function exitState()
end
function hitSurface()
end | gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Port_San_dOria/Zone.lua | 2 | 2194 | -----------------------------------
--
-- Zone: Port_San_dOria (232)
--
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
require("scripts/globals/server");
require("scripts/globals/settings");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
-- FIRST LOGIN (START CS)
if (prevZone == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x01F4;
end
player:setPos(-104, -8, -128, 227);
player:setHomePoint();
end
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
if (prevZone == 223) then
cs = 0x02BE;
player:setPos(-1.000, 0.000, 44.000, 0);
else
player:setPos(80,-16,-135,165);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
end
if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 1)then
cs =0x0004;
end
return cs;
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x02BC);
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 == 0x01F4) then
player:messageSpecial(ITEM_OBTAINED,536);
elseif (csid == 0x02BC) then
player:setPos(0,0,0,0,223);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
elseif (csid == 0x0004) then
player:setVar("COP_Ulmia_s_Path",2);
end
end;
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c77777708.lua | 2 | 3373 | --Witchcrafter Kimmy
function c77777708.initial_effect(c)
--pendulum summon
aux.EnablePendulumAttribute(c)
--splimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_PZONE)
e2:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE)
e2:SetTargetRange(1,0)
e2:SetCondition(aux.nfbdncon)
e2:SetTarget(c77777708.splimit)
c:RegisterEffect(e2)
--scale swap
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_PZONE)
e3:SetDescription(aux.Stringid(77777708,0))
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetCountLimit(1)
e3:SetCondition(c77777708.sccon)
-- e3:SetTarget(c77777708.sctg)
e3:SetOperation(c77777708.scop)
c:RegisterEffect(e3)
--atk down
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_PZONE)
e4:SetCode(EFFECT_UPDATE_ATTACK)
e4:SetTargetRange(0,LOCATION_MZONE)
e4:SetValue(-200)
c:RegisterEffect(e4)
--atk up
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetRange(LOCATION_PZONE)
e5:SetCode(EFFECT_UPDATE_ATTACK)
e5:SetTargetRange(LOCATION_MZONE,0)
e5:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x407))
e5:SetValue(200)
c:RegisterEffect(e5)
--Search for S/T
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(77777708,1))
e6:SetType(EFFECT_TYPE_IGNITION)
e6:SetRange(LOCATION_MZONE)
e6:SetProperty(EFFECT_FLAG_CARD_TARGET)
e6:SetCountLimit(1)
e6:SetCost(c77777708.cost)
e6:SetTarget(c77777708.target)
e6:SetOperation(c77777708.operation)
c:RegisterEffect(e6)
end
function c77777708.splimit(e,c,tp,sumtp,sumpos)
return not c:IsSetCard(0x407) and bit.band(sumtp,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM
end
function c77777708.sccon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c77777708.scop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local scl=c:GetLeftScale()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LSCALE)
e1:SetValue(c:GetRightScale())
e1:SetReset(RESET_EVENT+0x1ff0000)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_CHANGE_RSCALE)
e2:SetValue(scl)
c:RegisterEffect(e2)
end
function c77777708.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x407) and c:IsDestructable()
and (c:GetSequence()==6 or c:GetSequence()==7)
end
function c77777708.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c77777708.cfilter,tp,LOCATION_SZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectMatchingCard(tp,c77777708.cfilter,tp,LOCATION_SZONE,0,1,1,nil)
Duel.Destroy(g,REASON_COST)
end
function c77777708.filter(c)
return c:IsSetCard(0x407) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand()
end
function c77777708.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c77777708.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c77777708.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c77777708.filter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-3.0 |
waytim/darkstar | scripts/globals/abilities/drain_samba_ii.lua | 25 | 1434 | -----------------------------------
-- Ability: Drain Samba II
-- Inflicts the next target you strike with Drain Daze, allowing all those engaged in battle with it to drain its HP.
-- Obtained: Dancer Level 35
-- TP Required: 25%
-- Recast Time: 1:00
-- Duration: 1:30
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then
return MSGBASIC_UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 250) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
return 0,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(250);
end;
local duration = 120 + player:getMod(MOD_SAMBA_DURATION);
duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100;
player:delStatusEffect(EFFECT_HASTE_SAMBA);
player:delStatusEffect(EFFECT_ASPIR_SAMBA);
player:addStatusEffect(EFFECT_DRAIN_SAMBA,2,0,duration);
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/items/goblin_pie.lua | 18 | 1573 | -----------------------------------------
-- ID: 4539
-- Item: goblin_pie
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 12
-- Magic 12
-- Dexterity -1
-- Agility 3
-- Vitality -1
-- Charisma -5
-- Defense % 9
-----------------------------------------
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,4539);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 12);
target:addMod(MOD_MP, 12);
target:addMod(MOD_DEX, -1);
target:addMod(MOD_AGI, 3);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_CHR, -5);
target:addMod(MOD_DEFP, 9);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 12);
target:delMod(MOD_MP, 12);
target:delMod(MOD_DEX, -1);
target:delMod(MOD_AGI, 3);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_CHR, -5);
target:delMod(MOD_DEFP, 9);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/crescent_fish.lua | 2 | 1150 | -----------------------------------------
-- ID: 4473
-- Item: crescent_fish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
elseif (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4473);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND,-5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND,-5);
end;
| gpl-3.0 |
internetisalie/lua-for-idea | testdata/non-test-system-files/lua5.1-tests/db.lua | 18 | 12088 | -- testing debug library
local function dostring(s) return assert(loadstring(s))() end
print"testing debug library and debug information"
do
local a=1
end
function test (s, l, p)
collectgarbage() -- avoid gc during trace
local function f (event, line)
assert(event == 'line')
local l = table.remove(l, 1)
if p then print(l, line) end
assert(l == line, "wrong trace!!")
end
debug.sethook(f,"l"); loadstring(s)(); debug.sethook()
assert(table.getn(l) == 0)
end
do
local a = debug.getinfo(print)
assert(a.what == "C" and a.short_src == "[C]")
local b = debug.getinfo(test, "SfL")
assert(b.name == nil and b.what == "Lua" and b.linedefined == 11 and
b.lastlinedefined == b.linedefined + 10 and
b.func == test and not string.find(b.short_src, "%["))
assert(b.activelines[b.linedefined + 1] and
b.activelines[b.lastlinedefined])
assert(not b.activelines[b.linedefined] and
not b.activelines[b.lastlinedefined + 1])
end
-- test file and string names truncation
a = "function f () end"
local function dostring (s, x) return loadstring(s, x)() end
dostring(a)
assert(debug.getinfo(f).short_src == string.format('[string "%s"]', a))
dostring(a..string.format("; %s\n=1", string.rep('p', 400)))
assert(string.find(debug.getinfo(f).short_src, '^%[string [^\n]*%.%.%."%]$'))
dostring("\n"..a)
assert(debug.getinfo(f).short_src == '[string "..."]')
dostring(a, "")
assert(debug.getinfo(f).short_src == '[string ""]')
dostring(a, "@xuxu")
assert(debug.getinfo(f).short_src == "xuxu")
dostring(a, "@"..string.rep('p', 1000)..'t')
assert(string.find(debug.getinfo(f).short_src, "^%.%.%.p*t$"))
dostring(a, "=xuxu")
assert(debug.getinfo(f).short_src == "xuxu")
dostring(a, string.format("=%s", string.rep('x', 500)))
assert(string.find(debug.getinfo(f).short_src, "^x*"))
dostring(a, "=")
assert(debug.getinfo(f).short_src == "")
a = nil; f = nil;
repeat
local g = {x = function ()
local a = debug.getinfo(2)
assert(a.name == 'f' and a.namewhat == 'local')
a = debug.getinfo(1)
assert(a.name == 'x' and a.namewhat == 'field')
return 'xixi'
end}
local f = function () return 1+1 and (not 1 or g.x()) end
assert(f() == 'xixi')
g = debug.getinfo(f)
assert(g.what == "Lua" and g.func == f and g.namewhat == "" and not g.name)
function f (x, name) -- local!
name = name or 'f'
local a = debug.getinfo(1)
assert(a.name == name and a.namewhat == 'local')
return x
end
-- breaks in different conditions
if 3>4 then break end; f()
if 3<4 then a=1 else break end; f()
while 1 do local x=10; break end; f()
local b = 1
if 3>4 then return math.sin(1) end; f()
a = 3<4; f()
a = 3<4 or 1; f()
repeat local x=20; if 4>3 then f() else break end; f() until 1
g = {}
f(g).x = f(2) and f(10)+f(9)
assert(g.x == f(19))
function g(x) if not x then return 3 end return (x('a', 'x')) end
assert(g(f) == 'a')
until 1
test([[if
math.sin(1)
then
a=1
else
a=2
end
]], {2,4,7})
test([[--
if nil then
a=1
else
a=2
end
]], {2,5,6})
test([[a=1
repeat
a=a+1
until a==3
]], {1,3,4,3,4})
test([[ do
return
end
]], {2})
test([[local a
a=1
while a<=3 do
a=a+1
end
]], {2,3,4,3,4,3,4,3,5})
test([[while math.sin(1) do
if math.sin(1)
then
break
end
end
a=1]], {1,2,4,7})
test([[for i=1,3 do
a=i
end
]], {1,2,1,2,1,2,1,3})
test([[for i,v in pairs{'a','b'} do
a=i..v
end
]], {1,2,1,2,1,3})
test([[for i=1,4 do a=1 end]], {1,1,1,1,1})
print'+'
a = {}; L = nil
local glob = 1
local oldglob = glob
debug.sethook(function (e,l)
collectgarbage() -- force GC during a hook
local f, m, c = debug.gethook()
assert(m == 'crl' and c == 0)
if e == "line" then
if glob ~= oldglob then
L = l-1 -- get the first line where "glob" has changed
oldglob = glob
end
elseif e == "call" then
local f = debug.getinfo(2, "f").func
a[f] = 1
else assert(e == "return")
end
end, "crl")
function f(a,b)
collectgarbage()
local _, x = debug.getlocal(1, 1)
local _, y = debug.getlocal(1, 2)
assert(x == a and y == b)
assert(debug.setlocal(2, 3, "pera") == "AA".."AA")
assert(debug.setlocal(2, 4, "maçã") == "B")
x = debug.getinfo(2)
assert(x.func == g and x.what == "Lua" and x.name == 'g' and
x.nups == 0 and string.find(x.source, "^@.*db%.lua"))
glob = glob+1
assert(debug.getinfo(1, "l").currentline == L+1)
assert(debug.getinfo(1, "l").currentline == L+2)
end
function foo()
glob = glob+1
assert(debug.getinfo(1, "l").currentline == L+1)
end; foo() -- set L
-- check line counting inside strings and empty lines
_ = 'alo\
alo' .. [[
]]
--[[
]]
assert(debug.getinfo(1, "l").currentline == L+11) -- check count of lines
function g(...)
do local a,b,c; a=math.sin(40); end
local feijao
local AAAA,B = "xuxu", "mamão"
f(AAAA,B)
assert(AAAA == "pera" and B == "maçã")
do
local B = 13
local x,y = debug.getlocal(1,5)
assert(x == 'B' and y == 13)
end
end
g()
assert(a[f] and a[g] and a[assert] and a[debug.getlocal] and not a[print])
-- tests for manipulating non-registered locals (C and Lua temporaries)
local n, v = debug.getlocal(0, 1)
assert(v == 0 and n == "(*temporary)")
local n, v = debug.getlocal(0, 2)
assert(v == 2 and n == "(*temporary)")
assert(not debug.getlocal(0, 3))
assert(not debug.getlocal(0, 0))
function f()
assert(select(2, debug.getlocal(2,3)) == 1)
assert(not debug.getlocal(2,4))
debug.setlocal(2, 3, 10)
return 20
end
function g(a,b) return (a+1) + f() end
assert(g(0,0) == 30)
debug.sethook(nil);
assert(debug.gethook() == nil)
-- testing access to function arguments
X = nil
a = {}
function a:f (a, b, ...) local c = 13 end
debug.sethook(function (e)
assert(e == "call")
dostring("XX = 12") -- test dostring inside hooks
-- testing errors inside hooks
assert(not pcall(loadstring("a='joao'+1")))
debug.sethook(function (e, l)
assert(debug.getinfo(2, "l").currentline == l)
local f,m,c = debug.gethook()
assert(e == "line")
assert(m == 'l' and c == 0)
debug.sethook(nil) -- hook is called only once
assert(not X) -- check that
X = {}; local i = 1
local x,y
while 1 do
x,y = debug.getlocal(2, i)
if x==nil then break end
X[x] = y
i = i+1
end
end, "l")
end, "c")
a:f(1,2,3,4,5)
assert(X.self == a and X.a == 1 and X.b == 2 and X.arg.n == 3 and X.c == nil)
assert(XX == 12)
assert(debug.gethook() == nil)
-- testing upvalue access
local function getupvalues (f)
local t = {}
local i = 1
while true do
local name, value = debug.getupvalue(f, i)
if not name then break end
assert(not t[name])
t[name] = value
i = i + 1
end
return t
end
local a,b,c = 1,2,3
local function foo1 (a) b = a; return c end
local function foo2 (x) a = x; return c+b end
assert(debug.getupvalue(foo1, 3) == nil)
assert(debug.getupvalue(foo1, 0) == nil)
assert(debug.setupvalue(foo1, 3, "xuxu") == nil)
local t = getupvalues(foo1)
assert(t.a == nil and t.b == 2 and t.c == 3)
t = getupvalues(foo2)
assert(t.a == 1 and t.b == 2 and t.c == 3)
assert(debug.setupvalue(foo1, 1, "xuxu") == "b")
assert(({debug.getupvalue(foo2, 3)})[2] == "xuxu")
-- cannot manipulate C upvalues from Lua
assert(debug.getupvalue(io.read, 1) == nil)
assert(debug.setupvalue(io.read, 1, 10) == nil)
-- testing count hooks
local a=0
debug.sethook(function (e) a=a+1 end, "", 1)
a=0; for i=1,1000 do end; assert(1000 < a and a < 1012)
debug.sethook(function (e) a=a+1 end, "", 4)
a=0; for i=1,1000 do end; assert(250 < a and a < 255)
local f,m,c = debug.gethook()
assert(m == "" and c == 4)
debug.sethook(function (e) a=a+1 end, "", 4000)
a=0; for i=1,1000 do end; assert(a == 0)
debug.sethook(print, "", 2^24 - 1) -- count upperbound
local f,m,c = debug.gethook()
assert(({debug.gethook()})[3] == 2^24 - 1)
debug.sethook()
-- tests for tail calls
local function f (x)
if x then
assert(debug.getinfo(1, "S").what == "Lua")
local tail = debug.getinfo(2)
assert(not pcall(getfenv, 3))
assert(tail.what == "tail" and tail.short_src == "(tail call)" and
tail.linedefined == -1 and tail.func == nil)
assert(debug.getinfo(3, "f").func == g1)
assert(getfenv(3))
assert(debug.getinfo(4, "S").what == "tail")
assert(not pcall(getfenv, 5))
assert(debug.getinfo(5, "S").what == "main")
assert(getfenv(5))
print"+"
end
end
function g(x) return f(x) end
function g1(x) g(x) end
local function h (x) local f=g1; return f(x) end
h(true)
local b = {}
debug.sethook(function (e) table.insert(b, e) end, "cr")
h(false)
debug.sethook()
local res = {"return", -- first return (from sethook)
"call", "call", "call", "call",
"return", "tail return", "return", "tail return",
"call", -- last call (to sethook)
}
for _, k in ipairs(res) do assert(k == table.remove(b, 1)) end
lim = 30000
local function foo (x)
if x==0 then
assert(debug.getinfo(lim+2).what == "main")
for i=2,lim do assert(debug.getinfo(i, "S").what == "tail") end
else return foo(x-1)
end
end
foo(lim)
print"+"
-- testing traceback
assert(debug.traceback(print) == print)
assert(debug.traceback(print, 4) == print)
assert(string.find(debug.traceback("hi", 4), "^hi\n"))
assert(string.find(debug.traceback("hi"), "^hi\n"))
assert(not string.find(debug.traceback("hi"), "'traceback'"))
assert(string.find(debug.traceback("hi", 0), "'traceback'"))
assert(string.find(debug.traceback(), "^stack traceback:\n"))
-- testing debugging of coroutines
local function checktraceback (co, p)
local tb = debug.traceback(co)
local i = 0
for l in string.gmatch(tb, "[^\n]+\n?") do
assert(i == 0 or string.find(l, p[i]))
i = i+1
end
assert(p[i] == nil)
end
local function f (n)
if n > 0 then return f(n-1)
else coroutine.yield() end
end
local co = coroutine.create(f)
coroutine.resume(co, 3)
checktraceback(co, {"yield", "db.lua", "tail", "tail", "tail"})
co = coroutine.create(function (x)
local a = 1
coroutine.yield(debug.getinfo(1, "l"))
coroutine.yield(debug.getinfo(1, "l").currentline)
return a
end)
local tr = {}
local foo = function (e, l) table.insert(tr, l) end
debug.sethook(co, foo, "l")
local _, l = coroutine.resume(co, 10)
local x = debug.getinfo(co, 1, "lfLS")
assert(x.currentline == l.currentline and x.activelines[x.currentline])
assert(type(x.func) == "function")
for i=x.linedefined + 1, x.lastlinedefined do
assert(x.activelines[i])
x.activelines[i] = nil
end
assert(next(x.activelines) == nil) -- no 'extra' elements
assert(debug.getinfo(co, 2) == nil)
local a,b = debug.getlocal(co, 1, 1)
assert(a == "x" and b == 10)
a,b = debug.getlocal(co, 1, 2)
assert(a == "a" and b == 1)
debug.setlocal(co, 1, 2, "hi")
assert(debug.gethook(co) == foo)
assert(table.getn(tr) == 2 and
tr[1] == l.currentline-1 and tr[2] == l.currentline)
a,b,c = pcall(coroutine.resume, co)
assert(a and b and c == l.currentline+1)
checktraceback(co, {"yield", "in function <"})
a,b = coroutine.resume(co)
assert(a and b == "hi")
assert(table.getn(tr) == 4 and tr[4] == l.currentline+2)
assert(debug.gethook(co) == foo)
assert(debug.gethook() == nil)
checktraceback(co, {})
-- check traceback of suspended (or dead with error) coroutines
function f(i) if i==0 then error(i) else coroutine.yield(); f(i-1) end end
co = coroutine.create(function (x) f(x) end)
a, b = coroutine.resume(co, 3)
t = {"'yield'", "'f'", "in function <"}
while coroutine.status(co) == "suspended" do
checktraceback(co, t)
a, b = coroutine.resume(co)
table.insert(t, 2, "'f'") -- one more recursive call to 'f'
end
t[1] = "'error'"
checktraceback(co, t)
-- test acessing line numbers of a coroutine from a resume inside
-- a C function (this is a known bug in Lua 5.0)
local function g(x)
coroutine.yield(x)
end
local function f (i)
debug.sethook(function () end, "l")
for j=1,1000 do
g(i+j)
end
end
local co = coroutine.wrap(f)
co(10)
pcall(co)
pcall(co)
assert(type(debug.getregistry()) == "table")
print"OK"
| apache-2.0 |
Kapiainen/Lauhdutin | dist/@Resources/settings/slots/slot.lua | 1 | 3257 | local Slot
do
local _class_0
local _base_0 = {
update = function(self, setting)
if setting == nil then
return SKIN:Bang(('[!HideMeterGroup "Slot%d"]'):format(self.index))
end
SKIN:Bang(('[!SetOption "Slot%dTitle" "Text" "%s"]'):format(self.index, setting.title))
SKIN:Bang(('[!SetOption "Slot%dToolTip" "ToolTipText" "%s"]'):format(self.index, setting.tooltip))
SKIN:Bang(('[!ShowMeterGroup "Slot%d"]'):format(self.index))
SKIN:Bang(('[!HideMeterGroup "Slot%dSettings"]'):format(self.index))
local _exp_0 = setting.type
if ENUMS.SETTING_TYPES.ACTION == _exp_0 then
SKIN:Bang(('[!SetOption "Slot%dAction" "Text" "%s"]'):format(self.index, setting.label))
return SKIN:Bang(('[!ShowMeterGroup "Slot%dSettingAction"]'):format(self.index))
elseif ENUMS.SETTING_TYPES.BOOLEAN == _exp_0 then
if setting:getState() then
SKIN:Bang(('[!SetOption "Slot%dBoolean" "ImageName" "#@#settings\\gfx\\boolean_true.png"]'):format(self.index))
else
SKIN:Bang(('[!SetOption "Slot%dBoolean" "ImageName" "#@#settings\\gfx\\boolean_false.png"]'):format(self.index))
end
return SKIN:Bang(('[!ShowMeterGroup "Slot%dSettingBoolean"]'):format(self.index))
elseif ENUMS.SETTING_TYPES.FOLDER_PATH == _exp_0 then
SKIN:Bang(('[!SetOption "Slot%dFolderPathValue" "Text" "%s"]'):format(self.index, setting:getValue()))
SKIN:Bang(('[!SetOption "Slot%dFolderPathBrowse" "Text" "%s"]'):format(self.index, LOCALIZATION:get('button_label_browse', 'Browse')))
return SKIN:Bang(('[!ShowMeterGroup "Slot%dSettingFolderPath"]'):format(self.index))
elseif ENUMS.SETTING_TYPES.SPINNER == _exp_0 then
SKIN:Bang(('[!SetOption "Slot%dSpinnerValue" "Text" "%s"]'):format(self.index, setting:getValues()[setting:getIndex()].displayValue))
return SKIN:Bang(('[!ShowMeterGroup "Slot%dSettingSpinner"]'):format(self.index))
elseif ENUMS.SETTING_TYPES.INTEGER == _exp_0 then
SKIN:Bang(('[!SetOption "Slot%dIntegerValue" "Text" "%d"]'):format(self.index, setting:getValue()))
return SKIN:Bang(('[!ShowMeterGroup "Slot%dSettingInteger"]'):format(self.index))
elseif ENUMS.SETTING_TYPES.FOLDER_PATH_SPINNER == _exp_0 then
SKIN:Bang(('[!SetOption "Slot%dFolderPathSpinnerValue" "Text" "%s"]'):format(self.index, setting:getValues()[setting:getIndex()]))
SKIN:Bang(('[!SetOption "Slot%dFolderPathSpinnerBrowse" "Text" "%s"]'):format(self.index, LOCALIZATION:get('button_label_browse', 'Browse')))
return SKIN:Bang(('[!ShowMeterGroup "Slot%dSettingFolderPathSpinner"]'):format(self.index))
else
return assert(nil, 'settings.slots.slot.Slot.update')
end
end
}
_base_0.__index = _base_0
_class_0 = setmetatable({
__init = function(self, index)
assert(type(index) == 'number' and index % 1 == 0, 'settings.slots.slot.Slot')
self.index = index
end,
__base = _base_0,
__name = "Slot"
}, {
__index = _base_0,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
Slot = _class_0
end
return Slot
| mit |
waytim/darkstar | scripts/zones/Toraimarai_Canal/npcs/Tome_of_Magic.lua | 13 | 1839 | -----------------------------------
-- Area: Toraimarai Canal
-- NPC: Tome of Magic ( Needed for Mission )
-- Involved In Windurst Mission 7-1
-- @zone 169
-- @pos 142 13 -13 169 <many>
-----------------------------------
package.loaded["scripts/zones/Toraimarai_Canal/TextIDs"] = nil;
require("scripts/zones/Toraimarai_Canal/TextIDs");
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentMission = player:getCurrentMission(WINDURST);
local npcId = npc:getID();
if (npcId == 17469828) then
if (CurrentMission == THE_SIXTH_MINISTRY and player:getVar("MissionStatus") == 1) then
player:startEvent(0x0045);
end
elseif (npcId == 17469824) then
player:startEvent(0x0041);
elseif (npcId == 17469825) then
player:startEvent(0x0042);
elseif (npcId == 17469826) then
player:startEvent(0x0043);
elseif (npcId == 17469827) then
player:startEvent(0x0044);
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 == 0x0045) then
player:setVar("MissionStatus",2);
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Walls/npcs/Seven_of_Diamonds.lua | 4 | 1116 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Seven of Diamonds
-- Type: Standard NPC
-- @zone: 239
-- @pos: 6.612 -3.5 278.553
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if player:hasKeyItem(267) then
player:startEvent(0x0186);
else
player:startEvent(0x0108);
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/Bibiki_Bay/npcs/Clamming_Point.lua | 13 | 6769 | -----------------------------------
-- Area: Bibiki Bay
-- NPC: Clamming Point
-----------------------------------
package.loaded["scripts/zones/Bibiki_Bay/TextIDs"] = nil;
require("scripts/zones/Bibiki_Bay/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- Local Variables
-----------------------------------
-- clammingItems = item id, weight, drop rate, improved drop rate
local clammingItems = { 1311, 6, 0.001, 0.003, -- Oxblood
885, 6, 0.002, 0.006, -- Turtle Shell
1193, 6, 0.003, 0.009, -- HQ Crab Shell
1446, 6, 0.004, 0.012, -- Lacquer Tree Log
4318, 6, 0.005, 0.015, -- Bibiki Urchin
1586, 6, 0.008, 0.024, -- Titanictus Shell
5124, 20, 0.011, 0.033, -- Tropical Clam
690, 6, 0.014, 0.042, -- Elm Log
887, 6, 0.017, 0.051, -- Coral Fragment
703, 6, 0.021, 0.063, -- Petrified Log
691, 6, 0.025, 0.075, -- Maple Log
4468, 6, 0.029, 0.087, -- Pamamas
3270, 6, 0.033, 0.099, -- HQ Pugil Scales
888, 6, 0.038, 0.114, -- Seashell
4328, 6, 0.044, 0.132, -- Hobgoblin Bread
485, 6, 0.051, 0.153, -- Broken Willow Rod
510, 6, 0.058, 0.174, -- Goblin Armor
5187, 6, 0.065, 0.195, -- Elshimo Coconut
507, 6, 0.073, 0.219, -- Goblin Mail
881, 6, 0.081, 0.243, -- Crab Shell
4325, 6, 0.089, 0.267, -- Hobgoblin Pie
936, 6, 0.098, 0.294, -- Rock Salt
4361, 6, 0.107, 0.321, -- Nebimonite
864, 6, 0.119, 0.357, -- Fish Scales
4484, 6, 0.140, 0.420, -- Shall Shell
624, 6, 0.178, 0.534, -- Pamtam Kelp
1654, 35, 0.225, 0.675, -- Igneous Rock
17296, 7, 0.377, 0.784, -- Pebble
5123, 11, 0.628, 0.892, -- Jacknife
5122, 3, 1.000, 1.000 -- Bibiki Slug
};
-----------------------------------
-- Local Functions
-----------------------------------
local function giveImprovedResults(player)
if (player:getMod(MOD_CLAMMING_IMPROVED_RESULTS) > 0) then
return 1;
end
return 0;
end;
local function giveReducedIncidents(player)
if (player:getMod(MOD_CLAMMING_REDUCED_INCIDENTS) > 0) then
return 0.05;
end
return 0.1;
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(CLAMMING_KIT)) then
player:setLocalVar("ClammingPointID", npc:getID());
if (GetServerVariable("ClammingPoint_" .. npc:getID() .. "_InUse") == 1) then
player:messageSpecial(IT_LOOKS_LIKE_SOMEONE);
else
if (player:getVar("ClammingKitBroken") > 0) then -- Broken bucket
player:messageSpecial(YOU_CANNOT_COLLECT);
else
local delay = GetServerVariable("ClammingPoint_" .. npc:getID() .. "_Delay");
if ( delay > 0 and delay > os.time()) then -- player has to wait a little longer
player:messageSpecial(IT_LOOKS_LIKE_SOMEONE);
else
SetServerVariable("ClammingPoint_" .. npc:getID() .. "_InUse", 1);
SetServerVariable("ClammingPoint_" .. npc:getID() .. "_Delay", 0);
player:startEvent(0x0014, 0, 0, 0, 0, 0, 0, 0, 0);
end
end
end
else
player:messageSpecial(AREA_IS_LITTERED);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0014) then
if (player:getVar("ClammingKitSize") == 200 and math.random() <= giveReducedIncidents(player)) then
player:setLocalVar("SomethingJumpedInBucket", 1);
else
local dropRate = math.random();
local improvedResults = giveImprovedResults(player);
for itemDrop = 3, table.getn(clammingItems), 4 do
if (dropRate <= clammingItems[itemDrop + improvedResults]) then
player:setLocalVar("ClammedItem", clammingItems[itemDrop - 2]);
player:setVar("ClammedItem_" .. clammingItems[itemDrop - 2], player:getVar("ClammedItem_" .. clammingItems[itemDrop - 2]) + 1);
player:setVar("ClammingKitWeight", player:getVar("ClammingKitWeight") + clammingItems[itemDrop - 1]);
if (player:getVar("ClammingKitWeight") > player:getVar("ClammingKitSize")) then -- Broken bucket
player:setVar("ClammingKitBroken", 1);
end
break;
end
end
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0014) then
if (player:getLocalVar("SomethingJumpedInBucket") > 0) then
player:setLocalVar("SomethingJumpedInBucket", 0);
player:messageSpecial(SOMETHING_JUMPS_INTO);
player:setVar("ClammingKitBroken", 1);
for item = 1, table.getn(clammingItems), 4 do -- Remove items from bucket
player:setVar("ClammedItem_" .. clammingItems[item], 0);
end
else
local clammedItem = player:getLocalVar("ClammedItem");
if (clammedItem > 0) then
if (player:getVar("ClammingKitBroken") > 0) then --Broken bucket
player:messageSpecial(THE_WEIGHT_IS_TOO_MUCH, clammedItem);
for item = 1, table.getn(clammingItems), 4 do -- Remove items from bucket
player:setVar("ClammedItem_" .. clammingItems[item], 0);
end
else
player:messageSpecial(YOU_FIND_ITEM, clammedItem);
end
SetServerVariable("ClammingPoint_" .. player:getLocalVar("ClammingPointID") .. "_Delay", os.time() + 10);
player:setLocalVar("ClammedItem", 0);
end
end
SetServerVariable("ClammingPoint_" .. player:getLocalVar("ClammingPointID") .. "_InUse", 0);
player:setLocalVar("ClammingPointID", 0);
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/npcs/Geuhbe.lua | 5 | 1036 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Geuhbe
-- Type: Event Scene Replayer
-- @zone: 245
-- @pos: -74.309 -1 -114.174
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2731);
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 |
dkerr64/astlinux | package/prosody/modules/mod_listusers.lua | 34 | 2522 | function module.command(args)
local action = table.remove(args, 1);
if not action then -- Default, list registered users
local data_path = CFG_DATADIR or "data";
if not pcall(require, "luarocks.loader") then
pcall(require, "luarocks.require");
end
local lfs = require "lfs";
function decode(s)
return s:gsub("%%([a-fA-F0-9][a-fA-F0-9])", function (c)
return string.char(tonumber("0x"..c));
end);
end
for host in lfs.dir(data_path) do
local accounts = data_path.."/"..host.."/accounts";
if lfs.attributes(accounts, "mode") == "directory" then
for user in lfs.dir(accounts) do
if user:sub(1,1) ~= "." then
print(decode(user:gsub("%.dat$", "")).."@"..decode(host));
end
end
end
end
elseif action == "--connected" then -- List connected users
local socket = require "socket";
local default_local_interfaces = { };
if socket.tcp6 and config.get("*", "use_ipv6") ~= false then
table.insert(default_local_interfaces, "::1");
end
if config.get("*", "use_ipv4") ~= false then
table.insert(default_local_interfaces, "127.0.0.1");
end
local console_interfaces = config.get("*", "console_interfaces")
or config.get("*", "local_interfaces")
or default_local_interfaces
console_interfaces = type(console_interfaces)~="table"
and {console_interfaces} or console_interfaces;
local console_ports = config.get("*", "console_ports") or 5582
console_ports = type(console_ports) ~= "table" and { console_ports } or console_ports;
local st, conn = pcall(assert,socket.connect(console_interfaces[1], console_ports[1]));
if (not st) then print("Error"..(conn and ": "..conn or "")); return 1; end
local banner = config.get("*", "console_banner");
if (
(not banner) or
(
(type(banner) == "string") and
(banner:match("^| (.+)$"))
)
) then
repeat
local rec_banner = conn:receive()
until
rec_banner == "" or
rec_banner == nil; -- skip banner
end
conn:send("c2s:show()\n");
conn:settimeout(1); -- Only hit in case of failure
repeat local line = conn:receive()
if not line then break; end
local jid = line:match("^| (.+)$");
if jid then
jid = jid:gsub(" %- (%w+%(%d+%))$", "\t%1");
print(jid);
elseif line:match("^| OK:") then
return 0;
end
until false;
end
return 0;
end
| gpl-3.0 |
amostalong/SSFS | Assets/LuaFramework/ToLua/Lua/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| mit |
waytim/darkstar | scripts/zones/RuLude_Gardens/npcs/Adolie.lua | 13 | 1477 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Adolie
-- @zone 243
-- @pos -35 2 59
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,3) == false) then
player:startEvent(10091);
else
player:startEvent(0x001e); -- Standard dialog
end
end;
-- 0x0018 0x001e 0x001f 0x0020 0x009e 0x0062 0x009d 0x0061 0x0064 0x276b
-----------------------------------
-- 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 == 10091) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",3,true);
end
end;
| gpl-3.0 |
internetisalie/lua-for-idea | include/stdlibrary/math.lua | 2 | 3822 | --- standard mathematical functions.
-- @module math
module"math"
--local math = {}
---
-- Returns the absolute value of `x`.
function math.abs(x) return 0 end
---
-- Returns the arc cosine of `x` (in radians).
function math.acos(x) return 0 end
---
-- Returns the arc sine of `x` (in radians).
function math.asin(x) return 0 end
---
-- Returns the arc tangent of `x` (in radians).
function math.atan(x) return 0 end
---
-- Returns the arc tangent of `y/x` (in radians), but uses the signs
-- of both parameters to find the quadrant of the result. (It also handles
-- correctly the case of `x` being zero.)
function math.atan2(y, x) return 0 end
---
-- Returns the smallest integer larger than or equal to `x`.
function math.ceil(x) return 0 end
---
-- Returns the cosine of `x` (assumed to be in radians).
function math.cos(x) return 0 end
---
-- Returns the hyperbolic cosine of `x`.
function math.cosh(x) return 0 end
---
-- Returns the angle `x` (given in radians) in degrees.
function math.deg(x) return 0 end
---
-- Returns the value *e^x*.
function math.exp(x) end
---
-- Returns the largest integer smaller than or equal to `x`.
function math.floor(x) end
---
-- Returns the remainder of the division of `x` by `y` that rounds the
-- quotient towards zero.
function math.fmod(x, y) end
---
-- Returns `m` and `e` such that *x = m2^e*, `e` is an integer and the
-- absolute value of `m` is in the range *[0.5, 1)* (or zero when `x` is zero).
function math.frexp(x) end
---
-- The value `HUGE_VAL`, a value larger than or equal to any other
-- numerical value.
-- function math.huge end
-- * `math.HUGE_VAL`: math.HUGE_VAL
---
-- Returns *m2^e* (`e` should be an integer).
function math.ldexp(m, e) end
---
-- Returns the natural logarithm of `x`.
function math.log(x) end
---
-- Returns the base-10 logarithm of `x`.
function math.log10(x) end
---
-- Returns the maximum value among its arguments.
function math.max(x, ...) end
---
-- Returns the minimum value among its arguments.
function math.min(x, ...) end
---
-- Returns two numbers, the integral part of `x` and the fractional part of
-- `x`.
function math.modf(x) end
---
-- The value of *pi*.
-- function math.pi end
-- * `math.pi`: math.pi
---
-- Returns *x^y*. (You can also use the expression `x^y` to compute this
-- value.)
function math.pow(x, y) end
---
-- Returns the angle `x` (given in degrees) in radians.
function math.rad(x) end
---
-- This function is an interface to the simple pseudo-random generator
-- function `rand` provided by ANSI C. (No guarantees can be given for its
-- statistical properties.)
-- When called without arguments, returns a uniform pseudo-random real
-- number in the range *[0,1)*. When called with an integer number `m`,
-- `math.random` returns a uniform pseudo-random integer in the range *[1,
-- m]*. When called with two integer numbers `m` and `n`, `math.random`
-- returns a uniform pseudo-random integer in the range *[m, n]*.
function math.random(m, n) end
---
-- Sets `x` as the "seed" for the pseudo-random generator: equal seeds
-- produce equal sequences of numbers.
function math.randomseed(x) end
---
-- Returns the sine of `x` (assumed to be in radians).
function math.sin(x) return 0 end
---
-- Returns the hyperbolic sine of `x`.
function math.sinh(x) return 0 end
---
-- Returns the square root of `x`. (You can also use the expression `x^0.5`
-- to compute this value.)
function math.sqrt(x) return 0 end
---
-- Returns the tangent of `x` (assumed to be in radians).
function math.tan(x) return 0 end
---
-- Returns the hyperbolic tangent of `x`.
function math.tanh(x) return 0 end
math.PI = 3.1415
return math
| apache-2.0 |
waytim/darkstar | scripts/globals/items/holy_bolt.lua | 26 | 1227 | -----------------------------------------
-- ID: 18153
-- Item: Holy Bolt
-- Additional Effect: Light Damage
-- Bolt dmg is affected by light/dark staves and Chatoyant
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 105;
if (target:getMainLvl() > player:getMainLvl()) then
chance = chance - 5 * (target:getMainLvl() - player:getMainLvl())
chance = utils.clamp(chance, 5, 95);
end
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = player:getStat(MOD_MND) - target:getStat(MOD_MND);
if (dmg > 40) then
dmg = dmg+(dmg-40)/2;
end
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
return SUBEFFECT_LIGHT_DAMAGE, MSGBASIC_ADD_EFFECT_DMG, dmg;
end
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Windurst_Walls/npcs/HomePoint#2.lua | 27 | 1270 | -----------------------------------
-- Area: Windurst Walls
-- NPC: HomePoint#2
-- @pos -212 0.001 -99 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 20);
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 == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c103950020.lua | 2 | 2474 | --Light Shard Dragon
function c103950020.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(nil),1)
c:EnableReviveLimit()
--ATK trace
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_ADJUST)
e1:SetRange(LOCATION_MZONE)
e1:SetOperation(c103950020.atktrace)
c:RegisterEffect(e1)
--Special Summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(103950020,0))
e2:SetType(EFFECT_TYPE_TRIGGER_F+EFFECT_TYPE_SINGLE)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e2:SetCondition(c103950020.spcon)
e2:SetTarget(c103950020.sptg)
e2:SetOperation(c103950020.spop)
c:RegisterEffect(e2)
--Self-destruct
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_SELF_DESTROY)
e3:SetCondition(c103950020.sdcon)
c:RegisterEffect(e3)
end
-- ATK trace operation
function c103950020.atktrace(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local atk=c:GetFlagEffectLabel(103950020)
if not atk then
c:RegisterFlagEffect(103950020,RESET_EVENT+RESET_TOFIELD,0,1,c:GetAttack())
else
c:SetFlagEffectLabel(103950020,c:GetAttack())
end
end
-- Special Summon condition
function c103950020.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local crp=c:GetReasonPlayer()
local atk=c:GetFlagEffectLabel(103950020)
return c:GetPreviousControler()==tp and tp~=crp and crp~=PLAYER_NONE and atk and atk >= 2000
end
-- Special Summon target
function c103950020.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
-- Special Summon operation
function c103950020.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local atk=c:GetFlagEffectLabel(103950020)
if atk and atk >= 2000 then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetReset(RESET_EVENT+0xff0000)
e1:SetCode(EFFECT_SET_BASE_ATTACK)
e1:SetValue(atk-500)
c:RegisterEffect(e1)
end
end
-- Self-destruct condition
function c103950020.sdcon(e)
return e:GetHandler():GetAttack() > 3000
end | gpl-3.0 |
waytim/darkstar | scripts/globals/items/crayfish.lua | 18 | 1409 | -----------------------------------------
-- ID: 4472
-- Item: crayfish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -3
-- Vitality 1
-- defense 10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4472);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -3);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_DEF, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -3);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_DEF, 10);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/galkan_sausage_+2.lua | 3 | 1249 | -----------------------------------------
-- ID: 5860
-- Item: galkan_sausage_+2
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength 5
-- Intelligence -6
-- Attack 11
-- Ranged Attack 11
-----------------------------------------
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,1800,5860);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_INT, -6);
target:addMod(MOD_ATT, 11);
target:addMod(MOD_RATT, 11);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_INT, -6);
target:delMod(MOD_ATT, 11);
target:delMod(MOD_RATT, 11);
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/mobskills/Gregale_Wing_Air.lua | 33 | 1081 | ---------------------------------------------
-- Gregale Wing
--
-- Description: An icy wind deals Ice damage to enemies within a very wide area of effect. Additional effect: Paralyze
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only Jormungand and Isgebind
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() ~= 1) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PARALYSIS;
MobStatusEffectMove(mob, target, typeEffect, 40, 0, 120);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_ICE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.