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 |
|---|---|---|---|---|---|
TheOnePharaoh/YGOPro-Custom-Cards | script/c405109.lua | 2 | 4004 | --Galaxy-Eyes Tachyon Binary Pulsar Dragon
function c405109.initial_effect(c)
--Synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(c405109.mfilter),aux.NonTuner(c405109.mfilter2),1)
c:EnableReviveLimit()
--Atk
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(405109,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_QUICK_O+EFFECT_TYPE_FIELD)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c405109.condition)
e1:SetCost(c405109.cost)
e1:SetOperation(c405109.operation)
c:RegisterEffect(e1)
--Recover
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(405109,1))
e2:SetCategory(CATEGORY_RECOVER)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_BATTLE_DAMAGE)
e2:SetCondition(c405109.con)
e2:SetTarget(c405109.tg)
e2:SetOperation(c405109.op)
c:RegisterEffect(e2)
--Banish
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(405109,2))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_BE_BATTLE_TARGET)
e3:SetCountLimit(1,405109)
e3:SetTarget(c405109.rtg)
e3:SetOperation(c405109.rop)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetType(EFFECT_TYPE_QUICK_O)
e4:SetRange(LOCATION_MZONE)
e4:SetCode(EVENT_BECOME_TARGET)
e4:SetCondition(c405109.rcon)
c:RegisterEffect(e4)
end
function c405109.mfilter(c)
return c:IsSetCard(0x7b)
end
function c405109.mfilter2(c)
return c:IsSetCard(0x55) or c:IsSetCard(0x7b)
end
function c405109.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:GetFlagEffect(405109)==0 and (Duel.GetAttackTarget()==c or (Duel.GetAttacker()==c) and Duel.GetAttackTarget()~=nil)
end
function c405109.cfilter(c)
return (c:IsSetCard(0x107b) and c:IsAbleToDeckAsCost()) or (c:IsAbleToExtraAsCost() and c:IsSetCard(0x107b)) and (c:IsLocation(LOCATION_GRAVE) or c:IsFaceup())
end
function c405109.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(405109)==0
and Duel.IsExistingMatchingCard(c405109.cfilter,tp,LOCATION_GRAVE+LOCATION_MZONE,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c405109.cfilter,tp,LOCATION_GRAVE+LOCATION_MZONE,0,1,1,e:GetHandler())
e:SetLabel(g:GetFirst():GetAttack())
Duel.SendtoDeck(g,nil,1,REASON_COST)
e:GetHandler():RegisterFlagEffect(405109,RESET_PHASE+PHASE_DAMAGE_CAL,0,1)
end
function c405109.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsFaceup() and c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(e:GetLabel()/2)
e1:SetReset(RESET_PHASE+PHASE_DAMAGE_CAL)
c:RegisterEffect(e1)
end
end
function c405109.con(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp
end
function c405109.tg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(ev)
Duel.SetOperationInfo(0,CATEGORY_RECOVER,nil,0,tp,ev)
end
function c405109.op(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Recover(p,d,REASON_EFFECT)
end
function c405109.rcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsContains(e:GetHandler())
end
function c405109.rtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemove() end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,e:GetHandler(),1,0,0)
end
function c405109.rop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsControler(tp) and Duel.Remove(c,nil,REASON_EFFECT+REASON_TEMPORARY)~=0 then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetLabelObject(c)
e1:SetCountLimit(1)
e1:SetOperation(c405109.retop)
Duel.RegisterEffect(e1,tp)
end
end
function c405109.retop(e,tp,eg,ep,ev,re,r,rp)
Duel.ReturnToField(e:GetLabelObject())
end | gpl-3.0 |
zorfmorf/loveprojects | bfrpg/src/lib/quickie/utf8.lua | 15 | 4556 | -- utf8.lua - Basic (and unsafe) utf8 string support in plain Lua - public domain
--
-- Written in 2013 by Matthias Richter (vrld@vrld.org)
--
-- This software is in the public domain. Where that dedication is not
-- recognized, you are granted a perpetual, irrevokable license to copy and
-- modify this file as you see fit. This software is distributed without any
-- warranty.
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- ALL FUNCTIONS ARE UNSAFE: THEY ASSUME VALID UTF8 INPUT
-- !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
-- Generic for iterator.
--
-- Arguments:
-- s ... The utf8 string.
-- i ... Last byte of the previous codepoint.
--
-- Returns:
-- k ... Number of the *last* byte of the codepoint.
-- c ... The utf8 codepoint (character).
-- n ... Width/number of bytes of the codepoint.
local function iter(s, i)
if i >= #s then return end
local b, nbytes = s:byte(i+1,i+1), 1
-- determine width of the codepoint by counting the number of set bits in the first byte
-- warning: there is no validation of the following bytes!
if b >= 0xc0 and b <= 0xdf then nbytes = 2 -- 1100 0000 to 1101 1111
elseif b >= 0xe0 and b <= 0xef then nbytes = 3 -- 1110 0000 to 1110 1111
elseif b >= 0xf0 and b <= 0xf7 then nbytes = 4 -- 1111 0000 to 1111 0111
elseif b >= 0xf8 and b <= 0xfb then nbytes = 5 -- 1111 1000 to 1111 1011
elseif b >= 0xfc and b <= 0xfd then nbytes = 6 -- 1111 1100 to 1111 1101
elseif b < 0x00 or b > 0x7f then error(("Invalid codepoint: 0x%02x"):format(b))
end
return i+nbytes, s:sub(i+1,i+nbytes), nbytes
end
-- Shortcut to the generic for iterator.
--
-- Usage:
-- for k, c, n in chars(s) do
-- ...
-- end
--
-- Meaning of k, c, and n is the same as in iter(s, i).
local function chars(s)
return iter, s, 0
end
-- Get length in characters of an utf8 string.
--
-- Arguments:
-- s ... The utf8 string.
--
-- Returns:
-- n ... Number of utf8 characters in s.
local function len(s)
-- assumes sane utf8 string: count the number of bytes that is *not* 10xxxxxx
local _, c = s:gsub('[^\128-\191]', '')
return c
end
-- Get substring, same semantics as string.sub(s,i,j).
--
-- Arguments:
-- s ... The utf8 string.
-- i ... Starting position, may be negative.
-- j ... (optional) Ending position, may be negative.
--
-- Returns:
-- t ... The substring.
local function sub(s, i, j)
local l = len(s)
j = j or l
if i < 0 then i = l + i + 1 end
if j < 0 then j = l + j + 1 end
if j < i then return '' end
local k, t = 1, {}
for _, c in chars(s) do
if k >= i then t[#t+1] = c end
if k >= j then break end
k = k + 1
end
return table.concat(t)
end
-- Split utf8 string in two substrings
--
-- Arguments:
-- s ... The utf8 string.
-- i ... The position to split, may be negative.
--
-- Returns:
-- left ... Substring before i.
-- right ... Substring after i.
local function split(s, i)
local l = len(s)
if i < 0 then i = l + i + 1 end
local k, pos = 1, 0
for byte in chars(s) do
if k > i then break end
pos, k = byte, k + 1
end
return s:sub(1, pos), s:sub(pos+1, -1)
end
-- Reverses order of characters in an utf8 string.
--
-- Arguments:
-- s ... The utf8 string.
--
-- Returns:
-- t ... The revered string.
local function reverse(s)
local t = {}
for _, c in chars(s) do
table.insert(t, 1, c)
end
return table.concat(t)
end
-- Convert a Unicode code point to a UTF-8 byte sequence
-- Logic stolen from this page:
-- http://scripts.sil.org/cms/scripts/page.php?site_id=nrsi&id=iws-appendixa
--
-- Arguments:
-- Number representing the Unicode code point (e.g. 0x265c).
--
-- Returns:
-- UTF-8 encoded string of the given character.
-- Numbers out of range produce a blank string.
local function encode(code)
if code < 0 then
error('Code point must not be negative.')
elseif code <= 0x7f then
return string.char(code)
elseif code <= 0x7ff then
local c1 = code / 64 + 192
local c2 = code % 64 + 128
return string.char(c1, c2)
elseif code <= 0xffff then
local c1 = code / 4096 + 224
local c2 = code % 4096 / 64 + 128
local c3 = code % 64 + 128
return string.char(c1, c2, c3)
elseif code <= 0x10ffff then
local c1 = code / 262144 + 240
local c2 = code % 262144 / 4096 + 128
local c3 = code % 4096 / 64 + 128
local c4 = code % 64 + 128
return string.char(c1, c2, c3, c4)
end
return ''
end
return {
iter = iter,
chars = chars,
len = len,
sub = sub,
split = split,
reverse = reverse,
encode = encode
}
| apache-2.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c77777751.lua | 2 | 1910 | --Necromantic Summoning
function c77777751.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,77777751)
e1:SetTarget(c77777751.target)
e1:SetOperation(c77777751.activate)
c:RegisterEffect(e1)
end
function c77777751.filter(c,e,tp)
return c:IsSetCard(0x1c8) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c77777751.filter2(c)
return c:IsSetCard(0x1c8)
end
function c77777751.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>=0
and Duel.IsExistingMatchingCard(c77777751.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c77777751.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c77777751.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
local tc=g:GetFirst()
if tc and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) then
local g2=Duel.GetMatchingGroup(c77777751.filter2,tp,LOCATION_MZONE,0,nil)
local tc2=g2:GetFirst()
while tc2 do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(300)
tc2:RegisterEffect(e1)
tc2=g2:GetNext()
end
end
local g3=Duel.GetMatchingGroup(c77777751.filter2,tp,LOCATION_MZONE,0,nil)
local tc3=g3:GetFirst()
while tc3 do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc3:RegisterEffect(e1)
tc3=g3:GetNext()
end
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c77777853.lua | 2 | 3254 | --Mystic Fauna Vinoceros
function c77777853.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,nil,aux.NonTuner(Card.IsSetCard,0x40a),1)
c:EnableReviveLimit()
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(77777853,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c77777853.spcon)
e1:SetTarget(c77777853.sptg)
e1:SetOperation(c77777853.spop)
c:RegisterEffect(e1)
--To Deck
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(77777853,1))
e2:SetCategory(CATEGORY_TODECK)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetTarget(c77777853.tdtg)
e2:SetOperation(c77777853.tdop)
c:RegisterEffect(e2)
--change target
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(77777853,2))
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_ATTACK_ANNOUNCE)
e3:SetCondition(c77777853.condition1)
e3:SetTarget(c77777853.target1)
e3:SetOperation(c77777853.activate1)
c:RegisterEffect(e3)
end
function c77777853.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SYNCHRO
end
function c77777853.spfilter(c,e,tp)
return c:IsSetCard(0x40a) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsType(TYPE_XYZ+TYPE_SYNCHRO)
end
function c77777853.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c77777853.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_GRAVE)
end
function c77777853.spop(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,c77777853.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c77777853.filter(c)
return c:IsSetCard(0x40a) and c:IsAbleToDeck()
end
function c77777853.tdtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c77777853.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TODECK,nil,nil,tp,LOCATION_GRAVE)
end
function c77777853.tdop(e,tp,eg,ep,ev,re,r,rp)
local g2=Duel.SelectMatchingCard(tp,c77777853.filter,tp,LOCATION_GRAVE,0,1,1,nil)
if g2:GetCount()>0 then
Duel.SendtoDeck(g2,nil,2,REASON_EFFECT)
end
end
function c77777853.condition1(e,tp,eg,ep,ev,re,r,rp)
return tp~=Duel.GetTurnPlayer()
end
function c77777853.filter1(c,e)
return c:IsCanBeEffectTarget(e)
end
function c77777853.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
local ag=eg:GetFirst():GetAttackableTarget()
local at=Duel.GetAttackTarget()
if chk==0 then return ag:IsExists(c77777853.filter1,1,at,e) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=ag:FilterSelect(tp,c77777853.filter1,1,1,at,e)
Duel.SetTargetCard(g)
end
function c77777853.activate1(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.ChangeAttackTarget(tc)
end
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c101010383.lua | 2 | 4690 | --created & coded by Lyris
--Blade Flight
function c101010383.initial_effect(c)
--"Blademaster" and "Bladewing" monsters you control cannot be targeted by your opponent's card effects. Once per turn, when a Spell, Trap, or Spell/Trap effect targets a "Blademaster" or "Bladewing" monster you control: You can return 1 of those targets to your hand, then you can Special Summon 1 monster from your hand with a different name than the returned monster.
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c101010383.target1)
e1:SetOperation(c101010383.operation1)
c:RegisterEffect(e1)
--instant(chain)
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOHAND)
e2:SetDescription(aux.Stringid(101010383,1))
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_CHAINING)
e2:SetCondition(c101010383.condition2)
e2:SetTarget(c101010383.target2)
e2:SetOperation(c101010383.operation2)
c:RegisterEffect(e2)
--cannot target
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e3:SetRange(LOCATION_SZONE)
e3:SetTargetRange(LOCATION_MZONE,0)
e3:SetTarget(c101010383.tg)
e3:SetValue(function(e,re,rp) return rp~=e:GetHandlerPlayer() end)
c:RegisterEffect(e3)
end
function c101010383.cfilter(c)
return c:IsLocation(LOCATION_MZONE) and c:IsFaceup() and c:IsSetCard(0xbb2)
end
function c101010383.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
e:SetLabel(0)
local ct=Duel.GetCurrentChain()
if ct==1 then return end
local pe=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
if not pe:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return end
if not pe:GetHandler():IsType(TYPE_SPELL+TYPE_TRAP) or not pe:IsHasType(EFFECT_TYPE_ACTIVATE) then return end
local tg=Duel.GetChainInfo(ct-1,CHAININFO_TARGET_CARDS)
if not tg or not tg:IsExists(c101010383.cfilter,1,nil) then return end
if not Duel.IsChainNegatable(ct-1) then return end
if Duel.SelectYesNo(tp,aux.Stringid(101010383,0)) then
e:SetLabel(1)
e:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOHAND)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_MZONE)
end
end
function c101010383.filter(c)
return c:IsFaceup() and c:IsSetCard(0xbb2) and c:IsAbleToHand()
end
function c101010383.sfilter(c,e,tp,code)
return c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsCode(code)
end
function c101010383.operation1(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if e:GetLabel()~=1 then return end
if not c:IsRelateToEffect(e) then return end
local ct=Duel.GetChainInfo(0,CHAININFO_CHAIN_COUNT)
local tg=Duel.GetChainInfo(ct-1,CHAININFO_TARGET_CARDS)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=tg:FilterSelect(tp,c101010383.filter,1,1,nil)
local tc=g:GetFirst()
if tc and Duel.SendtoHand(tc,nil,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_HAND) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=Duel.SelectMatchingCard(tp,c101010383.sfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp,tc:GetCode())
if sg:GetCount()>0 then
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
function c101010383.condition2(e,tp,eg,ep,ev,re,r,rp)
if not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return end
if not re:GetHandler():IsType(TYPE_TRAP) then return false end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not tg or not tg:IsExists(c101010383.cfilter,1,nil) then return false end
return Duel.IsChainNegatable(ev)
end
function c101010383.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0)
if eg:GetFirst():IsDestructable() then
eg:GetFirst():CreateEffectRelation(e)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c101010383.operation2(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND)
local g=tg:FilterSelect(tp,c101010383.filter,1,1,nil)
local tc=g:GetFirst()
if tc and Duel.SendtoHand(tc,nil,REASON_EFFECT)~=0 and tc:IsLocation(LOCATION_HAND) and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=Duel.SelectMatchingCard(tp,c101010383.sfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp,tc:GetCode())
if sg:GetCount()>0 then
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
function c101010383.tg(e,c)
return c:IsFaceup() and c:IsSetCard(0xbb2)
end
| gpl-3.0 |
gfgtdf/wesnoth-old | data/campaigns/The_Hammer_of_Thursagan/lua/spawns.lua | 4 | 1562 | -- Used for the bandit spawns in scenario 5
local helper = wesnoth.require "helper"
local utils = wesnoth.require "wml-utils"
local wml_actions = wesnoth.wml_actions
local T = wml.tag
function wml_actions.spawn_units(cfg)
local x = cfg.x or wml.error("[spawn_units] missing required x= attribute.")
local y = cfg.y or wml.error("[spawn_units] missing required y= attribute.")
local types = cfg.types or wml.error("[spawn_units] missing required types= attribute.")
local count = cfg.count or wml.error("[spawn_units] missing required count= attribute.")
local side = cfg.side or wml.error("[spawn_units] missing required side= attribute.")
local done = 0
for i=1,count do
local locs = wesnoth.get_locations({T["not"] { T.filter {} } , T["and"] { x = x, y = y, radius = 1 } })
if #locs == 0 then locs = wesnoth.get_locations({T["not"] { T.filter {} } , T["and"] { x = x, y = y, radius = 2 } }) end
if #locs == 0 then break end
done = done + 1
local unit_type = helper.rand(types)
local loc_i = helper.rand("1.."..#locs)
wml_actions.move_unit_fake({x = string.format("%d,%d", x, locs[loc_i][1]) , y = string.format("%d,%d", y, locs[loc_i][2]) , type = unit_type , side = side})
wesnoth.units.to_map({ type = unit_type , side = side, random_traits = "yes", generate_name = "yes" , upkeep = "loyal" }, locs[loc_i][1], locs[loc_i][2])
end
if done > 0 then
for then_child in wml.child_range(cfg, "then") do
local action = utils.handle_event_commands(then_child, "conditional")
if action ~= "none" then return end
end
end
end
| gpl-2.0 |
amostalong/SSFS | Assets/LuaFramework/ToLua/Lua/protobuf/protobuf.lua | 8 | 36644 | --
--------------------------------------------------------------------------------
-- FILE: protobuf.lua
-- DESCRIPTION: protoc-gen-lua
-- Google's Protocol Buffers project, ported to lua.
-- https://code.google.com/p/protoc-gen-lua/
--
-- Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com
-- All rights reserved.
--
-- Use, modification and distribution are subject to the "New BSD License"
-- as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
--
-- COMPANY: NetEase
-- CREATED: 2010年07月29日 14时30分02秒 CST
--------------------------------------------------------------------------------
--
local setmetatable = setmetatable
local rawset = rawset
local rawget = rawget
local error = error
local ipairs = ipairs
local pairs = pairs
local print = print
local table = table
local string = string
local tostring = tostring
local type = type
local pb = require "pb"
local wire_format = require "protobuf.wire_format"
local type_checkers = require "protobuf.type_checkers"
local encoder = require "protobuf.encoder"
local decoder = require "protobuf.decoder"
local listener_mod = require "protobuf.listener"
local containers = require "protobuf.containers"
local descriptor = require "protobuf.descriptor"
local FieldDescriptor = descriptor.FieldDescriptor
local text_format = require "protobuf.text_format"
module("protobuf.protobuf")
local function make_descriptor(name, descriptor, usable_key)
local meta = {
__newindex = function(self, key, value)
if usable_key[key] then
rawset(self, key, value)
else
error("error key: "..key)
end
end
};
meta.__index = meta
meta.__call = function()
return setmetatable({}, meta)
end
_M[name] = setmetatable(descriptor, meta);
end
make_descriptor("Descriptor", {}, {
name = true,
full_name = true,
filename = true,
containing_type = true,
fields = true,
nested_types = true,
enum_types = true,
extensions = true,
options = true,
is_extendable = true,
extension_ranges = true,
})
make_descriptor("FieldDescriptor", FieldDescriptor, {
name = true,
full_name = true,
index = true,
number = true,
type = true,
cpp_type = true,
label = true,
has_default_value = true,
default_value = true,
containing_type = true,
message_type = true,
enum_type = true,
is_extension = true,
extension_scope = true,
})
make_descriptor("EnumDescriptor", {}, {
name = true,
full_name = true,
values = true,
containing_type = true,
options = true
})
make_descriptor("EnumValueDescriptor", {}, {
name = true,
index = true,
number = true,
type = true,
options = true
})
-- Maps from field type to expected wiretype.
local FIELD_TYPE_TO_WIRE_TYPE = {
[FieldDescriptor.TYPE_DOUBLE] = wire_format.WIRETYPE_FIXED64,
[FieldDescriptor.TYPE_FLOAT] = wire_format.WIRETYPE_FIXED32,
[FieldDescriptor.TYPE_INT64] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_UINT64] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_INT32] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_FIXED64] = wire_format.WIRETYPE_FIXED64,
[FieldDescriptor.TYPE_FIXED32] = wire_format.WIRETYPE_FIXED32,
[FieldDescriptor.TYPE_BOOL] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_STRING] = wire_format.WIRETYPE_LENGTH_DELIMITED,
[FieldDescriptor.TYPE_GROUP] = wire_format.WIRETYPE_START_GROUP,
[FieldDescriptor.TYPE_MESSAGE] = wire_format.WIRETYPE_LENGTH_DELIMITED,
[FieldDescriptor.TYPE_BYTES] = wire_format.WIRETYPE_LENGTH_DELIMITED,
[FieldDescriptor.TYPE_UINT32] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_ENUM] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_SFIXED32] = wire_format.WIRETYPE_FIXED32,
[FieldDescriptor.TYPE_SFIXED64] = wire_format.WIRETYPE_FIXED64,
[FieldDescriptor.TYPE_SINT32] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_SINT64] = wire_format.WIRETYPE_VARINT
}
local NON_PACKABLE_TYPES = {
[FieldDescriptor.TYPE_STRING] = true,
[FieldDescriptor.TYPE_GROUP] = true,
[FieldDescriptor.TYPE_MESSAGE] = true,
[FieldDescriptor.TYPE_BYTES] = true
}
local _VALUE_CHECKERS = {
[FieldDescriptor.CPPTYPE_INT32] = type_checkers.Int32ValueChecker(),
[FieldDescriptor.CPPTYPE_INT64] = type_checkers.TypeChecker({string = true, number = true}),
[FieldDescriptor.CPPTYPE_UINT32] = type_checkers.Uint32ValueChecker(),
[FieldDescriptor.CPPTYPE_UINT64] = type_checkers.TypeChecker({string = true, number = true}),
[FieldDescriptor.CPPTYPE_DOUBLE] = type_checkers.TypeChecker({number = true}),
[FieldDescriptor.CPPTYPE_FLOAT] = type_checkers.TypeChecker({number = true}),
[FieldDescriptor.CPPTYPE_BOOL] = type_checkers.TypeChecker({boolean = true, bool = true, int=true}),
[FieldDescriptor.CPPTYPE_ENUM] = type_checkers.Int32ValueChecker(),
[FieldDescriptor.CPPTYPE_STRING] = type_checkers.TypeChecker({string = true})
}
local TYPE_TO_BYTE_SIZE_FN = {
[FieldDescriptor.TYPE_DOUBLE] = wire_format.DoubleByteSize,
[FieldDescriptor.TYPE_FLOAT] = wire_format.FloatByteSize,
[FieldDescriptor.TYPE_INT64] = wire_format.Int64ByteSize,
[FieldDescriptor.TYPE_UINT64] = wire_format.UInt64ByteSize,
[FieldDescriptor.TYPE_INT32] = wire_format.Int32ByteSize,
[FieldDescriptor.TYPE_FIXED64] = wire_format.Fixed64ByteSize,
[FieldDescriptor.TYPE_FIXED32] = wire_format.Fixed32ByteSize,
[FieldDescriptor.TYPE_BOOL] = wire_format.BoolByteSize,
[FieldDescriptor.TYPE_STRING] = wire_format.StringByteSize,
[FieldDescriptor.TYPE_GROUP] = wire_format.GroupByteSize,
[FieldDescriptor.TYPE_MESSAGE] = wire_format.MessageByteSize,
[FieldDescriptor.TYPE_BYTES] = wire_format.BytesByteSize,
[FieldDescriptor.TYPE_UINT32] = wire_format.UInt32ByteSize,
[FieldDescriptor.TYPE_ENUM] = wire_format.EnumByteSize,
[FieldDescriptor.TYPE_SFIXED32] = wire_format.SFixed32ByteSize,
[FieldDescriptor.TYPE_SFIXED64] = wire_format.SFixed64ByteSize,
[FieldDescriptor.TYPE_SINT32] = wire_format.SInt32ByteSize,
[FieldDescriptor.TYPE_SINT64] = wire_format.SInt64ByteSize
}
local TYPE_TO_ENCODER = {
[FieldDescriptor.TYPE_DOUBLE] = encoder.DoubleEncoder,
[FieldDescriptor.TYPE_FLOAT] = encoder.FloatEncoder,
[FieldDescriptor.TYPE_INT64] = encoder.Int64Encoder,
[FieldDescriptor.TYPE_UINT64] = encoder.UInt64Encoder,
[FieldDescriptor.TYPE_INT32] = encoder.Int32Encoder,
[FieldDescriptor.TYPE_FIXED64] = encoder.Fixed64Encoder,
[FieldDescriptor.TYPE_FIXED32] = encoder.Fixed32Encoder,
[FieldDescriptor.TYPE_BOOL] = encoder.BoolEncoder,
[FieldDescriptor.TYPE_STRING] = encoder.StringEncoder,
[FieldDescriptor.TYPE_GROUP] = encoder.GroupEncoder,
[FieldDescriptor.TYPE_MESSAGE] = encoder.MessageEncoder,
[FieldDescriptor.TYPE_BYTES] = encoder.BytesEncoder,
[FieldDescriptor.TYPE_UINT32] = encoder.UInt32Encoder,
[FieldDescriptor.TYPE_ENUM] = encoder.EnumEncoder,
[FieldDescriptor.TYPE_SFIXED32] = encoder.SFixed32Encoder,
[FieldDescriptor.TYPE_SFIXED64] = encoder.SFixed64Encoder,
[FieldDescriptor.TYPE_SINT32] = encoder.SInt32Encoder,
[FieldDescriptor.TYPE_SINT64] = encoder.SInt64Encoder
}
local TYPE_TO_SIZER = {
[FieldDescriptor.TYPE_DOUBLE] = encoder.DoubleSizer,
[FieldDescriptor.TYPE_FLOAT] = encoder.FloatSizer,
[FieldDescriptor.TYPE_INT64] = encoder.Int64Sizer,
[FieldDescriptor.TYPE_UINT64] = encoder.UInt64Sizer,
[FieldDescriptor.TYPE_INT32] = encoder.Int32Sizer,
[FieldDescriptor.TYPE_FIXED64] = encoder.Fixed64Sizer,
[FieldDescriptor.TYPE_FIXED32] = encoder.Fixed32Sizer,
[FieldDescriptor.TYPE_BOOL] = encoder.BoolSizer,
[FieldDescriptor.TYPE_STRING] = encoder.StringSizer,
[FieldDescriptor.TYPE_GROUP] = encoder.GroupSizer,
[FieldDescriptor.TYPE_MESSAGE] = encoder.MessageSizer,
[FieldDescriptor.TYPE_BYTES] = encoder.BytesSizer,
[FieldDescriptor.TYPE_UINT32] = encoder.UInt32Sizer,
[FieldDescriptor.TYPE_ENUM] = encoder.EnumSizer,
[FieldDescriptor.TYPE_SFIXED32] = encoder.SFixed32Sizer,
[FieldDescriptor.TYPE_SFIXED64] = encoder.SFixed64Sizer,
[FieldDescriptor.TYPE_SINT32] = encoder.SInt32Sizer,
[FieldDescriptor.TYPE_SINT64] = encoder.SInt64Sizer
}
local TYPE_TO_DECODER = {
[FieldDescriptor.TYPE_DOUBLE] = decoder.DoubleDecoder,
[FieldDescriptor.TYPE_FLOAT] = decoder.FloatDecoder,
[FieldDescriptor.TYPE_INT64] = decoder.Int64Decoder,
[FieldDescriptor.TYPE_UINT64] = decoder.UInt64Decoder,
[FieldDescriptor.TYPE_INT32] = decoder.Int32Decoder,
[FieldDescriptor.TYPE_FIXED64] = decoder.Fixed64Decoder,
[FieldDescriptor.TYPE_FIXED32] = decoder.Fixed32Decoder,
[FieldDescriptor.TYPE_BOOL] = decoder.BoolDecoder,
[FieldDescriptor.TYPE_STRING] = decoder.StringDecoder,
[FieldDescriptor.TYPE_GROUP] = decoder.GroupDecoder,
[FieldDescriptor.TYPE_MESSAGE] = decoder.MessageDecoder,
[FieldDescriptor.TYPE_BYTES] = decoder.BytesDecoder,
[FieldDescriptor.TYPE_UINT32] = decoder.UInt32Decoder,
[FieldDescriptor.TYPE_ENUM] = decoder.EnumDecoder,
[FieldDescriptor.TYPE_SFIXED32] = decoder.SFixed32Decoder,
[FieldDescriptor.TYPE_SFIXED64] = decoder.SFixed64Decoder,
[FieldDescriptor.TYPE_SINT32] = decoder.SInt32Decoder,
[FieldDescriptor.TYPE_SINT64] = decoder.SInt64Decoder
}
local FIELD_TYPE_TO_WIRE_TYPE = {
[FieldDescriptor.TYPE_DOUBLE] = wire_format.WIRETYPE_FIXED64,
[FieldDescriptor.TYPE_FLOAT] = wire_format.WIRETYPE_FIXED32,
[FieldDescriptor.TYPE_INT64] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_UINT64] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_INT32] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_FIXED64] = wire_format.WIRETYPE_FIXED64,
[FieldDescriptor.TYPE_FIXED32] = wire_format.WIRETYPE_FIXED32,
[FieldDescriptor.TYPE_BOOL] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_STRING] = wire_format.WIRETYPE_LENGTH_DELIMITED,
[FieldDescriptor.TYPE_GROUP] = wire_format.WIRETYPE_START_GROUP,
[FieldDescriptor.TYPE_MESSAGE] = wire_format.WIRETYPE_LENGTH_DELIMITED,
[FieldDescriptor.TYPE_BYTES] = wire_format.WIRETYPE_LENGTH_DELIMITED,
[FieldDescriptor.TYPE_UINT32] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_ENUM] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_SFIXED32] = wire_format.WIRETYPE_FIXED32,
[FieldDescriptor.TYPE_SFIXED64] = wire_format.WIRETYPE_FIXED64,
[FieldDescriptor.TYPE_SINT32] = wire_format.WIRETYPE_VARINT,
[FieldDescriptor.TYPE_SINT64] = wire_format.WIRETYPE_VARINT
}
local function IsTypePackable(field_type)
return NON_PACKABLE_TYPES[field_type] == nil
end
local function GetTypeChecker(cpp_type, field_type)
if (cpp_type == FieldDescriptor.CPPTYPE_STRING and field_type == FieldDescriptor.TYPE_STRING) then
return type_checkers.UnicodeValueChecker()
end
return _VALUE_CHECKERS[cpp_type]
end
local function _DefaultValueConstructorForField(field)
if field.label == FieldDescriptor.LABEL_REPEATED then
if type(field.default_value) ~= "table" or #(field.default_value) ~= 0 then
error('Repeated field default value not empty list:' .. tostring(field.default_value))
end
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
local message_type = field.message_type
return function (message)
return containers.RepeatedCompositeFieldContainer(message._listener_for_children, message_type)
end
else
local type_checker = GetTypeChecker(field.cpp_type, field.type)
return function (message)
return containers.RepeatedScalarFieldContainer(message._listener_for_children, type_checker)
end
end
end
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
local message_type = field.message_type
return function (message)
result = message_type._concrete_class()
result._SetListener(message._listener_for_children)
return result
end
end
return function (message)
return field.default_value
end
end
local function _AttachFieldHelpers(message_meta, field_descriptor)
local is_repeated = (field_descriptor.label == FieldDescriptor.LABEL_REPEATED)
local is_packed = (field_descriptor.has_options and field_descriptor.GetOptions().packed)
rawset(field_descriptor, "_encoder", TYPE_TO_ENCODER[field_descriptor.type](field_descriptor.number, is_repeated, is_packed))
rawset(field_descriptor, "_sizer", TYPE_TO_SIZER[field_descriptor.type](field_descriptor.number, is_repeated, is_packed))
rawset(field_descriptor, "_default_constructor", _DefaultValueConstructorForField(field_descriptor))
local AddDecoder = function(wiretype, is_packed)
local tag_bytes = encoder.TagBytes(field_descriptor.number, wiretype)
message_meta._decoders_by_tag[tag_bytes] = TYPE_TO_DECODER[field_descriptor.type](field_descriptor.number, is_repeated, is_packed, field_descriptor, field_descriptor._default_constructor)
end
AddDecoder(FIELD_TYPE_TO_WIRE_TYPE[field_descriptor.type], False)
if is_repeated and IsTypePackable(field_descriptor.type) then
AddDecoder(wire_format.WIRETYPE_LENGTH_DELIMITED, True)
end
end
local function _AddEnumValues(descriptor, message_meta)
for _, enum_type in ipairs(descriptor.enum_types) do
for _, enum_value in ipairs(enum_type.values) do
message_meta._member[enum_value.name] = enum_value.number
end
end
end
local function _InitMethod(message_meta)
return function()
local self = {}
self._cached_byte_size = 0
self._cached_byte_size_dirty = false
self._fields = {}
self._is_present_in_parent = false
self._listener = listener_mod.NullMessageListener()
self._listener_for_children = listener_mod.Listener(self)
return setmetatable(self, message_meta)
end
end
local function _AddPropertiesForRepeatedField(field, message_meta)
local property_name = field.name
message_meta._getter[property_name] = function(self)
local field_value = self._fields[field]
if field_value == nil then
field_value = field._default_constructor(self)
self._fields[field] = field_value
if not self._cached_byte_size_dirty then
message_meta._member._Modified(self)
end
end
return field_value
end
message_meta._setter[property_name] = function(self)
error('Assignment not allowed to repeated field "' .. property_name .. '" in protocol message object.')
end
end
local function _AddPropertiesForNonRepeatedCompositeField(field, message_meta)
local property_name = field.name
local message_type = field.message_type
message_meta._getter[property_name] = function(self)
local field_value = self._fields[field]
if field_value == nil then
field_value = message_type._concrete_class()
field_value:_SetListener(self._listener_for_children)
self._fields[field] = field_value
if not self._cached_byte_size_dirty then
message_meta._member._Modified(self)
end
end
return field_value
end
message_meta._setter[property_name] = function(self, new_value)
error('Assignment not allowed to composite field' .. property_name .. 'in protocol message object.' )
end
end
local function _AddPropertiesForNonRepeatedScalarField(field, message)
local property_name = field.name
local type_checker = GetTypeChecker(field.cpp_type, field.type)
local default_value = field.default_value
message._getter[property_name] = function(self)
local value = self._fields[field]
if value ~= nil then
return self._fields[field]
else
return default_value
end
end
message._setter[property_name] = function(self, new_value)
type_checker(new_value)
self._fields[field] = new_value
if not self._cached_byte_size_dirty then
message._member._Modified(self)
end
end
end
local function _AddPropertiesForField(field, message_meta)
constant_name = field.name:upper() .. "_FIELD_NUMBER"
message_meta._member[constant_name] = field.number
if field.label == FieldDescriptor.LABEL_REPEATED then
_AddPropertiesForRepeatedField(field, message_meta)
elseif field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
_AddPropertiesForNonRepeatedCompositeField(field, message_meta)
else
_AddPropertiesForNonRepeatedScalarField(field, message_meta)
end
end
local _ED_meta = {
__index = function(self, extension_handle)
local _extended_message = rawget(self, "_extended_message")
local value = _extended_message._fields[extension_handle]
if value ~= nil then
return value
end
if extension_handle.label == FieldDescriptor.LABEL_REPEATED then
value = extension_handle._default_constructor(self._extended_message)
elseif extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
value = extension_handle.message_type._concrete_class()
value:_SetListener(_extended_message._listener_for_children)
else
return extension_handle.default_value
end
_extended_message._fields[extension_handle] = value
return value
end,
__newindex = function(self, extension_handle, value)
local _extended_message = rawget(self, "_extended_message")
if (extension_handle.label == FieldDescriptor.LABEL_REPEATED or
extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE) then
error('Cannot assign to extension "'.. extension_handle.full_name .. '" because it is a repeated or composite type.')
end
local type_checker = GetTypeChecker(extension_handle.cpp_type, extension_handle.type)
type_checker.CheckValue(value)
_extended_message._fields[extension_handle] = value
_extended_message._Modified()
end
}
local function _ExtensionDict(message)
local o = {}
o._extended_message = message
return setmetatable(o, _ED_meta)
end
local function _AddPropertiesForFields(descriptor, message_meta)
for _, field in ipairs(descriptor.fields) do
_AddPropertiesForField(field, message_meta)
end
if descriptor.is_extendable then
message_meta._getter.Extensions = function(self) return _ExtensionDict(self) end
end
end
local function _AddPropertiesForExtensions(descriptor, message_meta)
local extension_dict = descriptor._extensions_by_name
for extension_name, extension_field in pairs(extension_dict) do
local constant_name = string.upper(extension_name) .. "_FIELD_NUMBER"
message_meta._member[constant_name] = extension_field.number
end
end
local function _AddStaticMethods(message_meta)
message_meta._member.RegisterExtension = function(extension_handle)
extension_handle.containing_type = message_meta._descriptor
_AttachFieldHelpers(message_meta, extension_handle)
if message_meta._extensions_by_number[extension_handle.number] == nil then
message_meta._extensions_by_number[extension_handle.number] = extension_handle
else
error(
string.format('Extensions "%s" and "%s" both try to extend message type "%s" with field number %d.',
extension_handle.full_name, actual_handle.full_name,
message_meta._descriptor.full_name, extension_handle.number))
end
message_meta._extensions_by_name[extension_handle.full_name] = extension_handle
end
message_meta._member.FromString = function(s)
local message = message_meta._member.__call()
message.MergeFromString(s)
return message
end
end
local function _IsPresent(descriptor, value)
if descriptor.label == FieldDescriptor.LABEL_REPEATED then
return value
elseif descriptor.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
return value._is_present_in_parent
else
return true
end
end
function sortFunc(a, b)
return a.index < b.index
end
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
local function _AddListFieldsMethod(message_descriptor, message_meta)
message_meta._member.ListFields = function (self)
local list_field = function(fields)
--local f, s, v = pairs(self._fields)
local f,s,v = pairsByKeys(self._fields, sortFunc)
local iter = function(a, i)
while true do
local descriptor, value = f(a, i)
if descriptor == nil then
return
elseif _IsPresent(descriptor, value) then
return descriptor, value
end
end
end
return iter, s, v
end
return list_field(self._fields)
end
end
local function _AddHasFieldMethod(message_descriptor, message_meta)
local singular_fields = {}
for _, field in ipairs(message_descriptor.fields) do
if field.label ~= FieldDescriptor.LABEL_REPEATED then
singular_fields[field.name] = field
end
end
message_meta._member.HasField = function (self, field_name)
field = singular_fields[field_name]
if field == nil then
error('Protocol message has no singular "'.. field_name.. '" field.')
end
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
value = self._fields[field]
return value ~= nil and value._is_present_in_parent
else
local valueTmp = self._fields[field]
return valueTmp ~= nil
end
end
end
local function _AddClearFieldMethod(message_descriptor, message_meta)
local singular_fields = {}
for _, field in ipairs(message_descriptor.fields) do
if field.label ~= FieldDescriptor.LABEL_REPEATED then
singular_fields[field.name] = field
end
end
message_meta._member.ClearField = function(self, field_name)
field = singular_fields[field_name]
if field == nil then
error('Protocol message has no singular "'.. field_name.. '" field.')
end
if self._fields[field] then
self._fields[field] = nil
end
message_meta._member._Modified(self)
end
end
local function _AddClearExtensionMethod(message_meta)
message_meta._member.ClearExtension = function(self, extension_handle)
if self._fields[extension_handle] == nil then
self._fields[extension_handle] = nil
end
message_meta._member._Modified(self)
end
end
local function _AddClearMethod(message_descriptor, message_meta)
message_meta._member.Clear = function(self)
self._fields = {}
message_meta._member._Modified(self)
end
end
local function _AddStrMethod(message_meta)
local format = text_format.msg_format
message_meta.__tostring = function(self)
return format(self)
end
end
local function _AddHasExtensionMethod(message_meta)
message_meta._member.HasExtension = function(self, extension_handle)
if extension_handle.label == FieldDescriptor.LABEL_REPEATED then
error(extension_handle.full_name .. ' is repeated.')
end
if extension_handle.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
value = self._fields[extension_handle]
return value ~= nil and value._is_present_in_parent
else
return self._fields[extension_handle]
end
end
end
local function _AddSetListenerMethod(message_meta)
message_meta._member._SetListener = function(self, listener)
if listener ~= nil then
self._listener = listener_mod.NullMessageListener()
else
self._listener = listener
end
end
end
local function _AddByteSizeMethod(message_descriptor, message_meta)
message_meta._member.ByteSize = function(self)
--kaiser
--bug:这里在Repeat字段的结构体如果第一个字段不是int变量会产生_cached_byte_size_dirty为false而导致byte size为0
--如果bytesize为0让它强制计算byte size
if not self._cached_byte_size_dirty and self._cached_byte_size > 0 then
return self._cached_byte_size
end
local size = 0
for field_descriptor, field_value in message_meta._member.ListFields(self) do
size = field_descriptor._sizer(field_value) + size
end
self._cached_byte_size = size
self._cached_byte_size_dirty = false
self._listener_for_children.dirty = false
return size
end
end
local function _AddSerializeToStringMethod(message_descriptor, message_meta)
message_meta._member.SerializeToString = function(self)
if not message_meta._member.IsInitialized(self) then
error('Message is missing required fields: ' ..
table.concat(message_meta._member.FindInitializationErrors(self), ','))
end
return message_meta._member.SerializePartialToString(self)
end
message_meta._member.SerializeToIOString = function(self, iostring)
if not message_meta._member.IsInitialized(self) then
error('Message is missing required fields: ' ..
table.concat(message_meta._member.FindInitializationErrors(self), ','))
end
return message_meta._member.SerializePartialToIOString(self, iostring)
end
end
local function _AddSerializePartialToStringMethod(message_descriptor, message_meta)
local concat = table.concat
local _internal_serialize = function(self, write_bytes)
for field_descriptor, field_value in message_meta._member.ListFields(self) do
field_descriptor._encoder(write_bytes, field_value)
end
end
local _serialize_partial_to_iostring = function(self, iostring)
local w = iostring.write
local write = function(value)
w(iostring, value)
end
_internal_serialize(self, write)
return
end
local _serialize_partial_to_string = function(self)
local out = {}
local write = function(value)
out[#out + 1] = value
end
_internal_serialize(self, write)
return concat(out)
end
message_meta._member._InternalSerialize = _internal_serialize
message_meta._member.SerializePartialToIOString = _serialize_partial_to_iostring
message_meta._member.SerializePartialToString = _serialize_partial_to_string
end
local function _AddMergeFromStringMethod(message_descriptor, message_meta)
local ReadTag = decoder.ReadTag
local SkipField = decoder.SkipField
local decoders_by_tag = message_meta._decoders_by_tag
local _internal_parse = function(self, buffer, pos, pend)
message_meta._member._Modified(self)
local field_dict = self._fields
local tag_bytes, new_pos
local field_decoder
while pos ~= pend do
tag_bytes, new_pos = ReadTag(buffer, pos)
field_decoder = decoders_by_tag[tag_bytes]
if field_decoder == nil then
new_pos = SkipField(buffer, new_pos, pend, tag_bytes)
if new_pos == -1 then
return pos
end
pos = new_pos
else
pos = field_decoder(buffer, new_pos, pend, self, field_dict)
end
end
return pos
end
message_meta._member._InternalParse = _internal_parse
local merge_from_string = function(self, serialized)
local length = #serialized
if _internal_parse(self, serialized, 0, length) ~= length then
error('Unexpected end-group tag.')
end
return length
end
message_meta._member.MergeFromString = merge_from_string
message_meta._member.ParseFromString = function(self, serialized)
message_meta._member.Clear(self)
merge_from_string(self, serialized)
end
end
local function _AddIsInitializedMethod(message_descriptor, message_meta)
local required_fields = {}
for _, field in ipairs(message_descriptor.fields) do
if field.label == FieldDescriptor.LABEL_REQUIRED then
required_fields[#required_fields + 1] = field
end
end
message_meta._member.IsInitialized = function(self, errors)
for _, field in ipairs(required_fields) do
if self._fields[field] == nil or
(field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE and not self._fields[field]._is_present_in_parent) then
if errors ~= nil then
errors[#errors + 1] = message_meta._member.FindInitializationErrors(self)
end
return false
end
end
for field, value in pairs(self._fields) do
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
if field.label == FieldDescriptor.LABEL_REPEATED then
for _, element in ipairs(value) do
if not element:IsInitialized() then
if errors ~= nil then
errors[#errors + 1] = message_meta._member.FindInitializationErrors(self)
end
return false
end
end
elseif value._is_present_in_parent and not value:IsInitialized() then
if errors ~= nil then
errors[#errors + 1] = message_meta._member.FindInitializationErrors(self)
end
return false
end
end
end
return true
end
message_meta._member.FindInitializationErrors = function(self)
local errors = {}
for _,field in ipairs(required_fields) do
if not message_meta._member.HasField(self, field.name) then
errors.append(field.name)
end
end
for field, value in message_meta._member.ListFields(self) do
if field.cpp_type == FieldDescriptor.CPPTYPE_MESSAGE then
if field.is_extension then
name = io:format("(%s)", field.full_name)
else
name = field.name
end
if field.label == FieldDescriptor.LABEL_REPEATED then
for i, element in ipairs(value) do
prefix = io:format("%s[%d].", name, i)
sub_errors = element:FindInitializationErrors()
for _, e in ipairs(sub_errors) do
errors[#errors + 1] = prefix .. e
end
end
else
prefix = name .. "."
sub_errors = value:FindInitializationErrors()
for _, e in ipairs(sub_errors) do
errors[#errors + 1] = prefix .. e
end
end
end
end
return errors
end
end
local function _AddMergeFromMethod(message_meta)
local LABEL_REPEATED = FieldDescriptor.LABEL_REPEATED
local CPPTYPE_MESSAGE = FieldDescriptor.CPPTYPE_MESSAGE
message_meta._member.MergeFrom = function (self, msg)
assert(msg ~= self)
message_meta._member._Modified(self)
local fields = self._fields
for field, value in pairs(msg._fields) do
if field.label == LABEL_REPEATED or field.cpp_type == CPPTYPE_MESSAGE then
field_value = fields[field]
if field_value == nil then
field_value = field._default_constructor(self)
fields[field] = field_value
end
field_value:MergeFrom(value)
else
self._fields[field] = value
end
end
end
end
local function _AddMessageMethods(message_descriptor, message_meta)
_AddListFieldsMethod(message_descriptor, message_meta)
_AddHasFieldMethod(message_descriptor, message_meta)
_AddClearFieldMethod(message_descriptor, message_meta)
if message_descriptor.is_extendable then
_AddClearExtensionMethod(message_meta)
_AddHasExtensionMethod(message_meta)
end
_AddClearMethod(message_descriptor, message_meta)
-- _AddEqualsMethod(message_descriptor, message_meta)
_AddStrMethod(message_meta)
_AddSetListenerMethod(message_meta)
_AddByteSizeMethod(message_descriptor, message_meta)
_AddSerializeToStringMethod(message_descriptor, message_meta)
_AddSerializePartialToStringMethod(message_descriptor, message_meta)
_AddMergeFromStringMethod(message_descriptor, message_meta)
_AddIsInitializedMethod(message_descriptor, message_meta)
_AddMergeFromMethod(message_meta)
end
local function _AddPrivateHelperMethods(message_meta)
local Modified = function (self)
if not self._cached_byte_size_dirty then
self._cached_byte_size_dirty = true
self._listener_for_children.dirty = true
self._is_present_in_parent = true
self._listener:Modified()
end
end
message_meta._member._Modified = Modified
message_meta._member.SetInParent = Modified
end
local function property_getter(message_meta)
local getter = message_meta._getter
local member = message_meta._member
return function (self, property)
local g = getter[property]
if g then
return g(self)
else
return member[property]
end
end
end
local function property_setter(message_meta)
local setter = message_meta._setter
return function (self, property, value)
local s = setter[property]
if s then
s(self, value)
else
error(property .. " not found")
end
end
end
function _AddClassAttributesForNestedExtensions(descriptor, message_meta)
local extension_dict = descriptor._extensions_by_name
for extension_name, extension_field in pairs(extension_dict) do
message_meta._member[extension_name] = extension_field
end
end
local function Message(descriptor)
local message_meta = {}
message_meta._decoders_by_tag = {}
rawset(descriptor, "_extensions_by_name", {})
for _, k in ipairs(descriptor.extensions) do
descriptor._extensions_by_name[k.name] = k
end
rawset(descriptor, "_extensions_by_number", {})
for _, k in ipairs(descriptor.extensions) do
descriptor._extensions_by_number[k.number] = k
end
message_meta._descriptor = descriptor
message_meta._extensions_by_name = {}
message_meta._extensions_by_number = {}
message_meta._getter = {}
message_meta._setter = {}
message_meta._member = {}
-- message_meta._name = descriptor.full_name
local ns = setmetatable({}, message_meta._member)
message_meta._member.__call = _InitMethod(message_meta)
message_meta._member.__index = message_meta._member
message_meta._member.type = ns
if rawget(descriptor, "_concrete_class") == nil then
rawset(descriptor, "_concrete_class", ns)
for k, field in ipairs(descriptor.fields) do
_AttachFieldHelpers(message_meta, field)
end
end
_AddEnumValues(descriptor, message_meta)
_AddClassAttributesForNestedExtensions(descriptor, message_meta)
_AddPropertiesForFields(descriptor, message_meta)
_AddPropertiesForExtensions(descriptor, message_meta)
_AddStaticMethods(message_meta)
_AddMessageMethods(descriptor, message_meta)
_AddPrivateHelperMethods(message_meta)
message_meta.__index = property_getter(message_meta)
message_meta.__newindex = property_setter(message_meta)
return ns
end
_M.Message = Message
| mit |
waytim/darkstar | scripts/globals/spells/bluemagic/eyes_on_me.lua | 31 | 1587 | -----------------------------------------
-- Spell: Eyes On Me
-- Deals dark damage to an enemy
-- Spell cost: 112 MP
-- Monster Type: Demons
-- Spell Type: Magical (Dark)
-- Blue Magic Points: 4
-- Stat Bonus: HP-5, MP+15
-- Level: 61
-- Casting Time: 4.5 seconds
-- Recast Time: 29.25 seconds
-- Magic Bursts on: Compression, Gravitation, Darkness
-- Combos: Magic Attack Bonus
-----------------------------------------
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.625;
if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then
multi = multi + 2.0;
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.0;
params.chr_wsc = 0.2;
damage = BlueMagicalSpell(caster, target, spell, params, CHR_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
erfan1292/sezar2 | libs/lua-redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| gpl-2.0 |
TienHP/Aquaria | files/scripts/entities/seaturtlesmall.lua | 6 | 1143 | -- 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
-- ================================================================================================
-- S M A L L S E A T U R T L E
-- ================================================================================================
dofile("scripts/entities/seaturtlecommon.lua")
function init(me)
v.commonInit(me, 1)
end
| gpl-2.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c56540009.lua | 2 | 1782 | --Loli Mamourou
function c56540009.initial_effect(c)
c:SetSPSummonOnce(56540009)
aux.AddSynchroProcedure2(c,nil,aux.NonTuner(nil))
c:EnableReviveLimit()
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(56540009,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetRange(LOCATION_EXTRA)
e1:SetCode(EVENT_DAMAGE)
e1:SetCountLimit(1,56540009+EFFECT_COUNT_CODE_DUEL)
e1:SetCondition(c56540009.surcon)
e1:SetTarget(c56540009.sptg)
e1:SetOperation(c56540009.spop)
c:RegisterEffect(e1)
end
function c56540009.surcon(e,tp,eg,ep,ev,re,r,rp)
return ep==tp and Duel.GetLP(tp)<=0
end
function c56540009.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
-- and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c56540009.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local g=Duel.GetMatchingGroup(aux.TRUE,tp,0,LOCATION_ONFIELD,e:GetHandler())
Duel.SendtoGrave(g,REASON_EFFECT)
--Duel.SetChainLimit(aux.FALSE)
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
Duel.SetLP(tp,2000)
Duel.SkipPhase(1-tp,PHASE_DRAW,RESET_PHASE+PHASE_END,1)
Duel.SkipPhase(1-tp,PHASE_STANDBY,RESET_PHASE+PHASE_END,1)
Duel.SkipPhase(1-tp,PHASE_MAIN1,RESET_PHASE+PHASE_END,1)
Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_END,1,1)
Duel.SkipPhase(1-tp,PHASE_MAIN2,RESET_PHASE+PHASE_END,1)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_BP)
e1:SetTargetRange(0,1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c38709246.lua | 2 | 1152 | --Singing Passion of Vocaloids
function c38709246.initial_effect(c)
c:SetUniqueOnField(1,0,38709246)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--extra summon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_HAND+LOCATION_MZONE,0)
e2:SetCode(EFFECT_EXTRA_SUMMON_COUNT)
e2:SetTarget(aux.TargetBoolFunction(c38709246.extratarget))
c:RegisterEffect(e2)
--atk up
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetRange(LOCATION_SZONE)
e3:SetTargetRange(LOCATION_MZONE,0)
e3:SetTarget(c38709246.atktg)
e3:SetValue(c38709246.atkval)
c:RegisterEffect(e3)
end
function c38709246.atktg(e,c)
return c:IsRace(RACE_MACHINE)
end
function c38709246.atkfilter(c)
return c:IsFaceup() and c:IsType(TYPE_SYNCHRO)
end
function c38709246.atkval(e,c)
return Duel.GetMatchingGroupCount(c38709246.atkfilter,c:GetControler(),LOCATION_MZONE,0,nil)*100
end
function c38709246.extratarget(c)
return c:IsType(TYPE_TUNER) and c:IsSetCard(0x0dac405)
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c20912271.lua | 2 | 2162 | --Rank-Up-Magic The Emperor's Force
function c20912271.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,20912271)
e1:SetTarget(c20912271.target)
e1:SetOperation(c20912271.activate)
c:RegisterEffect(e1)
end
function c20912271.filter1(c,e,tp)
local rk=c:GetRank()
return c:IsFaceup() and c:IsSetCard(0xd0a2) and c:IsType(TYPE_XYZ) and not c:IsCode(20912272)
and Duel.IsExistingMatchingCard(c20912271.filter2,tp,LOCATION_EXTRA,0,1,nil,e,tp,c,rk+1,c:GetCode())
end
function c20912271.filter2(c,e,tp,mc,rk,code)
if c.rum_limit_code and code~=c.rum_limit_code then return false end
return c:GetRank()==rk and (c:IsSetCard(0xd0a2)) and mc:IsCanBeXyzMaterial(c)
and c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_XYZ,tp,false,false)
end
function c20912271.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and c20912271.filter1(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingTarget(c20912271.filter1,tp,LOCATION_MZONE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c20912271.filter1,tp,LOCATION_MZONE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c20912271.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsFacedown() or not tc:IsRelateToEffect(e) or tc:IsControler(1-tp) or tc:IsImmuneToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c20912271.filter2,tp,LOCATION_EXTRA,0,1,1,nil,e,tp,tc,tc:GetRank()+1,tc:GetCode())
local sc=g:GetFirst()
if sc then
local mg=tc:GetOverlayGroup()
if mg:GetCount()~=0 then
Duel.Overlay(sc,mg)
end
sc:SetMaterial(Group.FromCards(tc))
Duel.Overlay(sc,Group.FromCards(tc))
Duel.SpecialSummon(sc,SUMMON_TYPE_XYZ,tp,tp,false,false,POS_FACEUP)
sc:CompleteProcedure()
end
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99970541.lua | 2 | 3271 | --DAL - Diva
function c99970541.initial_effect(c)
--Cannot Special Summon
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c99970541.splimit)
c:RegisterEffect(e1)
--To Hand
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e2:SetTarget(c99970541.thtg)
e2:SetOperation(c99970541.thop)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
local e4=e2:Clone()
e4:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
c:RegisterEffect(e4)
--ATK UP/Down
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(99970541,0))
e5:SetType(EFFECT_TYPE_IGNITION)
e5:SetRange(LOCATION_MZONE)
e5:SetCountLimit(1)
e5:SetCondition(c99970541.atkcon)
e5:SetOperation(c99970541.atkop)
c:RegisterEffect(e5)
end
function c99970541.splimit(e,se,sp,st)
return se:GetHandler():IsSetCard(9997)
end
function c99970541.thfilter(c)
return c:IsSetCard(9997) and c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsAbleToHand()
end
function c99970541.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c99970541.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c99970541.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c99970541.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
function c99970541.atkfilter(c)
return c:IsFaceup() and c:IsSetCard(9997) and c:IsType(TYPE_MONSTER)
end
function c99970541.atkcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c99970541.atkfilter,tp,LOCATION_MZONE,0,1,nil)
and Duel.IsExistingMatchingCard(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil)
end
function c99970541.atkop(e,tp,eg,ep,ev,re,r,rp)
local ct=Duel.GetMatchingGroupCount(c99970541.atkfilter,tp,LOCATION_MZONE,0,nil)
local g1=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
local tc1=g1:GetFirst()
while tc1 do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
e1:SetValue(-ct*200)
tc1:RegisterEffect(e1)
tc1=g1:GetNext()
end
local g2=Duel.GetMatchingGroup(c99970541.atkfilter,tp,LOCATION_MZONE,0,nil)
local tc2=g2:GetFirst()
while tc2 do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(ct*200)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc2:RegisterEffect(e1)
tc2=g2:GetNext()
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(100)
e1:SetReset(RESET_EVENT+0x1fe0000)
e:GetHandler():RegisterEffect(e1)
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c1392004.lua | 2 | 2044 | --Shadowbrave - Conroe
function c1392004.initial_effect(c)
--Special Summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(1392004,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetRange(LOCATION_HAND+LOCATION_GRAVE)
e1:SetCountLimit(1,1392004)
e1:SetCondition(c1392004.spcon)
e1:SetTarget(c1392004.sptg)
e1:SetOperation(c1392004.spop)
c:RegisterEffect(e1)
--Gain Effect
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_BE_MATERIAL)
e2:SetCondition(c1392004.efcon)
e2:SetOperation(c1392004.efop)
c:RegisterEffect(e2)
end
function c1392004.cfilter(c,tp,code)
return c:IsSetCard(0x920) and c:GetCode()~=code and c:IsPreviousLocation(LOCATION_MZONE) and c:GetPreviousControler()==tp
end
function c1392004.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c1392004.cfilter,1,nil,tp,e:GetHandler():GetCode())
end
function c1392004.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 c1392004.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function c1392004.efcon(e,tp,eg,ep,ev,re,r,rp)
return r==REASON_SYNCHRO
end
function c1392004.efop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local rc=c:GetReasonCard()
local e1=Effect.CreateEffect(rc)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(aux.tgval)
e1:SetReset(RESET_EVENT+0x1fe0000)
rc:RegisterEffect(e1,true)
if not rc:IsType(TYPE_EFFECT) then
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_ADD_TYPE)
e2:SetValue(TYPE_EFFECT)
e2:SetReset(RESET_EVENT+0x1fe0000)
rc:RegisterEffect(e2,true)
end
end | gpl-3.0 |
MAXrobotTelegram/teleseed | plugins/filter.lua | 6 | 3623 | local function save_filter(msg, name, value)
local hash = nil
if msg.to.type == 'channel' then
hash = 'chat:'..msg.to.id..':filters'
end
if msg.to.type == 'user' then
return 'SUPERGROUPS only'
end
if hash then
redis:hset(hash, name, value)
return "Successfull!"
end
end
local function get_filter_hash(msg)
if msg.to.type == 'channel' then
return 'chat:'..msg.to.id..':filters'
end
end
local function list_filter(msg)
if msg.to.type == 'user' then
return 'SUPERGROUPS only'
end
local hash = get_filter_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'Sencured Wordes:\n\n'
for i=1, #names do
text = text..'➡️ '..names[i]..'\n'
end
return text
end
end
local function get_filter(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
delete_msg(msg.id, ok_cb, false)
return 'WARNING!\nDon\'nt Use it!'
elseif value == 'kick' then
send_large_msg('channel#id'..msg.to.id, "BBye xD")
channel_kick_user('channel#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true)
delete_msg(msg.id, ok_cb, false)
end
end
end
local function get_filter_act(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'Warning'
elseif value == 'kick' then
return 'Kick YOU'
elseif value == 'none' then
return 'Out of filter'
end
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == "ilterlist" then
return list_filter(msg)
elseif matches[1] == "ilter" and matches[2] == "war1324jadlkhrou2aisn" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'msg'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "in" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'kick'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "out" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "clean" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "You Are Not MOD"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "about" then
return get_filter_act(msg, matches[3]:lower())
else
if is_sudo(msg) then
return
elseif is_admin(msg) then
return
elseif is_momod(msg) then
return
elseif tonumber(msg.from.id) == tonumber(our_id) then
return
else
return get_filter(msg, msg.text:lower())
end
end
end
return {
patterns = {
"^[!/][Ff](ilter) (.+) (.*)$",
"^[!/][Ff](ilterlist)$",
"(.*)",
},
run = run
}
| gpl-2.0 |
X-Raym/REAPER-ReaScripts | Regions/X-Raym_Create markers at selected items snap offset.lua | 1 | 2176 | --[[
* ReaScript Name: Create markers at selected items snap offset
* Author: X-Raym
* Author URI: https://www.extremraym.com
* Repository: GitHub > X-Raym > REAPER-ReaScripts
* Repository URI: https://github.com/X-Raym/REAPER-ReaScripts
* Licence: GPL v3
* REAPER: 5.0 pre 15
* Extensions: SWS/S&M 2.7.1
* Version: 1.0.2
--]]
--[[
* Changelog:
* v1.0.2 (2020-07-05)
+ Cancel button
* v1.0.1 (2019-02-24)
+ Message Box
* v1.0 (2015-06-09)
+ Initial Release
--]]
function main()
reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function.
retval = reaper.MB("Rename from:\n\t- Takes Names (OK)\n\t- Item Notes (NO)", "Create Markers", 3 ) -- We suppose that the user know the scale he want
if retval and retval ~= 2 then
-- INITIALIZE loop through selected items
for i = 0, reaper.CountSelectedMediaItems(0) - 1 do
-- GET ITEMS
item = reaper.GetSelectedMediaItem(0, i) -- Get selected item i
item_pos = reaper.GetMediaItemInfo_Value(item, "D_POSITION")
item_snap = reaper.GetMediaItemInfo_Value(item, "D_SNAPOFFSET")
take = reaper.GetActiveTake(item)
if take == nil then
item_color = reaper.GetDisplayedMediaItemColor(item)
else
item_color = reaper.GetDisplayedMediaItemColor2(item, take)
end
if retval == 6 then
if take ~= nil then
name = reaper.GetTakeName(take)
else
name = reaper.ULT_GetMediaItemNote(item)
end
else
name = reaper.ULT_GetMediaItemNote(item)
end
snap = item_pos + item_snap
reaper.AddProjectMarker2(0, false, snap, 0, name, -1, item_color)
end -- ENDLOOP through selected items
end
reaper.Undo_EndBlock("Create markers at selected items snap offset", -1) -- End of the undo block. Leave it at the bottom of your main function.
end
reaper.PreventUIRefresh(1) -- Prevent UI refreshing. Uncomment it only if the script works.
main() -- Execute your main function
reaper.PreventUIRefresh(-1) -- Restore UI Refresh. Uncomment it only if the script works.
reaper.UpdateArrange() -- Update the arrangement (often needed)
| gpl-3.0 |
chrox/koreader | frontend/dbg.lua | 5 | 1043 | local dump = require("dump")
local isAndroid, android = pcall(require, "android")
local Dbg = {
is_on = false,
ev_log = nil,
}
local Dbg_mt = {}
local function LvDEBUG(lv, ...)
local line = ""
for i,v in ipairs({...}) do
if type(v) == "table" then
line = line .. " " .. dump(v, lv)
else
line = line .. " " .. tostring(v)
end
end
if isAndroid then
android.LOGI("#"..line)
else
print("#"..line)
io.stdout:flush()
end
end
function Dbg_mt.__call(dbg, ...)
if dbg.is_on then LvDEBUG(math.huge, ...) end
end
function Dbg:turnOn()
self.is_on = true
-- create or clear ev log file
self.ev_log = io.open("ev.log", "w")
end
function Dbg:logEv(ev)
local log = ev.type.."|"..ev.code.."|"
..ev.value.."|"..ev.time.sec.."|"..ev.time.usec.."\n"
self.ev_log:write(log)
self.ev_log:flush()
end
function Dbg:traceback()
LvDEBUG(math.huge, debug.traceback())
end
setmetatable(Dbg, Dbg_mt)
return Dbg
| agpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/npcs/Gurdern.lua | 2 | 1251 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Gurdern
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,14) == false) then
player:startEvent(10052);
else
player:startEvent(0x0070);
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 == 10052) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",14,true)
end
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Port_Windurst/npcs/Hohbiba-Mubiba.lua | 17 | 1689 | -----------------------------------
-- Area: Port Windurst
-- NPC: Hohbiba-Mubiba
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,HOHBIBAMUBIBA_SHOP_DIALOG);
stock = {
0x429B, 1440,1, --Yew Wand
0x42A3, 91,1, --Bronze Rod
0x42C2, 3642,1, --Elm Staff
0x42C9, 18422,1, --Elm Pole
0x429A, 340,2, --Willow Wand
0x4282, 4945,2, --Bone Cudgel
0x42C1, 584,2, --Holly Staff
0x42C8, 4669,2, --Holly Pole
0x4299, 47,3, --Maple Wand
0x4280, 66,3, --Ash Club
0x4281, 1600,3, --Chestnut Club
0x42C0, 58,3, --Ash Staff
0x42C7, 386,3, --Ash Pole
0x4040, 143,3 --Bronze Dagger
}
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Bastok_Mines/npcs/Leonie.lua | 13 | 1060 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Leonie
-- Type: Room Renters
-- @zone: 234
-- @pos 118.871 -0.004 -83.916
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0238);
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/Bastok_Markets_[S]/npcs/Heumila.lua | 13 | 1045 | -----------------------------------
-- Area: Bastok Markets (S)
-- NPC: Heumila
-- Type: Past Event Watcher
-- @zone: 87
-- @pos
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0000);
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 |
dicene/Mudlet | src/mudlet-lua/lua/TableUtils.lua | 2 | 9481 | ----------------------------------------------------------------------------------
--- Mudlet Table Utils
----------------------------------------------------------------------------------
--- Tests if a table is empty: this is useful in situations where you find
--- yourself wanting to do 'if my_table == {}' and such.
---
--- @usage Testing if the table is empty.
--- <pre>
--- myTable = {}
--- if table.is_empty(myTable) then
--- echo("myTable is empty")
--- end
--- </pre>
function table.is_empty(tbl)
if next(tbl) == nil then
return true else return false
end
end
--- Lua debug function that prints the content of a Lua table on the screen, split up in keys and values.
--- Useful if you want to see what the capture groups contain i. e. the Lua table "matches".
---
--- @see display
function printTable( map )
echo("-------------------------------------------------------\n");
for k, v in pairs( map ) do
echo( "key=" .. k .. " value=" .. v .. "\n" )
end
echo("-------------------------------------------------------\n");
end
-- NOT LUADOC
-- This is supporting function for printTable().
function __printTable( k, v )
insertText("\nkey = " .. tostring(k) .. " value = " .. tostring( v ) )
end
--- Lua debug function that prints the content of a Lua table on the screen. <br/>
--- There are currently 3 functions with similar behaviour.
---
--- @see display
--- @see printTable
function listPrint( map )
echo("-------------------------------------------------------\n");
for k, v in ipairs( map ) do
echo( k .. ". ) " .. v .. "\n" );
end
echo("-------------------------------------------------------\n");
end
--- <b><u>TODO</u></b> listAdd( list, what )
function listAdd( list, what )
table.insert( list, what );
end
--- <b><u>TODO</u></b> listRemove( list, what )
function listRemove( list, what )
for k, v in ipairs( list ) do
if v == what then
table.remove( list, k )
end
end
end
--- Gets the actual size of non-index based tables. <br/><br/>
---
--- For index based tables you can get the size with the # operator: <br/>
--- This is the standard Lua way of getting the size of index tables i.e. ipairs() type of tables with
--- numerical indices. To get the size of tables that use user defined keys instead of automatic indices
--- (pairs() type) you need to use the function table.size() referenced above.
--- <pre>
--- myTableSize = # myTable
--- </pre>
function table.size(t)
if not t then
return 0
end
local i = 0
for k, v in pairs(t) do
i = i + 1
end
return i
end
--- Determines if a table contains a value as a key or as a value (recursive).
function table.contains(t, value)
if type(t) ~= "table" then
return nil, "first parameter passed isn't a table"
end
for k, v in pairs(t) do
if v == value then
return true
elseif k == value then
return true
elseif type(v) == "table" then
if table.contains(v, value) then
return true
end
end
end
return false
end
--- Table Union.
---
--- @return Returns a table that is the union of the provided tables. This is a union of key/value
--- pairs. If two or more tables contain different values associated with the same key,
--- that key in the returned table will contain a subtable containing all relevant values.
--- See table.n_union() for a union of values. Note that the resulting table may not be
--- reliably traversable with ipairs() due to the fact that it preserves keys. If there
--- is a gap in numerical indices, ipairs() will cease traversal.
---
--- @usage Example:
--- <pre>
--- tableA = {
--- [1] = 123,
--- [2] = 456,
--- ["test"] = "test",
--- }
---
--- tableB = {
--- [1] = 23,
--- [3] = 7,
--- ["test2"] = function() return true end,
--- }
---
--- tableC = {
--- [5] = "c",
--- }
---
--- table.union(tableA, tableB, tableC) will return:
--- {
--- [1] = {
--- 123,
--- 23,
--- },
--- [2] = 456,
--- [3] = 7,
--- [5] = "c",
--- ["test"] = "test",
--- ["test2"] = function() return true end,
--- }
--- </pre>
function table.union(...)
local sets = { ... }
local union = {}
for _, set in ipairs(sets) do
for key, val in pairs(set) do
if union[key] and union[key] ~= val then
if type(union[key]) == 'table' then
table.insert(union[key], val)
else
union[key] = { union[key], val }
end
else
union[key] = val
end
end
end
return union
end
--- Table Union.
---
--- @return Returns a numerically indexed table that is the union of the provided tables. This is
--- a union of unique values. The order and keys of the input tables are not preserved.
function table.n_union(...)
local sets = { ... }
local union = {}
local union_keys = {}
for _, set in ipairs(sets) do
for key, val in pairs(set) do
if not union_keys[val] then
union_keys[val] = true
table.insert(union, val)
end
end
end
return union
end
--- Table Intersection.
---
--- @return Returns a table that is the intersection of the provided tables. This is an
--- intersection of key/value pairs. See table.n_intersection() for an intersection of values.
--- Note that the resulting table may not be reliably traversable with ipairs() due to
--- the fact that it preserves keys. If there is a gap in numerical indices, ipairs() will
--- cease traversal.
---
--- @usage Example:
--- <pre>
--- tableA = {
--- [1] = 123,
--- [2] = 456,
--- [4] = { 1, 2 },
--- [5] = "c",
--- ["test"] = "test",
--- }
---
--- tableB = {
--- [1] = 123,
--- [2] = 4,
--- [3] = 7,
--- [4] = { 1, 2 },
--- ["test"] = function() return true end,
--- }
---
--- tableC = {
--- [1] = 123,
--- [4] = { 1, 2 },
--- [5] = "c",
--- }
---
--- table.intersection(tableA, tableB, tableC) will return:
--- {
--- [1] = 123,
--- [4] = { 1, 2 },
--- }
--- </pre>
function table.intersection(...)
sets = { ... }
if #sets < 2 then
return false
end
local intersection = {}
local function intersect(set1, set2)
local result = {}
for key, val in pairs(set1) do
if set2[key] then
if _comp(val, set2[key]) then
result[key] = val
end
end
end
return result
end
intersection = intersect(sets[1], sets[2])
for i, _ in ipairs(sets) do
if i > 2 then
intersection = intersect(intersection, sets[i])
end
end
return intersection
end
--- Table Intersection.
---
--- @return Returns a numerically indexed table that is the intersection of the provided tables.
--- This is an intersection of unique values. The order and keys of the input tables are
--- not preserved.
function table.n_intersection(...)
sets = { ... }
if #sets < 2 then
return false
end
local intersection = {}
local function intersect(set1, set2)
local intersection_keys = {}
local result = {}
for _, val1 in pairs(set1) do
for _, val2 in pairs(set2) do
if _comp(val1, val2) and not intersection_keys[val1] then
table.insert(result, val1)
intersection_keys[val1] = true
end
end
end
return result
end
intersection = intersect(sets[1], sets[2])
for i, _ in ipairs(sets) do
if i > 2 then
intersection = intersect(intersection, sets[i])
end
end
return intersection
end
--- Table Complement.
---
--- @return Returns a table that is the relative complement of the first table with respect to
--- the second table. Returns a complement of key/value pairs.
function table.complement(set1, set2)
if not set1 and set2 then
return false
end
if type(set1) ~= 'table' or type(set2) ~= 'table' then
return false
end
local complement = {}
for key, val in pairs(set1) do
if not _comp(set2[key], val) then
complement[key] = val
end
end
return complement
end
--- Table Complement.
---
--- @return Returns a table that is the relative complement of the first table with respect to
--- the second table. Returns a complement of values.
function table.n_complement(set1, set2)
if not set1 and set2 then
return false
end
local complement = {}
for _, val1 in pairs(set1) do
local insert = true
for _, val2 in pairs(set2) do
if _comp(val1, val2) then
insert = false
end
end
if insert then
table.insert(complement, val1)
end
end
return complement
end
function table.update(t1, t2)
local tbl = {}
for k, v in pairs(t1) do
tbl[k] = v
end
for k, v in pairs(t2) do
if type(v) == "table" then
tbl[k] = table.update(tbl[k] or {}, v)
else
tbl[k] = v
end
end
return tbl
end
---Returns the index of the value in a table
function table.index_of(table, element)
for index, value in ipairs(table) do
if value == element then
return index
end
end
return nil
end
-- returns a deep copy of the table with the metatable intact. Credit to Steve Donovan of Penlight.
function table.deepcopy(t)
if type(t) ~= 'table' then
return t
end
local mt = getmetatable(t)
local res = {}
for k, v in pairs(t) do
if type(v) == 'table' then
v = table.deepcopy(v)
end
res[k] = v
end
setmetatable(res, mt)
return res
end
| gpl-2.0 |
wireshark/wireshark | test/lua/pinfo.lua | 4 | 11056 | -- test script for Pinfo and Address functions
-- use with dhcp.pcap in test/captures directory
local major, minor, micro = get_version():match("(%d+)%.(%d+)%.(%d+)")
if major then
major = tonumber(major)
minor = tonumber(minor)
micro = tonumber(micro)
else
major = 99
minor = 99
micro = 99
end
------------- general test helper funcs ------------
local FRAME = "frame"
local OTHER = "other"
local packet_counts = {}
local function incPktCount(name)
if not packet_counts[name] then
packet_counts[name] = 1
else
packet_counts[name] = packet_counts[name] + 1
end
end
local function getPktCount(name)
return packet_counts[name] or 0
end
local passed = {}
local function setPassed(name)
if not passed[name] then
passed[name] = 1
else
passed[name] = passed[name] + 1
end
end
-- expected number of runs per type
-- note ip only runs 3 times because it gets removed
-- and dhcp only runs twice because the filter makes it run
-- once and then it gets replaced with a different one for the second time
local taptests = { [FRAME]=4, [OTHER]=0 }
local function getResults()
print("\n-----------------------------\n")
for k,v in pairs(taptests) do
if v ~= 0 and passed[k] ~= v then
print("Something didn't run or ran too much... tests failed!")
print("Listener type "..k.." expected: "..v..", but got: "..tostring(passed[k]))
return false
end
end
print("All tests passed!\n\n")
return true
end
local function testing(type,...)
print("---- Testing "..type.." ---- "..tostring(...).." for packet # "..getPktCount(type).." ----")
end
local function test(type,name, ...)
io.stdout:write("test "..type.."-->"..name.."-"..getPktCount(type).."...")
if (...) == true then
io.stdout:write("passed\n")
return true
else
io.stdout:write("failed!\n")
error(name.." test failed!")
end
end
---------
-- the following are so we can use pcall (which needs a function to call)
local function setPinfo(pinfo,name,value)
pinfo[name] = value
end
local function getPinfo(pinfo,name)
local foo = pinfo[name]
end
------------- test script ------------
----------------------------------
-- modify original test function, kinda sorta
local orig_test = test
test = function (...)
return orig_test(FRAME,...)
end
local tap = Listener.new()
function tap.packet(pinfo,tvb)
incPktCount(FRAME)
testing(FRAME,"Pinfo in Frame")
test("typeof-1", typeof(pinfo) == "Pinfo")
test("tostring-1", tostring(pinfo) == "a Pinfo")
testing(FRAME,"negative tests")
-- try to set read-only attributes
--[[
these tests *should* ALL pass, but currently pinfo read-only members
silently accept being set (though nothing happens) Blech!!
test("Pinfo.number-set-1",not pcall(setPinfo,pinfo,"number",0))
test("Pinfo.len-set-1",not pcall(setPinfo,pinfo,"len",0))
test("Pinfo.caplen-set-1",not pcall(setPinfo,pinfo,"caplen",0))
test("Pinfo.rel_ts-set-1",not pcall(setPinfo,pinfo,"rel_ts",0))
test("Pinfo.delta_ts-set-1",not pcall(setPinfo,pinfo,"delta_ts",0))
test("Pinfo.delta_dis_ts-set-1",not pcall(setPinfo,pinfo,"delta_dis_ts",0))
test("Pinfo.visited-set-1",not pcall(setPinfo,pinfo,"visited",0))
test("Pinfo.lo-set-1",not pcall(setPinfo,pinfo,"lo",0))
test("Pinfo.hi-set-1",not pcall(setPinfo,pinfo,"hi",0))
test("Pinfo.port_type-set-1",not pcall(setPinfo,pinfo,"port_type",0))
test("Pinfo.match-set-1",not pcall(setPinfo,pinfo,"match",0))
test("Pinfo.curr_proto-set-1",not pcall(setPinfo,pinfo,"curr_proto",0))
test("Pinfo.columns-set-1",not pcall(setPinfo,pinfo,"columns",0))
test("Pinfo.cols-set-1",not pcall(setPinfo,pinfo,"cols",0))
test("Pinfo.private-set-1",not pcall(setPinfo,pinfo,"private",0))
test("Pinfo.fragmented-set-1",not pcall(setPinfo,pinfo,"fragmented",0))
test("Pinfo.in_error_pkt-set-1",not pcall(setPinfo,pinfo,"in_error_pkt",0))
test("Pinfo.match_uint-set-1",not pcall(setPinfo,pinfo,"match_uint",0))
test("Pinfo.match_string-set-1",not pcall(setPinfo,pinfo,"match_string",0))
]]
-- wrong type being set
test("Pinfo.src-set-1",not pcall(setPinfo,pinfo,"src","foobar"))
test("Pinfo.dst-set-1",not pcall(setPinfo,pinfo,"dst","foobar"))
test("Pinfo.dl_src-set-1",not pcall(setPinfo,pinfo,"dl_src","foobar"))
test("Pinfo.dl_dst-set-1",not pcall(setPinfo,pinfo,"dl_dst","foobar"))
test("Pinfo.net_src-set-1",not pcall(setPinfo,pinfo,"net_src","foobar"))
test("Pinfo.net_dst-set-1",not pcall(setPinfo,pinfo,"net_dst","foobar"))
test("Pinfo.src_port-set-1",not pcall(setPinfo,pinfo,"src_port","foobar"))
test("Pinfo.dst_port-set-1",not pcall(setPinfo,pinfo,"dst_port","foobar"))
if major > 1 or minor > 10 then
test("Pinfo.can_desegment-set-1",not pcall(setPinfo,pinfo,"can_desegment","foobar"))
end
test("Pinfo.desegment_len-set-1",not pcall(setPinfo,pinfo,"desegment_len","foobar"))
test("Pinfo.desegment_offset-set-1",not pcall(setPinfo,pinfo,"desegment_offset","foobar"))
-- invalid attribute names
--[[
again, these *should* pass, but Pinfo silently allows it!
test("Pinfo.set-1",not pcall(setPinfo,pinfo,"foobar","foobar"))
test("Pinfo.get-12",not pcall(getPinfo,pinfo,"foobar"))
]]
testing(FRAME,"basic getter tests")
local pktlen, srcip, dstip, srcport, dstport
if pinfo.number == 1 or pinfo.number == 3 then
pktlen = 314
srcip = "0.0.0.0"
dstip = "255.255.255.255"
srcport = 68
dstport = 67
else
pktlen = 342
srcip = "192.168.0.1"
dstip = "192.168.0.10"
srcport = 67
dstport = 68
end
test("Pinfo.number-get-1",pinfo.number == getPktCount(FRAME))
test("Pinfo.len-get-1",pinfo.len == pktlen)
test("Pinfo.caplen-get-1",pinfo.caplen == pktlen)
test("Pinfo.visited-get-1",pinfo.visited == true)
test("Pinfo.lo-get-1",tostring(pinfo.lo) == srcip)
test("Pinfo.lo-get-2",typeof(pinfo.lo) == "Address")
test("Pinfo.hi-get-1",tostring(pinfo.hi) == dstip)
test("Pinfo.hi-get-2",typeof(pinfo.hi) == "Address")
test("Pinfo.port_type-get-1",pinfo.port_type == 3)
test("Pinfo.match-get-1",pinfo.match == 0)
test("Pinfo.curr_proto-get-1",tostring(pinfo.curr_proto) == "<Missing Protocol Name>")
test("Pinfo.columns-get-1",tostring(pinfo.columns) == "Columns")
test("Pinfo.columns-get-2",typeof(pinfo.columns) == "Columns")
test("Pinfo.cols-get-1",tostring(pinfo.cols) == "Columns")
test("Pinfo.cols-get-2",typeof(pinfo.cols) == "Columns")
test("Pinfo.private-get-1",type(pinfo.private) == "userdata")
test("Pinfo.fragmented-get-1",pinfo.fragmented == false)
test("Pinfo.in_error_pkt-get-1",pinfo.in_error_pkt == false)
test("Pinfo.match_uint-get-1",pinfo.match_uint == 0)
test("Pinfo.match_string-get-1",pinfo.match_string == nil)
test("Pinfo.src-get-1",tostring(pinfo.src) == srcip)
test("Pinfo.src-get-2",typeof(pinfo.src) == "Address")
test("Pinfo.dst-get-1",tostring(pinfo.dst) == dstip)
test("Pinfo.dst-get-2",typeof(pinfo.dst) == "Address")
test("Pinfo.dl_src-get-1",typeof(pinfo.dl_src) == "Address")
test("Pinfo.dl_dst-get-1",typeof(pinfo.dl_dst) == "Address")
test("Pinfo.net_src-get-1",tostring(pinfo.net_src) == srcip)
test("Pinfo.net_src-get-2",typeof(pinfo.net_src) == "Address")
test("Pinfo.net_dst-get-1",tostring(pinfo.net_dst) == dstip)
test("Pinfo.net_dst-get-2",typeof(pinfo.net_dst) == "Address")
test("Pinfo.src_port-get-1",pinfo.src_port == srcport)
test("Pinfo.dst_port-get-1",pinfo.dst_port == dstport)
if major > 1 or minor > 10 then
test("Pinfo.can_desegment-get-1",pinfo.can_desegment == 0)
end
test("Pinfo.desegment_len-get-1",pinfo.desegment_len == 0)
test("Pinfo.desegment_offset-get-1",pinfo.desegment_offset == 0)
test("pinfo.p2p_dir", pinfo.p2p_dir == P2P_DIR_UNKNOWN)
if pinfo.number == 1 then
test("Pinfo.rel_ts-get-1",pinfo.rel_ts == 0)
test("Pinfo.delta_ts-get-1",pinfo.delta_ts == 0)
test("Pinfo.delta_dis_ts-get-1",pinfo.delta_dis_ts == 0)
elseif pinfo.number == 2 then
test("Pinfo.rel_ts-get-1",pinfo.rel_ts == 0.000295)
test("Pinfo.delta_ts-get-1",pinfo.delta_ts == 0.000295)
test("Pinfo.delta_dis_ts-get-1",pinfo.delta_dis_ts == 0.000295)
elseif pinfo.number == 3 then
test("Pinfo.rel_ts-get-1",pinfo.rel_ts == 0.070031)
test("Pinfo.delta_ts-get-1",pinfo.delta_ts == 0.069736)
test("Pinfo.delta_dis_ts-get-1",pinfo.delta_dis_ts == 0.069736)
elseif pinfo.number == 4 then
test("Pinfo.rel_ts-get-1",pinfo.rel_ts == 0.070345)
test("Pinfo.delta_ts-get-1",pinfo.delta_ts == 0.000314)
test("Pinfo.delta_dis_ts-get-1",pinfo.delta_dis_ts == 0.000314)
end
testing(FRAME,"basic setter tests")
local tmp = pinfo.src
pinfo.src = pinfo.dst
pinfo.dst = tmp
test("Pinfo.src-set-1",tostring(pinfo.src) == dstip)
test("Pinfo.src-set-1",typeof(pinfo.src) == "Address")
test("Pinfo.dst-set-1",tostring(pinfo.dst) == srcip)
test("Pinfo.dst-set-1",typeof(pinfo.dst) == "Address")
local dl_dst_val = tostring(pinfo.dl_dst)
local dl_src_val = tostring(pinfo.dl_src)
tmp = pinfo.dl_src
pinfo.dl_src = pinfo.dl_dst
pinfo.dl_dst = tmp
test("Pinfo.dl_src-set-1",tostring(pinfo.dl_src) == dl_dst_val)
test("Pinfo.dl_dst-set-1",tostring(pinfo.dl_dst) == dl_src_val)
tmp = pinfo.net_src
pinfo.net_src = pinfo.net_dst
pinfo.net_dst = tmp
test("Pinfo.net_src-set-1",tostring(pinfo.net_src) == dstip)
test("Pinfo.net_src-set-1",typeof(pinfo.net_src) == "Address")
test("Pinfo.net_dst-set-1",tostring(pinfo.net_dst) == srcip)
test("Pinfo.net_dst-set-1",typeof(pinfo.net_dst) == "Address")
--[[
--there's a bug 9792 causing the pinfo.dst_port setter to actually set src_port
tmp = pinfo.src_port
pinfo.src_port = pinfo.dst_port
pinfo.dst_port = tmp
test("Pinfo.src_port-set-1",pinfo.src_port == dstport)
test("Pinfo.dst_port-set-1",pinfo.dst_port == srcport)
--]]
pinfo.src_port = pinfo.dst_port
test("Pinfo.src_port-set-1",pinfo.src_port == dstport)
if major > 1 or minor > 10 then
pinfo.can_desegment = 12
test("Pinfo.can_desegment-set-1",pinfo.can_desegment == 12)
end
pinfo.desegment_len = 34
test("Pinfo.desegment_len-set-1",pinfo.desegment_len == 34)
pinfo.desegment_offset = 45
test("Pinfo.desegment_offset-set-1",pinfo.desegment_offset == 45)
testing(FRAME,"Address functions")
test("Address-eq-1", pinfo.lo == pinfo.dst)
test("Address-eq-2", pinfo.lo ~= pinfo.hi)
test("Address-lt-1", pinfo.lo < pinfo.hi)
test("Address-lt-2", pinfo.hi > pinfo.lo)
test("Address-le-1", pinfo.lo <= pinfo.hi)
test("Address-le-2", pinfo.lo <= pinfo.dst)
setPassed(FRAME)
end
function tap.draw()
getResults()
end
| gpl-2.0 |
waytim/darkstar | scripts/globals/items/mihgo_mithkabob.lua | 18 | 1439 | -----------------------------------------
-- ID: 5708
-- Item: Mihgo Mithkabob
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- Dexterity 5
-- Vitality 2
-- Mind -2
-- Defense % 25
-- Defense Cap 65
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5708);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 5);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_MND, -2);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 60);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 5);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_MND, -2);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 60);
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/items/pumpkin_pie_+1.lua | 18 | 1357 | -----------------------------------------
-- ID: 4447
-- Item: pumpkin_pie_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 45
-- Intelligence 4
-- Charisma -1
-- MP Recovered While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,4447);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 45);
target:addMod(MOD_INT, 4);
target:addMod(MOD_CHR, -1);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 45);
target:delMod(MOD_INT, 4);
target:delMod(MOD_CHR, -1);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/spells/curaga_iv.lua | 2 | 1148 | -----------------------------------------
-- Spell: Curaga IV
-- Restores HP of all party members within area of effect.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local minCure = 450;
local divisor = 0.6666;
local constant = 330;
local power = getCurePowerOld(caster);
if(power > 560) then
divisor = 2.8333;
constant = 591.2;
elseif(power > 320) then
divisor = 1;
constant = 410;
end
local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,false);
final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100));
--Applying server mods....
final = final * CURE_POWER;
local diff = (target:getMaxHP() - target:getHP());
if(final > diff) then
final = diff;
end
target:addHP(final);
target:wakeUp();
caster:updateEnmityFromCure(target,final);
return final;
end; | gpl-3.0 |
db260179/openwrt-bpi-r1-luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_status/processes.lua | 75 | 1236 | -- 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.
f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status."))
f.reset = false
f.submit = false
t = f:section(Table, luci.sys.process.list())
t:option(DummyValue, "PID", translate("PID"))
t:option(DummyValue, "USER", translate("Owner"))
t:option(DummyValue, "COMMAND", translate("Command"))
t:option(DummyValue, "%CPU", translate("CPU usage (%)"))
t:option(DummyValue, "%MEM", translate("Memory usage (%)"))
hup = t:option(Button, "_hup", translate("Hang Up"))
hup.inputstyle = "reload"
function hup.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 1)
end
term = t:option(Button, "_term", translate("Terminate"))
term.inputstyle = "remove"
function term.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 15)
end
kill = t:option(Button, "_kill", translate("Kill"))
kill.inputstyle = "reset"
function kill.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 9)
end
return f | apache-2.0 |
waytim/darkstar | scripts/globals/weaponskills/infernal_scythe.lua | 10 | 1515 | -----------------------------------
-- Infernal Scythe
-- Scythe weapon skill
-- Skill Level: 300
-- Deals darkness elemental damage and lowers target's attack. Duration of effect varies with TP.
-- Attack Down effect is -25% attack.
-- Aligned with the Shadow Gorget & Aqua Gorget.
-- Aligned with the Shadow Belt & Aqua Belt.
-- Element: None
-- Modifiers: STR: 30% INT: 30%
-- 100%TP 200%TP 300%TP
-- 3.50 3.50 3.50
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.ftp100 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_DARK;
params.skill = SKILL_SYH;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.int_wsc = 0.7;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary);
if (damage > 0) then
local duration = (tp/1000 * 180)
if (target:hasStatusEffect(EFFECT_ATTACK_DOWN) == false) then
target:addStatusEffect(EFFECT_ATTACK_DOWN, 25, 0, duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Contatta/prosody-modules | mod_auth_external/mod_auth_external.lua | 31 | 4708 | --
-- Prosody IM
-- Copyright (C) 2010 Waqas Hussain
-- Copyright (C) 2010 Jeff Mitchell
-- Copyright (C) 2013 Mikael Nordfeldth
-- Copyright (C) 2013 Matthew Wild, finally came to fix it all
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
local lpty = assert(require "lpty", "mod_auth_external requires lpty: https://code.google.com/p/prosody-modules/wiki/mod_auth_external#Installation");
local usermanager = require "core.usermanager";
local new_sasl = require "util.sasl".new;
local server = require "net.server";
local have_async, async = pcall(require, "util.async");
local log = module._log;
local host = module.host;
local script_type = module:get_option_string("external_auth_protocol", "generic");
local command = module:get_option_string("external_auth_command", "");
local read_timeout = module:get_option_number("external_auth_timeout", 5);
local blocking = module:get_option_boolean("external_auth_blocking", not(have_async and server.event and lpty.getfd));
local auth_processes = module:get_option_number("external_auth_processes", 1);
assert(script_type == "ejabberd" or script_type == "generic", "Config error: external_auth_protocol must be 'ejabberd' or 'generic'");
assert(not host:find(":"), "Invalid hostname");
if not blocking then
log("debug", "External auth in non-blocking mode, yay!")
waiter, guard = async.waiter, async.guarder();
elseif auth_processes > 1 then
log("warn", "external_auth_processes is greater than 1, but we are in blocking mode - reducing to 1");
auth_processes = 1;
end
local ptys = {};
local pty_options = { throw_errors = false, no_local_echo = true, use_path = false };
for i = 1, auth_processes do
ptys[i] = lpty.new(pty_options);
end
local curr_process = 0;
function send_query(text)
curr_process = (curr_process%auth_processes)+1;
local pty = ptys[curr_process];
local finished_with_pty
if not blocking then
finished_with_pty = guard(pty); -- Prevent others from crossing this line while we're busy
end
if not pty:hasproc() then
local status, ret = pty:exitstatus();
if status and (status ~= "exit" or ret ~= 0) then
log("warn", "Auth process exited unexpectedly with %s %d, restarting", status, ret or 0);
return nil;
end
local ok, err = pty:startproc(command);
if not ok then
log("error", "Failed to start auth process '%s': %s", command, err);
return nil;
end
log("debug", "Started auth process");
end
pty:send(text);
if blocking then
return pty:read(read_timeout);
else
local response;
local wait, done = waiter();
server.addevent(pty:getfd(), server.event.EV_READ, function ()
response = pty:read();
done();
return -1;
end);
wait();
finished_with_pty();
return response;
end
end
function do_query(kind, username, password)
if not username then return nil, "not-acceptable"; end
local query = (password and "%s:%s:%s:%s" or "%s:%s:%s"):format(kind, username, host, password);
local len = #query
if len > 1000 then return nil, "policy-violation"; end
if script_type == "ejabberd" then
local lo = len % 256;
local hi = (len - lo) / 256;
query = string.char(hi, lo)..query;
elseif script_type == "generic" then
query = query..'\n';
end
local response, err = send_query(query);
if not response then
log("warn", "Error while waiting for result from auth process: %s", err or "unknown error");
elseif (script_type == "ejabberd" and response == "\0\2\0\0") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "0") then
return nil, "not-authorized";
elseif (script_type == "ejabberd" and response == "\0\2\0\1") or
(script_type == "generic" and response:gsub("\r?\n$", "") == "1") then
return true;
else
log("warn", "Unable to interpret data from auth process, %s", (response:match("^error:") and response) or ("["..#response.." bytes]"));
return nil, "internal-server-error";
end
end
local host = module.host;
local provider = {};
function provider.test_password(username, password)
return do_query("auth", username, password);
end
function provider.set_password(username, password)
return do_query("setpass", username, password);
end
function provider.user_exists(username)
return do_query("isuser", username);
end
function provider.create_user(username, password) return nil, "Account creation/modification not available."; end
function provider.get_sasl_handler()
local testpass_authentication_profile = {
plain_test = function(sasl, username, password, realm)
return usermanager.test_password(username, realm, password), true;
end,
};
return new_sasl(host, testpass_authentication_profile);
end
module:provides("auth", provider);
| mit |
waytim/darkstar | scripts/globals/items/dish_of_spaghetti_vongole_rosso_+1.lua | 18 | 1650 | -----------------------------------------
-- ID: 5198
-- Item: Dish of Spaghetti Vongole Rosso +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health % 20
-- Health Cap 95
-- Vitality 2
-- Mind -1
-- Defense % 25
-- Defense Cap 35
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5198);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 20);
target:addMod(MOD_FOOD_HP_CAP, 95);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 35);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 20);
target:delMod(MOD_FOOD_HP_CAP, 95);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 35);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
X-Raym/REAPER-ReaScripts | Items Properties/X-Raym_Paste clipboard content into selected items notes.lua | 1 | 1046 | --[[
* ReaScript Name: Paste clipboard content into selected items notes
* Author: X-Raym
* Author URI: https://extremraym.com
* Repository: GitHub > X-Raym > REAPER-ReaScripts
* Repository URI: https://github.com/X-Raym/REAPER-ReaScripts
* Licence: GPL v3
* Forum Thread: Scripts: Items Properties (various)
* Forum Thread URI: https://forum.cockos.com/showthread.php?t=195520
* REAPER: 5.0
* Version: 1.0
--]]
--[[
* Changelog:
* v1.0 (2020-04-23)
+ Initial Release
--]]
reaper.PreventUIRefresh(1)
reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function.
clipboard = reaper.CF_GetClipboard('')
if clipboard ~= "" then
for i = 0, reaper.CountSelectedMediaItems(0) - 1 do
item = reaper.GetSelectedMediaItem(0, i)
reaper.ULT_SetMediaItemNote( item, clipboard )
end
end
reaper.UpdateArrange()
reaper.Undo_EndBlock("Paste clipboard content into selected items notes", - 1) -- End of the undo block. Leave it at the bottom of your main function.
reaper.PreventUIRefresh(-1)
| gpl-3.0 |
thisishmed/butler | plugins/stats.lua | 12 | 6289 | -- 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..'\n تعداد پیام های فرد=> '..user.msgs..'\n\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 = 'کاربران: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nگروه ها: '..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 'این پلاگین تنها در گروه کار میکند'
end
end
if matches[2] == "bot" or "telemanager" then
if not is_sudo(msg) then
return "تنها برای سودو مجاز است"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "تنها برای سودو مجاز است"
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)",
"^[!/]([Ss]tats) (telemanager)"
},
run = run,
pre_process = pre_process
}
end
-- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ || ||-_-_-_-_-_
-- || || || ||
-- || || || ||
-- || || || ||
-- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
--
--
-- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_
-- ||\\ //|| //\\ || //|| //\\ // || || //
-- || \\ // || // \\ || // || // \\ // || || //
-- || \\ // || // \\ || // || // \\ || || || //
-- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || //
-- || \\ // || // \\ || // || // \\ || || || || \\
-- || \\ // || // \\ || // || // \\ \\ || || || \\
-- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\
--
--
-- ||-_-_-_- || || || //-_-_-_-_-_-
-- || || || || || //
-- ||_-_-_|| || || || //
-- || || || || \\
-- || || \\ // \\
-- || || \\ // //
-- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-//
--
--By @ali_ghoghnoos
--@telemanager_ch
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/effects/addendum_white.lua | 4 | 1901 | -----------------------------------
--
--
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:recalculateAbilitiesTable();
local bonus = effect:getPower();
local regen = effect:getSubPower();
target:addMod(MOD_WHITE_MAGIC_COST, -bonus);
target:addMod(MOD_WHITE_MAGIC_CAST, -bonus);
target:addMod(MOD_WHITE_MAGIC_RECAST, -bonus);
if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then
target:addMod(MOD_WHITE_MAGIC_COST, -10);
target:addMod(MOD_WHITE_MAGIC_CAST, -10);
target:addMod(MOD_WHITE_MAGIC_RECAST, -10);
target:addMod(MOD_BLACK_MAGIC_COST, 20);
target:addMod(MOD_BLACK_MAGIC_CAST, 20);
target:addMod(MOD_BLACK_MAGIC_RECAST, 20);
target:addMod(MOD_REGEN_EFFECT, regen);
target:addMod(MOD_REGEN_DURATION, regen*2);
end
target:recalculateSkillsTable();
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:recalculateAbilitiesTable();
local bonus = effect:getPower();
local regen = effect:getSubPower();
target:delMod(MOD_WHITE_MAGIC_COST, -bonus);
target:delMod(MOD_WHITE_MAGIC_CAST, -bonus);
target:delMod(MOD_WHITE_MAGIC_RECAST, -bonus);
if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then
target:delMod(MOD_WHITE_MAGIC_COST, -10);
target:delMod(MOD_WHITE_MAGIC_CAST, -10);
target:delMod(MOD_WHITE_MAGIC_RECAST, -10);
target:delMod(MOD_BLACK_MAGIC_COST, 20);
target:delMod(MOD_BLACK_MAGIC_CAST, 20);
target:delMod(MOD_BLACK_MAGIC_RECAST, 20);
target:delMod(MOD_REGEN_EFFECT, regen);
target:delMod(MOD_REGEN_DURATION, regen*2);
end
target:recalculateSkillsTable();
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/Northern_San_dOria/npcs/Doggomehr.lua | 13 | 1208 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Doggomehr
-- Guild Merchant NPC: Blacksmithing Guild
-- @pos -193.920 3.999 162.027 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(531,8,23,2)) then
player:showText(npc,DOGGOMEHR_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Crawlers_Nest/npcs/_5h1.lua | 13 | 2974 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: Strange Apparatus
-- @pos: 214 0 -339 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
require("scripts/zones/Crawlers_Nest/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0002, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0000, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0000) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Horlais_Peak/bcnms/contaminated_colosseum.lua | 4 | 1775 | -----------------------------------
-- Area: Horlias peak
-- Name: contaminated_colosseum
-- KSNM30
-----------------------------------
package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Horlais_Peak/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function OnBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function OnBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function OnBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
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);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Sacrarium/mobs/Keremet.lua | 2 | 1333 | -----------------------------------
-- Area: sacrarium
-- NPC: Keremet
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onMobSpawn
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
GetMobByID(16892050):updateEnmity(target); -- Commence the sack party.
GetMobByID(16892051):updateEnmity(target);
GetMobByID(16892052):updateEnmity(target);
GetMobByID(16892053):updateEnmity(target);
GetMobByID(16892054):updateEnmity(target);
GetMobByID(16892055):updateEnmity(target);
GetMobByID(16892056):updateEnmity(target);
GetMobByID(16892057):updateEnmity(target);
GetMobByID(16892058):updateEnmity(target);
GetMobByID(16892059):updateEnmity(target);
GetMobByID(16892060):updateEnmity(target);
GetMobByID(16892061):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
if (killer:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and killer:getVar("PromathiaStatus") == 3 and killer:hasKeyItem(RELIQUIARIUM_KEY)==false)then
-- print("mobdeath");
killer:setVar("PromathiaStatus",4);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/globals/items/bowl_of_riverfin_soup.lua | 18 | 1891 | -----------------------------------------
-- ID: 6069
-- Item: Bowl of Riverfin Soup
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- Accuracy % 14 Cap 90
-- Ranged Accuracy % 14 Cap 90
-- Attack % 18 Cap 80
-- Ranged Attack % 18 Cap 80
-- Amorph Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,6069);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_ACCP, 14);
target:addMod(MOD_FOOD_ACC_CAP, 90);
target:addMod(MOD_FOOD_RACCP, 14);
target:addMod(MOD_FOOD_RACC_CAP, 90);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_AMORPH_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_ACCP, 14);
target:delMod(MOD_FOOD_ACC_CAP, 90);
target:delMod(MOD_FOOD_RACCP, 14);
target:delMod(MOD_FOOD_RACC_CAP, 90);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_AMORPH_KILLER, 5);
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/mobskills/glittering_ruby.lua | 27 | 1144 | ---------------------------------------------------
-- Glittering Ruby
---------------------------------------------------
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)
--randomly give str/dex/vit/agi/int/mnd/chr (+12)
local effect = math.random();
local effectid = EFFECT_STR_BOOST;
if (effect<=0.14) then --STR
effectid = EFFECT_STR_BOOST;
elseif (effect<=0.28) then --DEX
effectid = EFFECT_DEX_BOOST;
elseif (effect<=0.42) then --VIT
effectid = EFFECT_VIT_BOOST;
elseif (effect<=0.56) then --AGI
effectid = EFFECT_AGI_BOOST;
elseif (effect<=0.7) then --INT
effectid = EFFECT_INT_BOOST;
elseif (effect<=0.84) then --MND
effectid = EFFECT_MND_BOOST;
else --CHR
effectid = EFFECT_CHR_BOOST;
end
target:addStatusEffect(effectid,math.random(12,14),0,90);
skill:setMsg(MSG_BUFF);
return effectid;
end
| gpl-3.0 |
waytim/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/Cavernous_Maw.lua | 29 | 1190 | -----------------------------------
-- Area: Abyssea - Tahrongi
-- NPC: Cavernous Maw
-- @pos -31.000, 47.000, -681.000 45
-- Teleports Players to Tahrongi Canyon
-----------------------------------
package.loaded["scripts/zones/Abyssea-Tahrongi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Abyssea-Tahrongi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00C8);
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 == 0x00C8 and option ==1) then
player:setPos(-28,46,-680,76,117);
end
end; | gpl-3.0 |
tenvick/hugular_cstolua | Client/tools/netProtocal/NetProtocalParserCode.lua | 8 | 3668 | ------------------- NetProtocalPaser---------------
local NetAPIList = NetAPIList
NetProtocalPaser = {}
function NetProtocalPaser:parsestring(msg, key, parentTable)
parentTable[key] = msg:ReadString()
end
function NetProtocalPaser:parseinteger(msg, key, parentTable)
parentTable[key] = msg:ReadInt()
end
function NetProtocalPaser:parsefloat(msg, key, parentTable)
parentTable[key] = msg:ReadFloat()
end
function NetProtocalPaser:parseshort(msg, key, parentTable)
parentTable[key] = msg:ReadShort()
end
function NetProtocalPaser:parsebyte(msg, key, parentTable)
parentTable[key] = msg:ReadByte()
end
function NetProtocalPaser:parseboolean(msg, key, parentTable)
parentTable[key] = msg:ReadBoolean()
end
function NetProtocalPaser:parsepkid(msg,key,parentTable)
parentTable[key] = msg:ReadString()
end
function NetProtocalPaser:parsechar(msg,key,parentTable)
parentTable[key] = msg:ReadChar()
end
function NetProtocalPaser:parseushort(msg,key,parentTable)
parentTable[key] = msg:ReadUShort()
end
function NetProtocalPaser:parseuint(msg,key,parentTable)
parentTable[key] = msg:ReadUInt()
end
function NetProtocalPaser:parseulong(msg,key,parentTable)
parentTable[key] = msg:ReadULong()
end
function NetProtocalPaser:formatstring(msg, value)
msg:WriteString(value)
end
function NetProtocalPaser:formatinteger(msg, value)
msg:WriteInt(value)
end
function NetProtocalPaser:formatshort(msg, value)
msg:WriteShort(value)
end
function NetProtocalPaser:formatfloat(msg, value)
msg:WriteFloat(value)
end
function NetProtocalPaser:formatbyte(msg, value)
msg:WriteByte(value)
end
function NetProtocalPaser:formatboolean(msg, value)
msg:WriteBoolean(value)
end
function NetProtocalPaser:formatchar(msg, value)
msg:WriteChar(value)
end
function NetProtocalPaser:formatushort(msg, value)
msg:WriteUShort(value)
end
function NetProtocalPaser:formatuint(msg, value)
msg:WriteUInt(value)
end
function NetProtocalPaser:formatulong(msg, value)
msg:WriteULong(value)
end
function NetProtocalPaser:formatArray(msg, value, valueType)
local funcName = "format" .. valueType
local func = self[funcName]
local arrayLen = #value
msg:WriteUShort(arrayLen)
for i=1, arrayLen, 1 do
local v = value[i]
func(self,msg,v)
end
end
function NetProtocalPaser:formatpkid(msg,value)
msg:WriteString(value)
end
function NetProtocalPaser:parseArray(msg, key, parentTable, valueType)
local funcName = "parse" .. valueType
local func = self[funcName]
parentTable[key]= {}
local arrayLen = msg:ReadUShort()
for i=1, arrayLen, 1 do
local tempT = {}
func(self,msg,"tempK", tempT)
table.insert(parentTable[key],tempT.tempK)
end
end
function NetProtocalPaser:parseMessage(msg,msgType)
local result = {}
msgType = "MSGTYPE" .. msgType
local dataStructName = NetAPIList:getDataStructFromMsgType(msgType)
if(dataStructName ~= "null") then
local funcName = "parse"..dataStructName
local func = NetProtocalPaser[funcName]
func(self, msg,nil,result)
end
return result
end
function NetProtocalPaser:formatMessage(msg,msgType, content)
msg:set_Type(msgType)
msgType = "MSGTYPE" .. msgType
local dataStructName = NetAPIList:getDataStructFromMsgType(msgType)
if(dataStructName ~= "null") then
local funcName = "format"..dataStructName
--print("---- formatMessage func name--- " .. funcName)
local func = NetProtocalPaser[funcName]
func(self, msg, content)
end
end
| mit |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99950341.lua | 2 | 3212 | --MSMM - Kyubey
function c99950341.initial_effect(c)
--Special Summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(99950341,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCost(c99950341.spcost)
e1:SetTarget(c99950341.sptg)
e1:SetOperation(c99950341.spop)
c:RegisterEffect(e1)
--Search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(99950341,1))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(aux.exccon)
e2:SetCost(c99950341.thcost)
e2:SetTarget(c99950341.thtg)
e2:SetOperation(c99950341.thop)
c:RegisterEffect(e2)
--Battle Indes
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e3:SetValue(1)
c:RegisterEffect(e3)
end
function c99950341.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsAbleToGraveAsCost() and c:IsDiscardable() end
Duel.SendtoGrave(c,REASON_COST+REASON_DISCARD)
end
function c99950341.spfilter(c,e,tp)
return c:IsSetCard(9995) and c:GetLevel()==5 and c:IsCanBeSpecialSummoned(e,0,tp,false,true)
end
function c99950341.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_DECK) and chkc:IsControler(tp) and c99950341.spfilter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c99950341.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c99950341.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c99950341.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummonStep(tc,0,tp,tp,false,true,POS_FACEUP) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_TRIGGER)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
Duel.SpecialSummonComplete()
end
function c99950341.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST)
end
function c99950341.thfilter(c)
return c:IsCode(99950000) and c:IsAbleToHand() and not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c99950341.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c99950341.thfilter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK+LOCATION_GRAVE)
end
function c99950341.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c99950341.thfilter,tp,LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end | gpl-3.0 |
waytim/darkstar | scripts/globals/weaponskills/hard_slash.lua | 11 | 1603 | -----------------------------------
-- Hard Slash
-- Great Sword weapon skill
-- Skill level: 5
-- Delivers a single-hit attack. Damage varies with TP.
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.5 1.75 2.0
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
-- ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 1.5; params.ftp200 = 1.75; params.ftp300 = 2.0;
-- wscs are in % so 0.2=20%
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;
-- critical mods, again in % (ONLY USE FOR params.critICAL HIT VARIES WITH TP)
params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0;
params.canCrit = false;
-- accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
-- attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Bhaflau_Thickets/npcs/qm1.lua | 15 | 1188 | -----------------------------------
-- Area: Bhaflau Thickets
-- NPC: ??? (Spawn Lividroot Amooshah(ZNM T2))
-- @pos 334 -10 184 52
-----------------------------------
package.loaded["scripts/zones/Bhaflau_Thickets/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bhaflau_Thickets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(2578,1) and trade:getItemCount() == 1) then -- Trade Oily Blood
player:tradeComplete();
SpawnMob(16990473,180):updateEnmity(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
waytim/darkstar | scripts/globals/abilities/pets/gust_breath.lua | 29 | 1334 | ---------------------------------------------------
-- Gust Breath
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/ability");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onUseAbility(pet, target, skill, action)
local master = pet:getMaster()
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_WIND); -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep;
pet:setTP(0)
local dmg = AbilityFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c101020022.lua | 1 | 2388 | --created by LionHeartKIng, coded by Lyris
--S・VINEのコースト・プリースト
function c101020022.initial_effect(c)
local e4=Effect.CreateEffect(c)
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_IGNITION)
e4:SetRange(LOCATION_MZONE)
e4:SetCountLimit(1)
e4:SetCondition(c101020022.spcon)
e4:SetTarget(c101020022.sptg)
e4:SetOperation(c101020022.spop)
c:RegisterEffect(e4)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetRange(LOCATION_REMOVED)
e1:SetCountLimit(1,101020022+EFFECT_COUNT_CODE_DUEL)
e1:SetCondition(c101020022.condition)
e1:SetTarget(c101020022.target)
e1:SetOperation(c101020022.operation)
c:RegisterEffect(e1)
end
function c101020022.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0)<=1
end
function c101020022.spfilter(c,e,tp)
return c:IsSetCard(0x785e) and not c:IsCode(101020022) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c101020022.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c101020022.spfilter,tp,LOCATION_REMOVED+LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_REMOVED+LOCATION_DECK)
end
function c101020022.spop(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,c101020022.spfilter,tp,LOCATION_REMOVED+LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c101020022.condition(e,tp,eg,ep,ev,re,r,rp)
local at=Duel.GetAttacker()
return at:GetControler()~=tp and Duel.GetAttackTarget()==nil
end
function c101020022.target(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0)
end
function c101020022.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 and Duel.NegateAttack() then
Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE,1)
end
end
| gpl-3.0 |
MinFu/luci | applications/luci-app-wshaper/luasrc/model/cbi/wshaper.lua | 56 | 1848 | -- Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
-- Licensed to the public under the Apache License 2.0.
require("luci.tools.webadmin")
m = Map("wshaper", translate("Wondershaper"),
translate("Wondershaper shapes traffic to ensure low latencies for interactive traffic even when your " ..
"internet connection is highly saturated."))
s = m:section(NamedSection, "settings", "wshaper", translate("Wondershaper settings"))
s.anonymous = true
network = s:option(ListValue, "network", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(network)
uplink = s:option(Value, "uplink", translate("Uplink"), translate("Upstream bandwidth in kbit/s"))
uplink.optional = false
uplink.datatype = "uinteger"
uplink.default = "240"
uplink = s:option(Value, "downlink", translate("Downlink"), translate("Downstream bandwidth in kbit/s"))
uplink.optional = false
uplink.datatype = "uinteger"
uplink.default = "200"
nopriohostsrc = s:option(DynamicList, "nopriohostsrc", translate("Low priority hosts (Source)"), translate("Host or Network in CIDR notation."))
nopriohostsrc.optional = true
nopriohostsrc.datatype = ipaddr
nopriohostsrc.placeholder = "10.0.0.1/32"
nopriohostdst = s:option(DynamicList, "nopriohostdst", translate("Low priority hosts (Destination)"), translate("Host or Network in CIDR notation."))
nopriohostdst.optional = true
nopriohostdst.datatype = ipaddr
nopriohostdst.placeholder = "10.0.0.1/32"
noprioportsrc = s:option(DynamicList, "noprioportsrc", translate("Low priority source ports"))
noprioportsrc.optional = true
noprioportsrc.datatype = "range(0,65535)"
noprioportsrc.placeholder = "21"
noprioportdst = s:option(DynamicList, "noprioportdst", translate("Low priority destination ports"))
noprioportdst.optional = true
noprioportdst.datatype = "range(0,65535)"
noprioportdst.placeholder = "21"
return m
| apache-2.0 |
waytim/darkstar | scripts/zones/Apollyon/mobs/Proto-Omega.lua | 4 | 3213 | -----------------------------------
-- Area: Apollyon (Central)
-- MOB: Proto-Omega
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID());
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
mob:setMod(MOD_UDMGPHYS, -75);
mob:setMod(MOD_UDMGRANGE, -75);
mob:setMod(MOD_UDMGMAGIC, 0);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local mobID = mob:getID();
local formTime = mob:getLocalVar("formWait")
local lifePercent = mob:getHPP();
local currentForm = mob:getLocalVar("form")
if (lifePercent < 70 and currentForm < 1) then
currentForm = 1;
mob:setLocalVar("form", currentForm)
mob:AnimationSub(2);
formTime = os.time() + 60;
mob:setMod(MOD_UDMGPHYS, 0);
mob:setMod(MOD_UDMGRANGE, 0);
mob:setMod(MOD_UDMGMAGIC, -75);
end
if (currentForm == 1) then
if (formTime < os.time()) then
if (mob:AnimationSub() == 1) then
mob:AnimationSub(2);
else
mob:AnimationSub(1);
end
mob:setLocalVar("formWait", os.time() + 60);
end
if (lifePercent < 30) then
mob:AnimationSub(2);
mob:setMod(MOD_UDMGPHYS, -50);
mob:setMod(MOD_UDMGRANGE, -50);
mob:setMod(MOD_UDMGMAGIC, -50);
mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain,
mob:getStatusEffect(EFFECT_REGAIN):setFlag(32);
currentForm = 2;
mob:setLocalVar("form", currentForm)
end
end
end;
-----------------------------------
-- onAdditionalEffect
-----------------------------------
function onAdditionalEffect(mob, player)
local chance = 20; -- wiki lists ~20% stun chance
local resist = applyResistanceAddEffect(mob,player,ELE_THUNDER,EFFECT_STUN);
if (math.random(0,99) >= chance or resist <= 0.5) then
return 0,0,0;
else
local duration = 5 * resist;
if (player:hasStatusEffect(EFFECT_STUN) == false) then
player:addStatusEffect(EFFECT_STUN, 0, 0, duration);
end
return SUBEFFECT_STUN, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_STUN;
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:addTitle(APOLLYON_RAVAGER);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
GetNPCByID(16932864+39):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+39):setStatus(STATUS_NORMAL);
end; | gpl-3.0 |
waytim/darkstar | scripts/globals/items/prime_beef_stewpot.lua | 18 | 1971 | -----------------------------------------
-- ID: 5548
-- Item: Prime Beef Stewpot
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +10% Cap 75
-- MP +15
-- Strength +2
-- Agility +1
-- Mind +1
-- HP Recovered while healing +7
-- MP Recovered while healing +2
-- Attack 18% Cap 60
-- Evasion +6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5548);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 75);
target:addMod(MOD_MP, 15);
target:addMod(MOD_STR, 2);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_MND, 1);
target:addMod(MOD_HPHEAL, 7);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 60);
target:addMod(MOD_EVA, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 75);
target:delMod(MOD_MP, 15);
target:delMod(MOD_STR, 2);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_MND, 1);
target:delMod(MOD_HPHEAL, 7);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 60);
target:delMod(MOD_EVA, 6);
end;
| gpl-3.0 |
jixianliang/DBProxy | examples/tutorial-keepalive.lua | 4 | 8032 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, 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%$ --]]
--[[
--]]
---
-- a flexible statement based load balancer with connection pooling
--
-- * build a connection pool of min_idle_connections for each backend and
-- maintain its size
-- * reusing a server-side connection when it is idling
--
--- config
--
-- connection pool
local min_idle_connections = 4
local max_idle_connections = 8
-- debug
local is_debug = true
--- end of config
---
-- read/write splitting sends all non-transactional SELECTs to the slaves
--
-- is_in_transaction tracks the state of the transactions
local is_in_transaction = 0
---
-- get a connection to a backend
--
-- as long as we don't have enough connections in the pool, create new connections
--
function connect_server()
-- make sure that we connect to each backend at least ones to
-- keep the connections to the servers alive
--
-- on read_query we can switch the backends again to another backend
if is_debug then
print()
print("[connect_server] ")
end
local least_idle_conns_ndx = 0
local least_idle_conns = 0
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[""].cur_idle_connections
if is_debug then
print(" [".. i .."].connected_clients = " .. s.connected_clients)
print(" [".. i .."].idling_connections = " .. cur_idle)
print(" [".. i .."].type = " .. s.type)
print(" [".. i .."].state = " .. s.state)
end
if s.state ~= proxy.BACKEND_STATE_DOWN then
-- try to connect to each backend once at least
if cur_idle == 0 then
proxy.connection.backend_ndx = i
if is_debug then
print(" [".. i .."] open new connection")
end
return
end
-- try to open at least min_idle_connections
if least_idle_conns_ndx == 0 or
( cur_idle < min_idle_connections and
cur_idle < least_idle_conns ) then
least_idle_conns_ndx = i
least_idle_conns = s.idling_connections
end
end
end
if least_idle_conns_ndx > 0 then
proxy.connection.backend_ndx = least_idle_conns_ndx
end
if proxy.connection.backend_ndx > 0 then
local s = proxy.global.backends[proxy.connection.backend_ndx]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[""].cur_idle_connections
if cur_idle >= min_idle_connections then
-- we have 4 idling connections in the pool, that's good enough
if is_debug then
print(" using pooled connection from: " .. proxy.connection.backend_ndx)
end
return proxy.PROXY_IGNORE_RESULT
end
end
if is_debug then
print(" opening new connection on: " .. proxy.connection.backend_ndx)
end
-- open a new connection
end
---
-- put the successfully authed connection into the connection pool
--
-- @param auth the context information for the auth
--
-- auth.packet is the packet
function read_auth_result( auth )
if auth.packet:byte() == proxy.MYSQLD_PACKET_OK then
-- auth was fine, disconnect from the server
proxy.connection.backend_ndx = 0
elseif auth.packet:byte() == proxy.MYSQLD_PACKET_EOF then
-- we received either a
--
-- * MYSQLD_PACKET_ERR and the auth failed or
-- * MYSQLD_PACKET_EOF which means a OLD PASSWORD (4.0) was sent
print("(read_auth_result) ... not ok yet");
elseif auth.packet:byte() == proxy.MYSQLD_PACKET_ERR then
-- auth failed
end
end
---
-- read/write splitting
function read_query( packet )
if is_debug then
print("[read_query]")
print(" authed backend = " .. proxy.connection.backend_ndx)
print(" used db = " .. proxy.connection.client.default_db)
end
if packet:byte() == proxy.COM_QUIT then
-- don't send COM_QUIT to the backend. We manage the connection
-- in all aspects.
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
return proxy.PROXY_SEND_RESULT
end
if proxy.connection.backend_ndx == 0 then
-- we don't have a backend right now
--
-- let's pick a master as a good default
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[proxy.connection.client.username].cur_idle_connections
if cur_idle > 0 and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.type == proxy.BACKEND_TYPE_RW then
proxy.connection.backend_ndx = i
break
end
end
end
if true or proxy.connection.client.default_db and proxy.connection.client.default_db ~= proxy.connection.server.default_db then
-- sync the client-side default_db with the server-side default_db
proxy.queries:append(2, string.char(proxy.COM_INIT_DB) .. proxy.connection.client.default_db, { resultset_is_needed = true })
end
proxy.queries:append(1, packet, { resultset_is_needed = true })
return proxy.PROXY_SEND_QUERY
end
---
-- as long as we are in a transaction keep the connection
-- otherwise release it so another client can use it
function read_query_result( inj )
local res = assert(inj.resultset)
local flags = res.flags
if inj.id ~= 1 then
-- ignore the result of the USE <default_db>
return proxy.PROXY_IGNORE_RESULT
end
is_in_transaction = flags.in_trans
if not is_in_transaction then
-- release the backend
proxy.connection.backend_ndx = 0
end
end
---
-- close the connections if we have enough connections in the pool
--
-- @return nil - close connection
-- IGNORE_RESULT - store connection in the pool
function disconnect_client()
if is_debug then
print("[disconnect_client]")
end
if proxy.connection.backend_ndx == 0 then
-- currently we don't have a server backend assigned
--
-- pick a server which has too many idling connections and close one
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[proxy.connection.client.username].cur_idle_connections
if s.state ~= proxy.BACKEND_STATE_DOWN and
cur_idle > max_idle_connections then
-- try to disconnect a backend
proxy.connection.backend_ndx = i
if is_debug then
print(" [".. i .."] closing connection, idling: " .. cur_idle)
end
return
end
end
end
end
| gpl-2.0 |
forcecore/OpenRA | mods/ra/maps/soviet-06a/soviet06a.lua | 7 | 6355 | --[[
Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
ArmorAttack = { }
AttackPaths = { { AttackWaypoint1 }, { AttackWaypoint2 } }
BaseAttackers = { BaseAttacker1, BaseAttacker2 }
InfAttack = { }
IntroAttackers = { IntroEnemy1, IntroEnemy2, IntroEnemy3 }
Trucks = { Truck1, Truck2 }
AlliedInfantryTypes = { "e1", "e1", "e3" }
AlliedArmorTypes = { "jeep", "jeep", "1tnk", "1tnk", "2tnk", "2tnk", "arty" }
SovietReinforcements1 = { "e6", "e6", "e6", "e6", "e6" }
SovietReinforcements2 = { "e4", "e4", "e2", "e2", "e2" }
SovietReinforcements1Waypoints = { McvWaypoint.Location, APCWaypoint1.Location }
SovietReinforcements2Waypoints = { McvWaypoint.Location, APCWaypoint2.Location }
TruckGoalTrigger = { CPos.New(83, 7), CPos.New(83, 8), CPos.New(83, 9), CPos.New(83, 10), CPos.New(84, 10), CPos.New(84, 11), CPos.New(84, 12), CPos.New(85, 12), CPos.New(86, 12), CPos.New(87, 12), CPos.New(87, 13), CPos.New(88, 13), CPos.New(89, 13), CPos.New(90, 13), CPos.New(90, 14), CPos.New(90, 15), CPos.New(91, 15), CPos.New(92, 15), CPos.New(93, 15), CPos.New(94, 15) }
CameraBarrierTrigger = { CPos.New(65, 39), CPos.New(65, 40), CPos.New(66, 40), CPos.New(66, 41), CPos.New(67, 41), CPos.New(67, 42), CPos.New(68, 42), CPos.New(68, 43), CPos.New(68, 44) }
CameraBaseTrigger = { CPos.New(53, 42), CPos.New(54, 42), CPos.New(54, 41), CPos.New(55, 41), CPos.New(56, 41), CPos.New(56, 40), CPos.New(57, 40), CPos.New(57, 39), CPos.New(58, 39), CPos.New(59, 39), CPos.New(59, 38), CPos.New(60, 38), CPos.New(61, 38) }
Trigger.OnEnteredFootprint(TruckGoalTrigger, function(a, id)
if not truckGoalTrigger and a.Owner == player and a.Type == "truk" then
truckGoalTrigger = true
player.MarkCompletedObjective(sovietObjective)
player.MarkCompletedObjective(SaveAllTrucks)
end
end)
Trigger.OnEnteredFootprint(CameraBarrierTrigger, function(a, id)
if not cameraBarrierTrigger and a.Owner == player then
cameraBarrierTrigger = true
local cameraBarrier = Actor.Create("camera", true, { Owner = player, Location = CameraBarrier.Location })
Trigger.AfterDelay(DateTime.Seconds(15), function()
cameraBarrier.Destroy()
end)
end
end)
Trigger.OnEnteredFootprint(CameraBaseTrigger, function(a, id)
if not cameraBaseTrigger and a.Owner == player then
cameraBaseTrigger = true
local cameraBase1 = Actor.Create("camera", true, { Owner = player, Location = CameraBase1.Location })
local cameraBase2 = Actor.Create("camera", true, { Owner = player, Location = CameraBase2.Location })
local cameraBase3 = Actor.Create("camera", true, { Owner = player, Location = CameraBase3.Location })
local cameraBase4 = Actor.Create("camera", true, { Owner = player, Location = CameraBase4.Location })
Trigger.AfterDelay(DateTime.Minutes(1), function()
cameraBase1.Destroy()
cameraBase2.Destroy()
cameraBase3.Destroy()
cameraBase4.Destroy()
end)
end
end)
Trigger.OnAllKilled(Trucks, function()
enemy.MarkCompletedObjective(alliedObjective)
end)
Trigger.OnAnyKilled(Trucks, function()
player.MarkFailedObjective(SaveAllTrucks)
end)
Trigger.OnKilled(Apwr, function(building)
BaseApwr.exists = false
end)
Trigger.OnKilled(Barr, function(building)
BaseTent.exists = false
end)
Trigger.OnKilled(Proc, function(building)
BaseProc.exists = false
end)
Trigger.OnKilled(Weap, function(building)
BaseWeap.exists = false
end)
Trigger.OnKilled(Apwr2, function(building)
BaseApwr2.exists = false
end)
Trigger.OnKilled(Dome, function()
player.MarkCompletedObjective(sovietObjective2)
Media.PlaySpeechNotification(player, "ObjectiveMet")
end)
-- Activate the AI once the player deployed the Mcv
Trigger.OnRemovedFromWorld(Mcv, function()
if not mcvDeployed then
mcvDeployed = true
BuildBase()
SendEnemies()
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor)
Trigger.AfterDelay(DateTime.Minutes(2), function()
Utils.Do(BaseAttackers, function(actor)
IdleHunt(actor)
end)
end)
end
end)
WorldLoaded = function()
player = Player.GetPlayer("USSR")
enemy = Player.GetPlayer("Greece")
Camera.Position = CameraStart.CenterPosition
Mcv.Move(McvWaypoint.Location)
Harvester.FindResources()
Utils.Do(IntroAttackers, function(actor)
IdleHunt(actor)
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == enemy and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == enemy and building.Health < 3/4 * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements1, SovietReinforcements1Waypoints)
Reinforcements.ReinforceWithTransport(player, "apc", SovietReinforcements2, SovietReinforcements2Waypoints)
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
alliedObjective = enemy.AddPrimaryObjective("Destroy all Soviet troops.")
sovietObjective = player.AddPrimaryObjective("Escort the Convoy.")
sovietObjective2 = player.AddSecondaryObjective("Destroy the Allied radar dome to stop enemy\nreinforcements.")
SaveAllTrucks = player.AddSecondaryObjective("Keep all trucks alive.")
end
Tick = function()
if player.HasNoRequiredUnits() then
enemy.MarkCompletedObjective(alliedObjective)
end
if enemy.Resources >= enemy.ResourceCapacity * 0.75 then
enemy.Cash = enemy.Cash + enemy.Resources - enemy.ResourceCapacity * 0.25
enemy.Resources = enemy.ResourceCapacity * 0.25
end
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c99960040.lua | 1 | 5694 | --BRS - Black Gold Saw
function c99960040.initial_effect(c)
--Xyz Summon
aux.AddXyzProcedure(c,nil,4,2)
c:EnableReviveLimit()
--Attach
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c99960040.attachcon)
e1:SetTarget(c99960040.attachtg)
e1:SetOperation(c99960040.attachop)
c:RegisterEffect(e1)
--Special Summon 1 BRS
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(99960040,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetCost(c99960040.spcost)
e2:SetTarget(c99960040.sptg)
e2:SetOperation(c99960040.spop)
c:RegisterEffect(e2)
--Halve ATK
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(99960040,1))
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetCountLimit(1)
e3:SetRange(LOCATION_MZONE)
e3:SetCost(c99960040.atkcost)
e3:SetTarget(c99960040.atktg)
e3:SetOperation(c99960040.atkop)
c:RegisterEffect(e3)
--ATK Up
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e4:SetRange(LOCATION_MZONE)
e4:SetCode(EFFECT_UPDATE_ATTACK)
e4:SetValue(c99960040.value)
c:RegisterEffect(e4)
--Detached
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_TODECK)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e5:SetCode(EVENT_TO_GRAVE)
e5:SetCondition(c99960040.detcon)
e5:SetTarget(c99960040.dettg)
e5:SetOperation(c99960040.detop)
c:RegisterEffect(e5)
end
function c99960040.attachcon(e,tp,eg,ep,ev,re,r,rp)
return re and re:GetHandler():IsSetCard(0x996) and not (e:GetHandler():IsPreviousLocation(LOCATION_EXTRA)
and e:GetHandler():GetSummonType()==SUMMON_TYPE_XYZ and re:GetHandler()==e:GetHandler())
end
function c99960040.attachfilter(c)
return not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end
function c99960040.attachtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c99960040.attachfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c99960040.attachfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_XMATERIAL)
Duel.SelectTarget(tp,c99960040.attachfilter,tp,LOCATION_GRAVE,0,1,1,nil)
end
function c99960040.attachop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsFaceup() and c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then
Duel.Overlay(c,Group.FromCards(tc))
end
end
function c99960040.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,700) end
Duel.PayLPCost(tp,700)
end
function c99960040.spfilter(c,e,tp)
return c:IsSetCard(0x996) and c:IsType(TYPE_XYZ) and c:GetRank()==4 and not c:IsCode(99960040)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c99960040.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c99960040.spfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c99960040.spop(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,c99960040.spfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c99960040.atkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c99960040.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(1-tp) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,Card.IsFaceup,tp,0,LOCATION_MZONE,1,1,nil)
end
function c99960040.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) and not tc:IsImmuneToEffect(e) then
local atk=tc:GetAttack()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(math.ceil(atk/2))
tc:RegisterEffect(e1)
if c:IsRelateToEffect(e) and c:IsFaceup() then
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetReset(RESET_EVENT+0x1ff0000+RESET_PHASE+PHASE_END)
e2:SetValue(math.ceil(atk/2))
c:RegisterEffect(e2)
end
end
end
function c99960040.value(e,c)
return Duel.GetMatchingGroupCount(Card.IsType,c:GetControler(),0,LOCATION_GRAVE,nil,TYPE_MONSTER)*100
end
function c99960040.detcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_COST) and re:IsHasType(0x7e0) and re:IsActiveType(TYPE_MONSTER)
and bit.band(c:GetPreviousLocation(),LOCATION_OVERLAY)~=0
end
function c99960040.dettg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TODECK,e:GetHandler(),1,0,0)
end
function c99960040.detop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SendtoDeck(c,nil,0,REASON_EFFECT)
end
end | gpl-3.0 |
waytim/darkstar | scripts/zones/Balgas_Dais/bcnms/rank_2_mission.lua | 26 | 1908 | -----------------------------------
-- Area: Horlais Peak
-- Name: Mission Rank 2
-- @pos 299 -123 345 146
-----------------------------------
package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Balgas_Dais/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)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompletedMission(player:getNation(),5)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
if (player:hasKeyItem(DARK_KEY)) then
player:addKeyItem(KINDRED_CREST);
player:messageSpecial(KEYITEM_OBTAINED,KINDRED_CREST);
player:setVar("MissionStatus",9);
player:delKeyItem(DARK_KEY);
end
end
end; | gpl-3.0 |
peterfillmore/proxmark3-14a-TagFuzz | client/lualibs/read14a.lua | 9 | 4126 | --[[
This is a library to read 14443a tags. It can be used something like this
local reader = require('read14a')
result, err = reader.read1443a()
if not result then
print(err)
return
end
print(result.name)
--]]
-- Loads the commands-library
local cmds = require('commands')
local TIMEOUT = 2000 -- Shouldn't take longer than 2 seconds
local ISO14A_COMMAND = {
ISO14A_CONNECT = 1,
ISO14A_NO_DISCONNECT = 2,
ISO14A_APDU = 4,
ISO14A_RAW = 8,
ISO14A_REQUEST_TRIGGER = 0x10,
ISO14A_APPEND_CRC = 0x20,
ISO14A_SET_TIMEOUT = 0x40
}
local ISO14443a_TYPES = {}
ISO14443a_TYPES[0x00] = "NXP MIFARE Ultralight | Ultralight C"
ISO14443a_TYPES[0x04] = "NXP MIFARE (various !DESFire !DESFire EV1)"
ISO14443a_TYPES[0x08] = "NXP MIFARE CLASSIC 1k | Plus 2k"
ISO14443a_TYPES[0x09] = "NXP MIFARE Mini 0.3k"
ISO14443a_TYPES[0x10] = "NXP MIFARE Plus 2k"
ISO14443a_TYPES[0x11] = "NXP MIFARE Plus 4k"
ISO14443a_TYPES[0x18] = "NXP MIFARE Classic 4k | Plus 4k"
ISO14443a_TYPES[0x20] = "NXP MIFARE DESFire 4k | DESFire EV1 2k/4k/8k | Plus 2k/4k | JCOP 31/41"
ISO14443a_TYPES[0x24] = "NXP MIFARE DESFire | DESFire EV1"
ISO14443a_TYPES[0x28] = "JCOP31 or JCOP41 v2.3.1"
ISO14443a_TYPES[0x38] = "Nokia 6212 or 6131 MIFARE CLASSIC 4K"
ISO14443a_TYPES[0x88] = "Infineon MIFARE CLASSIC 1K"
ISO14443a_TYPES[0x98] = "Gemplus MPCOS"
local function tostring_1443a(sak)
return ISO14443a_TYPES[sak] or ("Unknown (SAK=%x)"):format(sak)
end
local function parse1443a(data)
--[[
Based on this struct :
typedef struct {
byte_t uid[10];
byte_t uidlen;
byte_t atqa[2];
byte_t sak;
byte_t ats_len;
byte_t ats[256];
} __attribute__((__packed__)) iso14a_card_select_t;
--]]
local count,uid,uidlen, atqa, sak, ats_len, ats= bin.unpack('H10CH2CC',data)
uid = uid:sub(1,2*uidlen)
--print("uid, atqa, sak: ",uid, atqa, sak)
--print("TYPE: ", tostring_1443a(sak))
return { uid = uid, atqa = atqa, sak = sak, name = tostring_1443a(sak)}
end
--- Sends a USBpacket to the device
-- @param command - the usb packet to send
-- @param ignoreresponse - if set to true, we don't read the device answer packet
-- which is usually recipe for fail. If not sent, the host will wait 2s for a
-- response of type CMD_ACK
-- @return packet,nil if successfull
-- nil, errormessage if unsuccessfull
local function sendToDevice(command, ignoreresponse)
core.clearCommandBuffer()
local err = core.SendCommand(command:getBytes())
if err then
print(err)
return nil, err
end
if ignoreresponse then return nil,nil end
local response = core.WaitForResponseTimeout(cmds.CMD_ACK,TIMEOUT)
return response,nil
end
-- This function does a connect and retrieves som einfo
-- @param dont_disconnect - if true, does not disable the field
-- @return if successfull: an table containing card info
-- @return if unsuccessfull : nil, error
local function read14443a(dont_disconnect)
local command, result, info, err, data
command = Command:new{cmd = cmds.CMD_READER_ISO_14443a,
arg1 = ISO14A_COMMAND.ISO14A_CONNECT}
if dont_disconnect then
command.arg1 = command.arg1 + ISO14A_COMMAND.ISO14A_NO_DISCONNECT
end
local result,err = sendToDevice(command)
if result then
local count,cmd,arg0,arg1,arg2 = bin.unpack('LLLL',result)
if arg0 == 0 then
return nil, "iso14443a card select failed"
end
data = string.sub(result,count)
info, err = parse1443a(data)
else
err ="No response from card"
end
if err then
print(err)
return nil, err
end
return info
end
---
-- Waits for a mifare card to be placed within the vicinity of the reader.
-- @return if successfull: an table containing card info
-- @return if unsuccessfull : nil, error
local function waitFor14443a()
print("Waiting for card... press any key to quit")
while not core.ukbhit() do
res, err = read14443a()
if res then return res end
-- err means that there was no response from card
end
return nil, "Aborted by user"
end
local library = {
read1443a = read14443a,
read = read14443a,
waitFor14443a = waitFor14443a,
parse1443a = parse1443a,
sendToDevice = sendToDevice,
ISO14A_COMMAND = ISO14A_COMMAND,
}
return library | gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Quicksand_Caves/npcs/_5sa.lua | 4 | 1222 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -418 0 790 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-425);
local difZ = player:getZPos()-(790);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if(Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
waytim/darkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Kf_ghrah_whm.lua | 23 | 1894 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- MOB: Kf'ghrah WHM
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic"); -- no spells are currently set due to lack of info
-----------------------------------
-- onMobSpawn
-- Set core Skin and mob elemental bonus
-----------------------------------
function onMobSpawn(mob)
mob:AnimationSub(0);
mob:setLocalVar("roamTime", os.time());
mob:setModelId(1167); -- light
end;
-----------------------------------
-- onMobRoam
-- AutochangeForm
-----------------------------------
function onMobRoam(mob)
local roamTime = mob:getLocalVar("roamTime");
local roamForm;
if (os.time() - roamTime > 60) then
roamForm = math.random(1,3) -- forms 2 and 3 are spider and bird; can change forms at will
if (roamForm == 1) then
roamForm = 0; -- We don't want form 1 as that's humanoid - make it 0 for ball
end;
mob:AnimationSub(roamForm);
mob:setLocalVar("roamTime", os.time());
end;
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight
-- Free form change between ball, spider, and bird.
-----------------------------------
function onMobFight(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local battleForm;
if (mob:getBattleTime() - changeTime > 60) then
battleForm = math.random(1,3) -- same deal as above
if (battleForm == 1) then
battleForm = 0;
end;
mob:AnimationSub(battleForm);
mob:setLocalVar("changeTime", mob:getBattleTime());
end;
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/items/elshimo_coconut.lua | 18 | 1196 | -----------------------------------------
-- ID: 5187
-- Item: elshimo_coconut
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility -1
-- Intelligence -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5187);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, -1);
target:addMod(MOD_INT, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, -1);
target:delMod(MOD_INT, -1);
end;
| gpl-3.0 |
johnbelamaric/themis | vendor/github.com/apache/thrift/lib/lua/TServer.lua | 30 | 3992 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
require 'TFramedTransport'
require 'TBinaryProtocol'
-- TServer
TServer = __TObject:new{
__type = 'TServer'
}
-- 2 possible constructors
-- 1. {processor, serverTransport}
-- 2. {processor, serverTransport, transportFactory, protocolFactory}
function TServer:new(args)
if ttype(args) ~= 'table' then
error('TServer must be initialized with a table')
end
if args.processor == nil then
terror('You must provide ' .. ttype(self) .. ' with a processor')
end
if args.serverTransport == nil then
terror('You must provide ' .. ttype(self) .. ' with a serverTransport')
end
-- Create the object
local obj = __TObject.new(self, args)
if obj.transportFactory then
obj.inputTransportFactory = obj.transportFactory
obj.outputTransportFactory = obj.transportFactory
obj.transportFactory = nil
else
obj.inputTransportFactory = TFramedTransportFactory:new{}
obj.outputTransportFactory = obj.inputTransportFactory
end
if obj.protocolFactory then
obj.inputProtocolFactory = obj.protocolFactory
obj.outputProtocolFactory = obj.protocolFactory
obj.protocolFactory = nil
else
obj.inputProtocolFactory = TBinaryProtocolFactory:new{}
obj.outputProtocolFactory = obj.inputProtocolFactory
end
-- Set the __server variable in the handler so we can stop the server
obj.processor.handler.__server = self
return obj
end
function TServer:setServerEventHandler(handler)
self.serverEventHandler = handler
end
function TServer:_clientBegin(content, iprot, oprot)
if self.serverEventHandler and
type(self.serverEventHandler.clientBegin) == 'function' then
self.serverEventHandler:clientBegin(iprot, oprot)
end
end
function TServer:_preServe()
if self.serverEventHandler and
type(self.serverEventHandler.preServe) == 'function' then
self.serverEventHandler:preServe(self.serverTransport:getSocketInfo())
end
end
function TServer:_handleException(err)
if string.find(err, 'TTransportException') == nil then
print(err)
end
end
function TServer:serve() end
function TServer:handle(client)
local itrans, otrans =
self.inputTransportFactory:getTransport(client),
self.outputTransportFactory:getTransport(client)
local iprot, oprot =
self.inputProtocolFactory:getProtocol(itrans),
self.outputProtocolFactory:getProtocol(otrans)
self:_clientBegin(iprot, oprot)
while true do
local ret, err = pcall(self.processor.process, self.processor, iprot, oprot)
if ret == false and err then
if not string.find(err, "TTransportException") then
self:_handleException(err)
end
break
end
end
itrans:close()
otrans:close()
end
function TServer:close()
self.serverTransport:close()
end
-- TSimpleServer
-- Single threaded server that handles one transport (connection)
TSimpleServer = __TObject:new(TServer, {
__type = 'TSimpleServer',
__stop = false
})
function TSimpleServer:serve()
self.serverTransport:listen()
self:_preServe()
while not self.__stop do
client = self.serverTransport:accept()
self:handle(client)
end
self:close()
end
function TSimpleServer:stop()
self.__stop = true
end
| apache-2.0 |
waytim/darkstar | scripts/globals/items/persikos.lua | 18 | 1174 | -----------------------------------------
-- ID: 4274
-- Item: persikos
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility -7
-- Intelligence 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true 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,4274);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, -7);
target:addMod(MOD_INT, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, -7);
target:delMod(MOD_INT, 5);
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Chamber_of_Oracles/npcs/Pedestal_of_Ice.lua | 13 | 2373 | -----------------------------------
-- Area: Chamber of Oracles
-- NPC: Pedestal of Ice
-- Involved in Zilart Mission 7
-- @pos 199 -2 36 168
-------------------------------------
package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Chamber_of_Oracles/TextIDs");
-------------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ZilartStatus = player:getVar("ZilartStatus");
if (player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then
if (player:hasKeyItem(ICE_FRAGMENT)) then
player:delKeyItem(ICE_FRAGMENT);
player:setVar("ZilartStatus",ZilartStatus + 8);
player:messageSpecial(YOU_PLACE_THE,ICE_FRAGMENT);
if (ZilartStatus == 255) then
player:startEvent(0x0001);
end
elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted.
player:startEvent(0x0001);
else
player:messageSpecial(IS_SET_IN_THE_PEDESTAL,ICE_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES)) then
player:messageSpecial(HAS_LOST_ITS_POWER,ICE_FRAGMENT);
else
player:messageSpecial(PLACED_INTO_THE_PEDESTAL);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid == 0x0001) then
player:addTitle(LIGHTWEAVER);
player:setVar("ZilartStatus",0);
player:addKeyItem(PRISMATIC_FRAGMENT);
player:messageSpecial(KEYITEM_OBTAINED,PRISMATIC_FRAGMENT);
player:completeMission(ZILART,THE_CHAMBER_OF_ORACLES);
player:addMission(ZILART,RETURN_TO_DELKFUTTS_TOWER);
end
end;
| gpl-3.0 |
tomyun/Gearsystem | platforms/ios/dependencies/SDL-2.0.4-9174/premake/projects/testsprite2.lua | 7 | 1046 | -- 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>
--[[
testsprite2.lua
This file defines the testsprite2 test project. It depends on the SDL2main,
SDL2test, and SDL2 projects. It will not build on iOS or Cygwin.
]]
SDL_project "testsprite2"
SDL_kind "ConsoleApp"
SDL_notos "ios|cygwin"
SDL_language "C"
SDL_sourcedir "../test"
SDL_projectLocation "tests"
-- a list of items to copy from the sourcedir to the destination
SDL_copy { "icon.bmp" }
SDL_projectDependencies { "SDL2main", "SDL2test", "SDL2" }
SDL_files { "/testsprite2.*" }
| gpl-3.0 |
X-Raym/REAPER-ReaScripts | Theme/X-Raym_Theme auto-refresher (background).lua | 1 | 3006 | --[[
* ReaScript Name: Theme auto-refresher (background)
* Screenshot: https://i.imgur.com/yJnbHLQ.gif
* Author: X-Raym
* Author URI: https://www.extremraym.com
* Repository: GitHub > X-Raym > REAPER-ReaScripts
* Repository URI: https://github.com/X-Raym/REAPER-ReaScripts
* Forum Thread: Script: Theme auto-refresher
* Forum Thread URL: https://forum.cockos.com/showthread.php?p=2436611#post2436611
* Licence: GPL v3
* REAPER: 5.0
* Version: 1.0
--]]
--[[
* Changelog:
* v1.0 (2021-04-25)
+ Initial Release
--]]
-- USER CONFIG AREA -----------------------------------------------------------
console = true -- true/false: display debug messages in the console
refresh_rate = 0.1
------------------------------------------------------- END OF USER CONFIG AREA
if not reaper.JS_File_Stat then
reaper.MB("Missing dependency:\nPlease install js_reascriptAPI REAPER extension available from reapack. See Reapack.com for more infos.", "Error", 1 )
return
end
-- Set ToolBar Button State
function SetButtonState( set )
local is_new_value, filename, sec, cmd, mode, resolution, val = reaper.get_action_context()
reaper.SetToggleCommandState( sec, cmd, set or 0 )
reaper.RefreshToolbar2( sec, cmd )
end
-- Display a message in the console for debugging
function Msg(value)
if console then
reaper.ShowConsoleMsg(tostring(value) .. "\n")
end
end
-- Main Function (which loop in background)
function Main()
time = reaper.time_precise()
if time - init_time >= refresh_rate then
local retval, size, accessedTime, modifiedTime, cTime, deviceID, deviceSpecialID, inode, mode, numLinks, ownerUserID, ownerGroupID = reaper.JS_File_Stat( rt_config_path )
if modifiedTime ~= last_modifiedTime then
reaper.OpenColorThemeFile(theme_path)
reaper.UpdateArrange()
reaper.UpdateTimeline()
local mouse_x, mouse_y = reaper.GetMousePosition()
reaper.TrackCtl_SetToolTip("Theme Updated: " .. modifiedTime:sub(3), mouse_x + 17, mouse_y + 17, true)
last_modifiedTime = modifiedTime
end
init_time = time
end
reaper.defer(Main)
end
-- INIT
reaper.ClearConsole()
theme_path = reaper.GetLastColorThemeFile()
for line in io.lines(theme_path) do
folder = line:match("ui_img=(.+)")
if folder then
break
end
end
Msg("Current Theme:\n" .. theme_path)
os_sep = package.config:sub(1,1)
rt_config_path = reaper.GetResourcePath() .. os_sep .. "ColorThemes" .. os_sep .. folder .. os_sep .. "rtconfig.txt"
if not reaper.file_exists( rt_config_path ) then
Msg("rtconfig.txt file not found.")
return
end
Msg("Config File:\n" .. rt_config_path)
Msg("Modify and save this file to update the theme.")
init_time = reaper.time_precise()
retval, size, accessedTime, modifiedTime, cTime, deviceID, deviceSpecialID, inode, mode, numLinks, ownerUserID, ownerGroupID = reaper.JS_File_Stat( rt_config_path )
last_modifiedTime = modifiedTime
-- RUN
SetButtonState( 1 )
Main()
reaper.atexit( SetButtonState )
| gpl-3.0 |
focusworld/fcss | plugins/ingroup.lua | 24 | 53144 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'به ریلیم جدید ما خوش آمدید')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'ریلیم اضافه شد!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'شما صاحب گروه شدید')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'گروه اضافه شد و شما صاحب آن شدید')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'ریلیم حذف شد')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'گروه حذف شد')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local lock_link = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_link'] then
lock_link = data[tostring(msg.to.id)]['settings']['lock_link']
end
local sticker = "ok"
if data[tostring(msg.to.id)]['settings']['sticker'] then
sticker = data[tostring(msg.to.id)]['settings']['sticker']
end
local tag = "no"
if data[tostring(msg.to.id)]['settings']['tag'] then
tag = data[tostring(msg.to.id)]['settings']['tag']
end
local lock_badw = "no"
if data[tostring(msg.to.id)]['settings']['lock_badw'] then
lock_badw = data[tostring(msg.to.id)]['settings']['lock_badw']
end
local lock_english = "no"
if data[tostring(msg.to.id)]['settings']['lock_english'] then
lock_username = data[tostring(msg.to.id)]['settings']['lock_english']
end
local lock_arabic = "no"
if data[tostring(msg.to.id)]['settings']['lock_arabic'] then
lock_arabic = data[tostring(msg.to.id)]['settings']['lock_arabic']
end
local welcome = "group"
if data[tostring(msg.to.id)]['settings']['welcome'] then
welcome = data[tostring(msg.to.id)]['settings']['welcome']
end
local settings = data[tostring(target)]['settings']
local text = "تنظیمات گروه:\n⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙\n>قفل نام گروه : "..settings.lock_name.."\n>قفل عکس گروه : "..settings.lock_photo.."\n>قفل اعضا : "..settings.lock_member.."\n>ممنوعیت ارسال لینک : "..lock_link.."\n>حساسیت اسپم : "..NUM_MSG_MAX.."\n>قفل ربات ها : "..bots_protection.."\n>قفل تگ : "..tag.."\n>قفل اینگلیسی :"..lock_english.."\n>قفل فحش : "..lock_badw.."\n>Sbss Open Source Version\n"
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "قفط مدیران"
end
local data_cat = 'توضیحات'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'توضیحات گروه به این متن تغییر یافت:\n'..about
end
local function get_description(msg, data)
local data_cat = 'توضیحات'
if not data[tostring(msg.to.id)][data_cat] then
return 'توضیحی موجود نیست'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'درباره'..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'عربی از قبل قفل است'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'عربی قفل شد'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'عربی از قبل آزاد است'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'عربی آزاد شد'
end
end
local function lock_group_tag(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'yes' then
return 'تگ کردن از قبل قفل است🔒'
else
data[tostring(target)]['settings']['tag'] = 'yes'
save_data(_config.moderation.data, data)
return 'تگردن ممنوع شد✅🔒'
end
end
local function unlock_group_tag(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'no' then
return 'تگ کردن از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['tag'] = 'no'
save_data(_config.moderation.data, data)
return 'تگ کردن آزاد شد✅🔓'
end
end
local function lock_group_username(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران❗️"
end
local group_english_lock = data[tostring(target)]['settings']['lock_english']
if group_english_lock == 'yes' then
return 'ایگلیسی از قبل قفل است🔒'
else
data[tostring(target)]['settings']['lock_english'] = 'yes'
save_data(_config.moderation.data, data)
return 'اینگلیسی قفل شد✅🔒'
end
end
local function unlock_group_english(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران❗️"
end
local group_english_lock = data[tostring(target)]['settings']['lock_english']
if group_english_lock == 'no' then
return 'اینگلیسی از قبل باز است🔓'
else
data[tostring(target)]['settings']['lock_english'] = 'no'
save_data(_config.moderation.data, data)
return 'اینگلیسی ازاد شد✅🔓'
end
end
local function lock_group_badw(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_badw_lock = data[tostring(target)]['settings']['lock_badw']
if group_badw_lock == 'yes' then
return 'فحاشی از قبل ممنوع است🔒'
else
data[tostring(target)]['settings']['lock_badw'] = 'yes'
save_data(_config.moderation.data, data)
return 'فحاشی قفل شد✅🔒'
end
end
local function unlock_group_badw(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_badw_lock = data[tostring(target)]['settings']['lock_badw']
if group_badw_lock == 'no' then
return 'فحاشی از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['lock_badw'] = 'no'
save_data(_config.moderation.data, data)
return 'فحاشی آزاد شد✅🔓'
end
end
local function lock_group_link(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'ارسال لینک از قبل ممنوع است🔒'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'ارسال لینک ممنوع شد✅🔒'
end
end
local function unlock_group_link(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'ارسال لینک از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'lارسال لینک آزاد شد✅🔓'
end
end
local function lock_group_username(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران❗️"
end
local group_username_lock = data[tostring(target)]['settings']['lock_username']
if group_username_lock == 'yes' then
return 'یوزر نیم از قبل قفل است🔒'
else
data[tostring(target)]['settings']['lock_username'] = 'yes'
save_data(_config.moderation.data, data)
return 'یوزر نیم آزاد شد✅🔒'
end
end
local function unlock_group_username(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_username_lock = data[tostring(target)]['settings']['lock_username']
if group_username_lock == 'no' then
return 'ارسال یوزر نیم از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['lock_username'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال یوزر نیم آژاد شد✅🔓'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'قفل ربات ها از قبل فعال است'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'ورود ربات ها قفل شد'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'ورود ربات ها از قبل آزاد است'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'ورود ربات ها ازاد شد'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'نام گروه از قبل قفل است'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'نام گروه قفل شد'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'نام گروه از قبل باز است'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'نام گروه باز شد'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "فقط توسط گلوبال ادمین ها"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'ارسال پیام سریع ممنوع از قبل ممنوع بود'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'اسپم قفل شد'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "فقط برای گلوبال ادمین ها"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'اسپم قفل نیست!'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال سریع پیام آزاد شد'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'ورود اعضا از قبل قفل است'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ورود اعضا قفل شد'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'عضو گیری ازاد است'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'عضو گیری ازاد شد'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'خروج از قبل ممنوع بود'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'کسانی که خارج میشوند بن خواهند شد'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'خروج آزاد بود'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'خروج آزاد شد'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'عکس گروه قفل نیست'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'عکس گروه باز شد'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local data_cat = 'قوانین'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'قوانین گروه به این متن تغییر یافت:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'گروه از قبل اد شده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'ریلیم از قبل اد شده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'گروه اضافه نشده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'ریلیم اد نشده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'قوانین'
if not data[tostring(msg.to.id)][data_cat] then
return 'قانونی موجود نیست'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'قوانین گروه:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'عکس ذخیره شد!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'گروه اضافه نشده')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' از قبل مدیر است')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' ترفیع یافت')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'گروه اضافه نشده')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' مدیر نیست !')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' تنزل یافت')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setleader_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as leader")
local text = msg.from.print_name:gsub("_", " ").." اکنون صاحب گروه است "
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'ترفیع' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'تنزل' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'گروه اد نشده'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'دراین گروه هیچ مدیری وجود ندارد'
end
local i = 1
local message = '\nلیست مدیر های گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'اضافه' and not matches[2] then
if is_realm(msg) then
return 'خطا : از قبل ریلیم بوده'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'اضافه' and matches[2] == 'ریلیم' then
if is_group(msg) then
return 'خطا : اینجا یک گروه است'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'حذف' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'حذف' and matches[2] == 'ریلیم' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'تنظیم نام' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'تنظیم عکس' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'لطفا عکس جدید گروه را ارسال کنید'
end
if matches[1] == 'ترفیع' and not matches[2] then
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'ترفیع' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'ترفیع',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'تنزل' and not matches[2] then
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'تنزل' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "شما نمیتوانید مقام خود را حذف کنید"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'تنزل',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'لیست مدیران' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'توضیحات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'قوانین' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'تنظیم' then
if matches[2] == 'قوانین' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'توضیحات' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'قفل' then
local target = msg.to.id
if matches[2] == 'نام' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'اعضا' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'اسپم' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'ربات ها' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'لینک' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link🔒 ")
return lock_group_link(msg, data, target)
end
if matches[2] == 'تگ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag🔒 ")
return lock_group_tag(msg, data, target)
end
if matches[2] == 'فحش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw🔒 ")
return lock_group_badw(msg, data, target)
end
if matches[2] == 'اینگلیسی' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english🔒 ")
return lock_group_english(msg, data, target)
end
if matches[2] == 'خروج' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'بازکردن' then
local target = msg.to.id
if matches[2] == 'نام' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'اعضا' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'عکس' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'اسپم' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'ربات ها' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'لینک' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link🔓 ")
return unlock_group_link(msg, data, target)
end
if matches[2] == 'تگ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag🔓 ")
return unlock_group_tag(msg, data, target)
end
if matches[2] == 'فحش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw🔓 ")
return unlock_group_badw(msg, data, target)
end
if matches[2] == 'اینگلیسی' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english🔓 ")
return unlock_group_english(msg, data, target)
end
if matches[2] == 'خروج' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' or matches[1] == 'تنظیمات' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'لینک جدید' and not is_realm(msg) then
if not is_momod(msg) then
return "فقط برای مدیران"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*خطا : \nربات سازنده گروه نیست')
end
send_large_msg(receiver, "لینک جدید ساخته شد")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'لینک' then
if not is_momod(msg) then
return "فقط مدیران"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "اول با لینک جدید یک لینک جدید بسازید"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link
end
if matches[1] == 'لینک خصوصی' then
if not is_momod(msg) then
return "فقط برای مدیران"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "اول با لینک جدید یک لینک جدید بسازید"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link)
end
if matches[1] == 'دارنده' and matches[2] then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as leader")
local text = matches[2].." added as leader"
return text
end
if matches[1] == 'دارنده' and not matches[2] then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setleader_by_reply, false)
end
end
if matches[1] == 'صاحب گروه' then
local group_leader = data[tostring(msg.to.id)]['set_owner']
if not group_leader then
return "no leader,ask admins in support groups to set leader for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /leader")
return "آیدی صاحب گروه : ["..group_leader..']'
end
if matches[1] == 'صاحب' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as leader"
send_large_msg(receiver, text)
return
end
if matches[1] == 'حساسیت' then
if not is_momod(msg) then
return "شما مجاز نیستید"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "عددی از بین 5 و 20 انتخاب کنید"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'حساسیت اسپم تغییر یافت به '..matches[2]
end
if matches[1] == 'پاک کردن' then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
if matches[2] == 'اعضا' then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'مدیران' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'مدیری در گروه نیست'
end
local message = '\nلیست مدیران گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' and matches[2] == 'قوانین' then
local data_cat = 'قوانین'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'توضیحات' then
local data_cat = 'توضیحات'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'راهنما' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'کد' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^(اضافه)$",
"^(اضافه) (ریلیم)$",
"^(حذف)$",
"^(حذف) (ریلیم)$",
"^(قوانین)$",
"^(توضیحات)$",
"^(تنظیم نام) (.*)$",
"^(تنظیم عکس)$",
"^(ترفیع) (.*)$",
"^(ترفیع)",
"^(راهنما)$",
"^(پاک کردن) (.*)$",
"^(kill) (chat)$",
"^(kill) (realm)$",
"^(تنزل) (.*)$",
"^(تنزل)",
"^(تنظیم) ([^%s]+) (.*)$",
"^(قفل) (.*)$",
"^(دارنده) (%d+)$",
"^(دارنده)",
"^(صاحب گروه)$",
"^(کد) (.*)$",
"^(صاحب) (%d+) (%d+)$",-- (group id) (leader id)
"^(بازکردن) (.*)$",
"^(حساسیت) (%d+)$",
"^(تنظیمات)$",
-- "^(public) (.*)$",
"^(لیست مدیران)$",
"^(لینک جدید)$",
"^(لینک)$",
"^(kickinactive)$",
"^(kickinactive) (%d+)$",
"^(لینک خصوصی)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
gfgtdf/wesnoth-old | data/lua/wml/set_variable.lua | 2 | 4731 | local helper = wesnoth.require "helper"
function wesnoth.wml_actions.set_variable(cfg, variables)
local name = cfg.name or wml.error "trying to set a variable with an empty name"
if variables == nil then variables = wml.variables end
if cfg.value ~= nil then -- check for nil because user may try to set a variable as false
variables[name] = cfg.value
end
if cfg.literal ~= nil then
variables[name] = wml.shallow_literal(cfg).literal
end
if cfg.to_variable then
variables[name] = variables[cfg.to_variable]
end
if cfg.suffix then
variables[name] = (variables[name] or '') .. (cfg.suffix or '')
end
if cfg.prefix then
variables[name] = (cfg.prefix or '') .. (variables[name] or '')
end
if cfg.add then
variables[name] = (tonumber(variables[name]) or 0) + (tonumber(cfg.add) or 0)
end
if cfg.sub then
variables[name] = (tonumber(variables[name]) or 0) - (tonumber(cfg.sub) or 0)
end
if cfg.multiply then
variables[name] = (tonumber(variables[name]) or 0) * (tonumber(cfg.multiply) or 0)
end
if cfg.divide then
local divide = tonumber(cfg.divide) or 0
if divide == 0 then wml.error("division by zero on variable " .. name) end
variables[name] = (tonumber(variables[name]) or 0) / divide
end
if cfg.modulo then
local modulo = tonumber(cfg.modulo) or 0
if modulo == 0 then wml.error("division by zero on variable " .. name) end
variables[name] = (tonumber(variables[name]) or 0) % modulo
end
if cfg.abs then
variables[name] = math.abs(tonumber(variables[name]) or 0)
end
if cfg.root then
local root = tonumber(cfg.root)
local root_fcn
if cfg.root == "square" then
root = 2
root_fcn = math.sqrt
else
if cfg.root == "cube" then
root = 3
end
root_fcn = function(n) return n ^ (1 / root) end
end
local radicand = tonumber(variables[name]) or 0
if radicand < 0 and root % 2 == 0 then
if root == 2 then
wml.error("square root of negative number on variable " .. name)
else
wml.error(string.format("%dth root of negative number on variable %s", root, name))
end
end
variables[name] = root_fcn(radicand)
end
if cfg.power then
variables[name] = (tonumber(variables[name]) or 0) ^ (tonumber(cfg.power) or 0)
end
if cfg.round then
local var = tonumber(variables[name] or 0)
local round_val = cfg.round
if round_val == "ceil" then
variables[name] = math.ceil(var)
elseif round_val == "floor" then
variables[name] = math.floor(var)
elseif round_val == "trunc" then
-- Storing to a variable first because modf returns two values,
-- and I'm not sure if set_variable will complain about the extra parameter
local new_val = math.modf(var)
variables[name] = new_val
else
local decimals = math.modf(tonumber(round_val) or 0)
local value = var * (10 ^ decimals)
value = helper.round(value)
value = value * (10 ^ -decimals)
variables[name] = value
end
end
-- unlike the other math operations, ipart and fpart do not act on
-- the value already contained in the variable
-- but on the value assigned to the respective key
if cfg.ipart then
local ivalue = math.modf(tonumber(cfg.ipart) or 0)
variables[name] = ivalue
end
if cfg.fpart then
local ivalue, fvalue = math.modf(tonumber(cfg.fpart) or 0)
variables[name] = fvalue
end
if cfg.string_length ~= nil then
variables[name] = string.len(tostring(cfg.string_length))
end
if cfg.time then
if cfg.time == "stamp" then
variables[name] = wesnoth.get_time_stamp()
end
end
if cfg.rand then
variables[name] = helper.rand(tostring(cfg.rand))
end
if cfg.formula then
local fcn = wesnoth.compile_formula(cfg.formula)
variables[name] = fcn(variables[name])
end
local join_child = wml.get_child(cfg, "join")
if join_child then
local array_name = join_child.variable or wml.error "missing variable= attribute in [join]"
local separator = join_child.separator
local key_name = join_child.key or "value"
local remove_empty = join_child.remove_empty
local string_to_join = ''
for i, element in ipairs(wml.array_variables[array_name]) do
if element[key_name] ~= nil or (not remove_empty) then
if #string_to_join > 0 then
string_to_join = string_to_join .. separator
end
local elem = element[key_name]
if type(elem) == 'boolean' then
-- Use yes/no instead of true/false for booleans
elem = elem and 'yes' or 'no'
elseif getmetatable(elem) ~= 'translatable string' then
-- Not entirely sure if this branch is necessary, since it probably only triggers for numbers
-- It certainly can't hurt, though.
elem = tostring(elem)
end
string_to_join = string_to_join .. elem
end
end
variables[name] = string_to_join
end
end
| gpl-2.0 |
TienHP/Aquaria | files/scripts/entities/trillious.lua | 6 | 3458 | -- 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
-- ================================================================================================
-- T R I L L I O U S
-- ================================================================================================
-- ================================================================================================
-- L O C A L V A R I A B L E S
-- ================================================================================================
v.swimTime = 1.25
v.swimTimer = v.swimTime - v.swimTime/4
v.gasTimer = 1
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init(me)
setupBasicEntity(me,
"trillious-head", -- texture
8, -- health
2, -- manaballamount
2, -- exp
1, -- money
32, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
1, -- 0/1 hit other entities off/on (uses collideRadius)
4000 -- updateCull -1: disabled, default: 4000
)
-- entity_initPart(partName, partTexture, partPosition, partFlipH, partFlipV,
-- partOffsetInterpolateTo, partOffsetInterpolateTime
entity_initPart(me,
"FlipperLeft",
"trillious-flipper",
-12,
32,
1,
0,
0)
entity_initPart(me,
"FlipperRight",
"trillious-flipper",
12,
32,
1,
1,
0)
entity_partRotate(me, "FlipperLeft", 45, v.swimTime/2, -1, 1, 1)
entity_partRotate(me, "FlipperRight", -45, v.swimTime/2, -1, 1, 1)
entity_setDeathParticleEffect(me, "PurpleExplode")
entity_addRandomVel(me, 500)
-- entity_scale(0.8, 0.8)
end
function update(me, dt)
entity_handleShotCollisions(me)
if v.gasTimer > 0 then
v.gasTimer = v.gasTimer - dt
if v.gasTimer < 0 then
v.gasTimer = 8
entity_fireGas(me, 40, 4, 0.25, "Gas", 0, 0.8, 0.6, 0, 0, 2)
entity_addRandomVel(me, 1000)
spawnParticleEffect("tinygreenexplode", entity_x(me), entity_y(me))
entity_sound(me, "boil")
end
end
-- entity_doEntityAvoidance(dt, 256, 1);
entity_doCollisionAvoidance(me, dt, 12, 0.1);
entity_updateMovement(me, dt)
end
function enterState(me)
if entity_getState(me)==STATE_IDLE then
entity_setMaxSpeed(me, 400)
end
end
function exitState(me)
end
function damage(me, attacker, bone, damageType, dmg)
if damageType == DT_ENEMY_GAS then
return false
end
return true
end
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/abilities/pets/thunder_ii.lua | 4 | 1130 | ---------------------------------------------------
-- Aero 2
---------------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
require("/scripts/globals/magic");
---------------------------------------------------
function OnAbilityCheck(player, target, ability)
return 0,0;
end;
function OnPetAbility(target, pet, skill)
local spell = getSpell(165);
--calculate raw damage
local dmg = calculateMagicDamage(178,1,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
--get resist multiplier (1x if no resist)
local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_LIGHTNING);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = mobAddBonuses(pet,spell,target,dmg, 6);
--add on TP bonuses
local tp = pet:getTP();
if tp < 100 then
tp = 100;
end
dmg = dmg * tp / 100;
--add in final adjustments
dmg = finalMagicAdjustments(pet,target,spell,dmg);
return dmg;
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c59925840.lua | 2 | 1194 | --Vocaloid Oliver
function c59925840.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(59925840,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_DAMAGE)
e1:SetCondition(c59925840.sumcon)
e1:SetTarget(c59925840.sumtg)
e1:SetOperation(c59925840.sumop)
c:RegisterEffect(e1)
--nontuner
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_NONTUNER)
c:RegisterEffect(e2)
end
function c59925840.sumcon(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_BATTLE)>0 and ep==tp
end
function c59925840.sumtg(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 c59925840.sumop(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)
end
end | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Arrapago_Reef/npcs/qm10.lua | 4 | 2891 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: ???
-- Starts: Corsair Af1 ,AF2 ,AF3
-- @pos 457.128 -8.249 60.795 54
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local mJob = player:getMainJob();
local mLvl = player:getMainLvl();
local equipedForAll = player:getQuestStatus(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
local NoStringsAttached = player:getQuestStatus(AHT_URHGAN,NO_STRINGS_ATTACHED);
local NoStringsAttachedProgress = player:getVar("NoStringsAttachedProgress");
if (equipedForAll == QUEST_AVAILABLE and mJob == JOB_COR and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x0E4);
elseif(equipedForAll == QUEST_ACCEPTED and player:getVar("EquipedforAllOccasions") ==3) then
player:startEvent(0x0E7);
player:delKeyItem(WHEEL_LOCK_TRIGGER);
elseif(equipedForAll == QUEST_COMPLETED and player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_AVAILABLE and mJob == JOB_COR and mLvl >= AF2_QUEST_LEVEL) then
player:startEvent(0x0E8);
elseif(player:getVar("NavigatingtheUnfriendlySeas") ==4) then
player:startEvent(0x0E9);
elseif(NoStringsAttachedProgress == 3) then
player:startEvent(0x00d6); -- "You see an old, dented automaton..."
else
player:messageSpecial(8327); -- "There is nothing else of interest here."
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 == 0x0E4) then
player:addQuest(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
player:setVar("EquipedforAllOccasions",1);
elseif(csid== 0x0E7) then
player:setVar("EquipedforAllOccasions",4);
elseif(csid == 0x0E8) then
player:addQuest(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS);
player:setVar("NavigatingtheUnfriendlySeas",1);
elseif(csid == 0x0E9) then
player:addItem(15601) -- Receive item Corsairs culottes
player:messageSpecial(ITEM_OBTAINED,15601);
player:completeQuest(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS);
player:setVar("NavigatingtheUnfriendlySeas",0);
player:setVar("HydrogauageTimer",0);
elseif(csid == 0x00d6) then
player:addKeyItem(798);
player:messageSpecial(KEYITEM_OBTAINED,ANTIQUE_AUTOMATON);
player:setVar("NoStringsAttachedProgress",4);
end
end;
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c11111131.lua | 2 | 4073 | --Vocaloid Kaai Yuki Mdl - Gl104
function c11111131.initial_effect(c)
c:EnableReviveLimit()
--pendulum summon
aux.EnablePendulumAttribute(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--cannot direct attack
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
c:RegisterEffect(e2)
--cannot set
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_CANNOT_SSET)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(1,1)
c:RegisterEffect(e3)
--cannot trigger
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetCode(EFFECT_CANNOT_TRIGGER)
e4:SetProperty(EFFECT_FLAG_SET_AVAILABLE)
e4:SetRange(LOCATION_MZONE)
e4:SetTargetRange(LOCATION_SZONE,LOCATION_SZONE)
e4:SetTarget(c11111131.distg)
c:RegisterEffect(e4)
--to pzone
local e5=Effect.CreateEffect(c)
e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e5:SetCategory(CATEGORY_DESTROY)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_DESTROYED)
e5:SetCondition(c11111131.con)
e5:SetOperation(c11111131.op)
c:RegisterEffect(e5)
--act limit
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_FIELD)
e6:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e6:SetCode(EFFECT_CANNOT_ACTIVATE)
e6:SetRange(LOCATION_PZONE)
e6:SetTargetRange(1,1)
e6:SetValue(c11111131.activelimit)
c:RegisterEffect(e6)
--place pcard
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_IGNITION)
e7:SetRange(LOCATION_PZONE)
e7:SetCountLimit(1)
e7:SetCondition(c11111131.pencon)
e7:SetCost(c11111131.pencost)
e7:SetTarget(c11111131.pentg)
e7:SetOperation(c11111131.penop)
c:RegisterEffect(e7)
end
function c11111131.distg(e,c)
return c:IsFacedown()
end
function c11111131.penfilter1(c)
return c:IsDestructable() and c:GetSequence()==6
end
function c11111131.penfilter2(c)
return c:IsDestructable() and c:GetSequence()==7
end
function c11111131.con(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
if not p1 and not p2 then return false end
return (e:GetHandler():IsReason(REASON_EFFECT) or e:GetHandler():IsReason(REASON_BATTLE)) and
(p1 and p1:IsDestructable()) or (p2 and p2:IsDestructable()) and e:GetHandler():GetPreviousLocation()==LOCATION_MZONE
end
function c11111131.op(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
local g1=nil
local g2=nil
if p1 then
g1=Duel.GetMatchingGroup(c11111131.penfilter1,tp,LOCATION_SZONE,0,nil)
end
if p2 then
g2=Duel.GetMatchingGroup(c11111131.penfilter2,tp,LOCATION_SZONE,0,nil)
if g1 then
g1:Merge(g2)
else
g1=g2
end
end
if g1 and Duel.Destroy(g1,REASON_EFFECT)~=0 then
local c=e:GetHandler()
Duel.MoveToField(c,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
function c11111131.activelimit(e,re,tp)
return re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:IsActiveType(TYPE_TRAP)
end
function c11111131.pencost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,800) end
Duel.PayLPCost(tp,800)
end
function c11111131.penfilter4(c)
return c:IsType(TYPE_MONSTER) and c:IsRace(RACE_MACHINE) and c:IsType(TYPE_PENDULUM)
end
function c11111131.pencon(e,tp,eg,ep,ev,re,r,rp)
local seq=e:GetHandler():GetSequence()
return Duel.GetFieldCard(tp,LOCATION_SZONE,13-seq)==nil
end
function c11111131.pentg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c11111131.penfilter4,tp,LOCATION_EXTRA+LOCATION_HAND,0,1,nil) end
end
function c11111131.penop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD)
local g=Duel.SelectMatchingCard(tp,c11111131.penfilter4,tp,LOCATION_EXTRA+LOCATION_HAND,0,1,1,nil)
if g:GetCount()>0 then
local tc=g:GetFirst()
Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
| gpl-3.0 |
waytim/darkstar | scripts/zones/Heavens_Tower/npcs/Rakano-Marukano.lua | 13 | 2303 | -----------------------------------
-- Area: Heavens Tower
-- NPC: Rakano-Marukano
-- Type: Immigration NPC
-- @pos 6.174 -1 32.285 242
-----------------------------------
package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local new_nation = WINDURST;
local old_nation = player:getNation();
local rank = getNationRank(new_nation);
if (old_nation == new_nation) then
player:startEvent(0x2714,0,0,0,old_nation);
elseif (player:getCurrentMission(old_nation) ~= 255 or player:getVar("MissionStatus") ~= 0) then
player:startEvent(0x2713,0,0,0,new_nation);
elseif (old_nation ~= new_nation) then
local has_gil = 0;
local cost = 0;
if (rank == 1) then
cost = 40000;
elseif (rank == 2) then
cost = 12000;
elseif (rank == 3) then
cost = 4000;
end
if (player:getGil() >= cost) then
has_gil = 1
end
player:startEvent(0x2712,0,1,player:getRank(),new_nation,has_gil,cost);
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 == 0x2712 and option == 1) then
local new_nation = WINDURST;
local rank = getNationRank(new_nation);
local cost = 0;
if (rank == 1) then
cost = 40000;
elseif (rank == 2) then
cost = 12000;
elseif (rank == 3) then
cost = 4000;
end
player:setNation(new_nation)
player:setGil(player:getGil() - cost);
player:setRankPoints(0);
end
end; | gpl-3.0 |
chrox/koreader | frontend/ui/widget/pathchooser.lua | 6 | 1614 | local ButtonDialog = require("ui/widget/buttondialog")
local FileChooser = require("ui/widget/filechooser")
local UIManager = require("ui/uimanager")
local util = require("ffi/util")
local DEBUG = require("dbg")
local _ = require("gettext")
local PathChooser = FileChooser:extend{
title = _("Choose Path"),
no_title = false,
is_popout = false,
is_borderless = true,
show_filesize = false,
file_filter = function() return false end, -- filter out regular files
}
function PathChooser:onMenuSelect(item)
self.path = util.realpath(item.path)
local sub_table = self:genItemTableFromPath(self.path)
-- if sub table only have one entry(itself) we do nothing
if #sub_table > 1 then
self:changeToPath(item.path)
end
return true
end
function PathChooser:onMenuHold(item)
local onConfirm = self.onConfirm
self.button_dialog = ButtonDialog:new{
buttons = {
{
{
text = _("Confirm"),
callback = function()
if onConfirm then onConfirm(item.path) end
UIManager:close(self.button_dialog)
UIManager:close(self)
end,
},
{
text = _("Cancel"),
callback = function()
UIManager:close(self.button_dialog)
UIManager:close(self)
end,
},
},
},
}
UIManager:show(self.button_dialog)
return true
end
return PathChooser
| agpl-3.0 |
vovkasm/liteide | liteidex/src/memleak_update.lua | 3 | 1533 | local tmp = "/tmp"
local sep = "/"
local upper = ".."
require"lfs"
print (lfs._VERSION)
local memcheck = [[
//lite_memory_check_begin
#if defined(WIN32) && defined(_MSC_VER) && defined(_DEBUG)
#define _CRTDBG_MAP_ALLOC
#include <stdlib.h>
#include <crtdbg.h>
#define DEBUG_NEW new( _NORMAL_BLOCK, __FILE__, __LINE__ )
#define new DEBUG_NEW
#endif
//lite_memory_check_end
]]
function update_memleak(file,name)
local f = io.open(file,"r")
if f == nil then return end
local data = f:read("*all")
f:close()
local find = string.find(data,"//lite_memory_check_begin")
if find ~= nil then
print("skip file:",file)
return
end
print(">>process file:",file)
local i = 0
local last = 0
while true do
i = string.find(data,"#include",i+1)
if i == nil then break end
last = i
end
i = string.find(data,"\n",last+1)
if i == nil then
return
end
f = io.open(file,"w")
if f == nil then return end
f:write(string.sub(data,1,i)..memcheck..string.sub(data,i+1,#data))
f:close()
end
function process_file(file,name)
local ext = string.match(file,"%.%w+$")
if ext == ".cpp" then
update_memleak(file,name)
end
end
function attrdir (path)
for file in lfs.dir(path) do
if file ~= "." and file ~= ".." then
local f = path..sep..file
local attr = lfs.attributes (f)
assert (type(attr) == "table")
if attr.mode == "directory" then
attrdir (f)
else
process_file(f,file)
end
end
end
end
attrdir("./liteapp")
attrdir("./api")
attrdir("./plugins")
attrdir("./utils")
| lgpl-2.1 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/shadow_of_death.lua | 4 | 1194 | -----------------------------------
-- Shadow Of Death
-- Scythe weapon skill
-- Skill Level: 70
-- Delivers a dark elemental attack. Damage varies with TP.
-- Aligned with the Snow Gorget & Aqua Gorget.
-- Aligned with the Snow Belt & Aqua Belt.
-- Element: Dark
-- Modifiers: STR:30% ; INT:30%
-- 100%TP 200%TP 300%TP
-- 1.00 2.50 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 2.5; params.ftp300 = 3;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.3; 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/Quicksand_Caves/npcs/qm5.lua | 12 | 2198 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: ??? (qm5)
-- Involved in Quest: The Missing Piece
-- @pos
--1:770 0 -419
--2:657 0 -537
--3:749 0 -573
--4:451 -16 -739
--5:787 -16 -819
--spawn in npc_list is 770 0 -419
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TheMissingPiece = player:getQuestStatus(OUTLANDS,THE_MISSING_PIECE);
local HasAncientFragment = player:hasKeyItem(ANCIENT_TABLET_FRAGMENT);
local HasAncientTablet = player:hasKeyItem(TABLET_OF_ANCIENT_MAGIC);
--Need to make sure the quest is flagged the player is no further along in the quest
if (TheMissingPiece == QUEST_ACCEPTED and not(HasAncientTablet or HasAncientFragment or player:getTitle() == ACQUIRER_OF_ANCIENT_ARCANUM)) then
player:addKeyItem(ANCIENT_TABLET_FRAGMENT);
player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_TABLET_FRAGMENT);
--move the ??? to a random location
local i = math.random(0,100);
if (i >= 0 and i < 20) then
npc:setPos(770,0,-419,0);
elseif (i >= 20 and i < 40) then
npc:setPos(657,0,-537,0);
elseif (i >= 40 and i < 60) then
npc:setPos(749,0,-573,0);
elseif (i >= 60 and i < 80) then
npc:setPos(451,-16,-739,0);
elseif (i >= 80 and i <= 100) then
npc:setPos(787,-16,-819,0);
else
npc:setPos(787,-16,-819,0);
end;
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("RESULT:",option);
end;
| gpl-3.0 |
ZACTELEGRAM1/EMAM-ALI | plugins/search_youtube.lua | 674 | 1270 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
local function searchYoutubeVideos(text)
local url = 'https://www.googleapis.com/youtube/v3/search?'
url = url..'part=snippet'..'&maxResults=4'..'&type=video'
url = url..'&q='..URL.escape(text)
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local data = httpsRequest(url)
if not data then
print("HTTP Error")
return nil
elseif not data.items then
return nil
end
return data.items
end
local function run(msg, matches)
local text = ''
local items = searchYoutubeVideos(matches[1])
if not items then
return "Error!"
end
for k,item in pairs(items) do
text = text..'http://youtu.be/'..item.id.videoId..' '..
item.snippet.title..'\n\n'
end
return text
end
return {
description = "Search video on youtube and send it.",
usage = "!youtube [term]: Search for a youtube video and send it.",
patterns = {
"^!youtube (.*)"
},
run = run
}
end
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/weaponskills/numbing_shot.lua | 4 | 1626 | -----------------------------------
-- Numbing Shot
-- Marksmanship weapon skill
-- Skill level: 290
-- Main of sub must be Ranger or Corsair
-- Aligned with the Thunder & Breeze Gorget.
-- Aligned with the Thunder Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: STR 30% MND 25%
-- 100%TP 200%TP 300%TP
-- 3.00 3.00 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.25; 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 = doRangedWeaponskill(player, target, params);
local crticalHit = false;
if damage > 0 then
tp = player:getTP();
duration = (tp/100 * 30) + 60;
if(target:hasStatusEffect(EFFECT_PARALYSIS) == false) then
-- paralyze proc based on lvl difference
local power = 20 + (player:getMainLvl() - target:getMainLvl())*3;
if(power > 30) then
power = 30;
end
if(power < 5) then
power = 5;
end
target:addStatusEffect(EFFECT_PARALYSIS, power, 0, duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
saeqe/nod | plugins/tophoto.lua | 24 | 1059 | local function tosticker(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/stickers/'..msg.from.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
send_photo(get_receiver(msg), file, ok_cb, false)
redis:del("sticker:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.media then
if msg.media.type == 'document' and is_momod(msg) and redis:get("sticker:photo") then
if redis:get("sticker:photo") == 'waiting' then
load_document(msg.id, tosticker, msg)
end
end
end
if matches[1] == "tophoto" and is_momod(msg) then
redis:set("sticker:photo", "waiting")
return 'Please send your sticker now'
end
end
return {
patterns = {
"^[!/](tophoto)$",
"%[(document)%]",
},
run = run,
}
| gpl-2.0 |
steven-jackson/PersonalLoot | libs/AceGUI-3.0/widgets/AceGUIWidget-DropDown.lua | 9 | 19445 | --[[ $Id: AceGUIWidget-DropDown.lua 1116 2014-10-12 08:15:46Z nevcairiel $ ]]--
local AceGUI = LibStub("AceGUI-3.0")
-- Lua APIs
local min, max, floor = math.min, math.max, math.floor
local select, pairs, ipairs, type = select, pairs, ipairs, type
local tsort = table.sort
-- WoW APIs
local PlaySound = PlaySound
local UIParent, CreateFrame = UIParent, CreateFrame
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: CLOSE
local function fixlevels(parent,...)
local i = 1
local child = select(i, ...)
while child do
child:SetFrameLevel(parent:GetFrameLevel()+1)
fixlevels(child, child:GetChildren())
i = i + 1
child = select(i, ...)
end
end
local function fixstrata(strata, parent, ...)
local i = 1
local child = select(i, ...)
parent:SetFrameStrata(strata)
while child do
fixstrata(strata, child, child:GetChildren())
i = i + 1
child = select(i, ...)
end
end
do
local widgetType = "Dropdown-Pullout"
local widgetVersion = 3
--[[ Static data ]]--
local backdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\DialogFrame\\UI-DialogBox-Border",
edgeSize = 32,
tileSize = 32,
tile = true,
insets = { left = 11, right = 12, top = 12, bottom = 11 },
}
local sliderBackdrop = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true, tileSize = 8, edgeSize = 8,
insets = { left = 3, right = 3, top = 3, bottom = 3 }
}
local defaultWidth = 200
local defaultMaxHeight = 600
--[[ UI Event Handlers ]]--
-- HACK: This should be no part of the pullout, but there
-- is no other 'clean' way to response to any item-OnEnter
-- Used to close Submenus when an other item is entered
local function OnEnter(item)
local self = item.pullout
for k, v in ipairs(self.items) do
if v.CloseMenu and v ~= item then
v:CloseMenu()
end
end
end
-- See the note in Constructor() for each scroll related function
local function OnMouseWheel(this, value)
this.obj:MoveScroll(value)
end
local function OnScrollValueChanged(this, value)
this.obj:SetScroll(value)
end
local function OnSizeChanged(this)
this.obj:FixScroll()
end
--[[ Exported methods ]]--
-- exported
local function SetScroll(self, value)
local status = self.scrollStatus
local frame, child = self.scrollFrame, self.itemFrame
local height, viewheight = frame:GetHeight(), child:GetHeight()
local offset
if height > viewheight then
offset = 0
else
offset = floor((viewheight - height) / 1000 * value)
end
child:ClearAllPoints()
child:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, offset)
child:SetPoint("TOPRIGHT", frame, "TOPRIGHT", self.slider:IsShown() and -12 or 0, offset)
status.offset = offset
status.scrollvalue = value
end
-- exported
local function MoveScroll(self, value)
local status = self.scrollStatus
local frame, child = self.scrollFrame, self.itemFrame
local height, viewheight = frame:GetHeight(), child:GetHeight()
if height > viewheight then
self.slider:Hide()
else
self.slider:Show()
local diff = height - viewheight
local delta = 1
if value < 0 then
delta = -1
end
self.slider:SetValue(min(max(status.scrollvalue + delta*(1000/(diff/45)),0), 1000))
end
end
-- exported
local function FixScroll(self)
local status = self.scrollStatus
local frame, child = self.scrollFrame, self.itemFrame
local height, viewheight = frame:GetHeight(), child:GetHeight()
local offset = status.offset or 0
if viewheight < height then
self.slider:Hide()
child:SetPoint("TOPRIGHT", frame, "TOPRIGHT", 0, offset)
self.slider:SetValue(0)
else
self.slider:Show()
local value = (offset / (viewheight - height) * 1000)
if value > 1000 then value = 1000 end
self.slider:SetValue(value)
self:SetScroll(value)
if value < 1000 then
child:ClearAllPoints()
child:SetPoint("TOPLEFT", frame, "TOPLEFT", 0, offset)
child:SetPoint("TOPRIGHT", frame, "TOPRIGHT", -12, offset)
status.offset = offset
end
end
end
-- exported, AceGUI callback
local function OnAcquire(self)
self.frame:SetParent(UIParent)
--self.itemFrame:SetToplevel(true)
end
-- exported, AceGUI callback
local function OnRelease(self)
self:Clear()
self.frame:ClearAllPoints()
self.frame:Hide()
end
-- exported
local function AddItem(self, item)
self.items[#self.items + 1] = item
local h = #self.items * 16
self.itemFrame:SetHeight(h)
self.frame:SetHeight(min(h + 34, self.maxHeight)) -- +34: 20 for scrollFrame placement (10 offset) and +14 for item placement
item.frame:SetPoint("LEFT", self.itemFrame, "LEFT")
item.frame:SetPoint("RIGHT", self.itemFrame, "RIGHT")
item:SetPullout(self)
item:SetOnEnter(OnEnter)
end
-- exported
local function Open(self, point, relFrame, relPoint, x, y)
local items = self.items
local frame = self.frame
local itemFrame = self.itemFrame
frame:SetPoint(point, relFrame, relPoint, x, y)
local height = 8
for i, item in pairs(items) do
if i == 1 then
item:SetPoint("TOP", itemFrame, "TOP", 0, -2)
else
item:SetPoint("TOP", items[i-1].frame, "BOTTOM", 0, 1)
end
item:Show()
height = height + 16
end
itemFrame:SetHeight(height)
fixstrata("TOOLTIP", frame, frame:GetChildren())
frame:Show()
self:Fire("OnOpen")
end
-- exported
local function Close(self)
self.frame:Hide()
self:Fire("OnClose")
end
-- exported
local function Clear(self)
local items = self.items
for i, item in pairs(items) do
AceGUI:Release(item)
items[i] = nil
end
end
-- exported
local function IterateItems(self)
return ipairs(self.items)
end
-- exported
local function SetHideOnLeave(self, val)
self.hideOnLeave = val
end
-- exported
local function SetMaxHeight(self, height)
self.maxHeight = height or defaultMaxHeight
if self.frame:GetHeight() > height then
self.frame:SetHeight(height)
elseif (self.itemFrame:GetHeight() + 34) < height then
self.frame:SetHeight(self.itemFrame:GetHeight() + 34) -- see :AddItem
end
end
-- exported
local function GetRightBorderWidth(self)
return 6 + (self.slider:IsShown() and 12 or 0)
end
-- exported
local function GetLeftBorderWidth(self)
return 6
end
--[[ Constructor ]]--
local function Constructor()
local count = AceGUI:GetNextWidgetNum(widgetType)
local frame = CreateFrame("Frame", "AceGUI30Pullout"..count, UIParent)
local self = {}
self.count = count
self.type = widgetType
self.frame = frame
frame.obj = self
self.OnAcquire = OnAcquire
self.OnRelease = OnRelease
self.AddItem = AddItem
self.Open = Open
self.Close = Close
self.Clear = Clear
self.IterateItems = IterateItems
self.SetHideOnLeave = SetHideOnLeave
self.SetScroll = SetScroll
self.MoveScroll = MoveScroll
self.FixScroll = FixScroll
self.SetMaxHeight = SetMaxHeight
self.GetRightBorderWidth = GetRightBorderWidth
self.GetLeftBorderWidth = GetLeftBorderWidth
self.items = {}
self.scrollStatus = {
scrollvalue = 0,
}
self.maxHeight = defaultMaxHeight
frame:SetBackdrop(backdrop)
frame:SetBackdropColor(0, 0, 0)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
frame:SetClampedToScreen(true)
frame:SetWidth(defaultWidth)
frame:SetHeight(self.maxHeight)
--frame:SetToplevel(true)
-- NOTE: The whole scroll frame code is copied from the AceGUI-3.0 widget ScrollFrame
local scrollFrame = CreateFrame("ScrollFrame", nil, frame)
local itemFrame = CreateFrame("Frame", nil, scrollFrame)
self.scrollFrame = scrollFrame
self.itemFrame = itemFrame
scrollFrame.obj = self
itemFrame.obj = self
local slider = CreateFrame("Slider", "AceGUI30PulloutScrollbar"..count, scrollFrame)
slider:SetOrientation("VERTICAL")
slider:SetHitRectInsets(0, 0, -10, 0)
slider:SetBackdrop(sliderBackdrop)
slider:SetWidth(8)
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Vertical")
slider:SetFrameStrata("FULLSCREEN_DIALOG")
self.slider = slider
slider.obj = self
scrollFrame:SetScrollChild(itemFrame)
scrollFrame:SetPoint("TOPLEFT", frame, "TOPLEFT", 6, -12)
scrollFrame:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -6, 12)
scrollFrame:EnableMouseWheel(true)
scrollFrame:SetScript("OnMouseWheel", OnMouseWheel)
scrollFrame:SetScript("OnSizeChanged", OnSizeChanged)
scrollFrame:SetToplevel(true)
scrollFrame:SetFrameStrata("FULLSCREEN_DIALOG")
itemFrame:SetPoint("TOPLEFT", scrollFrame, "TOPLEFT", 0, 0)
itemFrame:SetPoint("TOPRIGHT", scrollFrame, "TOPRIGHT", -12, 0)
itemFrame:SetHeight(400)
itemFrame:SetToplevel(true)
itemFrame:SetFrameStrata("FULLSCREEN_DIALOG")
slider:SetPoint("TOPLEFT", scrollFrame, "TOPRIGHT", -16, 0)
slider:SetPoint("BOTTOMLEFT", scrollFrame, "BOTTOMRIGHT", -16, 0)
slider:SetScript("OnValueChanged", OnScrollValueChanged)
slider:SetMinMaxValues(0, 1000)
slider:SetValueStep(1)
slider:SetValue(0)
scrollFrame:Show()
itemFrame:Show()
slider:Hide()
self:FixScroll()
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion)
end
do
local widgetType = "Dropdown"
local widgetVersion = 30
--[[ Static data ]]--
--[[ UI event handler ]]--
local function Control_OnEnter(this)
this.obj.button:LockHighlight()
this.obj:Fire("OnEnter")
end
local function Control_OnLeave(this)
this.obj.button:UnlockHighlight()
this.obj:Fire("OnLeave")
end
local function Dropdown_OnHide(this)
local self = this.obj
if self.open then
self.pullout:Close()
end
end
local function Dropdown_TogglePullout(this)
local self = this.obj
PlaySound("igMainMenuOptionCheckBoxOn") -- missleading name, but the Blizzard code uses this sound
if self.open then
self.open = nil
self.pullout:Close()
AceGUI:ClearFocus()
else
self.open = true
self.pullout:SetWidth(self.pulloutWidth or self.frame:GetWidth())
self.pullout:Open("TOPLEFT", self.frame, "BOTTOMLEFT", 0, self.label:IsShown() and -2 or 0)
AceGUI:SetFocus(self)
end
end
local function OnPulloutOpen(this)
local self = this.userdata.obj
local value = self.value
if not self.multiselect then
for i, item in this:IterateItems() do
item:SetValue(item.userdata.value == value)
end
end
self.open = true
self:Fire("OnOpened")
end
local function OnPulloutClose(this)
local self = this.userdata.obj
self.open = nil
self:Fire("OnClosed")
end
local function ShowMultiText(self)
local text
for i, widget in self.pullout:IterateItems() do
if widget.type == "Dropdown-Item-Toggle" then
if widget:GetValue() then
if text then
text = text..", "..widget:GetText()
else
text = widget:GetText()
end
end
end
end
self:SetText(text)
end
local function OnItemValueChanged(this, event, checked)
local self = this.userdata.obj
if self.multiselect then
self:Fire("OnValueChanged", this.userdata.value, checked)
ShowMultiText(self)
else
if checked then
self:SetValue(this.userdata.value)
self:Fire("OnValueChanged", this.userdata.value)
else
this:SetValue(true)
end
if self.open then
self.pullout:Close()
end
end
end
--[[ Exported methods ]]--
-- exported, AceGUI callback
local function OnAcquire(self)
local pullout = AceGUI:Create("Dropdown-Pullout")
self.pullout = pullout
pullout.userdata.obj = self
pullout:SetCallback("OnClose", OnPulloutClose)
pullout:SetCallback("OnOpen", OnPulloutOpen)
self.pullout.frame:SetFrameLevel(self.frame:GetFrameLevel() + 1)
fixlevels(self.pullout.frame, self.pullout.frame:GetChildren())
self:SetHeight(44)
self:SetWidth(200)
self:SetLabel()
self:SetPulloutWidth(nil)
end
-- exported, AceGUI callback
local function OnRelease(self)
if self.open then
self.pullout:Close()
end
AceGUI:Release(self.pullout)
self.pullout = nil
self:SetText("")
self:SetDisabled(false)
self:SetMultiselect(false)
self.value = nil
self.list = nil
self.open = nil
self.hasClose = nil
self.frame:ClearAllPoints()
self.frame:Hide()
end
-- exported
local function SetDisabled(self, disabled)
self.disabled = disabled
if disabled then
self.text:SetTextColor(0.5,0.5,0.5)
self.button:Disable()
self.button_cover:Disable()
self.label:SetTextColor(0.5,0.5,0.5)
else
self.button:Enable()
self.button_cover:Enable()
self.label:SetTextColor(1,.82,0)
self.text:SetTextColor(1,1,1)
end
end
-- exported
local function ClearFocus(self)
if self.open then
self.pullout:Close()
end
end
-- exported
local function SetText(self, text)
self.text:SetText(text or "")
end
-- exported
local function SetLabel(self, text)
if text and text ~= "" then
self.label:SetText(text)
self.label:Show()
self.dropdown:SetPoint("TOPLEFT",self.frame,"TOPLEFT",-15,-14)
self:SetHeight(40)
self.alignoffset = 26
else
self.label:SetText("")
self.label:Hide()
self.dropdown:SetPoint("TOPLEFT",self.frame,"TOPLEFT",-15,0)
self:SetHeight(26)
self.alignoffset = 12
end
end
-- exported
local function SetValue(self, value)
if self.list then
self:SetText(self.list[value] or "")
end
self.value = value
end
-- exported
local function GetValue(self)
return self.value
end
-- exported
local function SetItemValue(self, item, value)
if not self.multiselect then return end
for i, widget in self.pullout:IterateItems() do
if widget.userdata.value == item then
if widget.SetValue then
widget:SetValue(value)
end
end
end
ShowMultiText(self)
end
-- exported
local function SetItemDisabled(self, item, disabled)
for i, widget in self.pullout:IterateItems() do
if widget.userdata.value == item then
widget:SetDisabled(disabled)
end
end
end
local function AddListItem(self, value, text, itemType)
if not itemType then itemType = "Dropdown-Item-Toggle" end
local exists = AceGUI:GetWidgetVersion(itemType)
if not exists then error(("The given item type, %q, does not exist within AceGUI-3.0"):format(tostring(itemType)), 2) end
local item = AceGUI:Create(itemType)
item:SetText(text)
item.userdata.obj = self
item.userdata.value = value
item:SetCallback("OnValueChanged", OnItemValueChanged)
self.pullout:AddItem(item)
end
local function AddCloseButton(self)
if not self.hasClose then
local close = AceGUI:Create("Dropdown-Item-Execute")
close:SetText(CLOSE)
self.pullout:AddItem(close)
self.hasClose = true
end
end
-- exported
local sortlist = {}
local function SetList(self, list, order, itemType)
self.list = list
self.pullout:Clear()
self.hasClose = nil
if not list then return end
if type(order) ~= "table" then
for v in pairs(list) do
sortlist[#sortlist + 1] = v
end
tsort(sortlist)
for i, key in ipairs(sortlist) do
AddListItem(self, key, list[key], itemType)
sortlist[i] = nil
end
else
for i, key in ipairs(order) do
AddListItem(self, key, list[key], itemType)
end
end
if self.multiselect then
ShowMultiText(self)
AddCloseButton(self)
end
end
-- exported
local function AddItem(self, value, text, itemType)
if self.list then
self.list[value] = text
AddListItem(self, value, text, itemType)
end
end
-- exported
local function SetMultiselect(self, multi)
self.multiselect = multi
if multi then
ShowMultiText(self)
AddCloseButton(self)
end
end
-- exported
local function GetMultiselect(self)
return self.multiselect
end
local function SetPulloutWidth(self, width)
self.pulloutWidth = width
end
--[[ Constructor ]]--
local function Constructor()
local count = AceGUI:GetNextWidgetNum(widgetType)
local frame = CreateFrame("Frame", nil, UIParent)
local dropdown = CreateFrame("Frame", "AceGUI30DropDown"..count, frame, "UIDropDownMenuTemplate")
local self = {}
self.type = widgetType
self.frame = frame
self.dropdown = dropdown
self.count = count
frame.obj = self
dropdown.obj = self
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.ClearFocus = ClearFocus
self.SetText = SetText
self.SetValue = SetValue
self.GetValue = GetValue
self.SetList = SetList
self.SetLabel = SetLabel
self.SetDisabled = SetDisabled
self.AddItem = AddItem
self.SetMultiselect = SetMultiselect
self.GetMultiselect = GetMultiselect
self.SetItemValue = SetItemValue
self.SetItemDisabled = SetItemDisabled
self.SetPulloutWidth = SetPulloutWidth
self.alignoffset = 26
frame:SetScript("OnHide",Dropdown_OnHide)
dropdown:ClearAllPoints()
dropdown:SetPoint("TOPLEFT",frame,"TOPLEFT",-15,0)
dropdown:SetPoint("BOTTOMRIGHT",frame,"BOTTOMRIGHT",17,0)
dropdown:SetScript("OnHide", nil)
local left = _G[dropdown:GetName() .. "Left"]
local middle = _G[dropdown:GetName() .. "Middle"]
local right = _G[dropdown:GetName() .. "Right"]
middle:ClearAllPoints()
right:ClearAllPoints()
middle:SetPoint("LEFT", left, "RIGHT", 0, 0)
middle:SetPoint("RIGHT", right, "LEFT", 0, 0)
right:SetPoint("TOPRIGHT", dropdown, "TOPRIGHT", 0, 17)
local button = _G[dropdown:GetName() .. "Button"]
self.button = button
button.obj = self
button:SetScript("OnEnter",Control_OnEnter)
button:SetScript("OnLeave",Control_OnLeave)
button:SetScript("OnClick",Dropdown_TogglePullout)
local button_cover = CreateFrame("BUTTON",nil,self.frame)
self.button_cover = button_cover
button_cover.obj = self
button_cover:SetPoint("TOPLEFT",self.frame,"BOTTOMLEFT",0,25)
button_cover:SetPoint("BOTTOMRIGHT",self.frame,"BOTTOMRIGHT")
button_cover:SetScript("OnEnter",Control_OnEnter)
button_cover:SetScript("OnLeave",Control_OnLeave)
button_cover:SetScript("OnClick",Dropdown_TogglePullout)
local text = _G[dropdown:GetName() .. "Text"]
self.text = text
text.obj = self
text:ClearAllPoints()
text:SetPoint("RIGHT", right, "RIGHT" ,-43, 2)
text:SetPoint("LEFT", left, "LEFT", 25, 2)
local label = frame:CreateFontString(nil,"OVERLAY","GameFontNormalSmall")
label:SetPoint("TOPLEFT",frame,"TOPLEFT",0,0)
label:SetPoint("TOPRIGHT",frame,"TOPRIGHT",0,0)
label:SetJustifyH("LEFT")
label:SetHeight(18)
label:Hide()
self.label = label
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion)
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c44559824.lua | 1 | 7307 | --Qilin, Thunder King of the Sky Nirvana
function c44559824.initial_effect(c)
c:SetUniqueOnField(1,0,44559824)
--fusion material
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(c44559824.fuscon)
e1:SetOperation(c44559824.fusop)
c:RegisterEffect(e1)
--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(aux.fuslimit)
c:RegisterEffect(e2)
--Immune
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CANNOT_BE_EFFECT_TARGET)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetValue(aux.tgoval)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e4:SetValue(c44559824.tgvalue)
c:RegisterEffect(e4)
--destroy
local e5=Effect.CreateEffect(c)
e5:SetCategory(CATEGORY_DESTROY)
e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_SPSUMMON_SUCCESS)
e5:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e5:SetCondition(c44559824.descon)
e5:SetTarget(c44559824.destg)
e5:SetOperation(c44559824.desop)
c:RegisterEffect(e5)
--actlimit
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_FIELD)
e6:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e6:SetCode(EFFECT_CANNOT_ACTIVATE)
e6:SetRange(LOCATION_MZONE)
e6:SetTargetRange(0,1)
e6:SetValue(c44559824.aclimit)
e6:SetCondition(c44559824.actcon)
c:RegisterEffect(e6)
--sp restrict
local e7=Effect.CreateEffect(c)
e7:SetDescription(aux.Stringid(44559824,0))
e7:SetCode(EVENT_BATTLE_DESTROYING)
e7:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e7:SetCondition(c44559824.condition)
e7:SetOperation(c44559824.operation)
c:RegisterEffect(e7)
end
function c44559824.ffilter1(c)
return (c:IsFusionSetCard(0x2016) or c:IsHasEffect(511002961)) and not c:IsHasEffect(6205579)
end
function c44559824.ffilter2(c)
if c:IsHasEffect(6205579) then return false end
return c:IsHasEffect(511002961) or c:IsRace(RACE_THUNDER) or c:IsHasEffect(44559838)
end
function c44559824.exfilter(c,g)
return c:IsFaceup() and c:IsCanBeFusionMaterial() and not g:IsContains(c)
end
function c44559824.check1(c,mg,sg,chkf,tp)
local g=mg:Clone()
if sg:IsContains(c) then g:Sub(sg) end
return g:IsExists(c44559824.check2,1,c,c,chkf,tp)
end
function c44559824.check2(c,c2,chkf,tp)
local g=Group.FromCards(c,c2)
if g:IsExists(aux.TuneMagFusFilter,1,nil,g,tp) then return false end
local g1=Group.CreateGroup() local g2=Group.CreateGroup() local fs=false
local tc=g:GetFirst()
while tc do
if c44559824.ffilter1(tc) or tc:IsHasEffect(511002961) then g1:AddCard(tc) if aux.FConditionCheckF(tc,chkf) then fs=true end end
if c44559824.ffilter2(tc) or tc:IsHasEffect(511002961) then g2:AddCard(tc) if aux.FConditionCheckF(tc,chkf) then fs=true end end
tc=g:GetNext()
end
if chkf~=PLAYER_NONE then
return fs and g1:IsExists(aux.FConditionFilterF2c,1,nil,g2)
else return g1:IsExists(aux.FConditionFilterF2c,1,nil,g2) end
end
function c44559824.fuscon(e,g,gc,chkf)
if g==nil then return true end
local chkf=bit.band(chkf,0xff)
local mg=g:Filter(Card.IsCanBeFusionMaterial,nil,e:GetHandler())
local sg=Group.CreateGroup()
local c=e:GetHandler()
local tp=e:GetHandlerPlayer()
local fc=Duel.GetFieldCard(tp,LOCATION_SZONE,5)
if fc and fc:IsHasEffect(44559840) and fc:IsCanRemoveCounter(tp,0x1117,3,REASON_EFFECT) then
sg=Duel.GetMatchingGroup(c44559824.exfilter,tp,0,LOCATION_MZONE,nil,g)
mg:Merge(sg)
end
if gc then
if not gc:IsCanBeFusionMaterial(e:GetHandler()) then return false end
return c44559824.check1(gc,mg,sg,chkf)
end
return mg:IsExists(c44559824.check1,1,nil,mg,sg,chkf)
end
function c44559824.fusop(e,tp,eg,ep,ev,re,r,rp,gc,chkf)
local fc=Duel.GetFieldCard(tp,LOCATION_SZONE,5)
local c=e:GetHandler()
local exg=Group.CreateGroup()
local mg=eg:Filter(Card.IsCanBeFusionMaterial,nil,e:GetHandler())
local p=tp
local sfhchk=false
if fc and fc:IsHasEffect(44559840) and fc:IsCanRemoveCounter(tp,0x1117,3,REASON_EFFECT) then
local sg=Duel.GetMatchingGroup(c44559824.exfilter,tp,0,LOCATION_MZONE,nil,eg)
exg:Merge(sg)
mg:Merge(sg)
end
if Duel.IsPlayerAffectedByEffect(tp,511004008) and Duel.SelectYesNo(1-tp,65) then
p=1-tp Duel.ConfirmCards(1-tp,g)
if mg:IsExists(Card.IsLocation,1,nil,LOCATION_HAND) then sfhchk=true end
end
if gc then
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_FMATERIAL)
local g1=mg:FilterSelect(p,c44559824.check2,1,1,gc,gc,chkf)
local tc1=g1:GetFirst()
if c44559824.exfilter(tc1,eg) then
fc:RemoveCounter(tp,0x1117,3,REASON_EFFECT)
end
if sfhchk then Duel.ShuffleHand(tp) end
Duel.SetFusionMaterial(g1)
return
end
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_FMATERIAL)
local g1=mg:FilterSelect(p,c44559824.check1,1,1,nil,mg,exg,chkf)
local tc1=g1:GetFirst()
if c44559824.exfilter(tc1,eg) then
fc:RemoveCounter(tp,0x1117,3,REASON_EFFECT)
mg:Sub(exg)
end
Duel.Hint(HINT_SELECTMSG,p,HINTMSG_FMATERIAL)
local g2=mg:FilterSelect(p,c44559824.check2,1,1,tc1,tc1,chkf)
if c44559824.exfilter(g2:GetFirst(),eg) then fc:RemoveCounter(tp,0x1117,3,REASON_EFFECT) end
g1:Merge(g2)
if sfhchk then Duel.ShuffleHand(tp) end
Duel.SetFusionMaterial(g1)
end
function c44559824.tgvalue(e,re,rp)
return rp~=e:GetHandlerPlayer()
end
function c44559824.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_FUSION
end
function c44559824.desfilter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable()
end
function c44559824.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c44559824.desfilter,tp,0,LOCATION_ONFIELD,1,nil) end
local g=Duel.GetMatchingGroup(c44559824.desfilter,tp,0,LOCATION_ONFIELD,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c44559824.desop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c44559824.desfilter,tp,0,LOCATION_ONFIELD,nil)
if g:GetCount()>0 then
Duel.Destroy(g,REASON_EFFECT)
end
end
function c44559824.aclimit(e,re,tp)
return not re:GetHandler():IsImmuneToEffect(e)
end
function c44559824.actcon(e)
return Duel.GetAttacker()==e:GetHandler() or Duel.GetAttackTarget()==e:GetHandler()
end
function c44559824.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsRelateToBattle() and c:GetBattleTarget():IsType(TYPE_MONSTER)
end
function c44559824.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetTargetRange(0,1)
e1:SetCondition(c44559824.sumcon)
e1:SetTarget(c44559824.sumlimit)
e1:SetLabel(Duel.GetTurnCount())
if Duel.GetTurnPlayer()==tp then
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN)
else
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,2)
end
Duel.RegisterEffect(e1,tp)
local e2=e1:Clone()
e2:SetCode(EFFECT_CANNOT_SUMMON)
Duel.RegisterEffect(e2,tp)
end
function c44559824.sumcon(e)
return Duel.GetTurnCount()~=e:GetLabel() and Duel.GetTurnPlayer()~=e:GetOwnerPlayer()
end
function c44559824.sumlimit(e,c)
return c:IsType(TYPE_EFFECT)
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c20161999.lua | 2 | 4483 | --Lizardfolk Swamp
function c20161999.initial_effect(c)
c:SetUniqueOnField(1,0,20161999)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetTarget(c20161999.target)
e1:SetOperation(c20161999.activate)
c:RegisterEffect(e1)
--position
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(20161999,0))
e2:SetCategory(CATEGORY_POSITION)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetTarget(c20161999.postg)
e2:SetOperation(c20161999.posop)
c:RegisterEffect(e2)
--todeck
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(20161999,1))
e3:SetCategory(CATEGORY_TODECK)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_DESTROYED)
e3:SetCountLimit(1)
e3:SetCondition(c20161999.tdcon)
e3:SetTarget(c20161999.tdtg)
e3:SetOperation(c20161999.tdop)
c:RegisterEffect(e3)
--spsummon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(20161999,2))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c20161999.spcon)
e4:SetTarget(c20161999.sptg)
e4:SetOperation(c20161999.spop)
c:RegisterEffect(e4)
end
function c20161999.posfilter(c)
return c:IsFaceup() and not c:IsRace(RACE_REPTILE)
end
function c20161999.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local sg=Duel.GetMatchingGroup(c20161999.posfilter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,sg,sg:GetCount(),0,0)
end
function c20161999.activate(e,tp,eg,ep,ev,re,r,rp)
local sg=Duel.GetMatchingGroup(c20161999.posfilter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
if sg:GetCount()>0 then
Duel.ChangePosition(sg,POS_FACEUP_DEFENSE,0,POS_FACEUP_ATTACK,0)
end
end
function c20161999.postg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c20161999.posfilter,Duel.GetTurnPlayer(),LOCATION_MZONE,0,1,nil) end
local g=Duel.GetMatchingGroup(c20161999.posfilter,Duel.GetTurnPlayer(),LOCATION_MZONE,0,nil)
Duel.SetOperationInfo(0,CATEGORY_POSITION,g,g:GetCount(),0,0)
end
function c20161999.posop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c20161999.posfilter,Duel.GetTurnPlayer(),LOCATION_MZONE,0,nil)
Duel.ChangePosition(g,POS_FACEUP_DEFENSE,0,POS_FACEUP_ATTACK,0)
end
function c20161999.tdfilter(c)
return c:IsPreviousLocation(LOCATION_MZONE) and c:IsPreviousPosition(POS_FACEUP) and c:IsPreviousSetCard(0xab90) or c:IsPreviousSetCard(0xab91) or c:IsPreviousSetCard(0xab92)
end
function c20161999.tdcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c20161999.tdfilter,1,nil)
end
function c20161999.filter2(c)
return c:IsAbleToDeck()
end
function c20161999.tdtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and c20161999.filter2(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c20161999.filter2,tp,0,LOCATION_HAND+LOCATION_ONFIELD+LOCATION_GRAVE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
end
function c20161999.tdop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsControler(1-tp) then
Duel.SendtoDeck(tc,nil,1,REASON_EFFECT)
end
end
function c20161999.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY) and not e:GetHandler():IsReason(REASON_RULE) and rp==1-tp
end
function c20161999.spfilter(c,e,tp)
return c:IsType(TYPE_MONSTER) and c:IsSetCard(0xab90) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c20161999.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c20161999.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c20161999.spop(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,c20161999.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c59821050.lua | 2 | 5978 | --The Idol Master of Time and Space Sumire Hikami
function c59821050.initial_effect(c)
--synchro summon
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0xa1a2),aux.NonTuner(Card.IsSetCard,0xa1a2),1)
c:EnableReviveLimit()
--pendulum summon
aux.EnablePendulumAttribute(c)
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e1)
--extra summon
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_PZONE)
e2:SetCode(EFFECT_EXTRA_SUMMON_COUNT)
e2:SetTargetRange(LOCATION_HAND+LOCATION_MZONE,0)
e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xa1a2))
c:RegisterEffect(e2)
--cannot disable summon
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_CANNOT_DISABLE_SUMMON)
e3:SetRange(LOCATION_PZONE)
e3:SetProperty(EFFECT_FLAG_IGNORE_RANGE+EFFECT_FLAG_SET_AVAILABLE)
e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0xa1a2))
c:RegisterEffect(e3)
--immune effect
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_IMMUNE_EFFECT)
e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e4:SetRange(LOCATION_MZONE)
e4:SetValue(c59821050.immfilter)
c:RegisterEffect(e4)
--atk down
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_FIELD)
e5:SetRange(LOCATION_PZONE)
e5:SetCode(EFFECT_UPDATE_ATTACK)
e5:SetTargetRange(0,LOCATION_MZONE)
e5:SetValue(-400)
c:RegisterEffect(e5)
--place pcard
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(59821050,0))
e6:SetType(EFFECT_TYPE_IGNITION)
e6:SetRange(LOCATION_PZONE)
e6:SetCountLimit(1,59821050)
e6:SetCondition(c59821050.pencon)
e6:SetTarget(c59821050.pentg)
e6:SetOperation(c59821050.penop)
c:RegisterEffect(e6)
--atk
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetCode(EFFECT_UPDATE_ATTACK)
e7:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e7:SetRange(LOCATION_MZONE)
e7:SetValue(c59821050.atkval)
c:RegisterEffect(e7)
--special summon
local e8=Effect.CreateEffect(c)
e8:SetDescription(aux.Stringid(59821050,1))
e8:SetCategory(CATEGORY_SPECIAL_SUMMON)
e8:SetCode(EVENT_BATTLE_DESTROYING)
e8:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e8:SetCondition(c59821050.spcon)
e8:SetCost(c59821050.spcost)
e8:SetTarget(c59821050.sptg)
e8:SetOperation(c59821050.spop)
c:RegisterEffect(e8)
--to pzone
local e9=Effect.CreateEffect(c)
e9:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e9:SetCategory(CATEGORY_DESTROY)
e9:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e9:SetCode(EVENT_DESTROYED)
e9:SetCondition(c59821050.con)
e9:SetOperation(c59821050.op)
c:RegisterEffect(e9)
end
function c59821050.immfilter(e,te)
return te:IsActiveType(TYPE_SPELL) and te:GetOwnerPlayer()~=e:GetHandlerPlayer()
end
function c59821050.penfilter4(c)
return c:IsSetCard(0xa1a2) or c:IsCode(59821039) or c:IsCode(59821040) or c:IsCode(59821041) or c:IsCode(59821042) or c:IsCode(59821043) or c:IsCode(59821044) or c:IsCode(59821045) or c:IsCode(59821046) or c:IsCode(59821048) or c:IsCode(59821049)
end
function c59821050.pencon(e,tp,eg,ep,ev,re,r,rp)
local seq=e:GetHandler():GetSequence()
return Duel.GetFieldCard(tp,LOCATION_SZONE,13-seq)==nil
end
function c59821050.pentg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c59821050.penfilter4,tp,LOCATION_EXTRA,0,1,nil) end
end
function c59821050.penop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD)
local g=Duel.SelectMatchingCard(tp,c59821050.penfilter4,tp,LOCATION_EXTRA,0,1,1,nil)
if g:GetCount()>0 then
local tc=g:GetFirst()
Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end
function c59821050.atkval(e,c)
return Duel.GetFieldGroupCount(c:GetControler(),0,LOCATION_ONFIELD)*200
end
function c59821050.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
if not c:IsRelateToBattle() or c:IsFacedown() then return false end
return bc:IsLocation(LOCATION_GRAVE) and bc:IsType(TYPE_MONSTER)
end
function c59821050.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckLPCost(tp,800) end
Duel.PayLPCost(tp,800)
end
function c59821050.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local bc=e:GetHandler():GetBattleTarget()
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and bc:IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetTargetCard(bc)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,bc,1,0,LOCATION_GRAVE)
end
function c59821050.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
function c59821050.penfilter1(c)
return c:IsDestructable() and c:GetSequence()==6
end
function c59821050.penfilter2(c)
return c:IsDestructable() and c:GetSequence()==7
end
function c59821050.con(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
if not p1 and not p2 then return false end
return (e:GetHandler():IsReason(REASON_EFFECT) or e:GetHandler():IsReason(REASON_BATTLE)) and
(p1 and p1:IsDestructable()) or (p2 and p2:IsDestructable()) and e:GetHandler():GetPreviousLocation()==LOCATION_MZONE
end
function c59821050.op(e,tp,eg,ep,ev,re,r,rp)
local p1=Duel.GetFieldCard(tp,LOCATION_SZONE,6)
local p2=Duel.GetFieldCard(tp,LOCATION_SZONE,7)
local g1=nil
local g2=nil
if p1 then
g1=Duel.GetMatchingGroup(c59821050.penfilter1,tp,LOCATION_SZONE,0,nil)
end
if p2 then
g2=Duel.GetMatchingGroup(c59821050.penfilter2,tp,LOCATION_SZONE,0,nil)
if g1 then
g1:Merge(g2)
else
g1=g2
end
end
if g1 and Duel.Destroy(g1,REASON_EFFECT)~=0 then
local c=e:GetHandler()
Duel.MoveToField(c,tp,tp,LOCATION_SZONE,POS_FACEUP,true)
end
end | gpl-3.0 |
TheOnePharaoh/YGOPro-Custom-Cards | script/c494476155.lua | 2 | 2643 | function c494476155.initial_effect(c)
--synchro
aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsSetCard,0x0600),aux.NonTuner(nil),1)
c:EnableReviveLimit()
--gain atk
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_MZONE,0)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetTarget(c494476155.atktg)
e1:SetValue(c494476155.atkval)
c:RegisterEffect(e1)
--atk directly
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_DIRECT_ATTACK)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c494476155.tg)
c:RegisterEffect(e2)
--spsummon
local e3=Effect.CreateEffect(c)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SUMMON_SUCCESS)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1,494476155)
e3:SetCondition(c494476155.spcon)
e3:SetTarget(c494476155.sptg)
e3:SetOperation(c494476155.spop)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e4)
end
function c494476155.tg(e,c)
return c:IsType(TYPE_MONSTER)
end
function c494476155.atktg(e,c)
return c:IsSetCard(0x600)
end
function c494476155.atkfilter(c)
return c:IsFaceup() and c:IsSetCard(0x600)
end
function c494476155.atkval(e,c)
return (Duel.GetMatchingGroupCount(c494476155.atkfilter,c:GetControler(),LOCATION_MZONE,0,c)*500)+500
end
function c494476155.cfilter(c,tp)
return c:IsFaceup() and c:IsSetCard(0x600) and c:IsControler(tp)
end
function c494476155.spcon(e,tp,eg,ep,ev,re,r,rp)
return not eg:IsContains(e:GetHandler()) and eg:IsExists(c494476155.cfilter,1,nil,tp)
end
function c494476155.spfilter(c,e,tp)
return c:IsSetCard(0x600) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c494476155.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c494476155.spfilter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c494476155.spfilter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c494476155.spfilter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c494476155.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/items/quus.lua | 2 | 1131 | -----------------------------------------
-- ID: 5793
-- Item: quus
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
elseif (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5793);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/globals/abilities/steal.lua | 2 | 2731 | -----------------------------------
-- Ability: Steal
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-- these are the quadavs that the thf af1 item can be stolen from
-- bronze quadav groupid = 7949
-- garnet quadav groupid = 7960
-- silver quadav groupid = 7977
-- zircorn quadav groupid = 7985
validThfQuestMobs = {17379367,17379368,17379459,17379470,17379477,17379489,17379493,17379495,17379501,17379505,17379509,
17379513,17379517,17379521,17379525,17379529,17379533,17379538,17379543,17379547,17379552,17379556,
17379560,17379565,17379569,17379573,17379577,17379581,17379585,17379597,17379363,17379364,17379462,
17379473,17379480,17379496,17379498,17379500,17379504,17379508,17379512,17379516,17379520,17379524,
17379528,17379532,17379536,17379541,17379546,17379550,17379555,17379559,17379563,17379568,17379572,
17379576,17379580,17379584,17379588,17379600,17379361,17379362,17379460,17379471,17379478,17379490,
17379491,17379497,17379502,17379506,17379510,17379514,17379518,17379522,17379526,17379530,17379534,
17379539,17379544,17379548,17379553,17379557,17379561,17379566,17379570,17379574,17379578,17379582,
17379586,17379598,17379365,17379366,17379461,17379472,17379479,17379492,17379494,17379499,17379503,
17379507,17379511,17379515,17379519,17379523,17379527,17379531,17379535,17379540,17379545,17379549,
17379554,17379558,17379562,17379567,17379571,17379575,17379579,17379583,17379587,17379599};
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
return 0,0;
end;
function OnUseAbility(player, target, ability)
local thfLevel;
local stolen = 0;
if(player:getMainJob() == JOB_THF) then
thfLevel = player:getMainLvl();
else
thfLevel = player:getSubLvl();
end
local stealMod = player:getMod(MOD_STEAL);
if((player:getEquipID(SLOT_RING1) == 13291 or player:getEquipID(SLOT_RING2) == 13291) and player:GetHPP() < 75 and player:getTP() < 100) then
stealMod = stealMod + 3;
end; --Rogue's Ring
local stealChance = 50 + stealMod * 2 + thfLevel - target:getMainLvl();
if(math.random(100) < stealChance) then
stolen = target:getStealItem();
if (checkThfAfQuest(player, target) == true) then
stolen = 4569;
end
player:addItem(stolen);
ability:setMsg(125);
else
ability:setMsg(153);
end
return stolen;
end;
function checkThfAfQuest(player, target)
local targid = target:getID();
if(player:getVar("theTenshodoShowdownCS") == 3) then
for key, value in pairs(validThfQuestMobs) do
if value == targid then
return true
end
end
return false
end
end;
| gpl-3.0 |
waytim/darkstar | scripts/globals/weaponskills/rampage.lua | 11 | 1472 | -----------------------------------
-- Rampage
-- Axe weapon skill
-- Skill level: 175
-- Delivers a five-hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1 1 1
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 5;
params.ftp100 = 0.5; params.ftp200 = 0.5; params.ftp300 = 0.5;
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.10; params.crit200 = 0.30; params.crit300 = 0.50;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.5;
params.crit100 = 0.0; params.crit200 = 0.20; params.crit300 = 0.40;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
dmccuskey/dmc-sockets | examples/dmc-sockets-basic/dmc_corona/lib/dmc_lua/json.lua | 49 | 2030 | --====================================================================--
-- dmc_lua/json.lua
--
-- consistent method which which to load json on various systems
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2014-2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Lua Library: JSON Shim
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.2.0"
--====================================================================--
--== Setup, Constants
-- these are some popular json modules
local JSON_LIBS = { 'dkjson', 'cjson', 'json' }
local has_json, json
for _, name in ipairs( JSON_LIBS ) do
has_json, json = pcall( require, name )
if has_json then break end
end
assert( has_json, "json module not found" )
return json
| mit |
dmccuskey/dmc-performance | dmc_corona/dmc_performance.lua | 1 | 7616 | --====================================================================--
-- dmc_corona/dmc_performance.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (c) 2011-2015 David McCuskey
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Corona Library : DMC Performance
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "1.1.0"
--====================================================================--
--== DMC Corona Library Config
--====================================================================--
--====================================================================--
--== Support Functions
local Utils = {} -- make copying from dmc_utils easier
--== Start: copy from lua_utils ==--
-- extend()
-- Copy key/values from one table to another
-- Will deep copy any value from first table which is itself a table.
--
-- @param fromTable the table (object) from which to take key/value pairs
-- @param toTable the table (object) in which to copy key/value pairs
-- @return table the table (object) that received the copied items
--
function Utils.extend( fromTable, toTable )
if not fromTable or not toTable then
error( "table can't be nil" )
end
function _extend( fT, tT )
for k,v in pairs( fT ) do
if type( fT[ k ] ) == "table" and
type( tT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], tT[ k ] )
elseif type( fT[ k ] ) == "table" then
tT[ k ] = _extend( fT[ k ], {} )
else
tT[ k ] = v
end
end
return tT
end
return _extend( fromTable, toTable )
end
--== End: copy from lua_utils ==--
--====================================================================--
--== Configuration
local dmc_lib_data
-- boot dmc_corona with boot script or
-- setup basic defaults if it doesn't exist
--
if false == pcall( function() require( 'dmc_corona_boot' ) end ) then
_G.__dmc_corona = {
dmc_corona={},
}
end
dmc_lib_data = _G.__dmc_corona
--====================================================================--
--== DMC Performance
--====================================================================--
--====================================================================--
--== Configuration
dmc_lib_data.dmc_performance = dmc_lib_data.dmc_performance or {}
local DMC_PERFORMANCE_DEFAULTS = {
output_markers = 'false',
memory_active = 'false'
}
local dmc_performance_data = Utils.extend( dmc_lib_data.dmc_performance, DMC_PERFORMANCE_DEFAULTS )
--====================================================================--
--== Imports
-- none
--====================================================================--
--== Setup, Constants
local collectgarbage = collectgarbage
local mabs, mfloor = math.abs, math.floor
local sysinfo, systimer = system.getInfo, system.getTimer
local sformat = string.format
local tcancel, tdelay = timer.cancel, timer.performWithDelay
local tonumber, tostring, type = tonumber, tostring, type
local Perf = {}
local firstTimeMarker = nil
local lastTimeMarker = nil
local timeMarks = {}
local memoryWatcherCallback = nil
--====================================================================--
--== Support Functions
local function castValue( v )
local ret = nil
if v=='true' then
ret = true
elseif v=='false' then
ret = false
else
ret = tonumber( v )
end
return ret
end
local function markerOutput( str, params )
params = params or {}
if params.prefix==nil then params.prefix="MARK " end
print( sformat( "%s: %s", params.prefix, str ) )
end
--====================================================================--
-- Performance Module
--====================================================================--
--======================================================--
-- Time Marker
function Perf.markTime( marker, params )
params = params or {}
if params.reset==true then lastTimeMarker = nil end
if params.print==nil then params.print = true end
--==--
local t = systimer()
local precision = 100000
local delta = 0
if firstTimeMarker==nil and dmc_performance_data.output_markers then
markerOutput( sformat( "Application Started: (T:%s)", tostring(t) ) )
firstTimeMarker = t
end
if lastTimeMarker==nil then lastTimeMarker = t end
if params.print and dmc_performance_data.output_markers then
delta = mfloor((t-lastTimeMarker)*precision)/precision
markerOutput( sformat( "%s: %s (T:%s)", marker, tostring(delta), tostring(t) ) )
end
lastTimeMarker = t
if marker then timeMarks[ marker ] = t end
end
function Perf.markTimeDiff( marker1, marker2 )
local precision = 100000
local t1, t2 = timeMarks[marker1], timeMarks[marker2]
local delta = mfloor((t1-t2 )*precision)/precision
if dmc_performance_data.output_markers then
markerOutput( sformat( "%s <=> %s <d> %s", marker1, marker2, tostring(mabs(delta)) ), {prefix="MARK <d>"} )
end
end
--======================================================--
-- Memory Monitor
-- Memory Monitor function
function Perf.memoryMonitor( param )
collectgarbage()
local memory = collectgarbage( 'count' )
local texture = sysinfo( 'textureMemoryUsed' ) / 1048576
if type(param)=='string' then print(param) end
print( sformat( "M: %s T: %s", tostring(memory), tostring(texture) ) )
end
-- watchMemory()
-- prints out current memory values
--
-- value (boolean:
-- if true, start memory watching every frame
-- if false, stop current memory watching
-- if number, start memory watching every Number of milliseconds
--
function Perf.watchMemory( value )
-- print( "Perf.watchMemory", value )
local f
if value==true then
-- setup constant, frame rate memory watch
Runtime:addEventListener( 'enterFrame', Perf.memoryMonitor )
memoryWatcherCallback = function()
Runtime:removeEventListener( 'enterFrame', Perf.memoryMonitor )
memoryWatcherCallback = nil
end
elseif type(value)=='number' and value > 0 then
local timer = tdelay( value, Perf.memoryMonitor, 0 )
memoryWatcherCallback = function()
tcancel( timer )
memoryWatcherCallback = nil
end
elseif value==false and memoryWatcherCallback ~= nil then
-- stop watching memory
memoryWatcherCallback()
end
end
if dmc_performance_data.memory_active then
dmc_performance_data.memory_active = castValue( dmc_performance_data.memory_active )
Perf.watchMemory( dmc_performance_data.memory_active )
end
return Perf
| mit |
TheOnePharaoh/YGOPro-Custom-Cards | script/c87002901.lua | 2 | 2465 | --May-Raias King
function c87002901.initial_effect(c)
c:EnableReviveLimit()
--cannot special summon
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
c:RegisterEffect(e1)
--spsummon proc
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_SPSUMMON_PROC)
e2:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e2:SetRange(LOCATION_HAND)
e2:SetCondition(c87002901.hspcon)
e2:SetOperation(c87002901.hspop)
c:RegisterEffect(e2)
--battle indestructable
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e3:SetValue(1)
c:RegisterEffect(e3)
--special summon
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(87002901,0))
e4:SetCategory(CATEGORY_SPECIAL_SUMMON)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCountLimit(1,87002901+EFFECT_COUNT_CODE_DUEL)
e4:SetCondition(c87002901.spcon)
e4:SetTarget(c87002901.sptg)
e4:SetOperation(c87002901.spop)
c:RegisterEffect(e4)
end
function c87002901.hspfilter(c)
return c:IsFaceup() and c:IsType(TYPE_MONSTER) and c:IsSetCard(0xe291ca) and c:IsAbleToRemoveAsCost()
end
function c87002901.hspcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>-1
and Duel.IsExistingMatchingCard(c87002901.hspfilter,c:GetControler(),LOCATION_GRAVE,0,5,nil)
end
function c87002901.hspop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c87002901.hspfilter,c:GetControler(),LOCATION_GRAVE,0,5,5,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c87002901.spcon(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,0x41)==0x41
end
function c87002901.specfilter(c,e,tp)
return c:GetCode()==87002902
end
function c87002901.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_DECK)
end
function c87002901.spop(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,c87002901.specfilter,tp,LOCATION_HAND+LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,true,false,POS_FACEUP_ATTACK)
end
end
| gpl-3.0 |
waytim/darkstar | scripts/globals/items/dhalmel_steak.lua | 18 | 1376 | -----------------------------------------
-- ID: 4438
-- Item: dhalmel_steak
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Strength 4
-- Intelligence -1
-- Attack % 25
-- Attack Cap 45
-----------------------------------------
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,10800,4438);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 4);
target:addMod(MOD_INT, -1);
target:addMod(MOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 45);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 4);
target:delMod(MOD_INT, -1);
target:delMod(MOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 45);
end;
| gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Heavens_Tower/npcs/_6q2.lua | 2 | 2698 | -----------------------------------
-- Area: Heaven's Tower
-- NPC: Vestal Chamber (chamber of the Star Sibyl)
-- @pos 0 -49 37 242
-----------------------------------
package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil;
package.loaded["scripts/globals/missions"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Heavens_Tower/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CurrentMission = player:getCurrentMission(WINDURST);
MissionStatus = player:getVar("MissionStatus");
if(CurrentMission == A_NEW_JOURNEY and MissionStatus == 0) then
player:startEvent(0x0099);
elseif(player:hasKeyItem(MESSAGE_TO_JEUNO_WINDURST)) then
player:startEvent(0x00A6);
elseif(player:getRank() == 5 and CurrentMission == 255 and player:hasCompletedMission(WINDURST,THE_FINAL_SEAL) == false) then
player:startEvent(0x00BE);
elseif(player:hasKeyItem(BURNT_SEAL)) then
player:startEvent(0x00C0);
elseif(CurrentMission == THE_SHADOW_AWAITS and MissionStatus == 0) then
player:startEvent(0x00D6);
elseif(CurrentMission == THE_SHADOW_AWAITS and player:hasKeyItem(SHADOW_FRAGMENT)) then
player:startEvent(0x00D8);
else
player:startEvent(0x009A);
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 == 0x0099) then
player:setVar("MissionStatus",1);
player:delKeyItem(STAR_CRESTED_SUMMONS);
player:addKeyItem(LETTER_TO_THE_AMBASSADOR);
player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_AMBASSADOR);
elseif(csid == 0x00A6 or csid == 0x00BE) then
if(option == 0) then
player:addMission(WINDURST,THE_FINAL_SEAL);
player:addKeyItem(NEW_FEIYIN_SEAL);
player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL);
player:setVar("MissionStatus",10);
end
player:delKeyItem(MESSAGE_TO_JEUNO_WINDURST);
elseif(csid == 0x00D6) then
player:setVar("MissionStatus",2);
player:delKeyItem(STAR_CRESTED_SUMMONS);
player:addTitle(STARORDAINED_WARRIOR);
elseif(csid == 0x00C0 or csid == 0x00D8) then
finishMissionTimeline(player,1,csid,option);
end
end; | gpl-3.0 |
waytim/darkstar | scripts/globals/items/holy_maul_+1.lua | 41 | 1077 | -----------------------------------------
-- ID: 17114
-- Item: Holy Maul +1
-- Additional Effect: Light Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/North_Gustaberg/npcs/Hunting_Bear.lua | 4 | 2294 | -----------------------------------
-- Area: North Gustaberg
-- NPC: Hunting Bear
-- Type: NPC Quest
-- Involved in Quest: The Gustaberg Tour
-- @zone: 106
-- @pos: -232.415 40.465 426.495
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg/TextIDs"] = nil;
require("scripts/zones/North_Gustaberg/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TheGustabergTour = player:getQuestStatus(BASTOK, THE_GUSTABERG_TOUR);
if (TheGustabergTour == QUEST_COMPLETED) then
player:startEvent(0x0017); -- final dialog if quest complete
elseif (TheGustabergTour == QUEST_ACCEPTED) then
if (player:getPartySize() == 6) then
--nil if player is not in party; this works fine
--check that all player's levels are <= 5 (or actually just < 6)
--also check that they are in zone
local questreq = true;
local pmemb;
for pmemb = 0, 5, 1 do
local memb = player:getPartyMember(pmemb, 0);
questreq = questreq and (memb:getMainLvl() < 6 and memb:getZone() == 106); -- North Gustaberg is 106 pre-Adoulin, at least
end
if (questreq) then
player:startEvent(0x0016);
else
player:startEvent(0x0015);
end
else
player:startEvent(0x0015);
end
else
player:startEvent(0x0014);
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 == 0x0016) then
player:addGil(GIL_RATE*500);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*500);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,THE_GUSTABERG_TOUR);
player:addTitle(GUSTABERG_TOURIST);
end
end;
| gpl-3.0 |
waytim/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/qm20.lua | 17 | 1888 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: ???
-- Spawns: Glavoid
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16961947) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(FAT_LINED_COCKATRICE_SKIN) and player:hasKeyItem(SODDEN_SANDWORM_HUSK)
and player:hasKeyItem(LUXURIANT_MANTICORE_MANE) -- I broke it into 3 lines at the 'and' because it was so long.
and player:hasKeyItem(STICKY_GNAT_WING)) then
player:startEvent(1020, FAT_LINED_COCKATRICE_SKIN, SODDEN_SANDWORM_HUSK, LUXURIANT_MANTICORE_MANE, STICKY_GNAT_WING); -- Ask if player wants to use KIs
else
player:startEvent(1021, FAT_LINED_COCKATRICE_SKIN, SODDEN_SANDWORM_HUSK, LUXURIANT_MANTICORE_MANE, STICKY_GNAT_WING); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16961947):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(FAT_LINED_COCKATRICE_SKIN);
player:delKeyItem(SODDEN_SANDWORM_HUSK);
player:delKeyItem(LUXURIANT_MANTICORE_MANE);
player:delKeyItem(STICKY_GNAT_WING);
end
end; | gpl-3.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Sacrarium/npcs/qm2.lua | 2 | 1356 | -----------------------------------
-- ???
-- Area: Sacrarium
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false)then
-- print("pop");
SpawnMob(16891970,240):updateEnmity(player);
SpawnMob(16891971,240):updateEnmity(player);
SpawnMob(16891972,240):updateEnmity(player);
elseif(player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false)then
player:addKeyItem(RELIQUIARIUM_KEY);
player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);--There is nothing out of the ordinary here
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
TienHP/Aquaria | files/scripts/entities/sporechildflower.lua | 6 | 1138 | -- 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
dofile("scripts/include/sporechildflowertemplate.lua")
function init(me)
v.commonInit(me, "SporeChildFlowerRed")
end
function update(me, dt)
v.commonUpdate(me, dt)
end
function enterState(me, state)
v.commonEnterState(me, state)
if entity_isState(me, STATE_OPENED) then
-- do effect
msg("EFFECT!")
end
end
| gpl-2.0 |
ffxinfinity/ffxinfinity | FFXI Server-Development/Build Files/scripts/zones/Windurst_Waters_[S]/npcs/Miah_Riyuh.lua | 2 | 1045 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Miah Riyuh
-- Type: Standard NPC
-- @zone: 94
-- @pos: 5.323 -2 37.462
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0079);
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/Konschtat_Highlands/npcs/qm2.lua | 13 | 1465 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: qm2 (???)
-- Involved in Quest: Forge Your Destiny
-- @pos -709 2 102 108
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Konschtat_Highlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(OUTLANDS,FORGE_YOUR_DESTINY) == QUEST_ACCEPTED) then
if (trade:getItemCount() == 1 and trade:hasItemQty(1151,1) and GetMobAction(17219999) == 0) then -- Oriental Steel
SpawnMob(17219999, 300):updateClaim(player); -- Spawn Forger, Despawn after inactive for 5 minutes
player:tradeComplete();
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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);
end; | gpl-3.0 |
niegenug/wesnoth | data/campaigns/tutorial/lua/character_selection.lua | 22 | 2203 | -- #textdomain wesnoth-tutorial
-- Allows the player to choose whether they want to play Konrad or Li’sar
-- for the tutorial
local helper = wesnoth.require "lua/helper.lua"
local T = helper.set_wml_tag_metatable {}
local wml_actions = wesnoth.wml_actions
local _ = wesnoth.textdomain "wesnoth-tutorial"
function wml_actions.select_character()
local character_selection_dialog = {
maximum_height = 250,
maximum_width = 400,
T.helptip { id="tooltip_large" }, -- mandatory field
T.tooltip { id="tooltip_large" }, -- mandatory field
T.grid {
T.row {
T.column {
grow_factor = 1,
border = "all",
border_size = 5,
horizontal_alignment = "left",
T.label {
definition = "title",
label = _"Select Character"
}
}
},
T.row {
T.column {
grow_factor = 1,
border = "all",
border_size = 5,
horizontal_alignment = "left",
T.label {
label = _"Who do you want to play?"
}
}
},
T.row {
T.column {
T.grid {
T.row {
T.column {
grow_factor = 1,
border = "all",
border_size = 5,
T.image {
label = "units/konrad-fighter.png"
}
},
T.column {
grow_factor = 1,
border = "all",
border_size = 5,
T.image {
label = "units/human-princess.png"
}
}
},
T.row {
T.column {
grow_factor = 1,
border = "all",
border_size = 5,
T.button {
label = _"Konrad",
return_value = 1
}
},
T.column {
grow_factor = 1,
border = "all",
border_size = 5,
T.button {
label = _"Li’sar",
return_value = 2
}
}
}
}
}
}
}
}
local character = wesnoth.show_dialog(character_selection_dialog)
local unit = wesnoth.get_variable("student_store")
if character == 2 then
wesnoth.put_unit(unit.x, unit.y, {
type = "Fighteress",
id = unit.id,
name = _"Li’sar",
profile = "portraits/lisar.png",
canrecruit = true,
facing = unit.facing,
})
else
wesnoth.put_unit(unit)
end
wesnoth.redraw {}
end
| gpl-2.0 |
waytim/darkstar | scripts/globals/spells/paralyga.lua | 21 | 1694 | -----------------------------------------
-- Spell: Paralyze
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if (target:hasStatusEffect(EFFECT_PARALYSIS)) then --effect already on, do nothing
spell:setMsg(75);
else
-- Calculate duration.
local duration = math.random(20,120);
-- Grabbing variables for paralyze potency
local pMND = caster:getStat(MOD_MND);
local mMND = target:getStat(MOD_MND);
local dMND = (pMND - mMND);
-- Calculate potency.
local potency = (pMND + dMND)/5; --simplified from (2 * (pMND + dMND)) / 10
if potency > 30 then
potency = 30;
end
--printf("Duration : %u",duration);
--printf("Potency : %u",potency);
local resist = applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_PARALYSIS);
if (resist >= 0.5) then --there are no quarter or less hits, if target resists more than .5 spell is resisted completely
if (target:addStatusEffect(EFFECT_PARALYSIS,potency,0,duration*resist)) then
spell:setMsg(236);
else
-- no effect
spell:setMsg(75);
end
else
-- resist
spell:setMsg(85);
end
end
return EFFECT_PARALYSIS;
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.