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 |
|---|---|---|---|---|---|
dr01d3r/darkstar | scripts/zones/Upper_Jeuno/npcs/Mhao_Kehtsoruho.lua | 14 | 1054 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Mhao Kehtsoruho
-- Type: Past Event Watcher
-- @zone 244
-- @pos -73.032 -1 146.919
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x27bd);
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 |
dr01d3r/darkstar | scripts/globals/abilities/curing_waltz.lua | 6 | 2663 | -----------------------------------
-- Ability: Curing Waltz
-- Heals HP to target player.
-- Obtained: Dancer Level 15
-- TP Required: 20%
-- Recast Time: 00:06
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (target:getHP() == 0) then
return MSGBASIC_CANNOT_ON_THAT_TARG,0;
elseif (player:hasStatusEffect(EFFECT_SABER_DANCE)) then
return MSGBASIC_UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 200) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
--[[ Apply "Waltz Ability Delay" reduction
1 modifier = 1 second]]
local recastMod = player:getMod(MOD_WALTZ_DELAY);
if (recastMod ~= 0) then
local newRecast = ability:getRecast() +recastMod;
ability:setRecast(utils.clamp(newRecast,0,newRecast));
end
-- Apply "Fan Dance" Waltz recast reduction
if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then
local fanDanceMerits = target:getMerit(MERIT_FAN_DANCE);
-- Every tier beyond the 1st is -5% recast time
if (fanDanceMerits > 5) then
ability:setRecast(ability:getRecast() * ((fanDanceMerits -5)/100));
end
end
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(200);
end;
--Grabbing variables.
local vit = target:getStat(MOD_VIT);
local chr = player:getStat(MOD_CHR);
local mjob = player:getMainJob(); --19 for DNC main.
local sjob = player:getSubJob();
local cure = 0;
--Performing sj mj check.
if (mjob == 19) then
cure = (vit+chr)*0.25+60;
end
if (sjob == 19) then
cure = (vit+chr)*0.125+60;
end
-- apply waltz modifiers
cure = math.floor(cure * (1.0 + (player:getMod(MOD_WALTZ_POTENTCY)/100)));
--Reducing TP.
--Applying server mods....
cure = cure * CURE_POWER;
--Cap the final amount to max HP.
if ((target:getMaxHP() - target:getHP()) < cure) then
cure = (target:getMaxHP() - target:getHP());
end
--Do it
target:restoreHP(cure);
target:wakeUp();
player:updateEnmityFromCure(target,cure);
return cure;
end;
| gpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c37803970.lua | 2 | 1388 | --アメイジング・ペンデュラム
function c37803970.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,37803970+EFFECT_COUNT_CODE_OATH)
e1:SetCondition(c37803970.condition)
e1:SetTarget(c37803970.target)
e1:SetOperation(c37803970.activate)
c:RegisterEffect(e1)
end
function c37803970.condition(e,tp,eg,ep,ev,re,r,rp)
return not Duel.GetFieldCard(tp,LOCATION_SZONE,6) and not Duel.GetFieldCard(tp,LOCATION_SZONE,7)
end
function c37803970.thfilter(c)
return c:IsFaceup() and c:IsSetCard(0x98) and c:IsType(TYPE_PENDULUM) and c:IsAbleToHand()
end
function c37803970.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local g=Duel.GetMatchingGroup(c37803970.thfilter,tp,LOCATION_EXTRA,0,nil)
return g:GetClassCount(Card.GetCode)>=2
end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,2,tp,LOCATION_EXTRA)
end
function c37803970.activate(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c37803970.thfilter,tp,LOCATION_EXTRA,0,nil)
if g:GetClassCount(Card.GetCode)>=2 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g1=g:Select(tp,1,1,nil)
g:Remove(Card.IsCode,nil,g1:GetFirst():GetCode())
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g2=g:Select(tp,1,1,nil)
g1:Merge(g2)
Duel.SendtoHand(g1,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g1)
end
end
| gpl-2.0 |
abolfazlabbasifx/telegramadminbot | plugins/setcmd.lua | 15 | 1205 | do
local function save_value(msg, name, value)
if (not name or not value) then
return
end
local hash = nil
if msg.to.type == 'chat' or 'channel' then
hash = 'botcommand:variables'
end
if hash then
redis:hset(hash, name, value)
return "انجام شد"
end
end
local function get_variables_hash(msg)
if msg.to.type == 'chat' or 'channel' then
return 'botcommand:variables'
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
local function run(msg, matches)
if matches[1]:lower() == 'setcommand' then
if not is_momod(msg) then
return "فقط برای مدیر!"
end
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local name1 = user_print_name(msg.from)
local text = save_value(msg, name, value)
return text
end
if matches[1] == '!' or '/' or '#' then
return get_value(msg, matches[2])
else
return
end
end
return {
patterns = {
"^[!/#](setcommand) ([^%s]+) (.+)$",
"^([!/#])(.+)$",
},
run = run
}
end
| gpl-2.0 |
jamesbates/vlc | share/lua/playlist/pluzz.lua | 105 | 3740 | --[[
$Id$
Copyright © 2011 VideoLAN
Authors: Ludovic Fauvet <etix at l0cal dot com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "pluzz.fr/%w+" )
or string.match( vlc.path, "info.francetelevisions.fr/.+")
or string.match( vlc.path, "france4.fr/%w+")
end
-- Helpers
function key_match( line, key )
return string.match( line, "name=\"" .. key .. "\"" )
end
function get_value( line )
local _,_,r = string.find( line, "content=\"(.*)\"" )
return r
end
-- Parse function.
function parse()
p = {}
if string.match ( vlc.path, "www.pluzz.fr/%w+" ) then
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "id=\"current_video\"" ) then
_,_,redirect = string.find (line, "href=\"(.-)\"" )
print ("redirecting to: " .. redirect )
return { { path = redirect } }
end
end
end
if string.match ( vlc.path, "www.france4.fr/%w+" ) then
while true do
line = vlc.readline()
if not line then break end
-- maybe we should get id from tags having video/cappuccino type instead
if string.match( line, "id=\"lavideo\"" ) then
_,_,redirect = string.find (line, "href=\"(.-)\"" )
print ("redirecting to: " .. redirect )
return { { path = redirect } }
end
end
end
if string.match ( vlc.path, "info.francetelevisions.fr/.+" ) then
title = ""
arturl = "http://info.francetelevisions.fr/video-info/player_sl/Images/PNG/gene_ftv.png"
while true do
line = vlc.readline()
if not line then break end
-- Try to find the video's path
if key_match( line, "urls--url--video" ) then
video = get_value( line )
end
-- Try to find the video's title
if key_match( line, "vignette--titre--court" ) then
title = get_value( line )
title = vlc.strings.resolve_xml_special_chars( title )
print ("playing: " .. title )
end
-- Try to find the video's thumbnail
if key_match( line, "vignette" ) then
arturl = get_value( line )
if not string.match( line, "http://" ) then
arturl = "http://info.francetelevisions.fr/" .. arturl
end
end
end
if video then
-- base url is hardcoded inside a js source file
-- see http://www.pluzz.fr/layoutftv/arches/common/javascripts/jquery.player-min.js
base_url = "mms://a988.v101995.c10199.e.vm.akamaistream.net/7/988/10199/3f97c7e6/ftvigrp.download.akamai.com/10199/cappuccino/production/publication/"
table.insert( p, { path = base_url .. video; name = title; arturl = arturl; } )
end
end
return p
end
| gpl-2.0 |
mrgreywater/TressFX | amd_tressfx/premake/premake5.lua | 2 | 3448 | _AMD_LIBRARY_NAME = "TressFX"
_AMD_LIBRARY_NAME_ALL_CAPS = string.upper(_AMD_LIBRARY_NAME)
-- Set _AMD_LIBRARY_NAME before including amd_premake_util.lua
dofile ("../../premake/amd_premake_util.lua")
workspace ("AMD_" .. _AMD_LIBRARY_NAME)
configurations { "DLL_Debug", "DLL_Release", "Lib_Debug", "Lib_Release", "DLL_Release_MT" }
platforms { "Win32", "x64" }
location "../build"
filename ("AMD_" .. _AMD_LIBRARY_NAME .. _AMD_VS_SUFFIX)
startproject ("AMD_" .. _AMD_LIBRARY_NAME)
filter "platforms:Win32"
system "Windows"
architecture "x86"
filter "platforms:x64"
system "Windows"
architecture "x64"
externalproject "AMD_LIB_Minimal"
kind "StaticLib"
language "C++"
location "../../amd_lib/shared/d3d11/build"
filename ("AMD_LIB_Minimal" .. _AMD_VS_SUFFIX)
uuid "0D2AEA47-7909-69E3-8221-F4B9EE7FCF44"
configmap {
["DLL_Debug"] = "Debug",
["DLL_Release"] = "Release",
["Lib_Debug"] = "Debug",
["Lib_Release"] = "Release",
["DLL_Release_MT"] = "Release_MT" }
project ("AMD_" .. _AMD_LIBRARY_NAME)
language "C++"
location "../build"
filename ("AMD_" .. _AMD_LIBRARY_NAME .. _AMD_VS_SUFFIX)
uuid "252C0AF0-91E1-82E5-1AD6-7CBC868A79E9"
targetdir "../lib/%{_AMD_LIBRARY_DIR_LAYOUT}"
objdir "../build/%{_AMD_LIBRARY_DIR_LAYOUT}"
warnings "Extra"
exceptionhandling "Off"
rtti "Off"
-- Specify WindowsTargetPlatformVersion here for VS2015
windowstarget (_AMD_WIN_SDK_VERSION)
files { "../inc/**.h", "../src/**.h", "../src/**.cpp", "../src/Shaders/**.hlsl" }
includedirs { "../inc", "../../amd_lib/shared/common/inc", "../../amd_lib/shared/d3d11/inc" }
links { "AMD_LIB_Minimal" }
filter "configurations:DLL_*"
kind "SharedLib"
defines { "_USRDLL", "AMD_%{_AMD_LIBRARY_NAME_ALL_CAPS}_COMPILE_DYNAMIC_LIB=1" }
-- Copy DLL and import library to the lib directory
postbuildcommands { amdLibPostbuildCommands() }
postbuildmessage "Copying build output to lib directory..."
filter "configurations:Lib_*"
kind "StaticLib"
defines { "_LIB", "AMD_%{_AMD_LIBRARY_NAME_ALL_CAPS}_COMPILE_DYNAMIC_LIB=0" }
filter "configurations:*_Debug"
defines { "WIN32", "_DEBUG", "_WINDOWS", "_WIN32_WINNT=0x0601", "_SCL_SECURE_NO_WARNINGS" }
flags { "Symbols", "FatalWarnings", "Unicode" }
-- add "d" to the end of the library name for debug builds
targetsuffix "d"
filter "configurations:*_Release"
defines { "WIN32", "NDEBUG", "_WINDOWS", "_WIN32_WINNT=0x0601", "_SCL_SECURE_NO_WARNINGS" }
flags { "FatalWarnings", "Unicode" }
optimize "On"
filter "configurations:DLL_Release_MT"
defines { "WIN32", "NDEBUG", "_WINDOWS", "_WIN32_WINNT=0x0601", "_SCL_SECURE_NO_WARNINGS" }
flags { "FatalWarnings", "Unicode" }
-- link against the static runtime to avoid introducing a dependency
-- on the particular version of Visual Studio used to build the DLLs
flags { "StaticRuntime" }
optimize "On"
filter "action:vs*"
-- specify exception handling model for Visual Studio to avoid
-- "'noexcept' used with no exception handling mode specified"
-- warning in vs2015
buildoptions { "/EHsc" }
filter "platforms:Win32"
targetname "%{_AMD_LIBRARY_PREFIX}%{_AMD_LIBRARY_NAME}_x86"
filter "platforms:x64"
targetname "%{_AMD_LIBRARY_PREFIX}%{_AMD_LIBRARY_NAME}_x64"
| mit |
SalvationDevelopment/Salvation-Scripts-Production | c79965360.lua | 7 | 2412 | --アマゾネスの秘宝
function c79965360.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c79965360.target)
e1:SetOperation(c79965360.operation)
c:RegisterEffect(e1)
--Equip limit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_EQUIP_LIMIT)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetValue(c79965360.eqlimit)
c:RegisterEffect(e2)
--destroy rep
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_INDESTRUCTABLE_COUNT)
e3:SetValue(c79965360.valcon)
e3:SetCountLimit(1)
c:RegisterEffect(e3)
--destroy
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(79965360,0))
e4:SetCategory(CATEGORY_DESTROY)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e4:SetCode(EVENT_BATTLED)
e4:SetRange(LOCATION_SZONE)
e4:SetCondition(c79965360.descon)
e4:SetTarget(c79965360.destg)
e4:SetOperation(c79965360.desop)
c:RegisterEffect(e4)
end
function c79965360.eqlimit(e,c)
return c:IsSetCard(0x4)
end
function c79965360.filter(c)
return c:IsFaceup() and c:IsSetCard(0x4)
end
function c79965360.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c79965360.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c79965360.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c79965360.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c79965360.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
function c79965360.valcon(e,re,r,rp)
return r==REASON_BATTLE
end
function c79965360.descon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetEquipTarget()==Duel.GetAttacker() and Duel.GetAttackTarget()
end
function c79965360.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,Duel.GetAttackTarget(),1,0,0)
end
function c79965360.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetAttackTarget()
if tc:IsRelateToBattle() then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c42776855.lua | 2 | 3617 | --追走の翼
function c42776855.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,0x1e0)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c42776855.target)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_CHAIN_SOLVED)
e2:SetLabelObject(e1)
e2:SetCondition(c42776855.tgcon)
e2:SetOperation(c42776855.tgop)
c:RegisterEffect(e2)
--indes
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e3:SetRange(LOCATION_SZONE)
e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e3:SetTarget(c42776855.indestg)
e3:SetValue(1)
c:RegisterEffect(e3)
local e4=e3:Clone()
e4:SetCode(EFFECT_INDESTRUCTABLE_EFFECT)
e4:SetValue(c42776855.efilter)
c:RegisterEffect(e4)
--destroy
local e5=Effect.CreateEffect(c)
e5:SetDescription(aux.Stringid(42776855,0))
e5:SetCategory(CATEGORY_DESTROY)
e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e5:SetCode(EVENT_BATTLE_START)
e5:SetRange(LOCATION_SZONE)
e5:SetCondition(c42776855.atkcon)
e5:SetOperation(c42776855.atkop)
c:RegisterEffect(e5)
--Destroy2
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e7:SetRange(LOCATION_SZONE)
e7:SetCode(EVENT_LEAVE_FIELD)
e7:SetProperty(EFFECT_FLAG_DELAY)
e7:SetCondition(c42776855.descon2)
e7:SetOperation(c42776855.desop2)
c:RegisterEffect(e7)
end
function c42776855.filter(c)
return c:IsFaceup() and c:IsType(TYPE_SYNCHRO)
end
function c42776855.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c42776855.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c42776855.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c42776855.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c42776855.tgcon(e,tp,eg,ep,ev,re,r,rp)
return re==e:GetLabelObject()
end
function c42776855.tgop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS):GetFirst()
if c:IsRelateToEffect(re) and tc:IsFaceup() and tc:IsRelateToEffect(re) then
c:SetCardTarget(tc)
end
end
function c42776855.indestg(e,c)
return e:GetHandler():IsHasCardTarget(c)
end
function c42776855.efilter(e,re)
return e:GetOwnerPlayer()~=re:GetOwnerPlayer()
end
function c42776855.atkcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=c:GetFirstCardTarget()
if not tc then return false end
local bc=tc:GetBattleTarget()
return tc:IsLocation(LOCATION_MZONE) and bc and bc:IsFaceup() and bc:IsLocation(LOCATION_MZONE) and bc:IsLevelAbove(5)
end
function c42776855.atkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local tc=c:GetFirstCardTarget()
if not tc then return false end
local bc=tc:GetBattleTarget()
local atk=bc:GetBaseAttack()
if bc:IsRelateToBattle() and Duel.Destroy(bc,REASON_EFFECT)~=0 and bc:IsType(TYPE_MONSTER) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(atk)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
function c42776855.descon2(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
return tc and eg:IsContains(tc)
end
function c42776855.desop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c9024367.lua | 2 | 1900 | --ギャラクシー・ドラグーン
function c9024367.initial_effect(c)
--atklimit
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e1:SetValue(c9024367.bttg)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_DIRECT_ATTACK)
c:RegisterEffect(e2)
--atkup
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetCondition(c9024367.atkcon)
e3:SetValue(1000)
c:RegisterEffect(e3)
--disable
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e4:SetCode(EVENT_ATTACK_ANNOUNCE)
e4:SetOperation(c9024367.disop)
c:RegisterEffect(e4)
local e5=e4:Clone()
e5:SetCode(EVENT_BE_BATTLE_TARGET)
c:RegisterEffect(e5)
end
function c9024367.bttg(e,c)
return c:IsFacedown() or not c:IsRace(RACE_DRAGON)
end
function c9024367.atkcon(e)
local ph=Duel.GetCurrentPhase()
local bc=e:GetHandler():GetBattleTarget()
return (ph==PHASE_DAMAGE or ph==PHASE_DAMAGE_CAL) and bc and bc:IsRace(RACE_DRAGON)
end
function c9024367.disop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
if bc and bc:IsRace(RACE_DRAGON) then
c:CreateRelation(bc,RESET_EVENT+0x1fe0000)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetCondition(c9024367.discon)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
bc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetCondition(c9024367.discon)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_BATTLE)
bc:RegisterEffect(e2)
end
end
function c9024367.discon(e)
return e:GetOwner():IsRelateToCard(e:GetHandler())
end
| gpl-2.0 |
dr01d3r/darkstar | scripts/zones/Abyssea-Misareaux/npcs/qm13.lua | 14 | 1548 | -----------------------------------
-- Zone: Abyssea-Misareaux
-- NPC: qm13 (???)
-- Spawns Cirein-Croin
-- @pos ? ? ? 216
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17662481) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(GLISTENING_OROBON_LIVER) and player:hasKeyItem(DOFFED_POROGGO_HAT)) then
player:startEvent(1021, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Ask if player wants to use KIs
else
player:startEvent(1020, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- 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 == 1021 and option == 1) then
SpawnMob(17662481):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(GLISTENING_OROBON_LIVER);
player:delKeyItem(DOFFED_POROGGO_HAT);
end
end;
| gpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c30299166.lua | 5 | 1377 | --ワーム・テンタクルス
function c30299166.initial_effect(c)
--multi atk
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(30299166,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCondition(c30299166.mtcon)
e1:SetCost(c30299166.mtcost)
e1:SetTarget(c30299166.mttg)
e1:SetOperation(c30299166.mtop)
c:RegisterEffect(e1)
end
function c30299166.mtcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsAbleToEnterBP()
end
function c30299166.costfilter(c)
return c:IsSetCard(0x3e) and c:IsRace(RACE_REPTILE) and c:IsAbleToRemoveAsCost()
end
function c30299166.mtcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c30299166.costfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c30299166.costfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c30299166.mttg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetEffectCount(EFFECT_EXTRA_ATTACK)==0 end
end
function c30299166.mtop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EXTRA_ATTACK)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
c:RegisterEffect(e1)
end
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c93016201.lua | 4 | 4057 | --王宮の弾圧
function c93016201.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c93016201.cost1)
e1:SetTarget(c93016201.target1)
e1:SetOperation(c93016201.activate1)
c:RegisterEffect(e1)
--Activate(timing)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(93016201,0))
e2:SetType(EFFECT_TYPE_ACTIVATE)
e2:SetCode(EVENT_SPSUMMON)
e2:SetCondition(c93016201.condition2)
e2:SetCost(c93016201.cost2)
e2:SetTarget(c93016201.target2)
e2:SetOperation(c93016201.activate2)
c:RegisterEffect(e2)
--instant
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(93016201,0))
e3:SetType(EFFECT_TYPE_QUICK_O)
e3:SetRange(LOCATION_SZONE)
e3:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e3:SetCode(EVENT_SPSUMMON)
e3:SetCondition(c93016201.condition2)
e3:SetCost(c93016201.cost2)
e3:SetTarget(c93016201.target2)
e3:SetOperation(c93016201.activate2)
c:RegisterEffect(e3)
--instant(chain)
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(93016201,0))
e4:SetType(EFFECT_TYPE_QUICK_O)
e4:SetRange(LOCATION_SZONE)
e4:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e4:SetCode(EVENT_CHAINING)
e4:SetCondition(c93016201.condition3)
e4:SetCost(c93016201.cost3)
e4:SetTarget(c93016201.target3)
e4:SetOperation(c93016201.activate3)
c:RegisterEffect(e4)
end
function c93016201.cost1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
e:SetLabel(0)
if not Duel.CheckLPCost(tp,800) then return end
local ct=Duel.GetCurrentChain()
if ct==1 then return end
local pe=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
if not pe:IsHasCategory(CATEGORY_SPECIAL_SUMMON) then return end
if not Duel.IsChainDisablable(ct-1) then return end
if Duel.SelectYesNo(tp,aux.Stringid(93016201,1)) then
Duel.PayLPCost(tp,800)
e:SetLabel(1)
end
end
function c93016201.target1(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
if e:GetLabel()~=1 then return end
local ct=Duel.GetCurrentChain()
local te=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
local tc=te:GetHandler()
Duel.SetOperationInfo(0,CATEGORY_DISABLE,tc,1,0,0)
if tc:IsRelateToEffect(te) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,tc,1,0,0)
end
end
function c93016201.activate1(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 te=Duel.GetChainInfo(ct-1,CHAININFO_TRIGGERING_EFFECT)
local tc=te:GetHandler()
if Duel.NegateEffect(ct-1) and tc:IsRelateToEffect(te) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c93016201.condition2(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentChain()==0
end
function c93016201.cost2(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 c93016201.target2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,eg,eg:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,eg:GetCount(),0,0)
end
function c93016201.activate2(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
Duel.NegateSummon(eg)
Duel.Destroy(eg,REASON_EFFECT)
end
function c93016201.condition3(e,tp,eg,ep,ev,re,r,rp)
return re:IsHasCategory(CATEGORY_SPECIAL_SUMMON) and Duel.IsChainDisablable(ev)
end
function c93016201.cost3(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 c93016201.target3(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 re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c93016201.activate3(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.NegateEffect(ev) and re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
asmagill/hammerspoon-config | utils/_keys/viKeys.lua | 1 | 2931 | local module = {}
module.debugging = false -- whether to print status updates
local eventtap = require "hs.eventtap"
local event = eventtap.event
local inspect = require "hs.inspect"
local watchable = require "hs.watchable"
local keyHandler = function(e)
local watchFor = { h = "left", j = "down", k = "up", l = "right" }
local actualKey = e:getCharacters(true)
local replacement = watchFor[actualKey:lower()]
if replacement then
local isDown = e:getType() == event.types.keyDown
local flags = {}
for k, v in pairs(e:getFlags()) do
if v and k ~= "fn" then -- fn will be down because that's our "wrapper", so ignore it
table.insert(flags, k)
end
end
if module.debugging then print("viKeys: " .. replacement, inspect(flags), isDown) end
local replacementEvent = event.newKeyEvent(flags, replacement, isDown)
if isDown then
-- allow for auto-repeat
replacementEvent:setProperty(event.properties.keyboardEventAutorepeat, e:getProperty(event.properties.keyboardEventAutorepeat))
end
return true, { replacementEvent }
else
return false -- do nothing to the event, just pass it along
end
end
local modifierHandler = function(e)
local flags = e:getFlags()
local onlyFNPressed = false
for k, v in pairs(flags) do
onlyFNPressed = v and k == "fn"
if not onlyFNPressed then break end
end
-- you must tap and hold fn by itself to turn this on
if onlyFNPressed and not module.keyListener then
if module.debugging then print("viKeys: keyhandler on") end
module.keyListener = eventtap.new({ event.types.keyDown, event.types.keyUp }, keyHandler):start()
-- however, adding additional modifiers afterwards is ok... its only when fn isn't down that we switch back off
elseif not flags.fn and module.keyListener then
if module.debugging then print("viKeys: keyhandler off") end
module.keyListener:stop()
module.keyListener = nil
end
return false
end
module.watchables = watchable.new("viKeys", true)
module.modifierListener = eventtap.new({ event.types.flagsChanged }, modifierHandler)
module.start = function()
module.watchables.enabled = true
module.modifierListener:start()
end
module.stop = function()
if module.keyListener then
module.keyListener:stop()
module.keyListener = nil
end
module.modifierListener:stop()
module.watchables.enabled = false
end
module.toggle = function()
if module.watchable.enabled then
module.stop()
else
module.start()
end
end
module.watchExternalToggle = watchable.watch("viKeys.enabled", function(w, p, k, o, n)
if not o and n then
module.start()
elseif o and not n then
module.stop()
end
end)
module.start() -- autostart
return module
| mit |
SalvationDevelopment/Salvation-Scripts-Production | c11439455.lua | 2 | 2686 | --月光蒼猫
function c11439455.initial_effect(c)
--atk up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(11439455,0))
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCountLimit(1,11439455)
e1:SetTarget(c11439455.atktg)
e1:SetOperation(c11439455.atkop)
c:RegisterEffect(e1)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(11439455,1))
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e3:SetCode(EVENT_DESTROYED)
e3:SetCondition(c11439455.spcon)
e3:SetTarget(c11439455.sptg)
e3:SetOperation(c11439455.spop)
c:RegisterEffect(e3)
end
function c11439455.atkfilter(c)
return c:IsFaceup() and c:IsSetCard(0xdf) and not c:IsCode(11439455)
end
function c11439455.atktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c11439455.atkfilter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c11439455.atkfilter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
local g=Duel.SelectTarget(tp,c11439455.atkfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_ATKCHANGE,g,1,0,0)
end
function c11439455.atkop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_ATTACK_FINAL)
e2:SetValue(tc:GetBaseAttack()*2)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e2)
end
end
function c11439455.spcon(e,tp,eg,ep,ev,re,r,rp)
return bit.band(r,REASON_EFFECT+REASON_BATTLE)~=0 and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c11439455.spfilter(c,e,tp)
return c:IsSetCard(0xdf) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c11439455.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c11439455.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c11439455.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,c11439455.spfilter,tp,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
| gpl-2.0 |
adamlamers/rapidjson | build/premake4.lua | 5 | 3441 | function setTargetObjDir(outDir)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
--"_debug_win32_vs2008"
local suffix = "_" .. cfg .. "_" .. plat .. "_" .. action
targetPath = outDir
suffix = string.lower(suffix)
local obj_path = "../intermediate/" .. cfg .. "/" .. action .. "/" .. prj.name
obj_path = string.lower(obj_path)
configuration {cfg, plat}
targetdir(targetPath)
objdir(obj_path)
targetsuffix(suffix)
end
end
end
function linkLib(libBaseName)
for _, cfg in ipairs(configurations()) do
for _, plat in ipairs(platforms()) do
local action = _ACTION or ""
local prj = project()
local cfgName = cfg
--"_debug_win32_vs2008"
local suffix = "_" .. cfgName .. "_" .. plat .. "_" .. action
libFullName = libBaseName .. string.lower(suffix)
configuration {cfg, plat}
links(libFullName)
end
end
end
solution "test"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
configuration "gmake"
buildoptions "-msse4.2 -Werror=cast-qual"
project "gtest"
kind "StaticLib"
files {
"../thirdparty/gtest/src/gtest-all.cc",
"../thirdparty/gtest/src/**.h",
}
includedirs {
"../thirdparty/gtest/",
"../thirdparty/gtest/include",
}
setTargetObjDir("../thirdparty/lib")
project "unittest"
kind "ConsoleApp"
files {
"../include/**.h",
"../test/unittest/**.cpp",
"../test/unittest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
project "perftest"
kind "ConsoleApp"
files {
"../include/**.h",
"../test/perftest/**.cpp",
"../test/perftest/**.c",
"../test/perftest/**.h",
}
includedirs {
"../include/",
"../thirdparty/gtest/include/",
"../thirdparty/",
"../thirdparty/jsoncpp/include/",
"../thirdparty/libjson/",
"../thirdparty/yajl/include/",
}
libdirs "../thirdparty/lib"
setTargetObjDir("../bin")
linkLib "gtest"
links "gtest"
solution "example"
configurations { "debug", "release" }
platforms { "x32", "x64" }
location ("./" .. (_ACTION or ""))
language "C++"
flags { "ExtraWarnings" }
includedirs "../include/"
configuration "debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "release"
defines { "NDEBUG" }
flags { "Optimize", "EnableSSE2" }
configuration "vs*"
defines { "_CRT_SECURE_NO_WARNINGS" }
project "condense"
kind "ConsoleApp"
files "../example/condense/*"
setTargetObjDir("../bin")
project "pretty"
kind "ConsoleApp"
files "../example/pretty/*"
setTargetObjDir("../bin")
project "tutorial"
kind "ConsoleApp"
files "../example/tutorial/*"
setTargetObjDir("../bin")
project "serialize"
kind "ConsoleApp"
files "../example/serialize/*"
setTargetObjDir("../bin")
| mit |
koreader/koreader | spec/unit/gettext_spec.lua | 9 | 18066 | local test_po_part1 = [[
# KOReader PATH/TO/FILE.PO
# Copyright (C) 2005-2019 KOReader Development Team
#
# Translators:
# Frans de Jonge <fransdejonge@gmail.com>, 2014-2019
# Markismus <zulde.zuldemans@gmail.com>, 2014
msgid ""
msgstr ""
"Project-Id-Version: KOReader\n"
"Report-Msgid-Bugs-To: https://github.com/koreader/koreader-base/issues\n"
"POT-Creation-Date: 2019-08-10 06:01+0000\n"
"PO-Revision-Date: 2019-08-08 06:34+0000\n"
"Last-Translator: Frans de Jonge <fransdejonge@gmail.com>\n"
"Language-Team: Dutch (Netherlands) (http://www.transifex.com/houqp/koreader/language/nl_NL/)\n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Language: nl_NL\n"
]]
local test_plurals_nl = [[
"Plural-Forms: nplurals=2; plural=(n != 1);\n"
]]
local test_plurals_none = [[
"Plural-Forms: nplurals=1; plural=0;"
]]
local test_plurals_ar = [[
"Plural-Forms: nplurals=6; plural=n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5;\n"
]]
local test_plurals_ru = [[
"Plural-Forms: nplurals=4; plural=(n%10==1 && n%100!=11 ? 0 : n%10>=2 && n%10<=4 && (n%100<12 || n%100>14) ? 1 : n%10==0 || (n%10>=5 && n%10<=9) || (n%100>=11 && n%100<=14)? 2 : 3);\n"
]]
local test_plurals_simple = [[
"Plural-Forms: nplurals=2; plural=(n > 2);\n"
]]
local test_plurals_many = [[
"Plural-Forms: nplurals=5; plural=(n > 3 ? 3 : n > 2 ? 2 : n > 1 ? 1 : 0);"
]]
local test_po_part2 = [[
#: frontend/ui/widget/configdialog.lua:1016
msgid ""
"\n"
"message"
msgstr "\nbericht"
#: frontend/device/android/device.lua:259
msgid "1 item"
msgid_plural "%1 items"
msgstr[0] "1 ding"
msgstr[1] "%1 dingen"
msgstr[2] "%1 dingen 2"
msgstr[3] ""
msgstr[4] ""
msgstr[5] ""
#: frontend/device/android/device.lua:359
msgid "1 untranslated"
msgid_plural "%1 untranslated"
msgstr[0] ""
msgstr[1] ""
msgstr[2] ""
msgstr[3] ""
msgstr[4] ""
msgstr[5] ""
#: frontend/ui/data/css_tweaks.lua:17
msgctxt "Style tweaks category"
msgid "Pages"
msgstr "Pagina's"
#: frontend/ui/data/css_tweaks.lua:20
msgctxt "Other pages"
msgid "Pages"
msgstr "Pages different context"
#: frontend/ui/data/css_tweaks.lua:30
msgctxt "Context 1"
msgid "Page"
msgid_plural "Pages"
msgstr[0] "Pagina"
msgstr[1] "Pagina's"
msgstr[2] "Pagina's plural 2"
msgstr[3] "Pagina's plural 3"
msgstr[4] "Pagina's plural 4"
msgstr[5] "Pagina's plural 5"
#: frontend/ui/data/css_tweaks.lua:40
msgctxt "Context 2"
msgid "Page"
msgid_plural "Pages"
msgstr[0] "Pagina context 2 plural 0"
msgstr[1] "Pagina's context 2 plural 1"
msgstr[2] "Pagina's context 2 plural 2"
msgstr[3] ""
msgstr[4] ""
msgstr[5] ""
#: frontend/ui/data/css_tweaks.lua:50
#, fuzzy
msgid "Fuzzy"
msgstr "Fuzzy translated"
]]
describe("GetText module", function()
local GetText
local test_po_ar
local test_po_nl, test_po_ru
local test_po_none, test_po_simple
local test_po_many
setup(function()
require("commonrequire")
GetText = require("gettext")
GetText.dirname = "i18n-test"
local lfs = require("libs/libkoreader-lfs")
lfs.mkdir(GetText.dirname)
lfs.mkdir(GetText.dirname.."/nl_NL")
lfs.mkdir(GetText.dirname.."/none")
lfs.mkdir(GetText.dirname.."/ar")
lfs.mkdir(GetText.dirname.."/ru")
lfs.mkdir(GetText.dirname.."/simple")
lfs.mkdir(GetText.dirname.."/many")
test_po_nl = GetText.dirname.."/nl_NL/koreader.po"
local f = io.open(test_po_nl, "w")
f:write(test_po_part1, test_plurals_nl, test_po_part2)
f:close()
-- same file, just different plural for testing
test_po_none = GetText.dirname.."/none/koreader.po"
f = io.open(test_po_none, "w")
f:write(test_po_part1, test_plurals_none, test_po_part2)
f:close()
-- same file, just different plural for testing
test_po_ar = GetText.dirname.."/ar/koreader.po"
f = io.open(test_po_ar, "w")
f:write(test_po_part1, test_plurals_ar, test_po_part2)
f:close()
-- same file, just different plural for testing
test_po_ru = GetText.dirname.."/ru/koreader.po"
f = io.open(test_po_ru, "w")
f:write(test_po_part1, test_plurals_ru, test_po_part2)
f:close()
-- same file, just different plural for testing
test_po_simple = GetText.dirname.."/simple/koreader.po"
f = io.open(test_po_simple, "w")
f:write(test_po_part1, test_plurals_simple, test_po_part2)
f:close()
-- same file, just different plural for testing
test_po_many = GetText.dirname.."/many/koreader.po"
f = io.open(test_po_many, "w")
f:write(test_po_part1, test_plurals_many, test_po_part2)
f:close()
end)
teardown(function()
os.remove(test_po_nl)
os.remove(test_po_none)
os.remove(test_po_ar)
os.remove(test_po_ru)
os.remove(test_po_simple)
os.remove(test_po_many)
os.remove(GetText.dirname.."/nl_NL")
os.remove(GetText.dirname.."/none")
os.remove(GetText.dirname.."/ar")
os.remove(GetText.dirname.."/ru")
os.remove(GetText.dirname.."/simple")
os.remove(GetText.dirname.."/many")
os.remove(GetText.dirname)
end)
describe("changeLang", function()
it("should return nil when passing newlang = C", function()
assert.is_nil(GetText.changeLang("C"))
end)
it("should return nil when passing empty string or nil value", function()
assert.is_nil(GetText.changeLang(nil))
assert.is_nil(GetText.changeLang(""))
end)
it("should return nil when passing values that start with en_US", function()
assert.is_nil(GetText.changeLang("en_US"))
assert.is_nil(GetText.changeLang("en_US:en"))
assert.is_nil(GetText.changeLang("en_US.utf8"))
end)
it("should return false when it can't find a po file", function()
assert.is_false(GetText.changeLang("nonsense"))
assert.is_false(GetText.changeLang("more_NONSENSE"))
end)
end)
describe("cannot find string", function()
it("gettext should return input string", function()
assert.is_equal("bla", GetText("bla"))
end)
it("ngettext should return input string", function()
assert.is_equal("bla", GetText.ngettext("bla", "blabla", 1))
assert.is_equal("blabla", GetText.ngettext("bla", "blabla", 2))
end)
it("pgettext should return input string", function()
assert.is_equal("bla", GetText.pgettext("some context", "bla"))
end)
it("npgettext should return input string", function()
assert.is_equal("bla", GetText.npgettext("some context", "bla", "blabla", 1))
assert.is_equal("blabla", GetText.npgettext("some context", "bla", "blabla", 2))
end)
end)
describe("language with standard plurals", function()
GetText.changeLang("nl_NL")
it("gettext should ignore fuzzy strings", function()
assert.is_equal("Fuzzy", GetText("Fuzzy"))
end)
it("gettext should translate multiline string", function()
assert.is_equal("\nbericht", GetText("\nmessage"))
end)
it("ngettext should translate plurals", function()
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 5))
end)
it("pgettext should distinguish context", function()
assert.is_equal("Pagina's", GetText.pgettext("Style tweaks category", "Pages"))
assert.is_equal("Pages different context", GetText.pgettext("Other pages", "Pages"))
end)
it("npgettext should translate plurals and distinguish context", function()
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 1))
assert.is_equal("Pagina's", GetText.npgettext("Context 1", "Page", "Pages", 2))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 1))
assert.is_equal("Pagina's context 2 plural 1", GetText.npgettext("Context 2", "Page", "Pages", 2))
end)
end)
describe("language with simple plurals n > 2", function()
GetText.changeLang("simple")
it("gettext should ignore fuzzy strings", function()
assert.is_equal("Fuzzy", GetText("Fuzzy"))
end)
it("gettext should translate multiline string", function()
assert.is_equal("\nbericht", GetText("\nmessage"))
end)
it("ngettext should translate plurals", function()
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 3))
end)
it("pgettext should distinguish context", function()
assert.is_equal("Pagina's", GetText.pgettext("Style tweaks category", "Pages"))
assert.is_equal("Pages different context", GetText.pgettext("Other pages", "Pages"))
end)
it("npgettext should translate plurals and distinguish context", function()
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 1))
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 2))
assert.is_equal("Pagina's", GetText.npgettext("Context 1", "Page", "Pages", 3))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 1))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 2))
assert.is_equal("Pagina's context 2 plural 1", GetText.npgettext("Context 2", "Page", "Pages", 3))
end)
end)
describe("language with no plurals", function()
GetText.changeLang("none")
it("gettext should ignore fuzzy strings", function()
assert.is_equal("Fuzzy", GetText("Fuzzy"))
end)
it("gettext should translate multiline string", function()
assert.is_equal("\nbericht", GetText("\nmessage"))
end)
it("ngettext should translate plurals", function()
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 3))
end)
it("pgettext should distinguish context", function()
assert.is_equal("Pagina's", GetText.pgettext("Style tweaks category", "Pages"))
assert.is_equal("Pages different context", GetText.pgettext("Other pages", "Pages"))
end)
it("npgettext should translate plurals and distinguish context", function()
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 1))
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 2))
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 3))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 1))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 2))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 3))
end)
end)
describe("language with complex plurals (Arabic)", function()
GetText.changeLang("ar")
it("gettext should ignore fuzzy strings", function()
assert.is_equal("Fuzzy", GetText("Fuzzy"))
end)
it("gettext should translate multiline string", function()
assert.is_equal("\nbericht", GetText("\nmessage"))
end)
it("ngettext should translate plurals", function()
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("%1 dingen 2", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("%1 items", GetText.ngettext("1 item", "%1 items", 5))
end)
it("pgettext should distinguish context", function()
assert.is_equal("Pagina's", GetText.pgettext("Style tweaks category", "Pages"))
assert.is_equal("Pages different context", GetText.pgettext("Other pages", "Pages"))
end)
it("npgettext should translate plurals and distinguish context", function()
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 0))
assert.is_equal("Pagina's", GetText.npgettext("Context 1", "Page", "Pages", 1))
assert.is_equal("Pagina's plural 2", GetText.npgettext("Context 1", "Page", "Pages", 2))
assert.is_equal("Pagina's plural 3", GetText.npgettext("Context 1", "Page", "Pages", 5))
assert.is_equal("Pagina's plural 4", GetText.npgettext("Context 1", "Page", "Pages", 99))
assert.is_equal("Pagina's context 2 plural 1", GetText.npgettext("Context 2", "Page", "Pages", 1))
assert.is_equal("Pagina's context 2 plural 2", GetText.npgettext("Context 2", "Page", "Pages", 2))
assert.is_equal("Pages", GetText.npgettext("Context 2", "Page", "Pages", 5))
end)
end)
describe("language with complex plurals (Russian)", function()
GetText.changeLang("ru")
it("gettext should ignore fuzzy strings", function()
assert.is_equal("Fuzzy", GetText("Fuzzy"))
end)
it("gettext should translate multiline string", function()
assert.is_equal("\nbericht", GetText("\nmessage"))
end)
it("ngettext should translate plurals", function()
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("%1 dingen 2", GetText.ngettext("1 item", "%1 items", 5))
end)
it("pgettext should distinguish context", function()
assert.is_equal("Pagina's", GetText.pgettext("Style tweaks category", "Pages"))
assert.is_equal("Pages different context", GetText.pgettext("Other pages", "Pages"))
end)
it("npgettext should translate plurals and distinguish context", function()
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 1))
assert.is_equal("Pagina's", GetText.npgettext("Context 1", "Page", "Pages", 2))
assert.is_equal("Pagina's plural 2", GetText.npgettext("Context 1", "Page", "Pages", 5))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 1))
assert.is_equal("Pagina's context 2 plural 1", GetText.npgettext("Context 2", "Page", "Pages", 2))
assert.is_equal("Pagina's context 2 plural 2", GetText.npgettext("Context 2", "Page", "Pages", 5))
end)
end)
-- This one's mainly to test fallback stuff. Russian/Polish are hard
-- to follow, so there we focus on algorithm correctness.
describe("language with many plurals", function()
GetText.changeLang("many")
it("gettext should ignore fuzzy strings", function()
assert.is_equal("Fuzzy", GetText("Fuzzy"))
end)
it("gettext should translate multiline string", function()
assert.is_equal("\nbericht", GetText("\nmessage"))
end)
it("ngettext should translate plurals", function()
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("%1 dingen 2", GetText.ngettext("1 item", "%1 items", 3))
end)
it("ngettext should fallback to default plural if not yet translated", function()
assert.is_equal("1 ding", GetText.ngettext("1 item", "%1 items", 1))
assert.is_equal("%1 dingen", GetText.ngettext("1 item", "%1 items", 2))
assert.is_equal("%1 dingen 2", GetText.ngettext("1 item", "%1 items", 3))
assert.is_equal("%1 items", GetText.ngettext("1 item", "%1 items", 4))
assert.is_equal("%1 items", GetText.ngettext("1 item", "%1 items", 5))
assert.is_equal("1 untranslated", GetText.ngettext("1 untranslated", "%1 untranslated", 1))
assert.is_equal("%1 untranslated", GetText.ngettext("1 untranslated", "%1 untranslated", 2))
assert.is_equal("%1 untranslated", GetText.ngettext("1 untranslated", "%1 untranslated", 3))
assert.is_equal("%1 untranslated", GetText.ngettext("1 untranslated", "%1 untranslated", 4))
assert.is_equal("%1 untranslated", GetText.ngettext("1 untranslated", "%1 untranslated", 5))
end)
it("pgettext should distinguish context", function()
assert.is_equal("Pagina's", GetText.pgettext("Style tweaks category", "Pages"))
assert.is_equal("Pages different context", GetText.pgettext("Other pages", "Pages"))
end)
it("npgettext should translate plurals and distinguish context", function()
assert.is_equal("Pagina", GetText.npgettext("Context 1", "Page", "Pages", 1))
assert.is_equal("Pagina's", GetText.npgettext("Context 1", "Page", "Pages", 2))
assert.is_equal("Pagina's plural 3", GetText.npgettext("Context 1", "Page", "Pages", 5))
assert.is_equal("Pagina context 2 plural 0", GetText.npgettext("Context 2", "Page", "Pages", 1))
assert.is_equal("Pagina's context 2 plural 1", GetText.npgettext("Context 2", "Page", "Pages", 2))
assert.is_equal("Pages", GetText.npgettext("Context 2", "Page", "Pages", 5))
end)
end)
end)
| agpl-3.0 |
retep998/Vana | scripts/npcs/bowman3.lua | 2 | 10388 | --[[
Copyright (C) 2008-2016 Vana Development Team
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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
-- Rene (3rd Job - Bowman Instructor)
dofile("scripts/utils/jobHelper.lua");
dofile("scripts/utils/npcHelper.lua");
dofile("scripts/utils/tableHelper.lua");
zakum = getPlayerVariable("zakum_quest_status", type_int);
if getLevel() >= 50 then
jobLine, jobTrack, jobProgression = getJobMeta();
choices = {};
if getLevel() >= 70 and jobProgression == progression_second and jobLine == line_bowman then
append(choices, makeChoiceHandler(" I want to make the 3rd job advancement", function()
questState = getPlayerVariable("third_job_advancement", type_int);
if questState == nil then
addText("Welcome. ");
addText("I'm " .. blue("Rene") .. ", the chief of all bowmen, in charge of bringing out the best in each and every bowman that needs my guidance. ");
addText("You seem like the kind of bowman that wants to make the leap forward, the one ready to take on the challenges of the 3rd job advancement. ");
addText("But I've seen countless bowmen eager to make the jump just like you, only to see them fail. ");
addText("What about you? ");
addText("Are you ready to be tested and make the 3rd job advancement?");
answer = askYesNo();
if answer == answer_no then
addText("I don't think you are ready to face the tough challenges that lie ahead. ");
addText("Come see me only after you have convinced yourself that you're ready to make the next leap forward.");
sendNext();
else
addText("Good. You will be tested on two important aspects of the bowman: strength and wisdom. ");
addText("I'll now explain to you the physical half of the test. ");
addText("Remember " .. blue(npcRef(1012100)) .. " from Henesys? ");
addText("Go see her, and she'll give you the details on the first half of the test. ");
addText("Please complete the mission, and get " .. blue(itemRef(4031057)) .. " from " .. npcRef(1012100) .. ".");
sendNext();
addText("The mental half of the test can only start after you pass the physical part. ");
addText(blue(itemRef(4031057)) .. " will be the proof that you have indeed passed the test. ");
addText("I'll let " .. blue(npcRef(1012100)) .. " know in advance that you're making your way there, so get ready. ");
addText("It won't be easy, but I have faith in you. ");
addText("Good luck.");
sendBackNext();
setPlayerVariable("third_job_advancement", 1);
end
elseif questState == 1 or questState == 2 then
if getItemAmount(4031057) > 0 then
addText("Great job completing the physical part of the test. ");
addText("I knew you could do it. ");
addText("Now that you have passed the first half of the test, here's the second half. ");
addText("Please give me the necklace first.");
sendNext();
giveItem(4031057, -1);
setPlayerVariable("third_job_advancement", 3);
addText("Here's the second half of the test. ");
addText("This test will determine whether you are smart enough to take the next step towards greatness. ");
addText("There is a dark, snow-covered area called the Holy Ground at the snowfield in Ossyria, where even the monsters can't reach. ");
addText("In the center of the area lies a huge stone called the Holy Stone. ");
addText("You'll need to offer a special item as a sacrifice. ");
addText("Then the Holy Stone will test your wisdom right there on the spot.");
sendBackNext();
addText("You'll need to answer each and every question given to you with honesty and conviction. ");
addText("If you correctly answer all the questions, then the Holy Stone will formally accept you and hand you " .. blue(itemRef(4031058)) .. ". ");
addText("Bring back the necklace, and I will help you make the next leap forward. ");
addText("Good luck.");
sendBackNext();
else
addText("You don't have " .. blue(itemRef(4031057)) .. " with you. ");
addText("Please go see " .. blue(npcRef(1012100)) .. " of Henesys, pass the test, and bring " .. blue(itemRef(4031057)) .. " back with you. ");
addText("Then, and only then, will you be given the second test. ");
addText("Best of luck to you.");
sendNext();
end
elseif questState == 3 or questState == 4 then
if getItemAmount(4031058) > 0 or questState == 4 then
if questState == 3 then
addText("Great job completing the mental part of the test. ");
addText("You have wisely and correctly answered all the questions. ");
addText("I must say, I am quite impressed with the level of wisdom you displayed. ");
addText("Please hand me the necklace first, before we take the next step.");
sendNext();
giveItem(4031058, -1);
setPlayerVariable("third_job_advancement", 4);
end
addText("Okay! Now, I'll transform you into a much more powerful bowman. ");
addText("Before that, however, please make sure your SP has been thoroughly used. ");
addText("You'll need to use at least all the SP gained until Lv. 70 to make the 3rd job advancement. ");
addText("Oh, and since you have already chosen your occupation path from the 2nd job advancement, you won't have to choose again for the 3rd job advancement. ");
addText("So, do you want to do it right now?");
answer = askYesNo();
if answer == answer_no then
addText("You've already passed the test and all, so don't hesitate. ");
addText("Anyway, come talk to me once you have made up your mind. ");
addText("As long as you're ready for it, I'll get you through the 3rd job advancement.");
sendNext();
else
if getSp() > (getLevel() - 70) * 3 then
addText("Hmmm... you seem to have too much SP. ");
addText("You can't make the 3rd job advancement with so much SP. ");
addText("Use more in the 1st and 2nd advancement before returning here.");
sendNext();
else
setPlayerVariable("third_job_advancement", 5);
setJob(getJob() + 1);
giveSp(1);
giveAp(5);
if jobTrack == 1 then
addText("You have officialy become a " .. blue("Ranger") .. ". ");
addText("One of the skills that you'll truly embrace is a skill called " .. blue("Mortal Blow") .. " that allows Rangers to fire arrows from close-range. ");
addText(blue("Inferno") .. " allows Rangers to temporarily perform fire-based attacks on monsters, while skills like " .. blue("Puppet") .. " (summons a scarecrow which attracts the monsters' attention) and " .. blue("Silver Hawk") .. " (summons a Silver Hawk that attacks monsters) solidify the Bowman's status as a long-range attack extraordinaire.");
elseif jobTrack == 2 then
addText("You have officialy become a " .. blue("Sniper") .. ". ");
addText("One of the skills that you'll truly embrace is a skill called " .. blue("Mortal Blow") .. " that allows Snipers to fire arrows from close-range. ");
addText(blue("Blizzard") .. " allows the Snipers to temporarily perform ice-based attacks on monsters, while skills like " .. blue("Puppet") .. " (summons a scarecrow which attracts the monsters' attention) and " .. blue("Golden Eagle") .. " (summons a Golden Eagle that attacks monsters) solidify the Bowman's status as a long-range attack extraordinaire.");
end
sendNext();
addText("I've also given you a little bit of SP and AP, which will be beneficial to you. ");
addText("You have now become a powerful magician, indeed. ");
addText("Remember, though, that the real world will be awaiting with even tougher obstacles. ");
addText("Once you feel like you cannot reach a higher place, then come see me. ");
addText("I'll be here waiting.");
sendBackNext();
end
end
else
addText("You don't have " .. blue(itemRef(4031058)) .. " with you. ");
addText("Please find the dark, snow-covered area called the Holy Ground at the snowfield in Ossyria, offer the special item as a sacrifice, and answer each and every question asked with honesty and conviction to receive " .. blue(itemRef(4031058)) .. ". ");
addText("Bring that back to me to complete the 3rd job advancement test. ");
addText("Best of luck to you.");
sendOk();
end
end
end));
end
append(choices, makeChoiceHandler(" Please allow me to do the Zakum Dungeon Quest", function()
if zakum == nil then
if jobLine == line_beginner or jobLine == line_bowman then
setPlayerVariable("zakum_quest_status", 1);
addText("You want to be permitted to do the Zakum Dungeon Quest, right? ");
addText("Must be " .. blue(npcRef(2030008)) .. " ... ok, alright! ");
addText("I'm sure you'll be fine roaming around the dungeon. ");
addText("Here's hoping you'll be careful there ...");
else
addText("So you want me to give you my permission to go on the Zakum Dungeon Quest? ");
addText("But you don't seem to be a bowman under my jurisdiction, so please look for the Trainer that oversees your job.");
end
else
addText("How are you along with the Zakum Dungeon Quest? ");
addText("From what I've heard, there's this incredible monster at the innermost part of that place ... anyway, good luck. ");
addText("I'm sure you can do it.");
end
sendNext();
end));
addText("Can I help you?\r\n");
addText(blue(choiceRef(choices)));
choice = askChoice();
selectChoice(choices, choice);
else
addText("Hmm... It seems like there is nothing I can help you with. ");
addText("Come to me again when you get stronger. ");
addText("Zakum Dungeon quest is available from " .. blue("Level 50") .. " and 3rd Job Advancement at " .. blue("Level 70"));
sendOk();
end | gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c40164421.lua | 9 | 2902 | --ライトロード・メイデン ミネルバ
function c40164421.initial_effect(c)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(40164421,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetTarget(c40164421.thtg)
e1:SetOperation(c40164421.thop)
c:RegisterEffect(e1)
--discard deck
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(40164421,1))
e2:SetCategory(CATEGORY_DECKDES)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c40164421.discon)
e2:SetTarget(c40164421.distg)
e2:SetOperation(c40164421.disop)
c:RegisterEffect(e2)
--discard deck2
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(40164421,2))
e3:SetCategory(CATEGORY_DECKDES)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_PHASE+PHASE_END)
e3:SetRange(LOCATION_MZONE)
e3:SetCountLimit(1)
e3:SetCondition(c40164421.discon2)
e3:SetTarget(c40164421.distg2)
e3:SetOperation(c40164421.disop2)
c:RegisterEffect(e3)
end
function c40164421.cfilter(c)
return c:IsSetCard(0x38) and c:IsType(TYPE_MONSTER)
end
function c40164421.thfilter(c,lv)
return c:IsLevelBelow(lv) and c:IsRace(RACE_DRAGON) and c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsAbleToHand()
end
function c40164421.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local g=Duel.GetMatchingGroup(c40164421.cfilter,tp,LOCATION_GRAVE,0,nil)
local ct=g:GetClassCount(Card.GetCode)
return Duel.IsExistingMatchingCard(c40164421.thfilter,tp,LOCATION_DECK,0,1,nil,ct)
end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c40164421.thop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c40164421.cfilter,tp,LOCATION_GRAVE,0,nil)
local ct=g:GetClassCount(Card.GetCode)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local sg=Duel.SelectMatchingCard(tp,c40164421.thfilter,tp,LOCATION_DECK,0,1,1,nil,ct)
if sg:GetCount()>0 then
Duel.SendtoHand(sg,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,sg)
end
end
function c40164421.discon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_DECK+LOCATION_HAND)
end
function c40164421.distg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DECKDES,nil,0,tp,1)
end
function c40164421.disop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.DiscardDeck(p,d,REASON_EFFECT)
end
function c40164421.discon2(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer()
end
function c40164421.distg2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DECKDES,nil,0,tp,2)
end
function c40164421.disop2(e,tp,eg,ep,ev,re,r,rp)
Duel.DiscardDeck(tp,2,REASON_EFFECT)
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c66235877.lua | 6 | 1222 | --デス・デーモン・ドラゴン
function c66235877.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCode2(c,93220472,16475472,false,false)
--disable
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_DISABLE)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e1:SetTarget(c66235877.distg)
c:RegisterEffect(e1)
--disable effect
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetCode(EVENT_CHAIN_SOLVING)
e2:SetRange(LOCATION_MZONE)
e2:SetOperation(c66235877.disop)
c:RegisterEffect(e2)
--
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(66235877)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
c:RegisterEffect(e3)
end
function c66235877.distg(e,c)
return c:IsType(TYPE_FLIP)
end
function c66235877.disop(e,tp,eg,ep,ev,re,r,rp)
if re:IsActiveType(TYPE_FLIP) then Duel.NegateEffect(ev) end
if re:IsActiveType(TYPE_TRAP) and re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then
local g=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if g and g:IsContains(e:GetHandler()) then
Duel.NegateEffect(ev)
end
end
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c22653490.lua | 5 | 2605 | --電光千鳥
function c22653490.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsAttribute,ATTRIBUTE_WIND),4,2)
c:EnableReviveLimit()
--return to deck
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(22653490,0))
e1:SetCategory(CATEGORY_TODECK)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c22653490.tdcon1)
e1:SetTarget(c22653490.tdtg1)
e1:SetOperation(c22653490.tdop1)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(22653490,1))
e2:SetCategory(CATEGORY_TODECK)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1)
e2:SetRange(LOCATION_MZONE)
e2:SetCost(c22653490.tdcost2)
e2:SetTarget(c22653490.tdtg2)
e2:SetOperation(c22653490.tdop2)
c:RegisterEffect(e2)
end
function c22653490.tdcon1(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_XYZ
end
function c22653490.tdfilter1(c)
return c:IsFacedown() and c:IsAbleToDeck()
end
function c22653490.tdtg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and c22653490.tdfilter1(chkc) end
if chk==0 then return true end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,Card.IsFacedown,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
end
function c22653490.tdop1(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) and tc:IsControler(1-tp) and tc:IsFacedown() then
Duel.SendtoDeck(tc,nil,1,REASON_EFFECT)
end
end
function c22653490.tdcost2(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 c22653490.tdfilter2(c)
return c:IsFaceup() and c:IsAbleToDeck()
end
function c22653490.tdtg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsOnField() and c22653490.tdfilter2(chkc) end
if chk==0 then return Duel.IsExistingTarget(c22653490.tdfilter2,tp,0,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c22653490.tdfilter2,tp,0,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,1,0,0)
end
function c22653490.tdop2(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsControler(1-tp) and tc:IsFaceup() then
Duel.SendtoDeck(tc,nil,0,REASON_EFFECT)
end
end
| gpl-2.0 |
dr01d3r/darkstar | scripts/globals/spells/sacrifice.lua | 33 | 1201 | -----------------------------------------
-- Spell: Sacrifice
--
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local count = 1;
local removables = {EFFECT_FLASH, EFFECT_BLINDNESS, EFFECT_PARALYSIS, EFFECT_POISON, EFFECT_CURSE_I, EFFECT_CURSE_II, EFFECT_DISEASE, EFFECT_PLAGUE};
-- remove one effect and add it to me
for i, effect in ipairs(removables) do
if (target:hasStatusEffect(effect)) then
spell:setMsg(572);
local statusEffect = target:getStatusEffect(effect);
-- only add it to me if I don't have it
if (caster:hasStatusEffect(effect) == false) then
caster:addStatusEffect(effect, statusEffect:getPower(), statusEffect:getTickCount(), statusEffect:getDuration());
end
target:delStatusEffect(effect);
return 1;
end
end
spell:setMsg(75); -- no effect
return 0;
end;
| gpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c67249508.lua | 2 | 2019 | --竜星の凶暴化
function c67249508.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE)
e1:SetCondition(c67249508.condition)
e1:SetOperation(c67249508.activate)
c:RegisterEffect(e1)
end
function c67249508.condition(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetAttacker()
local at=Duel.GetAttackTarget()
if not at or tc:IsFacedown() or at:IsFacedown() then return false end
if tc:IsControler(1-tp) then tc=at end
e:SetLabelObject(tc)
return tc:IsControler(tp) and tc:IsLocation(LOCATION_MZONE) and tc:IsSetCard(0x9e)
end
function c67249508.activate(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=e:GetLabelObject()
if tc:IsRelateToBattle() and not tc:IsImmuneToEffect(e) then
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SET_ATTACK_FINAL)
e1:SetValue(tc:GetBaseAttack()*2)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE_CAL)
tc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SET_DEFENSE_FINAL)
e2:SetValue(tc:GetBaseDefense()*2)
e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_DAMAGE_CAL)
tc:RegisterEffect(e2)
local fid=c:GetFieldID()
tc:RegisterFlagEffect(67249508,RESET_EVENT+0x1fe0000,0,1,fid)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e3:SetCode(EVENT_DAMAGE_STEP_END)
e3:SetCountLimit(1)
e3:SetLabel(fid)
e3:SetLabelObject(tc)
e3:SetCondition(c67249508.descon)
e3:SetOperation(c67249508.desop)
e3:SetReset(RESET_PHASE+PHASE_DAMAGE)
Duel.RegisterEffect(e3,tp)
end
end
function c67249508.descon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
if tc:GetFlagEffectLabel(67249508)==e:GetLabel() then
return true
else
e:Reset()
return false
end
end
function c67249508.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
Duel.Destroy(tc,REASON_EFFECT)
end
| gpl-2.0 |
waruqi/xmake | xmake/core/sandbox/modules/interpreter/print.lua | 1 | 1546 | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file print.lua
--
-- load modules
local try = require("sandbox/modules/try")
local catch = require("sandbox/modules/catch")
-- print format string
function _print(format, ...)
-- print format string
if type(format) == "string" and format:find("%", 1, true) then
local args = {...}
try
{
function ()
-- attempt to print format string first
io.write(string.format(format, unpack(args)) .. "\n")
end,
catch
{
function ()
-- print multi-variables with raw lua action
print(format, unpack(args))
end
}
}
else
-- print multi-variables with raw lua action
print(format, ...)
end
end
-- load module
return _print
| apache-2.0 |
dr01d3r/darkstar | scripts/zones/RuLude_Gardens/npcs/Neraf-Najiruf.lua | 14 | 2050 | -----------------------------------
-- Area: Ru'Lud Gardens
-- NPC: Neraf-Najiruf
-- Involved in Quests: Save my Sister
-- @zone 243
-- @pos -36 2 60
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
saveMySister = player:getQuestStatus(JEUNO,SAVE_MY_SISTER);
if (saveMySister == QUEST_AVAILABLE and player:getVar("saveMySisterVar") == 3) then
player:startEvent(0x0062); -- Real start of this quest (with addquest)
elseif (saveMySister == QUEST_ACCEPTED) then
player:startEvent(0x0063); -- During quest
elseif (saveMySister == QUEST_COMPLETED and player:hasKeyItem(DUCAL_GUARDS_LANTERN) == true) then
player:startEvent(0x0061); -- last CS (after talk with baudin)
else
player:startEvent(0x009C); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0062) then
player:addQuest(JEUNO,SAVE_MY_SISTER);
player:setVar("saveMySisterVar", 0);
player:addKeyItem(DUCAL_GUARDS_LANTERN);
player:messageSpecial(KEYITEM_OBTAINED,DUCAL_GUARDS_LANTERN);
elseif (csid == 0x0061) then
player:delKeyItem(DUCAL_GUARDS_LANTERN);
player:setVar("saveMySisterFireLantern", 0);
end
end;
| gpl-3.0 |
grbd/premake-core | tests/base/test_table.lua | 18 | 1436 | --
-- tests/base/test_table.lua
-- Automated test suite for the new table functions.
-- Copyright (c) 2008-2013 Jason Perkins and the Premake project
--
local suite = test.declare("table")
local t
--
-- table.contains() tests
--
function suite.contains_OnContained()
t = { "one", "two", "three" }
test.istrue( table.contains(t, "two") )
end
function suite.contains_OnNotContained()
t = { "one", "two", "three" }
test.isfalse( table.contains(t, "four") )
end
--
-- table.flatten() tests
--
function suite.flatten_OnMixedValues()
t = { "a", { "b", "c" }, "d" }
test.isequal({ "a", "b", "c", "d" }, table.flatten(t))
end
--
-- table.implode() tests
--
function suite.implode()
t = { "one", "two", "three", "four" }
test.isequal("[one], [two], [three], [four]", table.implode(t, "[", "]", ", "))
end
--
-- table.indexof() tests
--
function suite.indexof_returnsIndexOfValueFound()
local idx = table.indexof({ "a", "b", "c" }, "b")
test.isequal(2, idx)
end
--
-- table.isempty() tests
--
function suite.isempty_ReturnsTrueOnEmpty()
test.istrue(table.isempty({}))
end
function suite.isempty_ReturnsFalseOnNotEmpty()
test.isfalse(table.isempty({ 1 }))
end
function suite.isempty_ReturnsFalseOnNotEmptyMap()
test.isfalse(table.isempty({ name = 'premake' }))
end
function suite.isempty_ReturnsFalseOnNotEmptyMapWithFalseKey()
test.isfalse(table.isempty({ [false] = 0 }))
end
| bsd-3-clause |
koreader/koreader | plugins/exporter.koplugin/template/md.lua | 4 | 1813 | local _ = require("gettext")
local formatters = {
none = {
formatter = "%s",
label = _("None")
},
bold = {
formatter = "**%s**",
label = _("Bold")
},
italic = {
formatter = "*%s*",
label = _("Italic")
},
bold_italic = {
formatter = "**_%s_**",
label = _("Bold italic")
},
underline_markdownit = {
formatter = "++%s++",
label = _("Underline (Markdownit style, with ++)")
},
underline_u_tag = {
formatter = "<u>%s</u>",
label = _("Underline (with <u></u> tags)")
},
strikethrough = {
formatter = "~~%s~~",
label = _("Strikethrough")
},
}
local function prepareBookContent(book, formatting_options, highlight_formatting)
local content = ""
local current_chapter = nil
content = content .. "# " .. book.title .. "\n"
content = content .. "##### " .. book.author:gsub("\n", ", ") .. "\n\n"
for _, note in ipairs(book) do
local entry = note[1]
if entry.chapter ~= current_chapter then
current_chapter = entry.chapter
content = content .. "## " .. current_chapter .. "\n"
end
content = content .. "### Page " .. entry.page .. " @ " .. os.date("%d %B %Y %I:%M %p", entry.time) .. "\n"
if highlight_formatting then
content = content .. string.format(formatters[formatting_options[entry.drawer]].formatter, entry.text) .."\n"
else
content = content .. entry.text .. "\n"
end
if entry.note then
content = content .. "\n---\n" .. entry.note .. "\n"
end
content = content .. "\n"
end
return content
end
return {
prepareBookContent = prepareBookContent,
formatters = formatters
}
| agpl-3.0 |
dr01d3r/darkstar | scripts/zones/Port_Windurst/npcs/Erabu-Fumulubu.lua | 53 | 1835 | -----------------------------------
-- Area: Port Windurst
-- NPC: Erabu-Fumulubu
-- Type: Fishing Synthesis Image Support
-- @pos -178.900 -2.789 76.200 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,5);
local SkillCap = getCraftSkillCap(player,SKILL_FISHING);
local SkillLevel = player:getSkillLevel(SKILL_FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),0,0,0); -- p1 = skill level
else
player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),19194,4031,0);
end
else
player:startEvent(0x271C); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x271C and option == 1) then
player:messageSpecial(FISHING_SUPPORT,0,0,1);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600);
end
end; | gpl-3.0 |
koreader/koreader | frontend/apps/cloudstorage/webdav.lua | 3 | 7166 | local BD = require("ui/bidi")
local ConfirmBox = require("ui/widget/confirmbox")
local DocumentRegistry = require("document/documentregistry")
local InfoMessage = require("ui/widget/infomessage")
local MultiInputDialog = require("ui/widget/multiinputdialog")
local UIManager = require("ui/uimanager")
local ReaderUI = require("apps/reader/readerui")
local WebDavApi = require("apps/cloudstorage/webdavapi")
local util = require("util")
local ffiutil = require("ffi/util")
local _ = require("gettext")
local T = require("ffi/util").template
local WebDav = {}
function WebDav:run(address, user, pass, path, folder_mode)
return WebDavApi:listFolder(address, user, pass, path, folder_mode)
end
function WebDav:downloadFile(item, address, username, password, local_path, callback_close)
local code_response = WebDavApi:downloadFile(WebDavApi:getJoinedPath(address, item.url), username, password, local_path)
if code_response == 200 then
local __, filename = util.splitFilePathName(local_path)
if G_reader_settings:isTrue("show_unsupported") and not DocumentRegistry:hasProvider(filename) then
UIManager:show(InfoMessage:new{
text = T(_("File saved to:\n%1"), BD.filepath(local_path)),
})
else
UIManager:show(ConfirmBox:new{
text = T(_("File saved to:\n%1\nWould you like to read the downloaded book now?"),
BD.filepath(local_path)),
ok_callback = function()
local Event = require("ui/event")
UIManager:broadcastEvent(Event:new("SetupShowReader"))
if callback_close then
callback_close()
end
ReaderUI:showReader(local_path)
end
})
end
else
UIManager:show(InfoMessage:new{
text = T(_("Could not save file to:\n%1"), BD.filepath(local_path)),
timeout = 3,
})
end
end
function WebDav:uploadFile(url, address, username, password, local_path, callback_close)
local path = WebDavApi:getJoinedPath(address, url)
path = WebDavApi:getJoinedPath(path, ffiutil.basename(local_path))
local code_response = WebDavApi:uploadFile(path, username, password, local_path)
if code_response >= 200 and code_response < 300 then
UIManager:show(InfoMessage:new{
text = T(_("File uploaded:\n%1"), BD.filepath(address)),
})
if callback_close then callback_close() end
else
UIManager:show(InfoMessage:new{
text = T(_("Could not upload file:\n%1"), BD.filepath(address)),
timeout = 3,
})
end
end
function WebDav:createFolder(url, address, username, password, folder_name, callback_close)
local code_response = WebDavApi:createFolder(address .. WebDavApi:urlEncode(url .. "/" .. folder_name), username, password, folder_name)
if code_response == 201 then
if callback_close then
callback_close()
end
else
UIManager:show(InfoMessage:new{
text = T(_("Could not create folder:\n%1"), folder_name),
})
end
end
function WebDav:config(item, callback)
local text_info = _([[Server address must be of the form http(s)://domain.name/path
This can point to a sub-directory of the WebDAV server.
The start folder is appended to the server path.]])
local hint_name = _("Server display name")
local text_name = ""
local hint_address = _("WebDAV address, for example https://example.com/dav")
local text_address = ""
local hint_username = _("Username")
local text_username = ""
local hint_password = _("Password")
local text_password = ""
local hint_folder = _("Start folder")
local text_folder = ""
local title
local text_button_ok = _("Add")
if item then
title = _("Edit WebDAV account")
text_button_ok = _("Apply")
text_name = item.text
text_address = item.address
text_username = item.username
text_password = item.password
text_folder = item.url
else
title = _("Add WebDAV account")
end
self.settings_dialog = MultiInputDialog:new {
title = title,
fields = {
{
text = text_name,
input_type = "string",
hint = hint_name ,
},
{
text = text_address,
input_type = "string",
hint = hint_address ,
},
{
text = text_username,
input_type = "string",
hint = hint_username,
},
{
text = text_password,
input_type = "string",
text_type = "password",
hint = hint_password,
},
{
text = text_folder,
input_type = "string",
hint = hint_folder,
},
},
buttons = {
{
{
text = _("Cancel"),
id = "close",
callback = function()
self.settings_dialog:onClose()
UIManager:close(self.settings_dialog)
end
},
{
text = _("Info"),
callback = function()
UIManager:show(InfoMessage:new{ text = text_info })
end
},
{
text = text_button_ok,
callback = function()
local fields = self.settings_dialog:getFields()
-- make sure the URL is a valid path
if fields[5] ~= "" then
if string.sub(fields[5], 1, 1) ~= '/' then
fields[5] = '/' .. fields[5]
end
end
if fields[1] ~= "" and fields[2] ~= "" then
if item then
-- edit
callback(item, fields)
else
-- add new
callback(fields)
end
self.settings_dialog:onClose()
UIManager:close(self.settings_dialog)
else
UIManager:show(InfoMessage:new{
text = _("Please fill in all fields.")
})
end
end
},
},
},
input_type = "text",
}
UIManager:show(self.settings_dialog)
self.settings_dialog:onShowKeyboard()
end
function WebDav:info(item)
local info_text = T(_"Type: %1\nName: %2\nAddress: %3", "WebDAV", item.text, item.address)
UIManager:show(InfoMessage:new{text = info_text})
end
return WebDav
| agpl-3.0 |
dr01d3r/darkstar | scripts/zones/Throne_Room/mobs/Shadow_Lord.lua | 23 | 5454 | -----------------------------------
-- Area: Throne Room
-- MOB: Shadow Lord
-- Mission 5-2 BCNM Fight
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
-- 1st form
-- after change magic or physical immunity every 5min or 1k dmg
-- 2nd form
-- the Shadow Lord will do nothing but his Implosion attack. This attack hits everyone in the battlefield, but he only has 4000 HP
if (mob:getID() < 17453060) then -- first phase AI
-- once he's under 50% HP, start changing immunities and attack patterns
if (mob:getHP() / mob:getMaxHP() <= 0.5) then
-- have to keep track of both the last time he changed immunity and the HP he changed at
local changeTime = mob:getLocalVar("changeTime");
local changeHP = mob:getLocalVar("changeHP");
-- subanimation 0 is first phase subanim, so just go straight to magic mode
if (mob:AnimationSub() == 0) then
mob:AnimationSub(1);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0);
mob:SetAutoAttackEnabled(false);
mob:SetMagicCastingEnabled(true);
mob:setMobMod(MOBMOD_MAGIC_COOL, 2);
--and record the time and HP this immunity was started
mob:setLocalVar("changeTime", mob:getBattleTime());
mob:setLocalVar("changeHP", mob:getHP());
-- subanimation 2 is physical mode, so check if he should change into magic mode
elseif (mob:AnimationSub() == 2 and (mob:getHP() <= changeHP - 1000 or
mob:getBattleTime() - changeTime > 300)) then
mob:AnimationSub(1);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0);
mob:SetAutoAttackEnabled(false);
mob:SetMagicCastingEnabled(true);
mob:setMobMod(MOBMOD_MAGIC_COOL, 2);
mob:setLocalVar("changeTime", mob:getBattleTime());
mob:setLocalVar("changeHP", mob:getHP());
-- subanimation 1 is magic mode, so check if he should change into physical mode
elseif (mob:AnimationSub() == 1 and (mob:getHP() <= changeHP - 1000 or
mob:getBattleTime() - changeTime > 300)) then
-- and use an ability before changing
mob:useMobAbility(673);
mob:AnimationSub(2);
mob:delStatusEffect(EFFECT_MAGIC_SHIELD);
mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD, 0, 1, 0, 0);
mob:SetAutoAttackEnabled(true);
mob:SetMagicCastingEnabled(false);
mob:setMobMod(MOBMOD_MAGIC_COOL, 10);
mob:setLocalVar("changeTime", mob:getBattleTime());
mob:setLocalVar("changeHP", mob:getHP());
end
end
else
-- second phase AI: Implode every 9 seconds
local lastImplodeTime = mob:getLocalVar("lastImplodeTime");
-- second phase AI: Implode every 9 seconds
if (mob:getBattleTime() - lastImplodeTime > 9) then
mob:useMobAbility(669);
mob:setLocalVar("lastImplodeTime", mob:getBattleTime());
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (mob:getID() < 17453060) then
player:startEvent(0x7d04);
player:setVar("mobid",mob:getID());
else
player:addTitle(SHADOW_BANISHER);
end
-- reset everything on death
mob:AnimationSub(0);
mob:SetAutoAttackEnabled(true);
mob:SetMagicCastingEnabled(true);
mob:delStatusEffect(EFFECT_MAGIC_SHIELD);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
-- reset everything on despawn
mob:AnimationSub(0);
mob:SetAutoAttackEnabled(true);
mob:SetMagicCastingEnabled(true);
mob:delStatusEffect(EFFECT_MAGIC_SHIELD);
mob:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("updateCSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("finishCSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x7d04) then
local mobid = player:getVar("mobid");
DespawnMob(mobid);
player:setVar("mobid",0);
--first phase dies, spawn second phase ID, make him engage, and disable
-- magic, auto attack, and abilities (all he does is case Implode by script)
mob = SpawnMob(mobid+3);
mob:updateEnmity(player);
mob:SetMagicCastingEnabled(false);
mob:SetAutoAttackEnabled(false);
mob:SetMobAbilityEnabled(false);
end
end;
| gpl-3.0 |
joev/SVUI-Temp | SVUI_UnitFrames/libs/Plugins/oUF_Druidness/oUF_Druidness.lua | 1 | 6343 | if(select(2, UnitClass('player')) ~= 'DRUID') then return end
--GLOBAL NAMESPACE
local _G = _G;
--LUA
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
local error = _G.error;
local print = _G.print;
local pairs = _G.pairs;
local next = _G.next;
local tostring = _G.tostring;
local type = _G.type;
--STRING
local string = _G.string;
local format = string.format;
--MATH
local math = _G.math;
local floor = math.floor
local ceil = math.ceil
--TABLE
local table = _G.table;
local wipe = _G.wipe;
--BLIZZARD API
local BEAR_FORM = _G.BEAR_FORM;
local CAT_FORM = _G.CAT_FORM;
local SPELL_POWER_MANA = _G.SPELL_POWER_MANA;
local UnitClass = _G.UnitClass;
local UnitPower = _G.UnitPower;
local UnitReaction = _G.UnitReaction;
local UnitPowerMax = _G.UnitPowerMax;
local UnitIsPlayer = _G.UnitIsPlayer;
local UnitPlayerControlled = _G.UnitPlayerControlled;
local GetShapeshiftFormID = _G.GetShapeshiftFormID;
local _, ns = ...
local oUF = ns.oUF or oUF
local ECLIPSE_BAR_SOLAR_BUFF_ID = _G.ECLIPSE_BAR_SOLAR_BUFF_ID
local ECLIPSE_BAR_LUNAR_BUFF_ID = _G.ECLIPSE_BAR_LUNAR_BUFF_ID
local SPELL_POWER_ECLIPSE = _G.SPELL_POWER_ECLIPSE
local MOONKIN_FORM = _G.MOONKIN_FORM
local ALERTED = false;
local TextColors = {
[1]={1,0.1,0.1},
[2]={1,0.5,0.1},
[3]={1,1,0.1},
[4]={0.5,1,0.1},
[5]={0.1,1,0.1}
};
local Debug
if AdiDebug then
Debug = AdiDebug:GetSink("oUF_Druidness")
else
Debug = function() end
end
local ProxyShow = function(self)
if(not self.isEnabled) then return end
self:Show()
end
local function CatOverMana(mana, form)
if mana.ManaBar:GetValue() < UnitPowerMax('player', SPELL_POWER_MANA) then
mana:ProxyShow()
return false
else
mana:Hide()
return form == CAT_FORM
end
end
local UpdateVisibility = function(self, event)
local bar = self.Druidness
local cat = bar.Cat
local mana = bar.Mana
local form = GetShapeshiftFormID()
if(form) then
if (form == BEAR_FORM or form == CAT_FORM) then
if(CatOverMana(mana, form)) then
cat:ProxyShow()
else
cat:Hide()
end
else
cat:Hide()
mana:Hide()
end
else
mana:Hide()
cat:Hide()
end
end
local UpdatePower = function(self, event, unit, powerType)
if(self.unit ~= unit) then return end
local bar = self.Druidness
if(bar.Mana and bar.Mana.ManaBar) then
local mana = bar.Mana
if(mana.PreUpdate) then
mana:PreUpdate(unit)
end
local min, max = UnitPower('player', SPELL_POWER_MANA), UnitPowerMax('player', SPELL_POWER_MANA)
mana.ManaBar:SetMinMaxValues(0, max)
mana.ManaBar:SetValue(min)
local r, g, b, t
if(mana.colorPower) then
t = self.colors.power["MANA"]
elseif(mana.colorClass and UnitIsPlayer(unit)) or
(mana.colorClassNPC and not UnitIsPlayer(unit)) or
(mana.colorClassPet and UnitPlayerControlled(unit) and not UnitIsPlayer(unit)) then
local _, class = UnitClass(unit)
t = self.colors.class[class]
elseif(mana.colorReaction and UnitReaction(unit, 'player')) then
t = self.colors.reaction[UnitReaction(unit, "player")]
elseif(mana.colorSmooth) then
r, g, b = self.ColorGradient(min / max, unpack(mana.smoothGradient or self.colors.smooth))
end
if(t) then
r, g, b = t[1], t[2], t[3]
end
if(b) then
mana.ManaBar:SetStatusBarColor(r, g, b)
local bg = mana.bg
if(bg) then
local mu = bg.multiplier or 1
bg:SetVertexColor(r * mu, g * mu, b * mu)
end
end
if(mana.PostUpdatePower) then
mana:PostUpdatePower(unit, min, max)
end
end
UpdateVisibility(self)
end
local UpdateComboPoints = function(self, event, unit)
if(unit == 'pet') then return end
local bar = self.Druidness;
local cpoints = bar.Cat;
if(bar.PreUpdate) then
bar:PreUpdate()
end
local current = 0
if(UnitHasVehicleUI'player') then
current = UnitPower("vehicle", SPELL_POWER_COMBO_POINTS);
else
current = UnitPower("player", SPELL_POWER_COMBO_POINTS);
end
if(cpoints) then
local MAX_COMBO_POINTS = UnitPowerMax("player", SPELL_POWER_COMBO_POINTS);
Debug("max combo points/current: ", MAX_COMBO_POINTS,current)
for i=1, MAX_COMBO_POINTS do
if(i <= current) then
if cpoints[i] then
cpoints[i]:Show()
if(bar.PointShow) then
bar.PointShow(cpoints[i])
end
end
else
if cpoints[i] then
cpoints[i]:Hide()
if(bar.PointHide) then
bar.PointHide(cpoints[i], i)
end
end
end
end
end
if(bar.PostUpdateComboPoints) then
return bar:PostUpdateComboPoints(current)
end
end
local Update = function(self, ...)
UpdatePower(self, ...)
UpdateComboPoints(self, ...)
return UpdateVisibility(self, ...)
end
local ForceUpdate = function(element)
return Update(element.__owner, 'ForceUpdate', element.__owner.unit, 'ECLIPSE')
end
local function Enable(self)
local bar = self.Druidness
if(bar) then
local mana = bar.Mana;
local cpoints = bar.Cat;
mana.ProxyShow = ProxyShow;
cpoints.ProxyShow = ProxyShow;
self:RegisterEvent('UNIT_POWER_FREQUENT', UpdatePower)
self:RegisterEvent('PLAYER_TALENT_UPDATE', UpdateVisibility, true)
self:RegisterEvent('UPDATE_SHAPESHIFT_FORM', UpdateVisibility, true)
self:RegisterEvent('PLAYER_TARGET_CHANGED', UpdateComboPoints, true)
self:RegisterEvent('UNIT_DISPLAYPOWER', UpdateComboPoints, true)
self:RegisterEvent('UNIT_MAXPOWER', UpdateComboPoints, true)
self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player")
self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player")
self:RegisterUnitEvent("UNIT_MAXPOWER", "player")
UpdateVisibility(self)
return true
end
end
local function Disable(self)
local bar = self.Druidness
if(bar) then
--local chicken = bar.Chicken
local mana = bar.Mana
--chicken:Hide()
mana:Hide()
self:RegisterEvent('UNIT_POWER_FREQUENT', UpdatePower)
self:UnregisterEvent('PLAYER_TALENT_UPDATE', UpdateVisibility)
self:UnregisterEvent('UPDATE_SHAPESHIFT_FORM', UpdateVisibility)
self:UnregisterEvent('UNIT_COMBO_POINTS', UpdateComboPoints)
self:UnregisterEvent('PLAYER_TARGET_CHANGED', UpdateComboPoints)
self:UnregisterEvent('UNIT_DISPLAYPOWER', UpdateComboPoints)
self:UnregisterEvent('UNIT_MAXPOWER', UpdateComboPoints)
end
end
oUF:AddElement('BoomChicken', Update, Enable, Disable)
| mit |
retep998/Vana | scripts/npcs/ludi017.lua | 2 | 1262 | --[[
Copyright (C) 2008-2016 Vana Development Team
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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
-- Fourth Eos Rock
dofile("scripts/utils/npcHelper.lua");
if isGm() or getItemAmount(4001020) > 0 then
addText("You can use " .. blue(itemRef(4001020)) .. " to activate " .. blue(npcRef(2040027)) .. ". ");
addText("Will you head over to " .. blue(npcRef(2040026)) .. " at the 41st floor??");
answer = askYesNo();
if answer == answer_yes then
giveItem(4001020, -1);
setMap(221021700, "go00");
end
else
addText("There's a rock that will enable you to teleport to " .. blue(npcRef(2040026)) .. ", but it cannot be activated without a scroll.");
sendOk();
end | gpl-2.0 |
dr01d3r/darkstar | scripts/zones/RuAun_Gardens/npcs/qm4.lua | 14 | 1482 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: ??? (Suzaku's Spawn)
-- Allows players to spawn the HNM Suzaku with a Gem of the South and a Summerstone.
-- @pos -514 -70 -264 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Gem of the South and Summerstone
if (GetMobAction(17309983) == 0 and trade:hasItemQty(1420,1) and trade:hasItemQty(1421,1) and trade:getItemCount() == 2) then
player:tradeComplete();
SpawnMob(17309983):updateClaim(player); -- Spawn Suzaku
player:showText(npc,SKY_GOD_OFFSET + 7);
npc:setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(SKY_GOD_OFFSET + 3);
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 |
SalvationDevelopment/Salvation-Scripts-Production | c97342942.lua | 7 | 1338 | --エクトプラズマー
function c97342942.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--release
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(97342942,0))
e2:SetCategory(CATEGORY_RELEASE+CATEGORY_DAMAGE)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_SZONE)
e2:SetProperty(EFFECT_FLAG_BOTH_SIDE)
e2:SetCode(EVENT_PHASE+PHASE_END)
e2:SetCountLimit(1)
e2:SetCondition(c97342942.condition)
e2:SetTarget(c97342942.target)
e2:SetOperation(c97342942.operation)
c:RegisterEffect(e2)
end
function c97342942.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c97342942.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_RELEASE,nil,1,tp,LOCATION_MZONE)
end
function c97342942.rfilter(c,e)
return c:IsFaceup() and c:IsReleasableByEffect() and not c:IsImmuneToEffect(e)
end
function c97342942.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
local rg=Duel.SelectReleaseGroup(tp,c97342942.rfilter,1,1,e:GetHandler(),e)
if Duel.Release(rg,REASON_EFFECT)>0 then
local atk=rg:GetFirst():GetBaseAttack()/2
Duel.Damage(1-tp,atk,REASON_EFFECT)
end
end
| gpl-2.0 |
dr01d3r/darkstar | scripts/globals/items/plate_of_ic_pilav.lua | 12 | 1953 | -----------------------------------------
-- ID: 5584
-- Item: plate_of_ic_pilav
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health % 14
-- Health Cap 65
-- Strength 4
-- Vitality -1
-- Intelligence -1
-- Health Regen While Healing 1
-- Attack % 22
-- Attack Cap 65
-- Ranged ATT % 22
-- Ranged ATT Cap 65
-----------------------------------------
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,5584);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 14);
target:addMod(MOD_FOOD_HP_CAP, 65);
target:addMod(MOD_STR, 4);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_INT, -1);
target:addMod(MOD_HPHEAL, 1);
target:addMod(MOD_FOOD_ATTP, 22);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_FOOD_RATTP, 22);
target:addMod(MOD_FOOD_RATT_CAP, 65);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 14);
target:delMod(MOD_FOOD_HP_CAP, 65);
target:delMod(MOD_STR, 4);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_INT, -1);
target:delMod(MOD_HPHEAL, 1);
target:delMod(MOD_FOOD_ATTP, 22);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_FOOD_RATTP, 22);
target:delMod(MOD_FOOD_RATT_CAP, 65);
end;
| gpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c75923050.lua | 5 | 2034 | --レアメタル・ヴァルキリー
function c75923050.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcCode2(c,92421852,38916461,true,true)
--atk up
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(75923050,0))
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c75923050.atkcon)
e1:SetValue(1000)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(75923050,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c75923050.spcon)
e2:SetTarget(c75923050.sptg)
e2:SetOperation(c75923050.spop)
c:RegisterEffect(e2)
end
function c75923050.atkcon(e)
local ph=Duel.GetCurrentPhase()
if not (ph==PHASE_DAMAGE or ph==PHASE_DAMAGE_CAL) then return false end
local a=Duel.GetAttacker()
local d=Duel.GetAttackTarget()
return a==e:GetHandler() and d==nil
end
function c75923050.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetTurnID()~=Duel.GetTurnCount()
end
function c75923050.spfilter(c,e,tp)
return c:IsCode(1412158) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c75923050.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and e:GetHandler():IsAbleToExtra()
and Duel.IsExistingMatchingCard(c75923050.spfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_TODECK,e:GetHandler(),1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA)
end
function c75923050.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_MZONE)<0 then return end
if c:IsRelateToEffect(e) and c:IsFaceup() and Duel.SendtoDeck(c,nil,2,REASON_EFFECT)~=0 then
local tc=Duel.GetFirstMatchingCard(c75923050.spfilter,tp,LOCATION_EXTRA,0,nil,e,tp)
if tc then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c80513550.lua | 4 | 2992 | --バッド・エンド・クイーン・ドラゴン
function c80513550.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c80513550.hspcon)
c:RegisterEffect(e1)
--damage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(80513550,0))
e2:SetCategory(CATEGORY_HANDES+CATEGORY_DRAW)
e2:SetCode(EVENT_BATTLE_DAMAGE)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e2:SetCondition(c80513550.hdcon)
e2:SetTarget(c80513550.hdtg)
e2:SetOperation(c80513550.hdop)
c:RegisterEffect(e2)
--Special Summon
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(80513550,1))
e3:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD)
e3:SetCategory(CATEGORY_SPECIAL_SUMMON)
e3:SetCode(EVENT_PHASE+PHASE_STANDBY)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1)
e3:SetCondition(c80513550.spcon)
e3:SetCost(c80513550.spcost)
e3:SetTarget(c80513550.sptg)
e3:SetOperation(c80513550.spop)
c:RegisterEffect(e3)
end
function c80513550.hspfilter(c)
return c:IsFaceup() and c:GetType()==TYPE_SPELL+TYPE_CONTINUOUS
end
function c80513550.hspcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c80513550.hspfilter,c:GetControler(),LOCATION_SZONE,0,3,nil)
end
function c80513550.hdcon(e,tp,eg,ep,ev,re,r,rp)
return ep~=tp and e:GetHandler()==Duel.GetAttacker()
end
function c80513550.hdtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,1-tp,1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c80513550.hdop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFieldGroupCount(tp,0,LOCATION_HAND)~=0 and Duel.IsPlayerCanDraw(tp,1) then
Duel.DiscardHand(1-tp,nil,1,1,REASON_EFFECT)
Duel.Draw(tp,1,REASON_EFFECT)
end
end
function c80513550.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c80513550.cfilter(c)
return c:IsFaceup() and c:GetType()==TYPE_SPELL+TYPE_CONTINUOUS and c:IsAbleToGraveAsCost()
end
function c80513550.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c80513550.cfilter,tp,LOCATION_SZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c80513550.cfilter,tp,LOCATION_SZONE,0,1,1,nil)
Duel.SendtoGrave(g,REASON_COST)
end
function c80513550.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 c80513550.spop(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c92377303.lua | 2 | 2574 | --黒衣の大賢者
function c92377303.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(92377303,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_HAND)
e1:SetProperty(EFFECT_FLAG_CHAIN_UNIQUE)
e1:SetCode(EVENT_CUSTOM+71625222)
e1:SetCondition(c92377303.spcon)
e1:SetCost(c92377303.cost)
e1:SetTarget(c92377303.sptg)
e1:SetOperation(c92377303.spop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetRange(LOCATION_DECK)
e2:SetProperty(EFFECT_FLAG_CHAIN_UNIQUE,EFFECT_FLAG2_NAGA)
c:RegisterEffect(e2)
--to hand
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(92377303,1))
e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetRange(LOCATION_MZONE)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetCondition(c92377303.thcon)
e3:SetTarget(c92377303.thtg)
e3:SetOperation(c92377303.thop)
c:RegisterEffect(e3)
end
function c92377303.spcon(e,tp,eg,ep,ev,re,r,rp)
return ep==tp
end
function c92377303.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,Card.IsCode,1,nil,46986414) end
local g=Duel.SelectReleaseGroup(tp,Card.IsCode,1,1,nil,46986414)
Duel.Release(g,REASON_COST)
end
function c92377303.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,true,false) end
if e:GetHandler():IsLocation(LOCATION_DECK) then
Duel.ConfirmCards(1-tp,e:GetHandler())
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c92377303.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
if Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP)~=0 then
c:CompleteProcedure()
end
end
function c92377303.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler()==re:GetHandler()
end
function c92377303.thfilter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c92377303.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c92377303.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c92377303.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c92377303.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Muffo/space-xy | frameworks/js-bindings/cocos2d-x/plugin/luabindings/auto/api/lua_cocos2dx_pluginx_auto_api.lua | 146 | 1793 | --------------------------------
-- @module plugin
--------------------------------------------------------
-- the plugin PluginProtocol
-- @field [parent=#plugin] PluginProtocol#PluginProtocol PluginProtocol preloaded module
--------------------------------------------------------
-- the plugin PluginManager
-- @field [parent=#plugin] PluginManager#PluginManager PluginManager preloaded module
--------------------------------------------------------
-- the plugin ProtocolAnalytics
-- @field [parent=#plugin] ProtocolAnalytics#ProtocolAnalytics ProtocolAnalytics preloaded module
--------------------------------------------------------
-- the plugin ProtocolIAP
-- @field [parent=#plugin] ProtocolIAP#ProtocolIAP ProtocolIAP preloaded module
--------------------------------------------------------
-- the plugin ProtocolAds
-- @field [parent=#plugin] ProtocolAds#ProtocolAds ProtocolAds preloaded module
--------------------------------------------------------
-- the plugin ProtocolShare
-- @field [parent=#plugin] ProtocolShare#ProtocolShare ProtocolShare preloaded module
--------------------------------------------------------
-- the plugin ProtocolSocial
-- @field [parent=#plugin] ProtocolSocial#ProtocolSocial ProtocolSocial preloaded module
--------------------------------------------------------
-- the plugin ProtocolUser
-- @field [parent=#plugin] ProtocolUser#ProtocolUser ProtocolUser preloaded module
--------------------------------------------------------
-- the plugin AgentManager
-- @field [parent=#plugin] AgentManager#AgentManager AgentManager preloaded module
--------------------------------------------------------
-- the plugin FacebookAgent
-- @field [parent=#plugin] FacebookAgent#FacebookAgent FacebookAgent preloaded module
return nil
| mit |
dr01d3r/darkstar | scripts/zones/Abyssea-Uleguerand/Zone.lua | 33 | 1487 | -----------------------------------
--
-- Zone: Abyssea - Uleguerand
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-Uleguerand/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Abyssea-Uleguerand/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-238, -40, -520.5, 0);
end
if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED
and player:getVar("1stTimeAyssea") == 0) then
player:setVar("1stTimeAyssea",1);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
dr01d3r/darkstar | scripts/zones/Batallia_Downs/npcs/qm2.lua | 17 | 1515 | -----------------------------------
-- Area: Batallia Downs
-- NPC: qm2 (???)
-- Pop for the quest "Chasing Quotas"
-----------------------------------
package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Batallia_Downs/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Sturmtiger = player:getVar("SturmtigerKilled");
if (player:getVar("ChasingQuotas_Progress") == 5 and Sturmtiger == 0) then
SpawnMob(17207696,300):updateClaim(player);
elseif (Sturmtiger == 1) then
player:addKeyItem(RANCHURIOMES_LEGACY);
player:messageSpecial(KEYITEM_OBTAINED,RANCHURIOMES_LEGACY);
player:setVar("ChasingQuotas_Progress",6);
player:setVar("SturmtigerKilled",0);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
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 |
nkgm/hammerspoon | extensions/inspect/init.lua | 11 | 10601 | --- === hs.inspect ===
---
--- Produce human-readable representations of Lua variables (particularly tables)
---
--- This extension is based on inspect.lua by Enrique García Cota
--- https://github.com/kikito/inspect.lua
local inspect ={
_VERSION = 'inspect.lua 3.0.0',
_URL = 'http://github.com/kikito/inspect.lua',
_DESCRIPTION = 'human-readable representations of tables',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
inspect.KEY = setmetatable({}, {__tostring = function() return 'inspect.KEY' end})
inspect.METATABLE = setmetatable({}, {__tostring = function() return 'inspect.METATABLE' end})
-- Apostrophizes the string if it has quotes, but not aphostrophes
-- Otherwise, it returns a regular quoted string
local function smartQuote(str)
if str:match('"') and not str:match("'") then
return "'" .. str .. "'"
end
return '"' .. str:gsub('"', '\\"') .. '"'
end
local controlCharsTranslation = {
["\a"] = "\\a", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n",
["\r"] = "\\r", ["\t"] = "\\t", ["\v"] = "\\v"
}
local function escapeChar(c) return controlCharsTranslation[c] end
local function escape(str)
local result = str:gsub("\\", "\\\\"):gsub("(%c)", escapeChar)
return result
end
local function isIdentifier(str)
return type(str) == 'string' and str:match( "^[_%a][_%a%d]*$" )
end
local function isSequenceKey(k, length)
return type(k) == 'number'
and 1 <= k
and k <= length
and math.floor(k) == k
end
local defaultTypeOrders = {
['number'] = 1, ['boolean'] = 2, ['string'] = 3, ['table'] = 4,
['function'] = 5, ['userdata'] = 6, ['thread'] = 7
}
local function sortKeys(a, b)
local ta, tb = type(a), type(b)
-- strings and numbers are sorted numerically/alphabetically
if ta == tb and (ta == 'string' or ta == 'number') then return a < b end
local dta, dtb = defaultTypeOrders[ta], defaultTypeOrders[tb]
-- Two default types are compared according to the defaultTypeOrders table
if dta and dtb then return defaultTypeOrders[ta] < defaultTypeOrders[tb]
elseif dta then return true -- default types before custom ones
elseif dtb then return false -- custom types after default ones
end
-- custom types are sorted out alphabetically
return ta < tb
end
local function getNonSequentialKeys(t)
local keys, length = {}, #t
for k,_ in pairs(t) do
if not isSequenceKey(k, length) then table.insert(keys, k) end
end
table.sort(keys, sortKeys)
return keys
end
local function getToStringResultSafely(t, mt)
local __tostring = type(mt) == 'table' and rawget(mt, '__tostring')
local str, ok
if type(__tostring) == 'function' then
ok, str = pcall(__tostring, t)
str = ok and str or 'error: ' .. tostring(str)
end
if type(str) == 'string' and #str > 0 then return str end
end
local maxIdsMetaTable = {
__index = function(self, typeName)
rawset(self, typeName, 0)
return 0
end
}
local idsMetaTable = {
__index = function (self, typeName)
local col = setmetatable({}, {__mode = "kv"})
rawset(self, typeName, col)
return col
end
}
local function countTableAppearances(t, tableAppearances)
tableAppearances = tableAppearances or setmetatable({}, {__mode = "k"})
if type(t) == 'table' then
if not tableAppearances[t] then
tableAppearances[t] = 1
for k,v in pairs(t) do
countTableAppearances(k, tableAppearances)
countTableAppearances(v, tableAppearances)
end
countTableAppearances(getmetatable(t), tableAppearances)
else
tableAppearances[t] = tableAppearances[t] + 1
end
end
return tableAppearances
end
local copySequence = function(s)
local copy, len = {}, #s
for i=1, len do copy[i] = s[i] end
return copy, len
end
local function makePath(path, ...)
local keys = {...}
local newPath, len = copySequence(path)
for i=1, #keys do
newPath[len + i] = keys[i]
end
return newPath
end
local function processRecursive(process, item, path)
if item == nil then return nil end
local processed = process(item, path)
if type(processed) == 'table' then
local processedCopy = {}
local processedKey
for k,v in pairs(processed) do
processedKey = processRecursive(process, k, makePath(path, k, inspect.KEY))
if processedKey ~= nil then
processedCopy[processedKey] = processRecursive(process, v, makePath(path, processedKey))
end
end
local mt = processRecursive(process, getmetatable(processed), makePath(path, inspect.METATABLE))
setmetatable(processedCopy, mt)
processed = processedCopy
end
return processed
end
local Inspector = {}
local Inspector_mt = {__index = Inspector}
function Inspector:puts(...)
local args = {...}
local buffer = self.buffer
local len = #buffer
for i=1, #args do
len = len + 1
buffer[len] = tostring(args[i])
end
end
function Inspector:down(f)
self.level = self.level + 1
f()
self.level = self.level - 1
end
function Inspector:tabify()
self:puts(self.newline, string.rep(self.indent, self.level))
end
function Inspector:alreadyVisited(v)
return self.ids[type(v)][v] ~= nil
end
function Inspector:getId(v)
local tv = type(v)
local id = self.ids[tv][v]
if not id then
id = self.maxIds[tv] + 1
self.maxIds[tv] = id
self.ids[tv][v] = id
end
return id
end
function Inspector:putKey(k)
if isIdentifier(k) then return self:puts(k) end
self:puts("[")
self:putValue(k)
self:puts("]")
end
function Inspector:putTable(t)
if t == inspect.KEY or t == inspect.METATABLE then
self:puts(tostring(t))
elseif self:alreadyVisited(t) then
self:puts('<table ', self:getId(t), '>')
elseif self.level >= self.depth then
self:puts('{...}')
else
if self.tableAppearances[t] > 1 then self:puts('<', self:getId(t), '>') end
local nonSequentialKeys = getNonSequentialKeys(t)
local length = #t
local mt = getmetatable(t)
local toStringResult = getToStringResultSafely(t, mt)
self:puts('{')
self:down(function()
if toStringResult then
self:puts(' -- ', escape(toStringResult))
if length >= 1 then self:tabify() end
end
local count = 0
for i=1, length do
if count > 0 then self:puts(',') end
self:puts(' ')
self:putValue(t[i])
count = count + 1
end
for _,k in ipairs(nonSequentialKeys) do
if count > 0 then self:puts(',') end
self:tabify()
self:putKey(k)
self:puts(' = ')
self:putValue(t[k])
count = count + 1
end
if mt then
if count > 0 then self:puts(',') end
self:tabify()
self:puts('<metatable> = ')
self:putValue(mt)
end
end)
if #nonSequentialKeys > 0 or mt then -- result is multi-lined. Justify closing }
self:tabify()
elseif length > 0 then -- array tables have one extra space before closing }
self:puts(' ')
end
self:puts('}')
end
end
function Inspector:putValue(v)
local tv = type(v)
if tv == 'string' then
self:puts(smartQuote(escape(v)))
elseif tv == 'number' or tv == 'boolean' or tv == 'nil' then
self:puts(tostring(v))
elseif tv == 'table' then
self:putTable(v)
else
self:puts('<',tv,' ',self:getId(v),'>')
end
end
--- hs.inspect.inspect(variable[, options]) -> string
--- Function
--- Gets a human readable version of the supplied Lua variable
---
--- Parameters:
--- * variable - A lua variable of some kind
--- * options - An optional table which can be used to influence the inspector. Valid keys are as follows:
--- * depth - A number representing the maximum depth to recurse into `variable`. Below that depth, data will be displayed as `{...}`
--- * newline - A string to use for line breaks. Defaults to `\n`
--- * indent - A string to use for indentation. Defaults to ` ` (two spaces)
--- * process - A function that will be called for each item. It should accept two arguments, `item` (the current item being processed) and `path` (the item's position in the variable being inspected. The function should either return a processed form of the variable, the original variable itself if it requires no processing, or `nil` to remove the item from the inspected output.
---
--- Returns:
--- * A string containing the human readable version of `variable`
---
--- Notes:
--- * For convenience, you can call this function as `hs.inspect(variable)`
--- * For more information on the options, and some examples, see [the upstream docs](https://github.com/kikito/inspect.lua)
function inspect.inspect(root, options)
options = options or {}
local depth = options.depth or math.huge
local newline = options.newline or '\n'
local indent = options.indent or ' '
local process = options.process
if process then
root = processRecursive(process, root, {})
end
local inspector = setmetatable({
depth = depth,
buffer = {},
level = 0,
ids = setmetatable({}, idsMetaTable),
maxIds = setmetatable({}, maxIdsMetaTable),
newline = newline,
indent = indent,
tableAppearances = countTableAppearances(root)
}, Inspector_mt)
inspector:putValue(root)
return table.concat(inspector.buffer)
end
setmetatable(inspect, { __call = function(_, ...) return inspect.inspect(...) end })
return inspect
| mit |
SalvationDevelopment/Salvation-Scripts-Production | c19353570.lua | 2 | 1195 | --影無茶ナイト
function c19353570.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(19353570,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_SUMMON_SUCCESS)
e1:SetCondition(c19353570.spcon)
e1:SetTarget(c19353570.sptg)
e1:SetOperation(c19353570.spop)
c:RegisterEffect(e1)
--unsynchroable
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetValue(1)
c:RegisterEffect(e2)
end
function c19353570.spcon(e,tp,eg,ep,ev,re,r,rp)
return rp==tp and eg:GetFirst():GetLevel()==3
end
function c19353570.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 c19353570.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c65685470.lua | 4 | 4192 | --六武衆の御霊代
function c65685470.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(65685470,0))
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetTarget(c65685470.eqtg)
e1:SetOperation(c65685470.eqop)
c:RegisterEffect(e1)
--unequip
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(65685470,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCondition(aux.IsUnionState)
e2:SetTarget(c65685470.sptg)
e2:SetOperation(c65685470.spop)
c:RegisterEffect(e2)
--Atk up
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_UPDATE_ATTACK)
e3:SetValue(500)
e3:SetCondition(aux.IsUnionState)
c:RegisterEffect(e3)
--Def up
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_EQUIP)
e4:SetCode(EFFECT_UPDATE_DEFENSE)
e4:SetValue(500)
e4:SetCondition(aux.IsUnionState)
c:RegisterEffect(e4)
--destroy sub
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_EQUIP)
e5:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE)
e5:SetCode(EFFECT_DESTROY_SUBSTITUTE)
e5:SetCondition(aux.IsUnionState)
e5:SetValue(1)
c:RegisterEffect(e5)
--draw
local e6=Effect.CreateEffect(c)
e6:SetDescription(aux.Stringid(65685470,2))
e6:SetCategory(CATEGORY_DRAW)
e6:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e6:SetCode(EVENT_BATTLE_DESTROYING)
e6:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e6:SetRange(LOCATION_SZONE)
e6:SetCondition(c65685470.drcon)
e6:SetTarget(c65685470.drtg)
e6:SetOperation(c65685470.drop)
c:RegisterEffect(e6)
--eqlimit
local e7=Effect.CreateEffect(c)
e7:SetType(EFFECT_TYPE_SINGLE)
e7:SetCode(EFFECT_EQUIP_LIMIT)
e7:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e7:SetValue(c65685470.eqlimit)
c:RegisterEffect(e7)
end
c65685470.old_union=true
function c65685470.eqlimit(e,c)
return c:IsSetCard(0x3d)
end
function c65685470.filter(c)
return c:IsFaceup() and c:IsSetCard(0x3d) and c:GetUnionCount()==0
end
function c65685470.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c65685470.filter(chkc) end
if chk==0 then return e:GetHandler():GetFlagEffect(65685470)==0 and Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c65685470.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local g=Duel.SelectTarget(tp,c65685470.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler())
Duel.SetOperationInfo(0,CATEGORY_EQUIP,g,1,0,0)
e:GetHandler():RegisterFlagEffect(65685470,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1)
end
function c65685470.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if not c:IsRelateToEffect(e) or c:IsFacedown() then return end
if not tc:IsRelateToEffect(e) or not c65685470.filter(tc) then
Duel.SendtoGrave(c,REASON_EFFECT)
return
end
if not Duel.Equip(tp,c,tc,false) then return end
aux.SetUnionState(c)
end
function c65685470.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():GetFlagEffect(65685470)==0 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
e:GetHandler():RegisterFlagEffect(65685470,RESET_EVENT+0x7e0000+RESET_PHASE+PHASE_END,0,1)
end
function c65685470.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,true,false,POS_FACEUP_ATTACK)
end
function c65685470.drcon(e,tp,eg,ep,ev,re,r,rp)
return aux.IsUnionState(e) and e:GetHandler():GetEquipTarget()==eg:GetFirst()
end
function c65685470.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c65685470.drop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
Duel.Draw(p,d,REASON_EFFECT)
end
| gpl-2.0 |
clehner/openwrt-packages | utils/luci-app-lxc/files/controller/lxc.lua | 77 | 2909 | --[[
LuCI LXC module
Copyright (C) 2014, Cisco Systems, Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Author: Petar Koretic <petar.koretic@sartura.hr>
]]--
module("luci.controller.lxc", package.seeall)
require "ubus"
local conn = ubus.connect()
if not conn then
error("Failed to connect to ubus")
end
function fork_exec(command)
local pid = nixio.fork()
if pid > 0 then
return
elseif pid == 0 then
-- change to root dir
nixio.chdir("/")
-- patch stdin, out, err to /dev/null
local null = nixio.open("/dev/null", "w+")
if null then
nixio.dup(null, nixio.stderr)
nixio.dup(null, nixio.stdout)
nixio.dup(null, nixio.stdin)
if null:fileno() > 2 then
null:close()
end
end
-- replace with target command
nixio.exec("/bin/sh", "-c", command)
end
end
function index()
page = node("admin", "services", "lxc")
page.target = cbi("lxc")
page.title = _("LXC Containers")
page.order = 70
page = entry({"admin", "services", "lxc_create"}, call("lxc_create"), nil)
page.leaf = true
page = entry({"admin", "services", "lxc_action"}, call("lxc_action"), nil)
page.leaf = true
page = entry({"admin", "services", "lxc_configuration_get"}, call("lxc_configuration_get"), nil)
page.leaf = true
page = entry({"admin", "services", "lxc_configuration_set"}, call("lxc_configuration_set"), nil)
page.leaf = true
end
function lxc_create(lxc_name, lxc_template)
luci.http.prepare_content("text/plain")
local uci = require("uci").cursor()
local url = uci:get("lxc", "lxc", "url")
if not pcall(dofile, "/etc/openwrt_release") then
return luci.http.write("1")
end
local target = _G.DISTRIB_TARGET:match('([^/]+)')
local data = conn:call("lxc", "create", { name = lxc_name, template = "download", args = { "--server", url, "--no-validate", "--dist", lxc_template, "--release", "bb", "--arch", target } } )
luci.http.write(data)
end
function lxc_action(lxc_action, lxc_name)
luci.http.prepare_content("application/json")
local data, ec = conn:call("lxc", lxc_action, lxc_name and { name = lxc_name} or {} )
luci.http.write_json(ec and {} or data)
end
function lxc_configuration_get(lxc_name)
luci.http.prepare_content("text/plain")
local f = io.open("/lxc/" .. lxc_name .. "/config", "r")
local content = f:read("*all")
f:close()
luci.http.write(content)
end
function lxc_configuration_set(lxc_name)
luci.http.prepare_content("text/plain")
local lxc_configuration = luci.http.formvalue("lxc_configuration")
if lxc_configuration == nil then
return luci.http.write("1")
end
local f, err = io.open("/lxc/" .. lxc_name .. "/config","w+")
if not f then
return luci.http.write("2")
end
f:write(lxc_configuration)
f:close()
luci.http.write("0")
end
| gpl-2.0 |
GabrielNicolasAvellaneda/boundary-plugin-zookeeper-deprecated | modules/framework/framework.lua | 1 | 7919 | -- [author] Gabriel Nicolas Avellaneda <avellaneda.gabriel@gmail.com>
local boundary = require('boundary')
local Emitter = require('core').Emitter
local Error = require('core').Error
local Object = require('core').Object
local Process = require('uv').Process
local timer = require('timer')
local math = require('math')
local string = require('string')
local os = require('os')
local io = require('io')
local http = require('http')
local table = require('table')
local net = require('net')
local framework = {}
framework.string = {}
framework.functional = {}
framework.table = {}
framework.util = {}
function framework.util.megaBytesToBytes(mb)
return mb * 1024 * 1024
end
function framework.functional.partial(func, x)
return function (...)
return func(x, ...)
end
end
function framework.functional.compose(f, g)
return function(...)
return g(f(...))
end
end
function framework.table.get(key, map)
return map[key]
end
function framework.table.keys(t)
local result = {}
for k,_ in pairs(t) do
table.insert(result, k)
end
return result
end
function framework.table.clone(t)
if type(t) ~= 'table' then return t end
local meta = getmetatable(t)
local target = {}
for k,v in pairs(t) do
if type(v) == 'table' then
target[k] = clone(v)
else
target[k] = v
end
end
setmetatable(target, meta)
return target
end
function framework.string.contains(pattern, str)
local s,e = string.find(str, pattern)
return s ~= nil
end
function framework.string.escape(str)
local s, c = string.gsub(str, '%.', '%%.')
s, c = string.gsub(s, '%-', '%%-')
return s
end
function framework.string.split(self, pattern)
local outResults = {}
local theStart = 1
local theSplitStart, theSplitEnd = string.find(self, pattern, theStart)
while theSplitStart do
table.insert( outResults, string.sub( self, theStart, theSplitStart-1 ) )
theStart = theSplitEnd + 1
theSplitStart, theSplitEnd = string.find( self, pattern, theStart )
end
table.insert( outResults, string.sub( self, theStart ) )
return outResults
end
function framework.string.trim(self)
return string.match(self,"^()%s*$") and "" or string.match(self,"^%s*(.*%S)" )
end
function framework.string.isEmpty(str)
return (str == nil or framework.string.trim(str) == '')
end
function framework.string.notEmpty(str)
return not framework.string.isEmpty(str)
end
-- You can call framework.string() to export all functions to the string table to the global table for easy access.
function exportable(t)
setmetatable(t, {
__call = function (t, warn)
for k,v in pairs(t) do
if (warn) then
if _G[k] ~= nil then
print('Warning: Overriding function ' .. k ..' on global space.')
end
end
_G[k] = v
end
end
})
end
-- Allow to export functions to global table
exportable(framework.string)
exportable(framework.util)
exportable(framework.functional)
exportable(framework.table)
local DataSource = Emitter:extend()
framework.DataSource = DataSource
function DataSource:initialize(params)
self.params = params
end
function DataSource:fetch(caller, callback)
error('fetch: you must implement on class or object instance.')
end
local NetDataSource = DataSource:extend()
function NetDataSource:initialize(host, port)
self.host = host
self.port = port
end
function NetDataSource:onFetch(socket)
p('you must override the NetDataSource:onFetch')
end
function NetDataSource:fetch(context, callback)
local socket
socket = net.createConnection(self.port, self.host, function ()
self:onFetch(socket)
if callback then
socket:once('data', function (data)
callback(data)
socket:shutdown()
end)
else
socket:shutdown()
end
end)
socket:on('error', function (err) self:emit('error', 'Socket error: ' .. err.message) end)
end
framework.NetDataSource = NetDataSource
local Plugin = Emitter:extend()
framework.Plugin = Plugin
framework.boundary = boundary
function Plugin:poll()
self:emit('before_poll')
self:onPoll()
self:emit('after_poll')
timer.setTimeout(self.pollInterval, function () self.poll(self) end)
end
function Plugin:report(metrics)
self:emit('report')
self:onReport(metrics)
end
function currentTimestamp()
return os.time()
end
function Plugin:onReport(metrics)
for metric, value in pairs(metrics) do
print(self:format(metric, value, self.source, currentTimestamp()))
end
end
function Plugin:format(metric, value, source, timestamp)
self:emit('format')
return self:onFormat(metric, value, source, timestamp)
end
function Plugin:onFormat(metric, value, source, timestamp)
return string.format('%s %f %s %s', metric, value, source, timestamp)
end
function Plugin:initialize(params, dataSource)
self.pollInterval = params.pollInterval or 1000
self.source = params.source or os.hostname()
self.dataSource = dataSource
self.version = params.version or '1.0'
self.name = params.name or 'Boundary Plugin'
self.dataSource:on('error', function (msg) self:error(msg) end)
print("_bevent:" .. self.name .. " up : version " .. self.version .. "|t:info|tags:lua,plugin")
end
function Plugin:onPoll()
self.dataSource:fetch(self, function (data) self:parseValues(data) end )
end
function Plugin:parseValues(data)
local metrics = self:onParseValues(data)
self:report(metrics)
end
function Plugin:onParseValues(data)
p('Plugin:onParseValues')
return {}
end
local CommandPlugin = Plugin:extend()
framework.CommandPlugin = CommandPlugin
function CommandPlugin:initialize(params)
Plugin.initialize(self, params)
if not params.command then
error('params.command undefined. You need to define the command to excetue.')
end
self.command = params.command
end
function CommandPlugin:execCommand(callback)
local proc = io.popen(self.command, 'r')
local output = proc:read("*a")
proc:close()
if callback then
callback(output)
end
end
function CommandPlugin:onPoll()
self:execCommand(function (output) self.parseCommandOutput(self, output) end)
end
function CommandPlugin:parseCommandOutput(output)
local metrics = self:onParseCommandOutput(output)
self:report(metrics)
end
function CommandPlugin:onParseCommandOutput(output)
print(output)
return {}
end
local NetPlugin = Plugin:extend()
framework.NetPlugin = NetPlugin
local HttpPlugin = Plugin:extend()
framework.HttpPlugin = HttpPlugin
function HttpPlugin:initialize(params)
Plugin.initialize(self, params)
self.reqOptions = {
host = params.host,
port = params.port,
path = params.path
}
end
function Plugin:error(err)
local msg = tostring(err)
print(msg)
end
function HttpPlugin:makeRequest(reqOptions, successCallback)
local req = http.request(reqOptions, function (res)
local data = ''
res:on('data', function (chunk)
data = data .. chunk
successCallback(data)
-- TODO: Verify when data its complete or when we need to use de end
end)
res:on('error', function (err)
local msg = 'Error while receiving a response: ' .. err.message
self:error(msg)
end)
end)
req:on('error', function (err)
local msg = 'Error while sending a request: ' .. err.message
self:error(msg)
end)
req:done()
end
function HttpPlugin:onPoll()
self:makeRequest(self.reqOptions, function (data)
self:parseResponse(data)
end)
end
function HttpPlugin:parseResponse(data)
local metrics = self:onParseResponse(data)
self:report(metrics)
end
function HttpPlugin:onParseResponse(data)
-- To be overriden on class instance
print(data)
return {}
end
local Accumulator = Emitter:extend()
function Accumulator:initialize()
self.map = {}
end
function Accumulator:accumulate(key, value)
local oldValue = self.map[key]
if oldValue == nil then
oldValue = value
end
self.map[key] = value
local diff = value - oldValue
return diff
end
function Accumulator:reset(key)
self.map[key] = nil
end
function Accumulator:resetAll()
self.map = {}
end
framework.Accumulator = Accumulator
return framework
| apache-2.0 |
dr01d3r/darkstar | scripts/zones/Castle_Oztroja/npcs/Tebhi.lua | 14 | 1073 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Tebhi
-- @pos -136 24 -21 151
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(13121,1) and trade:getItemCount() == 1) then -- Trade Beast collar
player:tradeComplete();
-- Tebhi disappears for 15min -------------- NOT IMPLEMENTED
player:setVar("scatIntoShadowCS",2);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
dr01d3r/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm0_1.lua | 17 | 1165 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: qm0 (warp player outside after they win fight)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0C);
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 == 0x0C and option == 1) then
player:setPos(291.459,-42.088,-401.161,163,130);
end
end; | gpl-3.0 |
dr01d3r/darkstar | scripts/globals/items/bataquiche_+1.lua | 12 | 1470 | -----------------------------------------
-- ID: 5169
-- Item: Bataquiche +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 10
-- Agility 1
-- Vitality -1
-- Ranged Acc % 7
-- Ranged Acc Cap 20
-----------------------------------------
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,5169);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 10);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 10);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 20);
end;
| gpl-3.0 |
holyodin776/demirogue | src/prelude/table.lua | 3 | 3725 | --
-- misc/table.lua
--
-- Utility functions for working with tables.
--
-- TODO: random functions need optional generator argument.
-- TODO: luafun might be a better option for a lot of these.
--
function table.keys( tbl )
local result = {}
for k, _ in pairs(tbl) do
result[#result+1] = k
end
return result
end
-- Really just a shallow copy.
function table.copy( tbl )
local result = {}
for k, v in pairs(tbl) do
result[k] = v
end
return result
end
function table.count( tbl )
local result = 0
for _ in pairs(tbl) do
result = result + 1
end
return result
end
function table.append( tbl1, tbl2 )
for i = 1, #tbl2 do
tbl1[#tbl1+1] = tbl2[i]
end
return tbl1
end
function table.random( tbl )
local count = table.count(tbl)
local index = math.random(1, count)
local k = nil
for i = 1, index do
k = next(tbl, k)
end
return k, tbl[k]
end
function table.shuffle( tbl )
for i = 1, #tbl-1 do
local index = math.random(i, #tbl)
tbl[i], tbl[index] = tbl[index], tbl[i]
end
end
function table.reverse( tbl )
local size = #tbl
for index = 1, math.ceil(size * 0.5) do
local mirrorIndex = size - (index - 1)
tbl[index], tbl[mirrorIndex] = tbl[mirrorIndex], tbl[index]
end
return tbl
end
function table.inverse( tbl )
local result = {}
for k, v in pairs(tbl) do
result[v] = k
end
return result
end
function table.collect( tbl, func )
local result = {}
for k, v in pairs(tbl) do
result[k] = func(v)
end
return result
end
local _literals = {
boolean =
function ( value )
if value then
return 'true'
else
return 'false'
end
end,
number =
function ( value )
if math.floor(value) == value then
return string.format("%d", value)
else
return string.format("%.4f", value)
end
end,
string =
function ( value )
return string.format("%q", value)
end
}
-- TODO: maybe move to its own file.
function table.compile( tbl, option )
local parts = { 'return ' }
local pads = { [0] = '', ' ', ' ' }
local next = next
local string_rep = string.rep
local type = type
local _literals = _literals
local function aux( tbl, indent )
if next(tbl) == nil then
parts[#parts+1] = '{}'
return
end
parts[#parts+1] = '{\n'
local padding = pads[indent]
if not padding then
padding = string_rep(' ', indent)
pads[indent] = padding
end
local size = #tbl
-- First off let's do the array part.
for index = 1, size do
local v = tbl[index]
parts[#parts+1] = padding
local vt = type(v)
if vt ~= 'table' then
parts[#parts+1] = _literals[vt](v)
else
aux(v, indent + 2)
end
parts[#parts+1] = ',\n'
end
-- Now non-array parts. This uses secret knowledge of how lua works, the
-- next() function will iterate over array parts first so we can skip them.
local k = next(tbl, (size ~= 0) and size or nil)
while k ~= nil do
parts[#parts+1] = padding
parts[#parts+1] = '['
local kt = type(k)
if kt ~= 'table' then
parts[#parts+1] = _literals[kt](k)
else
aux(k, indent + 2)
end
parts[#parts+1] = '] = '
local v = tbl[k]
local vt = type(v)
if vt ~= 'table' then
parts[#parts+1] = _literals[vt](v)
else
aux(v, indent + 2)
end
parts[#parts+1] = ',\n'
k = next(tbl, k)
end
-- Closing braces are dedented.
indent = indent - 2
padding = pads[indent]
if not padding then
padding = string_rep(' ', indent)
pads[indent] = padding
end
if padding ~= '' then
parts[#parts+1] = padding
end
parts[#parts+1] = '}'
end
aux(tbl, 2)
-- This is to stop complaints about files not ending in a newline.
parts[#parts+1] = '\n'
local result = table.concat(parts)
return result
end
| bsd-3-clause |
SalvationDevelopment/Salvation-Scripts-Production | c38450736.lua | 2 | 2925 | --甲虫装機 ウィーグ
function c38450736.initial_effect(c)
--equip
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetDescription(aux.Stringid(38450736,0))
e1:SetCategory(CATEGORY_EQUIP)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetTarget(c38450736.eqtg)
e1:SetOperation(c38450736.eqop)
c:RegisterEffect(e1)
--equip effect
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(1000)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_UPDATE_DEFENSE)
e3:SetValue(1000)
c:RegisterEffect(e3)
--atkup
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(38450736,1))
e3:SetCategory(CATEGORY_ATKCHANGE)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetCondition(c38450736.atkcon)
e3:SetTarget(c38450736.atktg)
e3:SetOperation(c38450736.atkop)
c:RegisterEffect(e3)
end
function c38450736.filter(c)
return c:IsSetCard(0x56) and c:IsType(TYPE_MONSTER) and not c:IsForbidden()
end
function c38450736.eqtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingMatchingCard(c38450736.filter,tp,LOCATION_GRAVE+LOCATION_HAND,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_LEAVE_GRAVE,nil,1,tp,LOCATION_GRAVE+LOCATION_HAND)
end
function c38450736.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end
if c:IsFacedown() or not c:IsRelateToEffect(e) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
local g=Duel.SelectMatchingCard(tp,aux.NecroValleyFilter(c38450736.filter),tp,LOCATION_GRAVE+LOCATION_HAND,0,1,1,nil)
local tc=g:GetFirst()
if tc then
if not Duel.Equip(tp,tc,c,true) then return end
local e1=Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_COPY_INHERIT+EFFECT_FLAG_OWNER_RELATE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetReset(RESET_EVENT+0x1fe0000)
e1:SetValue(c38450736.eqlimit)
tc:RegisterEffect(e1)
end
end
function c38450736.eqlimit(e,c)
return e:GetOwner()==c
end
function c38450736.atkcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ec=c:GetEquipTarget()
e:SetLabelObject(ec)
return ec and c:IsLocation(LOCATION_GRAVE) and ec:IsFaceup() and ec:IsLocation(LOCATION_MZONE)
end
function c38450736.atktg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local ec=e:GetLabelObject()
Duel.SetTargetCard(ec)
end
function c38450736.atkop(e,tp,eg,ep,ev,re,r,rp)
local ec=e:GetLabelObject()
if ec:IsLocation(LOCATION_MZONE) and ec:IsFaceup() and ec:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(1000)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
ec:RegisterEffect(e1)
end
end
| gpl-2.0 |
pmembrey/wireshark | test/lua/pcap_file.lua | 30 | 27491 | -- pcap_file_reader.lua
--------------------------------------------------------------------------------
--[[
This is a Wireshark Lua-based pcap capture file reader.
Author: Hadriel Kaplan
This "capture file" reader reads pcap files - the old style ones. Don't expect this to
be as good as the real thing; this is a simplistic implementation to show how to
create such file readers, and for testing purposes.
This script requires Wireshark v1.12 or newer.
--]]
--------------------------------------------------------------------------------
-- do not modify this table
local debug = {
DISABLED = 0,
LEVEL_1 = 1,
LEVEL_2 = 2
}
-- set this DEBUG to debug.LEVEL_1 to enable printing debug info
-- set it to debug.LEVEL_2 to enable really verbose printing
local DEBUG = debug.LEVEL_1
local wireshark_name = "Wireshark"
if not GUI_ENABLED then
wireshark_name = "Tshark"
end
-- verify Wireshark is new enough
local major, minor, micro = get_version():match("(%d+)%.(%d+)%.(%d+)")
if major and tonumber(major) <= 1 and ((tonumber(minor) <= 10) or (tonumber(minor) == 11 and tonumber(micro) < 3)) then
error( "Sorry, but your " .. wireshark_name .. " version (" .. get_version() .. ") is too old for this script!\n" ..
"This script needs " .. wireshark_name .. "version 1.12 or higher.\n" )
end
-- verify we have the Struct library in wireshark
-- technically we should be able to do this with 'require', but Struct is a built-in
assert(Struct.unpack, wireshark_name .. " does not have the Struct library!")
--------------------------------------------------------------------------------
-- early definitions
-- throughout most of this file I try to pre-declare things to help ease
-- reading it and following the logic flow, but some things just have to be done
-- before others, so this sections has such things that cannot be avoided
--------------------------------------------------------------------------------
-- first some variable declarations for functions we'll define later
local parse_file_header, parse_rec_header, read_common
-- these will be set inside of parse_file_header(), but we're declaring them up here
local default_settings =
{
debug = DEBUG,
corrected_magic = 0xa1b2c3d4,
version_major = 2,
version_minor = 4,
timezone = 0,
sigfigs = 0,
read_snaplen = 0, -- the snaplen we read from file
snaplen = 0, -- the snaplen we use (limited by WTAP_MAX_PACKET_SIZE)
linktype = -1, -- the raw linktype number in the file header
wtap_type = wtap_encaps.UNKNOWN, -- the mapped internal wtap number based on linktype
endianess = ENC_BIG_ENDIAN,
time_precision = wtap_tsprecs.USEC,
rec_hdr_len = 16, -- default size of record header
rec_hdr_patt = "I4 I4 I4 I4", -- pattern for Struct to use
num_rec_fields = 4, -- number of vars in pattern
}
local dprint = function() end
local dprint2 = function() end
local function reset_debug()
if default_settings.debug > debug.DISABLED then
dprint = function(...)
print(table.concat({"Lua:", ...}," "))
end
if default_settings.debug > debug.LEVEL_1 then
dprint2 = dprint
end
end
end
-- call it now
reset_debug()
--------------------------------------------------------------------------------
-- file reader handling functions for Wireshark to use
--------------------------------------------------------------------------------
----------------------------------------
-- The read_open() is called by Wireshark once per file, to see if the file is this reader's type.
-- Wireshark passes in (1) a File object and (2) CaptureInfo object to this function
-- It expects in return either nil or false to mean it's not our file type, or true if it is
-- In our case what this means is we figure out if the file has the magic header, and get the
-- endianess of the file, and the encapsulation type of its frames/records
local function read_open(file, capture)
dprint2("read_open() called")
local file_settings = parse_file_header(file)
if file_settings then
dprint2("read_open: success, file is for us")
-- save our state
capture.private_table = file_settings
-- if the file is for us, we MUST set the file position cursor to
-- where we want the first call to read() function to get it the next time
-- for example if we checked a few records to be sure it's or type
-- but in this simple example we only verify the file header (24 bytes)
-- and we want the file position to remain after that header for our read()
-- call, so we don't change it back
--file:seek("set",position)
-- these we can also set per record later during read operations
capture.time_precision = file_settings.time_precision
capture.encap = file_settings.wtap_type
capture.snapshot_length = file_settings.snaplen
return true
end
dprint2("read_open: file not for us")
-- if it's not for us, wireshark will reset the file position itself
return false
end
----------------------------------------
-- Wireshark/tshark calls read() for each frame/record in the file
-- It passes in (1) a File, (2) CaptureInfo, and (3) FrameInfo object to this function
-- It expects in return the file offset position the record starts at,
-- or nil/false if there's an error or end-of-file is reached.
-- The offset position is used later: wireshark remembers it and gives
-- it to seek_read() at various random times
local function read(file, capture, frame)
dprint2("read() called")
-- call our common reader function
local position = file:seek()
if not read_common("read", file, capture, frame) then
-- this isnt' actually an error, because it might just mean we reached end-of-file
-- so let's test for that (read(0) is a special case in Lua, see Lua docs)
if file:read(0) ~= nil then
dprint("read: failed to call read_common")
else
dprint2("read: reached end of file")
end
return false
end
dprint2("read: succeess")
-- return the position we got to (or nil if we hit EOF/error)
return position
end
----------------------------------------
-- Wireshark/tshark calls seek_read() for each frame/record in the file, at random times
-- It passes in (1) a File, (2) CaptureInfo, (3) FrameInfo object, and the offset position number
-- It expects in return true for successful parsing, or nil/false if there's an error.
local function seek_read(file, capture, frame, offset)
dprint2("seek_read() called")
-- first move to the right position in the file
file:seek("set",offset)
if not read_common("seek_read", file, capture, frame) then
dprint("seek_read: failed to call read_common")
return false
end
return true
end
----------------------------------------
-- Wireshark/tshark calls read_close() when it's closing the file completely
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- this is a good opportunity to clean up any state you may have created during
-- file reading. (in our case there's no real state)
local function read_close(file, capture)
dprint2("read_close() called")
-- we don't really have to reset anything, because we used the
-- capture.private_table and wireshark clears it for us after this function
return true
end
----------------------------------------
-- An often unused function, Wireshark calls this when the sequential walk-through is over
-- (i.e., no more calls to read(), only to seek_read()).
-- It passes in (1) a File and (2) CaptureInfo object to this function
-- This gives you a chance to clean up any state you used during read() calls, but remember
-- that there will be calls to seek_read() after this (in Wireshark, though not Tshark)
local function seq_read_close(file, capture)
dprint2("First pass of read() calls are over, but there may be seek_read() calls after this")
return true
end
----------------------------------------
-- ok, so let's create a FileHandler object
local fh = FileHandler.new("Lua-based PCAP reader", "lua_pcap", "A Lua-based file reader for PCAP-type files","rms")
-- set above functions to the FileHandler
fh.read_open = read_open
fh.read = read
fh.seek_read = seek_read
fh.read_close = read_close
fh.seq_read_close = seq_read_close
fh.extensions = "pcap;cap" -- this is just a hint
-- and finally, register the FileHandler!
register_filehandler(fh)
dprint2("FileHandler registered")
--------------------------------------------------------------------------------
-- ok now for the boring stuff that actually does the work
--------------------------------------------------------------------------------
----------------------------------------
-- in Lua, we have access to encapsulation types in the 'wtap_encaps' table, but
-- those numbers don't actually necessarily match the numbers in pcap files
-- for the encapsulation type, because the namespace got screwed up at some
-- point in the past (blame LBL NRG, not wireshark for that)
-- but I'm not going to create the full mapping of these two namespaces
-- instead we'll just use this smaller table to map them
-- these are taken from wiretap/pcap-common.c
local pcap2wtap = {
[0] = wtap_encaps.NULL,
[1] = wtap_encaps.ETHERNET,
[6] = wtap_encaps.TOKEN_RING,
[8] = wtap_encaps.SLIP,
[9] = wtap_encaps.PPP,
[101] = wtap_encaps.RAW_IP,
[105] = wtap_encaps.IEEE_802_11,
[127] = wtap_encaps.IEEE_802_11_RADIOTAP,
[140] = wtap_encaps.MTP2,
[141] = wtap_encaps.MTP3,
[143] = wtap_encaps.DOCSIS,
[147] = wtap_encaps.USER0,
[148] = wtap_encaps.USER1,
[149] = wtap_encaps.USER2,
[150] = wtap_encaps.USER3,
[151] = wtap_encaps.USER4,
[152] = wtap_encaps.USER5,
[153] = wtap_encaps.USER6,
[154] = wtap_encaps.USER7,
[155] = wtap_encaps.USER8,
[156] = wtap_encaps.USER9,
[157] = wtap_encaps.USER10,
[158] = wtap_encaps.USER11,
[159] = wtap_encaps.USER12,
[160] = wtap_encaps.USER13,
[161] = wtap_encaps.USER14,
[162] = wtap_encaps.USER15,
[186] = wtap_encaps.USB,
[187] = wtap_encaps.BLUETOOTH_H4,
[189] = wtap_encaps.USB_LINUX,
[195] = wtap_encaps.IEEE802_15_4,
}
-- we can use the above to directly map very quickly
-- but to map it backwards we'll use this, because I'm lazy:
local function wtap2pcap(encap)
for k,v in pairs(pcap2wtap) do
if v == encap then
return k
end
end
return 0
end
----------------------------------------
-- here are the "structs" we're going to parse, of the various records in a pcap file
-- these pattern string gets used in calls to Struct.unpack()
--
-- we will prepend a '<' or '>' later, once we figure out what endian-ess the files are in
--
-- this is a constant for minimum we need to read before we figure out the filetype
local FILE_HDR_LEN = 24
-- a pcap file header struct
-- this is: magic, version_major, version_minor, timezone, sigfigs, snaplen, encap type
local FILE_HEADER_PATT = "I4 I2 I2 i4 I4 I4 I4"
-- it's too bad Struct doesn't have a way to get the number of vars the pattern holds
-- another thing to add to my to-do list?
local NUM_HDR_FIELDS = 7
-- these will hold the '<'/'>' prepended version of above
--local file_header, rec_header
-- snaplen/caplen can't be bigger than this
local WTAP_MAX_PACKET_SIZE = 65535
----------------------------------------
-- different pcap file types have different magic values
-- we need to know various things about them for various functions
-- in this script, so this table holds all the info
--
-- See default_settings table above for the defaults used if this table
-- doesn't override them.
--
-- Arguably, these magic types represent different "Protocols" to dissect later,
-- but this script treats them all as "pcapfile" protocol.
--
-- From this table, we'll auto-create a value-string table for file header magic field
local magic_spells =
{
normal =
{
magic = 0xa1b2c3d4,
name = "Normal (Big-endian)",
},
swapped =
{
magic = 0xd4c3b2a1,
name = "Swapped Normal (Little-endian)",
endianess = ENC_LITTLE_ENDIAN,
},
modified =
{
-- this is for a ss991029 patched format only
magic = 0xa1b2cd34,
name = "Modified",
rec_hdr_len = 24,
rec_hdr_patt = "I4I4I4I4 I4 I2 I1 I1",
num_rec_fields = 8,
},
swapped_modified =
{
-- this is for a ss991029 patched format only
magic = 0x34cdb2a1,
name = "Swapped Modified",
rec_hdr_len = 24,
rec_hdr_patt = "I4I4I4I4 I4 I2 I1 I1",
num_rec_fields = 8,
endianess = ENC_LITTLE_ENDIAN,
},
nsecs =
{
magic = 0xa1b23c4d,
name = "Nanosecond",
time_precision = wtap_filetypes.TSPREC_NSEC,
},
swapped_nsecs =
{
magic = 0x4d3cb2a1,
name = "Swapped Nanosecond",
endianess = ENC_LITTLE_ENDIAN,
time_precision = wtap_filetypes.TSPREC_NSEC,
},
}
-- create a magic-to-spell entry table from above magic_spells table
-- so we can find them faster during file read operations
-- we could just add them right back into spells table, but this is cleaner
local magic_values = {}
for k,t in pairs(magic_spells) do
magic_values[t.magic] = t
end
-- the function which makes a copy of the default settings per file
local function new_settings()
dprint2("creating new file_settings")
local file_settings = {}
for k,v in pairs(default_settings) do
file_settings[k] = v
end
return file_settings
end
-- set the file_settings that the magic value defines in magic_values
local function set_magic_file_settings(magic)
local t = magic_values[magic]
if not t then
dprint("set_magic_file_settings: did not find magic settings for:",magic)
return false
end
local file_settings = new_settings()
-- the magic_values/spells table uses the same key names, so this is easy
for k,v in pairs(t) do
file_settings[k] = v
end
-- based on endianess, set the file_header and rec_header
-- and determine corrected_magic
if file_settings.endianess == ENC_BIG_ENDIAN then
file_settings.file_hdr_patt = '>' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '>' .. file_settings.rec_hdr_patt
file_settings.corrected_magic = magic
else
file_settings.file_hdr_patt = '<' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '<' .. file_settings.rec_hdr_patt
local m = Struct.pack(">I4", magic)
file_settings.corrected_magic = Struct.unpack("<I4", m)
end
file_settings.rec_hdr_len = Struct.size(file_settings.rec_hdr_patt)
return file_settings
end
----------------------------------------
-- internal functions declared previously
----------------------------------------
----------------------------------------
-- used by read_open(), this parses the file header
parse_file_header = function(file)
dprint2("parse_file_header() called")
-- by default, file:read() gets the next "string", meaning ending with a newline \n
-- but we want raw byte reads, so tell it how many bytes to read
local line = file:read(FILE_HDR_LEN)
-- it's ok for us to not be able to read it, but we need to tell wireshark the
-- file's not for us, so return false
if not line then return false end
dprint2("parse_file_header: got this line:\n'", Struct.tohex(line,false,":"), "'")
-- let's peek at the magic int32, assuming it's big-endian
local magic = Struct.unpack(">I4", line)
local file_settings = set_magic_file_settings(magic)
if not file_settings then
dprint("magic was: '", magic, "', so not a known pcap file?")
return false
end
-- this is: magic, version_major, version_minor, timezone, sigfigs, snaplen, encap type
local fields = { Struct.unpack(file_settings.file_hdr_patt, line) }
-- sanity check; also note that Struct.unpack() returns the fields plus
-- a number of where in the line it stopped reading (i.e., the end in this case)
-- so we got back number of fields + 1
if #fields ~= NUM_HDR_FIELDS + 1 then
-- this should never happen, since we already told file:read() to grab enough bytes
dprint("parse_file_header: failed to read the file header")
return nil
end
-- fields[1] is the magic, which we already parsed and saved before, but just to be sure
-- our endianess is set right, we validate what we got is what we expect now that
-- endianess has been corrected
if fields[1] ~= file_settings.corrected_magic then
dprint ("parse_file_header: endianess screwed up? Got:'", fields[1],
"', but wanted:", file_settings.corrected_magic)
return nil
end
file_settings.version_major = fields[2]
file_settings.version_minor = fields[3]
file_settings.timezone = fields[4]
file_settings.sigfigs = fields[5]
file_settings.read_snaplen = fields[6]
file_settings.linktype = fields[7]
-- wireshark only supports version 2.0 and later
if fields[2] < 2 then
dprint("got version =",VERSION_MAJOR,"but only version 2 or greater supported")
return false
end
-- convert pcap file interface type to wtap number type
file_settings.wtap_type = pcap2wtap[file_settings.linktype]
if not file_settings.wtap_type then
dprint("file nettype", file_settings.linktype,
"couldn't be mapped to wireshark wtap type")
return false
end
file_settings.snaplen = file_settings.read_snaplen
if file_settings.snaplen > WTAP_MAX_PACKET_SIZE then
file_settings.snaplen = WTAP_MAX_PACKET_SIZE
end
dprint2("read_file_header: got magic='", magic,
"', major version='", file_settings.version_major,
"', minor='", file_settings.version_minor,
"', timezone='", file_settings.timezone,
"', sigfigs='", file_settings.sigfigs,
"', read_snaplen='", file_settings.read_snaplen,
"', snaplen='", file_settings.snaplen,
"', nettype ='", file_settings.linktype,
"', wtap ='", file_settings.wtap_type)
--ok, it's a pcap file
dprint2("parse_file_header: success")
return file_settings
end
----------------------------------------
-- this is used by both read() and seek_read()
-- the calling function to this should have already set the file position correctly
read_common = function(funcname, file, capture, frame)
dprint2(funcname,": read_common() called")
-- get the state info
local file_settings = capture.private_table
-- first parse the record header, which will set the FrameInfo fields
if not parse_rec_header(funcname, file, file_settings, frame) then
dprint2(funcname, ": read_common: hit end of file or error")
return false
end
frame.encap = file_settings.wtap_type
-- now we need to get the packet bytes from the file record into the frame...
-- we *could* read them into a string using file:read(numbytes), and then
-- set them to frame.data so that wireshark gets it...
-- but that would mean the packet's string would be copied into Lua
-- and then sent right back into wireshark, which is gonna slow things
-- down; instead FrameInfo has a read_data() method, which makes
-- wireshark read directly from the file into the frame buffer, so we use that
if not frame:read_data(file, frame.captured_length) then
dprint(funcname, ": read_common: failed to read data from file into buffer")
return false
end
return true
end
----------------------------------------
-- the function to parse individual records
parse_rec_header = function(funcname, file, file_settings, frame)
dprint2(funcname,": parse_rec_header() called")
local line = file:read(file_settings.rec_hdr_len)
-- it's ok for us to not be able to read it, if it's end of file
if not line then return false end
-- this is: time_sec, time_usec, capture_len, original_len
local fields = { Struct.unpack(file_settings.rec_hdr_patt, line) }
-- sanity check; also note that Struct.unpack() returns the fields plus
-- a number of where in the line it stopped reading (i.e., the end in this case)
-- so we got back number of fields + 1
if #fields ~= file_settings.num_rec_fields + 1 then
dprint(funcname, ": parse_rec_header: failed to read the record header, got:",
#fields, ", expected:", file_settings.num_rec_fields)
return nil
end
local nsecs = fields[2]
if file_settings.time_precision == wtap_filetypes.TSPREC_USEC then
nsecs = nsecs * 1000
elseif file_settings.time_precision == wtap_filetypes.TSPREC_MSEC then
nsecs = nsecs * 1000000
end
frame.time = NSTime(fields[1], nsecs)
local caplen, origlen = fields[3], fields[4]
-- sanity check, verify captured length isn't more than original length
if caplen > origlen then
dprint("captured length of", caplen, "is bigger than original length of", origlen)
-- swap them, a cool Lua ability
caplen, origlen = origlen, caplen
end
if caplen > WTAP_MAX_PACKET_SIZE then
dprint("Got a captured_length of", caplen, "which is too big")
caplen = WTAP_MAX_PACKET_SIZE
end
frame.rec_type = wtap_rec_types.PACKET
frame.captured_length = caplen
frame.original_length = origlen
frame.flags = wtap_presence_flags.TS + wtap_presence_flags.CAP_LEN -- for timestamp|cap_len
dprint2(funcname,": parse_rec_header() returning")
return true
end
--------------------------------------------------------------------------------
-- file writer handling functions for Wireshark to use
--------------------------------------------------------------------------------
-- file encaps we can handle writing
local canwrite = {
[ wtap_encaps.NULL ] = true,
[ wtap_encaps.ETHERNET ] = true,
[ wtap_encaps.PPP ] = true,
[ wtap_encaps.RAW_IP ] = true,
[ wtap_encaps.IEEE_802_11 ] = true,
[ wtap_encaps.MTP2 ] = true,
[ wtap_encaps.MTP3 ] = true,
-- etc., etc.
}
-- we can't reuse the variables we used in the reader, because this script might be used to both
-- open a file for reading and write it out, at the same time, so we cerate another file_settings
-- instance.
-- set the file_settings for the little-endian version in magic_spells
local function create_writer_file_settings()
dprint2("create_writer_file_settings called")
local t = magic_spells.swapped
local file_settings = new_settings()
-- the magic_values/spells table uses the same key names, so this is easy
for k,v in pairs(t) do
file_settings[k] = v
end
-- based on endianess, set the file_header and rec_header
-- and determine corrected_magic
if file_settings.endianess == ENC_BIG_ENDIAN then
file_settings.file_hdr_patt = '>' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '>' .. file_settings.rec_hdr_patt
file_settings.corrected_magic = file_settings.magic
else
file_settings.file_hdr_patt = '<' .. FILE_HEADER_PATT
file_settings.rec_hdr_patt = '<' .. file_settings.rec_hdr_patt
local m = Struct.pack(">I4", file_settings.magic)
file_settings.corrected_magic = Struct.unpack("<I4", m)
end
file_settings.rec_hdr_len = Struct.size(file_settings.rec_hdr_patt)
return file_settings
end
----------------------------------------
-- The can_write_encap() function is called by Wireshark when it wants to write out a file,
-- and needs to see if this file writer can handle the packet types in the window.
-- We need to return true if we can handle it, else false
local function can_write_encap(encap)
dprint2("can_write_encap() called with encap=",encap)
return canwrite[encap] or false
end
local function write_open(file, capture)
dprint2("write_open() called")
local file_settings = create_writer_file_settings()
-- write out file header
local hdr = Struct.pack(file_settings.file_hdr_patt,
file_settings.corrected_magic,
file_settings.version_major,
file_settings.version_minor,
file_settings.timezone,
file_settings.sigfigs,
capture.snapshot_length,
wtap2pcap(capture.encap))
if not hdr then
dprint("write_open: error generating file header")
return false
end
dprint2("write_open generating:", Struct.tohex(hdr))
if not file:write(hdr) then
dprint("write_open: error writing file header to file")
return false
end
-- save settings
capture.private_table = file_settings
return true
end
local function write(file, capture, frame)
dprint2("write() called")
-- get file settings
local file_settings = capture.private_table
if not file_settings then
dprint("write() failed to get private table file settings")
return false
end
-- write out record header: time_sec, time_usec, capture_len, original_len
-- first get times
local nstime = frame.time
-- pcap format is in usecs, but wireshark's internal is nsecs
local nsecs = nstime.nsecs
if file_settings.time_precision == wtap_filetypes.TSPREC_USEC then
nsecs = nsecs / 1000
elseif file_settings.time_precision == wtap_filetypes.TSPREC_MSEC then
nsecs = nsecs / 1000000
end
local hdr = Struct.pack(file_settings.rec_hdr_patt,
nstime.secs,
nsecs,
frame.captured_length,
frame.original_length)
if not hdr then
dprint("write: error generating record header")
return false
end
if not file:write(hdr) then
dprint("write: error writing record header to file")
return false
end
-- we could write the packet data the same way, by getting frame.data and writing it out
-- but we can avoid copying those bytes into Lua by using the write_data() function
if not frame:write_data(file) then
dprint("write: error writing record data to file")
return false
end
return true
end
local function write_close(file, capture)
dprint2("write_close() called")
dprint2("Good night, and good luck")
return true
end
-- ok, so let's create another FileHandler object
local fh2 = FileHandler.new("Lua-based PCAP writer", "lua_pcap2", "A Lua-based file writer for PCAP-type files","wms")
-- set above functions to the FileHandler
fh2.can_write_encap = can_write_encap
fh2.write_open = write_open
fh2.write = write
fh2.write_close = write_close
fh2.extensions = "pcap;cap" -- this is just a hint
-- and finally, register the FileHandler!
register_filehandler(fh2)
dprint2("Second FileHandler registered")
| gpl-2.0 |
wfleurant/cjdns | contrib/lua/cjdns/addrcalc.lua | 19 | 1888 | -- Cjdns address conversion functions
-- Translated from Cjdns C code to lua code by Alex <alex@portlandmeshnet.org>
--- @module cjdns.addrcalc
local addrcalc = {}
local bit32 = require("bit32")
local sha2 = require("sha2")
function addrcalc.Base32_decode(input)
local numForAscii = {
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,99,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
}
local output = {}
local outputIndex = 0
local inputIndex = 0
local nextByte = 0
local bits = 0
while inputIndex < string.len(input) do
i = string.byte(input,inputIndex+1)
if bit32.band(i,0x80) ~= 0 then
error("Bad base32 decode input character " .. i)
end
b = numForAscii[i+1]
inputIndex = inputIndex + 1
if b > 31 then
error("Bad base32 decode input character " .. i)
end
nextByte = bit32.bor(nextByte, bit32.lshift(b, bits))
bits = bits + 5
if bits >= 8 then
output[outputIndex+1] = bit32.band(nextByte, 0xff)
outputIndex = outputIndex + 1
bits = bits - 8
nextByte = bit32.rshift(nextByte, 8)
end
end
if bits >= 5 or nextByte ~= 0 then
error("Bad base32 decode input, bits is " .. bits .. " and nextByte is " .. nextByte);
end
return string.char(unpack(output));
end
function addrcalc.pkey2ipv6(k)
if string.sub(k,-2) ~= ".k" then
error("Invalid key")
end
kdata = addrcalc.Base32_decode(string.sub(k,1,-3))
hash = sha2.sha512(kdata)
hash = sha2.sha512hex(hash)
addr = string.sub(hash,1,4)
for i = 2,8 do
addr = addr .. ":" .. string.sub(hash,i*4-3,i*4)
end
return addr
end
return addrcalc
| gpl-3.0 |
nandub/cjdns | contrib/lua/cjdns/addrcalc.lua | 19 | 1888 | -- Cjdns address conversion functions
-- Translated from Cjdns C code to lua code by Alex <alex@portlandmeshnet.org>
--- @module cjdns.addrcalc
local addrcalc = {}
local bit32 = require("bit32")
local sha2 = require("sha2")
function addrcalc.Base32_decode(input)
local numForAscii = {
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,
0, 1, 2, 3, 4, 5, 6, 7, 8, 9,99,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
99,99,10,11,12,99,13,14,15,99,16,17,18,19,20,99,
21,22,23,24,25,26,27,28,29,30,31,99,99,99,99,99,
}
local output = {}
local outputIndex = 0
local inputIndex = 0
local nextByte = 0
local bits = 0
while inputIndex < string.len(input) do
i = string.byte(input,inputIndex+1)
if bit32.band(i,0x80) ~= 0 then
error("Bad base32 decode input character " .. i)
end
b = numForAscii[i+1]
inputIndex = inputIndex + 1
if b > 31 then
error("Bad base32 decode input character " .. i)
end
nextByte = bit32.bor(nextByte, bit32.lshift(b, bits))
bits = bits + 5
if bits >= 8 then
output[outputIndex+1] = bit32.band(nextByte, 0xff)
outputIndex = outputIndex + 1
bits = bits - 8
nextByte = bit32.rshift(nextByte, 8)
end
end
if bits >= 5 or nextByte ~= 0 then
error("Bad base32 decode input, bits is " .. bits .. " and nextByte is " .. nextByte);
end
return string.char(unpack(output));
end
function addrcalc.pkey2ipv6(k)
if string.sub(k,-2) ~= ".k" then
error("Invalid key")
end
kdata = addrcalc.Base32_decode(string.sub(k,1,-3))
hash = sha2.sha512(kdata)
hash = sha2.sha512hex(hash)
addr = string.sub(hash,1,4)
for i = 2,8 do
addr = addr .. ":" .. string.sub(hash,i*4-3,i*4)
end
return addr
end
return addrcalc
| gpl-3.0 |
soundsrc/premake-stable | src/base/string.lua | 2 | 1262 | --
-- string.lua
-- Additions to Lua's built-in string functions.
-- Copyright (c) 2002-2008 Jason Perkins and the Premake project
--
--
-- Returns an array of strings, each of which is a substring of s
-- formed by splitting on boundaries formed by `pattern`.
--
function string.explode(s, pattern, plain)
if (pattern == '') then return false end
local pos = 0
local arr = { }
for st,sp in function() return s:find(pattern, pos, plain) end do
table.insert(arr, s:sub(pos, st-1))
pos = sp + 1
end
table.insert(arr, s:sub(pos))
return arr
end
--
-- Find the last instance of a pattern in a string.
--
function string.findlast(s, pattern, plain)
local curr = 0
repeat
local next = s:find(pattern, curr + 1, plain)
if (next) then curr = next end
until (not next)
if (curr > 0) then
return curr
end
end
--
-- Returns true if `haystack` starts with the sequence `needle`.
--
function string.startswith(haystack, needle)
return (haystack:find(needle, 1, true) == 1)
end
--
-- Escapes a filename for the shell
-- TODO: this is a very basic implementation.. don't depend on this for security
--
function string.shellescape(str)
return string.gsub(str, '([\]|&;<>()$`\\"\' \t\n*?\[#=\~%%])', '\\%1')
end
| bsd-3-clause |
jinxiaoye1987/RyzomCore | ryzom/common/data_common/r2/r2_ui_player_tracking.lua | 3 | 21867 | -- players tracking window
PlayerTracking =
{
CurrList = {},
CurrActiveList = {},
SortDir = {},
SelectedPlayerId = nil,
TextCache = {}, -- cache for text widgets
CenteredTextCache = {},
NumberCache = {}, -- cache for number widgets
BitmapCache = {}, -- cache for bitmap widgets
-- Map scenario flags to the bitmaps displayed in the first column
FlagsToTex =
{
[0] = { Bitmap = "blank.tga", Color = "0 0 0 0 " },
[1] = { Bitmap = "rap_not_invited_dm.tga", Color = "255 255 255 255" },
},
WaitingList = false,
FirstShow = true,
RefreshPeriod = 10,
MinRefreshPeriod = 4,
LastRefreshTime = 0,
LastRefreshQuerryTime = 0,
PendingRefresh = false,
ListReceived = false,
--
RaceTypeToUtf8 = {},
ReligionTypeToUtf8 = {},
ShardTypeToUtf8 = {},
LevelTypeToUtf8 = {},
}
local sampleList1 =
{
}
table.insert(sampleList1, { Id=0, Player = "plop", Guild="Guild1", Race=1, Religion=1, Shard=2, Level=1, Flags=0})
table.insert(sampleList1, { Id=1, Player = "titi", Guild="Guild1", Race=2, Religion=2, Shard=4, Level=2, Flags=1})
table.insert(sampleList1, { Id=2, Player = "bob", Guild="", Race=1, Religion=4, Shard=1, Level=1, Flags=1})
table.insert(sampleList1, { Id=3, Player = "bobette", Guild="Guild2", Race=1, Religion=2, Shard=1, Level=4, Flags=1})
table.insert(sampleList1, { Id=4, Player = "nico", Guild="Super guild", Race=8, Religion=1, Shard=2, Level=4, Flags=0})
table.insert(sampleList1, { Id=5, Player = "toto2", Guild="GG", Race=4, Religion=2, Shard=2, Level=4, Flags=1})
table.insert(sampleList1, { Id=6, Player = "titi2", Guild="Plop guild", Race=8, Religion=2, Shard=4, Level=4, Flags=1})
table.insert(sampleList1, { Id=7, Player = "bob2", Guild="Plop guild", Race=8, Religion=2, Shard=1, Level=8, Flags=0})
table.insert(sampleList1, { Id=8, Player = "bobette2", Guild="Guild1", Race=2, Religion=4, Shard=1, Level=8, Flags=0})
table.insert(sampleList1, { Id=9, Player = "nico2", Guild="Super guild", Race=8, Religion=2, Shard=1, Level=16, Flags=0})
table.insert(sampleList1, { Id=10, Player = "toto3", Guild="Guild2", Race=4, Religion=4, Shard=2, Level=16, Flags=1})
table.insert(sampleList1, { Id=11, Player = "titi3", Guild="GG", Race=1, Religion=1, Shard=4, Level=32, Flags=1})
table.insert(sampleList1, { Id=12, Player = "bob3", Guild="Plop guild", Race=8, Religion=2, Shard=1, Level=32, Flags=1})
table.insert(sampleList1, { Id=13, Player = "bobette3",Guild="GG", Race=8, Religion=4, Shard=2, Level=32, Flags=0})
table.insert(sampleList1, { Id=14, Player = "nico3", Guild="GG", Race=8, Religion=2, Shard=2, Level=4, Flags=1})
table.insert(sampleList1, { Id=15, Player = "toto4", Guild="", Race=4, Religion=1, Shard=1, Level=8, Flags=0})
table.insert(sampleList1, { Id=16, Player = "titi'", Guild="TSuper guild", Race=2, Religion=1, Shard=4, Level=2, Flags=1})
table.insert(sampleList1, { Id=17, Player = "bob4", Guild="GG", Race=2, Religion=4, Shard=4, Level=8, Flags=0})
table.insert(sampleList1, { Id=18, Player = "bobette4",Guild="Guild2", Race=4, Religion=2, Shard=1, Level=1, Flags=1})
table.insert(sampleList1, { Id=19, Player = "nico4", Guild="", Race=1, Religion=1, Shard=1, Level=2, Flags=1})
local boolToInt =
{
}
boolToInt[false] = 0
boolToInt[true] = 1
--*********************************
-- standard comparison
local function less(lhs, rhs)
if type(lhs) == "boolean" then
return boolToInt[lhs] < boolToInt[rhs]
else
return lhs < rhs
end
end
--*********************************
-- reversed comparison
local function more(lhs, rhs)
return not less(lhs,rhs)
end
--*********************************
-- sorting by race type
local function lessRaceType(lhs, rhs)
return PlayerTracking.RaceTypeToUtf8[lhs] < PlayerTracking.RaceTypeToUtf8[rhs]
end
--*********************************
-- sorting by religion type
local function lessReligionType(lhs, rhs)
return PlayerTracking.ReligionTypeToUtf8[lhs] < PlayerTracking.ReligionTypeToUtf8[rhs]
end
-- init sort dir
table.insert(PlayerTracking.SortDir, { Var="Flags", Up=false, Cmp = more })
table.insert(PlayerTracking.SortDir, { Var="Player", Up=false, Cmp = less})
table.insert(PlayerTracking.SortDir, { Var="Guild", Up=false, Cmp = less })
table.insert(PlayerTracking.SortDir, { Var="Race", Up=false, Cmp = lessRaceType })
table.insert(PlayerTracking.SortDir, { Var="Religion", Up=false, Cmp = lessReligionType })
table.insert(PlayerTracking.SortDir, { Var="Shard", Up=false, Cmp = less })
table.insert(PlayerTracking.SortDir, { Var="Level", Up=false, Cmp = less })
--***********************************************************************
function PlayerTracking:getWindow()
return getUI("ui:login:ring_players_tracking")
end
--***********************************************************************
function PlayerTracking:initRaceTypes()
for k = 0, 3 do
self.RaceTypeToUtf8[math.pow(2, k)] = i18n.get("uiRAP_PlayerRace_" .. tostring(k)):toUtf8()
end
end
--***********************************************************************
function PlayerTracking:initReligionTypes()
for k = 0, 2 do
self.ReligionTypeToUtf8[math.pow(2, k)] = i18n.get("uiRAP_PlayerReligion_" .. tostring(k)):toUtf8()
end
end
--***********************************************************************
function PlayerTracking:initShardTypes()
for k = 0, 2 do
self.ShardTypeToUtf8[math.pow(2, k)] = i18n.get("uiRAP_PlayerShard_" .. tostring(k)):toUtf8()
end
end
--***********************************************************************
function PlayerTracking:initLevelTypes()
for k = 0, 5 do
self.LevelTypeToUtf8[math.pow(2, k)] = i18n.get("uiRAP_PlayerLevel_" .. tostring(k)):toUtf8()
end
end
--***********************************************************************
function PlayerTracking:isConnected(flags)
return flags == 1
end
--***********************************************************************
function PlayerTracking:getColumn(name)
return getUI("ui:login:ring_players_tracking:content:main:enclosing:columns:getw:column_group:" .. name .. ":values")
end
--***********************************************************************
function PlayerTracking:getSelectList()
return getUI("ui:login:ring_players_tracking:content:main:enclosing:columns:getw:select")
end
local scratchUCStr = ucstring()
--***********************************************************************
function PlayerTracking:newTemplate(name, cache)
local group
if table.getn(cache) ~= 0 then
group = cache[table.getn(cache)]
table.remove(cache, table.getn(cache))
else
group = createGroupInstance(name, "", {})
end
return group
end
--***********************************************************************
-- build a new text group from utf8 text
function PlayerTracking:newTextLabel(value)
local group = self:newTemplate("rap_text", self.TextCache)
scratchUCStr:fromUtf8(value)
group:find("t").uc_hardtext_single_line_format = scratchUCStr
return group
end
--***********************************************************************
-- build a new text group from utf8 text
function PlayerTracking:newCenteredTextLabel(value)
local group = self:newTemplate("rap_text_centered", self.CenteredTextCache)
scratchUCStr:fromUtf8(value)
group:find("t").uc_hardtext_single_line_format = scratchUCStr
return group
end
--***********************************************************************
function PlayerTracking:newNumberLabel(value)
local group = self:newTemplate("rap_number", self.NumberCache)
group:find("t").uc_hardtext_single_line_format = tostring(value)
return group
end
--***********************************************************************
function PlayerTracking:newBitmap(texName, color)
if color == nil then color = "255 255 255 255" end
local group = self:newTemplate("rap_bitmap", self.BitmapCache)
group.f.texture = texName
group.f.color = color
return group
end
--***********************************************************************
function PlayerTracking:newBooleanLabel(value)
local group = self:newTemplate("rap_bitmap", self.BitmapCache)
if value == true then
group.f.texture="patch_on.tga"
group.f.color="255 255 255 255"
else
group.f.texture="blank.tga"
group.f.color="0 0 0 0"
end
return group
end
--***********************************************************************
function PlayerTracking:addLine(line)
self:getColumn("player"):addChild(self:newTextLabel(line.Player))
self:getColumn("guild"):addChild(self:newTextLabel(line.Guild))
self:getColumn("race"):addChild(self:newTextLabel(self.RaceTypeToUtf8[line.Race]))
self:getColumn("religion"):addChild(self:newTextLabel(self.ReligionTypeToUtf8[line.Religion]))
self:getColumn("shard"):addChild(self:newTextLabel(self.ShardTypeToUtf8[line.Shard]))
self:getColumn("level"):addChild(self:newNumberLabel(self.LevelTypeToUtf8[line.Level]))
self:getColumn("flags"):addChild(self:newBitmap(self.FlagsToTex[line.Flags].Bitmap, self.FlagsToTex[line.Flags].Color))
end
--***********************************************************************
function PlayerTracking:putColumnInCache(column, cache)
local childrenCount = column.childrenNb
for i = 0, childrenCount - 1 do
local child = column:getChild(column.childrenNb - 1)
table.insert(cache, child)
column:detachChild(child)
end
end
--***********************************************************************
function PlayerTracking:putMixedColumnInCache(column, textCache, bitmapCache)
local childrenCount = column.childrenNb
for i = 0, childrenCount - 1 do
local child = column:getChild(column.childrenNb - 1)
if child:find("t") then
table.insert(textCache, child)
else
table.insert(bitmapCache, child)
end
column:detachChild(child)
end
end
--***********************************************************************
function PlayerTracking:putInCache()
self.TextCache = {}
self.CenteredTextCache = {}
self.NumberCache = {}
self.BitmapCache = {}
self:putColumnInCache(self:getColumn("player"), self.TextCache)
self:putColumnInCache(self:getColumn("guild"), self.TextCache)
self:putColumnInCache(self:getColumn("race"), self.TextCache)
self:putColumnInCache(self:getColumn("shard"), self.TextCache)
self:putColumnInCache(self:getColumn("religion"), self.TextCache)
--
self:putColumnInCache(self:getColumn("level"), self.NumberCache)
--
self:putColumnInCache(self:getColumn("flags"), self.BitmapCache)
end
--***********************************************************************
function PlayerTracking:clear()
self:getColumn("flags"):clear()
self:getColumn("player"):clear()
self:getColumn("guild"):clear()
self:getColumn("race"):clear()
self:getColumn("religion"):clear()
self:getColumn("shard"):clear()
self:getColumn("level"):clear()
self.TextCache = {}
self.CenteredTextCache = {}
self.NumberCache = {}
self.BitmapCache = {}
self:getSelectList():clear()
self:getSelectList().active = false
self.CurrList = {}
self.CurrActiveList = {}
self.ListReceived = false
end
--***********************************************************************
function PlayerTracking:testFill1()
self:onPlayersListReceived(sampleList1)
end
--***********************************************************************
function PlayerTracking:onPlayersListReceived(list)
self.WaitingList = false
self.LastRefreshTime = nltime.getLocalTime() / 1000
self.ListReceived = true
self:fill(list)
end
--***********************************************************************
function PlayerTracking:fill(list)
self:initRaceTypes()
self:initReligionTypes()
self:initShardTypes()
self:initLevelTypes()
-- if the window is not active, then maybe an old msg -> ignore
if not self:getWindow().active then return end
self:enableButtons(true)
--
local startTime = nltime.getPreciseLocalTime()
debugInfo(tostring(self.SelectedPlayerId))
--
self:getWindow():find("teleport").frozen = true
self:getWindow():find("kick").frozen = true
self:getWindow():find("tell").frozen = true
--
self:putInCache()
--
debugInfo("***********************")
debugInfo("TextCache size = " .. table.getn(self.TextCache))
debugInfo("CenteredTextCache size = " .. table.getn(self.CenteredTextCache))
debugInfo("NumberCache size = " .. table.getn(self.NumberCache))
debugInfo("BitmapCache size = " .. table.getn(self.BitmapCache))
--self:clear()
self.CurrList = list
self.CurrActiveList = {}
self:sort()
local selectList = self:getSelectList()
selectList:clear()
local count = 0
local displayedCount = 0
for k, v in pairs(self.CurrList) do
count = count + 1
local active
self:addLine(v)
local newGroup = createGroupInstance("rap_select_line", "", { id=tostring(v.Id)})
selectList:addChild(newGroup)
newGroup:find("but").pushed = (v.Id == self.SelectedPlayerId)
table.insert(self.CurrActiveList, v)
displayedCount = displayedCount + 1
end
if displayedCount == 0 then
if count ~= 0 then
self:setErrorMessage("uiRAP_NoSessionForLangFilter")
else
--self:setErrorMessage(i18n.get("uiRAP_NoSessionFound"))
self:setErrorMessage(ucstring())
self:enableButtons(false)
end
else
self:clearMessage()
end
local endTime = nltime.getPreciseLocalTime()
debugInfo(string.format("time ellapsed = %d", 1000 * (endTime - startTime)))
end
--***********************************************************************
function PlayerTracking:setMessage(msg, color)
local errorTxt = self:getWindow():find("errorMsg")
errorTxt.uc_hardtext = msg
errorTxt.color = color
errorTxt.active=true
end
--***********************************************************************
function PlayerTracking:clearMessage()
local errorTxt = self:getWindow():find("errorMsg")
errorTxt.active = false
end
--***********************************************************************
function PlayerTracking:setErrorMessage(msg)
self:setMessage(msg, "255 0 0 255")
end
--***********************************************************************
function PlayerTracking:setInfoMessage(msg)
self:setMessage(msg, "255 255 255 255")
end
--***********************************************************************
function PlayerTracking:sort(list)
local sortDir = self.SortDir
local function sorter(lhs, rhs)
for k = 1, table.getn(sortDir) do
if lhs[sortDir[k].Var] ~= rhs[sortDir[k].Var] then
if sortDir[k].Up then
return not sortDir[k].Cmp(lhs[sortDir[k].Var], rhs[sortDir[k].Var])
else
return sortDir[k].Cmp(lhs[sortDir[k].Var], rhs[sortDir[k].Var])
end
end
end
return false
end
table.sort(self.CurrList, sorter)
end
--***********************************************************************
function PlayerTracking:headerLeftClick(down, criterion)
-- change column sort order
local parent = getUICaller().parent
parent.tdown.active = down
parent.tup.active = not down
-- insert
local sortDir = self.SortDir
for k = 1, table.getn(sortDir) do
if sortDir[k].Var == criterion then
sortDir[k].Up = not sortDir[k].Up
table.insert(sortDir, 1, sortDir[k])
table.remove(sortDir, k + 1)
if self.ListReceived then
self:fill(self.CurrList) -- update only if list has been received
end
return
end
end
end
--***********************************************************************
function PlayerTracking:getPlayerFromId(id)
for k, v in pairs(self.CurrList) do
if v.Id == id then return v end
end
return nil
end
--***********************************************************************
function PlayerTracking:onLineLeftClick()
self.SelectedPlayerId = self.CurrActiveList[self:getSelectList():getElementIndex(getUICaller().parent) + 1].Id
local selectList = self:getSelectList()
for k = 0, selectList.childrenNb - 1 do
local but = selectList:getChild(k):find("but")
if but == getUICaller() then
but.pushed = true
else
but.pushed = false
end
end
self:getWindow():find("kick").frozen = not self:isConnected(self:getPlayerFromId(self.SelectedPlayerId).Flags)
self:getWindow():find("teleport").frozen = not self:isConnected(self:getPlayerFromId(self.SelectedPlayerId).Flags)
self:getWindow():find("tell").frozen = false
end
--***********************************************************************
function PlayerTracking:onLineRightClick()
self:onLineLeftClick()
local menu = getUI("ui:login:ring_player_menu")
menu:find("tell").uc_hardtext = ucstring(i18n.get("uiRAP_MenuPlayerTell"):toUtf8() .. "'" .. self:getPlayerFromId(self.SelectedPlayerId).Player .."'")
menu:find("teleport").uc_hardtext = ucstring(i18n.get("uiRAP_MenuTeleportTo"):toUtf8() .. "'" .. self:getPlayerFromId(self.SelectedPlayerId).Player.."'")
menu:find("kick").uc_hardtext = ucstring(i18n.get("uiRAP_MenuKick"):toUtf8() .. "'" .. self:getPlayerFromId(self.SelectedPlayerId).Player.."'")
menu:find("kick").grayed = not self:isConnected(self:getPlayerFromId(self.SelectedPlayerId).Flags)
menu:find("teleport").grayed = not self:isConnected(self:getPlayerFromId(self.SelectedPlayerId).Flags)
launchContextMenuInGame("ui:login:ring_player_menu")
end
--***********************************************************************
-- called by C++ if session joining failed
function PlayerTracking:onJoinFailed()
messageBox(i18n.get("uiRAP_JoinFailed"))
end
--***********************************************************************
function PlayerTracking:onTell()
debugInfo("tell to owner of session" .. self.SelectedPlayerId)
player = ucstring()
player:fromUtf8(self:getPlayerFromId(self.SelectedPlayerId).Player)
tell(player)
end
--***********************************************************************
function PlayerTracking:onTeleportTo()
end
--***********************************************************************
function PlayerTracking:onKick()
end
--***********************************************************************
function PlayerTracking:onLineLeftDblClick()
local player = self:getPlayerFromId(self.SelectedPlayerId)
if self:isConnected(player.Flags) then
validMessageBox(i18n.get("uiRAP_JoinConfirm"), "lua", "PlayerTracking:onJoin()", "", "", "ui:login")
else
-- default to a tell
onTell()
end
end
--***********************************************************************
function PlayerTracking:refresh()
self.PendingRefresh = true
self.LastRefreshTime = nltime.getLocalTime() / 1000
self.WaitingList = true
debugInfo("*refresh*")
end
--***********************************************************************
function PlayerTracking:updatePendingRefresh()
if self.PendingRefresh then
local currTime = nltime.getLocalTime() / 1000
if currTime - self.LastRefreshQuerryTime > self.MinRefreshPeriod then
self.LastRefreshQuerryTime = currTime
self.PendingRefresh = false
game.getRingPlayerList()
end
end
end
--***********************************************************************
function PlayerTracking:onShow()
self:initRaceTypes()
self:initReligionTypes()
self:initShardTypes()
self:initLevelTypes()
setOnDraw(self:getWindow(), "PlayerTracking:onDraw()")
self:clear()
self:enableButtons(false)
self:refresh()
end
local waitTextColor = CRGBA(255, 255, 255, 255)
function PlayerTracking:connectError(errorTextId)
if not self.WaitingList then return end
self:clear()
self:setErrorMessage(i18n.get(errorTextId))
self.WaitingList = false
self.PendingRefresh = false
self.LastRefreshTime = nltime.getLocalTime() / 1000 -- force to wait some more
end
--***********************************************************************
-- called by C++ if retrieving of sessions failed
function PlayerTracking:onConnectionFailed()
self:connectError("uiRAP_ConnectionFailed")
end
--***********************************************************************
-- called by C++ if retrieving of sessions failed
function PlayerTracking:onDisconnection()
self:connectError("uiRAP_Disconnection")
end
--***********************************************************************
-- called by C++ if retrieving of sessions failed
function PlayerTracking:onConnectionClosed()
self:connectError("uiRAP_ConnectionClosed")
end
--***********************************************************************
function PlayerTracking:enableButtons(enabled)
local win = self:getWindow()
local alpha
if enabled then alpha = 255 else alpha = 128 end
self:getSelectList().active = enabled
end
--***********************************************************************
function PlayerTracking:show()
-- update msg
local win = self:getWindow()
win.active = true
if self.FirstShow then
local w, h = getWindowSize()
win.w = w * 5 / 6
win.h = h * 5 / 6
win:invalidateCoords()
win:updateCoords()
win:center()
win:invalidateCoords()
win:updateCoords()
self.FirstShow = false
end
win:blink(1)
end
--***********************************************************************
function PlayerTracking:enlargeColumns()
self:getWindow():find("header_line"):enlargeColumns(10)
end
--***********************************************************************
function PlayerTracking:resizeColumnsAndContainer()
self:getWindow():find("header_line"):resizeColumnsAndContainer(5)
end
--***********************************************************************
function PlayerTracking:onDraw()
local timeInSec = nltime.getLocalTime() / 1000
if self.WaitingList then
local waitText = i18n.get("uiRAP_WaitMsg" .. math.mod(os.time(), 3))
if not self.ListReceived then
self:setInfoMessage(waitText)
waitTextColor.A = 127 + 127 * (0.5 + 0.5 * math.cos(6 * timeInSec))
local errorTxt = self:getWindow():find("errorMsg")
errorTxt.color_rgba = waitTextColor
end
else
if timeInSec - self.LastRefreshTime > self.RefreshPeriod then
self:refresh()
end
end
self:updatePendingRefresh()
end
| agpl-3.0 |
holyodin776/demirogue | src/GraphGrammar.lua | 3 | 26648 | require 'Graph'
require 'graph2D'
GraphGrammar = {
Rule = {}
}
GraphGrammar.__index = GraphGrammar
GraphGrammar.Rule.__index = GraphGrammar.Rule
-- TODO: Describe graph grammar production rules in a nice terse comment...
-- - The pattern and substitute graphs should be non-empty and connected.
-- - All pattern and substitute vertices should have tag fields.
-- - Because there may be more than one way to replace the pattern with the
-- substitute, a map from pattern to substitute vertices has to be provided.
-- NOTE: this is used to reconnect dangling edges caused by the the removal
-- of the pattern subgraph.
-- TODO: 's' and '-' tags have special meaning (start and wildcard). Should
-- specify them somewhere instead of being spread over the code like
-- magic numbers.
-- Used when checking the pattern and subtitute graphs are connected.
local function _edgeFilter( edge )
return not edge.cosmetic
end
local function _vertexCheck( vertex )
return vertex.cosmetic
end
function GraphGrammar.Rule.new( pattern, substitute, map )
assert(not pattern:isEmpty(), 'pattern graph is empty')
assert(not substitute:isEmpty(), 'substitute graph is empty')
-- All vertices must be connected disregarding cosmetic edges.
-- TODO: we may need the concept of cosmetic vertex...
assert(pattern:isConnectedWithEdgeFilterAndVertexCheck(_edgeFilter, _vertexCheck), 'pattern is not connected')
assert(substitute:isConnectedWithEdgeFilterAndVertexCheck(_edgeFilter, _vertexCheck), 'substitute is not connected')
local negated = false
-- Check that the pattern and substitute graphs have tags.
for vertex, _ in pairs(pattern.vertices) do
assert(vertex.tags, 'no tags for pattern vertex')
assert(type(vertex.x) == 'number' and math.floor(vertex.x) == vertex.x, 'pattern vertex has no X value')
-- TODO: should use math.finite
assert(vertex.x == vertex.x, 'pattern vertex X value is NaN')
assert(type(vertex.y) == 'number' and math.floor(vertex.y) == vertex.y, 'pattern vertex has no Y value')
-- TODO: should use math.finite
assert(vertex.y == vertex.y, 'pattern vertex Y value is NaN')
local numPositive = 0
for tag, cond in pairs(vertex.tags) do
if cond then
numPositive = numPositive + 1
else
negated = true
end
end
assert(numPositive > 0, 'need one or more positive tags for a pattern vertex')
end
local tags = {}
for vertex, _ in pairs(substitute.vertices) do
assert(vertex.tag, ' no tag for substitute vertex')
assert(type(vertex.x) == 'number' and math.floor(vertex.x) == vertex.x, 'substitute vertex has no X value')
-- TODO: Use math.finite
assert(vertex.x == vertex.x, 'substitute vertex X value is NaN')
assert(type(vertex.y) == 'number' and math.floor(vertex.y) == vertex.y, 'substitute vertex has no X value')
-- TODO: Use math.finite
assert(vertex.y == vertex.y, 'substitute vertex Y value is NaN')
if vertex.tag ~= '-' then
tags[vertex.tag] = true
end
end
-- Check that the map uses valid vertices and is bijective.
local inverse = {}
for patternVertex, substituteVertex in pairs(map) do
assert(pattern.vertices[patternVertex], 'invalid map pattern vertex')
assert(substitute.vertices[substituteVertex], 'invalid map substitute vertex')
assert(not inverse[substituteVertex], 'map is not bijective')
inverse[substituteVertex] = patternVertex
end
-- Only start rules can have one vertex in the pattern.
local start = false
if table.count(pattern.vertices) == 1 then
local patternVertex = next(pattern.vertices)
assert(table.count(patternVertex.tags) == 1, 'single vertex pattern needs a single s tag')
assert(next(patternVertex.tags) == 's', 'single vertex pattern needs a single s tag')
start = true
end
-- No pattern non-start pattern rule can have start vertices ('s' tag).
if not start then
for patternVertex, _ in pairs(pattern.vertices) do
assert(not patternVertex.tags.s, 'non-start pattern has an s tag')
end
end
-- No substitute rule can have start vertices ('s' tag).
-- Only mapped substitute vertices can have a '-' tag.
for substituteVertex, _ in pairs(substitute.vertices) do
assert(substituteVertex.tag ~= 's', 'no s tag allowed in substitute')
assert(substituteVertex.tag ~= '-' or inverse[substituteVertex], "only mapped substitute vertex can have '-' tag")
end
-- All pattern vertices should be mapped.
-- NOTE: If I changed this check and replaced it with 'at least one pattern
-- vertex must be mapped' it should still create connected graphs.
-- The map is really used for determining where and when to reconnect
-- dangling edges left by the removal of the pattern subgraph.
assert(table.count(pattern.vertices) == table.count(map), 'substitute has less vertices than the pattern')
-- How many new vertices would be added by this rule. Useful for ensuring
-- we don't create too many vertices.
local vertexDelta = table.count(substitute.vertices) - table.count(pattern.vertices)
assert(vertexDelta >= 0, 'substitute has less vertices than the pattern')
-- How many edges are added (or removed) on mapped vertices by the
-- application of this rule. This is used to ensure we don't exceed the
-- maxValence specified when building.
local valenceDeltas = {}
for patternVertex, substituteVertex in pairs(map) do
local patternValence = pattern.valences[patternVertex]
local substituteValence = substitute.valences[substituteVertex]
local valenceDelta = substituteValence - patternValence
valenceDeltas[patternVertex] = valenceDelta
end
local spurs = graph2D.spurs(pattern)
-- Which edges in the pattern are present in the substitute?
-- { [substituteEdge] = patternEdge }
local mappedEdges = {}
for substituteEdge, _ in pairs(substitute.edges) do
if substituteEdge.subdivide then
local lengthFactor = substituteEdge.lengthFactor
assert(type(lengthFactor) == 'number' and lengthFactor > 0)
end
end
for patternEdge, patternEndVerts in pairs(pattern.edges) do
local patternVertex1 = patternEndVerts[1]
local patternVertex2 = patternEndVerts[2]
local substituteEdge = pattern.vertices[patternVertex1][patternVertex2]
if substituteEdge then
mappedEdges[substituteEdge] = patternEdge
end
end
-- Find out which unmapped substitutes are inside or outside the convex
-- hull of the mapped vertices.
local hullPoints = {}
local unmappedSubstituteVertices = {}
for substituteVertex, _ in pairs(substitute.vertices) do
if inverse[substituteVertex] then
hullPoints[#hullPoints+1] = Vector.new(substituteVertex)
else
unmappedSubstituteVertices[substituteVertex] = true
end
end
local exterior = {}
if #hullPoints < 3 then
exterior = unmappedSubstituteVertices
else
local hull = geometry.convexHull(hullPoints)
for substituteVertex, _ in pairs(unmappedSubstituteVertices) do
if not geometry.isPointInHull(substituteVertex, hull) then
exterior[substituteVertex] = true
end
end
end
local result = {
pattern = pattern,
substitute = substitute,
map = map,
tags = tags,
negated = negated,
vertexDelta = vertexDelta,
valenceDeltas = valenceDeltas,
start = start,
spurs = spurs,
mappedEdges = mappedEdges,
exterior = exterior,
}
setmetatable(result, GraphGrammar.Rule)
return result
end
local function _vertexEq( host, hostVertex, pattern, patternVertex )
-- TODO: lock should probably be called valenceLock or something.
if patternVertex.lock then
if pattern.valences[patternVertex] ~= host.valences[hostVertex] then
return false
end
end
if patternVertex.tags['-'] then
return true
end
return patternVertex.tags[hostVertex.tag]
end
local function _edgeEq( host, hostEdge, pattern, patternEdge )
return hostEdge.cosmetic == patternEdge.cosmetic
end
function GraphGrammar.Rule:matches( graph, maxValence )
-- TODO: Probably need an edgeEq as well..
local start = love.timer.getTime()
local success, result = graph:matches(self.pattern, _vertexEq, _edgeEq)
local finish = love.timer.getTime()
printf(' subgraph:%.4fs', finish-start)
-- If we have some matches we need to apply some more checks and reject
-- those which will cause us issues:
--
-- - We check the signed angles between edges to ensure we don't allow
-- 'flipped' matches though. For example a triangle graph:
--
-- a - a
-- \ |
-- a
--
-- Can be matches to another trangle in the host graph in six ways. Three
-- of the matches are rotations but the other three are 'flipped' (in
-- geometric terms mirrored). These cause the re-established
-- neighbourhood edges to intersect.
--
-- - If the valence of a vertex gets too high the graph drawing will create
-- a lot of intersecting edges. So we have a maxValence parameter and
-- check to see if it would be exceeded by the application of the rule.
--
-- - Check that negated neighbours are not present. A negated neighbour is
-- a tag in the pattern tag set with a false value.
--
-- - TODO: need to add blocked neighbours checking.
if success then
local start = love.timer.getTime()
-- Iterate backwards because we may be removing matches.
local numFlipFails = 0
local numValenceFails = 0
for index = #result, 1, -1 do
local match = result[index]
-- First off we need a map from pattern edges to host edges.
local edgeMap = {}
for patternEdge, patternEndVerts in pairs(self.pattern.edges) do
local graphVertex1 = match[patternEndVerts[1]]
local graphVertex2 = match[patternEndVerts[2]]
edgeMap[patternEdge] = graph.vertices[graphVertex1][graphVertex2]
end
-- Now we check that the signs of the signed angles match. See
-- comment above about flipped matches to see why.
local success = true
for patternVertex, spur in pairs(self.spurs) do
for _, patternEdgePair in ipairs(spur) do
local patternEdge1 = patternEdgePair.edge1
local patternEdge2 = patternEdgePair.edge2
local patternSignedAngle = patternEdgePair.signedAngle
local graphVertex = match[patternVertex]
local graphEdge1EndVerts = graph.edges[edgeMap[patternEdge1]]
local graphEdge1End = graphEdge1EndVerts[1]
if graphEdge1End == graphVertex then
graphEdge1End = graphEdge1EndVerts[2]
end
local graphEdge2EndVerts = graph.edges[edgeMap[patternEdge2]]
local graphEdge2End = graphEdge2EndVerts[1]
if graphEdge2End == graphVertex then
graphEdge2End = graphEdge2EndVerts[2]
end
local to1 = Vector.to(graphVertex, graphEdge1End)
local to2 = Vector.to(graphVertex, graphEdge2End)
local graphSignedAngle = to1:signedAngle(to2)
local sameSigns = math.sign(patternSignedAngle) == math.sign(graphSignedAngle)
-- print('[signed]', math.deg(patternSignedAngle), math.deg(graphSignedAngle), sameSigns)
if not sameSigns then
success = false
numFlipFails = numFlipFails + 1
break
end
end
if not success then
break
end
end
-- Check that we're not exceeding the maxValence constraint.
for patternVertex, graphVertex in pairs(match) do
local graphValence = graph.valences[graphVertex]
local outputValence = graphValence + self.valenceDeltas[patternVertex]
-- print('valence: ', graphValence, self.valenceDeltas[patternVertex], outputValence, maxValence, outputValence > maxValence)
if outputValence > maxValence then
numValenceFails = numValenceFails + 1
success = false
end
end
-- Check that no negated neightbours exist.
if success and self.negated then
local inverseMatch = table.inverse(match)
for patternVertex, _ in pairs(self.pattern.vertices) do
for tag, cond in pairs(patternVertex.tags) do
if not cond then
local graphVertex = match[patternVertex]
local graphPeers = graph.vertices[graphVertex]
for graphPeer, _ in pairs(graphPeers) do
-- The negated tag only applies to no-matched
-- graph vertices.
if not inverseMatch[graphPeer] and graphPeer.tag == tag then
success = false
break
end
end
end
if not success then
break
end
end
if not success then
break
end
end
end
if not success then
result[index] = result[#result]
result[#result] = nil
end
end
local finish = love.timer.getTime()
printf(' filter:%.4fs #flip:%d #:valence:%d', finish-start, numFlipFails, numValenceFails)
if #result == 0 then
return false
end
end
return success, result
end
-- Match should be one of the members of a result array from the matches()
-- method. If not, all bets are off and you better know what you're doing.
function GraphGrammar.Rule:replace( graph, match, params )
local start = love.timer.getTime()
-- Calculate the mean length of the matched edges.
local totalHostEdgeLength = 0
-- { [patternEdge] = <number> }
local hostLengthFactors = {}
local totalLengthFactors = 0
local numPatternEdges = 0
for patternEdge, patternEndVerts in pairs(self.pattern.edges) do
local graphVertex1 = match[patternEndVerts[1]]
local graphVertex2 = match[patternEndVerts[2]]
assert(graphVertex1)
assert(graphVertex2)
local hostEdgeLength = Vector.toLength(graphVertex1, graphVertex2)
totalHostEdgeLength = totalHostEdgeLength + hostEdgeLength
local graphEdge = graph.vertices[graphVertex1][graphVertex2]
hostLengthFactors[patternEdge] = graphEdge.lengthFactor
local graphEdge = graph.vertices[graphVertex1][graphVertex2]
totalLengthFactors = totalLengthFactors + (graphEdge.lengthFactor or 1)
numPatternEdges = numPatternEdges + 1
end
local meanHostEdgeLength = params.edgeLength
local meanLengthFactor = 1
if numPatternEdges > 0 then
meanHostEdgeLength = totalHostEdgeLength / numPatternEdges
meanLengthFactor = totalLengthFactors / numPatternEdges
end
-- We need the inverse of the matching map.
local inverseMatch = {}
for patternVertex, graphVertex in pairs(match) do
inverseMatch[graphVertex] = patternVertex
end
local matchAABB = graph2D.matchAABB(match)
-- If the AABB of the matched part of the host graph is too small enlarge.
if matchAABB:width() < 1 then
local fudge = 0.5
matchAABB.xmin = matchAABB.xmin - fudge
matchAABB.xmax = matchAABB.xmax + fudge
end
if matchAABB:height() < 1 then
local fudge = 0.5
matchAABB.ymin = matchAABB.ymin - fudge
matchAABB.ymax = matchAABB.ymax + fudge
end
-- Shrink to a quarter of the size.
-- matchAABB:scale(0.95)
-- First off let's find out which edges we'll need to re-establish.
-- { [patternVertex] = { graphVertex }* }
local danglers = {}
local cloneEdge = params.cloneEdge
for patternVertex, graphVertex in pairs(match) do
local dangles = {}
for graphPeer, graphEdge in pairs(graph.vertices[graphVertex]) do
-- If a graph vertex has a peer that isn't in the match we'll need
-- to reconnect it later.
if not inverseMatch[graphPeer] then
dangles[#dangles+1] = {
graphVertex = graphPeer,
graphEdge = cloneEdge(graphEdge),
}
end
end
danglers[patternVertex] = dangles
end
-- Now we remove the matched vertices from the graph, while we're at it
-- stash the postions of the removed vertices for when they're replaced by
-- substitute vertices. We also store the graph tags.
local substitutePositions = {}
local graphTags = {}
local map = self.map
for patternVertex, graphVertex in pairs(match) do
substitutePositions[map[patternVertex]] = Vector.new(graphVertex)
graphTags[map[patternVertex]] = graphVertex.tag
graph:removeVertex(graphVertex)
end
-- Add the, initially unconnected, substitute graph vertices.
local substitute = self.substitute
local substituteAABB = graph2D.aabb(substitute)
-- We make copies of the substitute vertices so we need a map from
-- substitute vertices to their copies.
local vertexClones = {}
local insertions = {}
local exterior = self.exterior
local cloneVertex = params.cloneVertex
for substituteVertex, _ in pairs(substitute.vertices) do
local clone = cloneVertex(substituteVertex)
if clone.tag == '-' then
clone.tag = graphTags[substituteVertex]
end
-- If the substitute vertex is replacing a pattern vertex
-- just use the already calculated position.
local position = substitutePositions[substituteVertex]
local projected = false
local draw = nil
if position then
clone.x, clone.y = position.x, position.y
else
-- The substitute vertex is not replacing a current graph vertex
-- so we need to create the position.
if self.start then
-- For start rules we can just map the position from substitute
-- to graph space.
local coord = substituteAABB:lerpTo(substituteVertex, matchAABB)
-- NaN checks.
-- TODO: Use math.finite
assert(coord.x == coord.x)
assert(coord.y == coord.y)
clone.x, clone.y = coord.x, coord.y
else
-- For non-start rules we must take rotation into account.
-- Luckily all non-start rules must have at least one edge in
-- the pattern graph so we can use the edge to orient
-- ourselves.
-- TODO: this doesn't work properly :^(
local patternEdge, patternEndVerts = next(self.pattern.edges)
assert(patternEdge)
local substituteOrigin = Vector.new(map[patternEndVerts[1]])
local substituteBasisX = Vector.to(substituteOrigin, map[patternEndVerts[2]])
substituteBasisX:normalise()
local substituteBasisY = substituteBasisX:perp()
local relSubstitutePos = Vector.to(substituteOrigin, substituteVertex)
local xProj = substituteBasisX:dot(relSubstitutePos)
local yProj = substituteBasisY:dot(relSubstitutePos)
local graphOrigin = Vector.new(match[patternEndVerts[1]])
local graphBasisXDir = Vector.to(graphOrigin, match[patternEndVerts[2]])
local graphBasisX = graphBasisXDir:normal()
local graphBasisY = graphBasisX:perp()
local normedXProj = xProj / math.max(xProj, yProj)
local normedYProj = yProj / math.max(xProj, yProj)
if exterior[substituteVertex] then
normedXProj = normedXProj * meanHostEdgeLength * 0.5
normedYProj = normedYProj * meanHostEdgeLength * 0.5
end
-- graphBasisX:scale(xProj)
-- graphBasisY:scale(yProj)
graphBasisX:scale(normedXProj)
graphBasisY:scale(normedYProj)
local coord = Vector.new {
x = graphOrigin.x + graphBasisX.x + graphBasisY.x,
y = graphOrigin.y + graphBasisX.y + graphBasisY.y,
}
projected = true
if params.replaceYield then
local x11, y11 = graphOrigin.x, graphOrigin.y
local x12, y12 = x11 + graphBasisXDir.x, y11 + graphBasisXDir.y
local x21, y21 = graphOrigin.x, graphOrigin.y
local x22, y22 = x21 + graphBasisX.x, y21 + graphBasisX.y
local x31, y31 = graphOrigin.x, graphOrigin.y
local x32, y32 = x31 + graphBasisY.x, y31 + graphBasisY.y
local x41, y41 = graphOrigin.x, graphOrigin.y
local x42, y42 = coord.x, coord.y
local lines = {
{ x = x11, y = y11 },
{ x = x12, y = y12 },
{ x = x21, y = y21 },
{ x = x22, y = y22 },
{ x = x31, y = y31 },
{ x = x32, y = y32 },
{ x = x11, y = y41 },
{ x = x42, y = y42 },
}
local dummy = next(graph.vertices)
if dummy then
dummy.lines = lines
end
while not gProgress do
coroutine.yield(graph)
end
gProgress = false
if dummy then
dummy.lines = nil
end
end
-- -- NaN checks.
-- assert(coord[1] == coord[1])
-- assert(coord[2] == coord[2])
clone.x, clone.y = coord.x, coord.y
end
end
vertexClones[substituteVertex] = clone
insertions[clone] = true
graph:addVertex(clone)
if params.replaceYield and projected then
while not gProgress do
coroutine.yield(graph)
end
gProgress = false
end
end
-- Now the substitute edges.
-- { [substitute.edge] = fresh copy of the edge }
local mappedEdges = self.mappedEdges
for substituteEdge, substituteEdgeEnds in pairs(substitute.edges) do
local clone = cloneEdge(substituteEdge)
local patternEdge = mappedEdges[substituteEdge]
if patternEdge then
clone.lengthFactor = hostLengthFactors[patternEdge]
assert(clone.lengthFactor)
elseif substituteEdge.subdivide then
assert(clone.lengthFactor)
-- This does slightly improve results...
-- local tax = (meanLengthFactor ~= 1) and 0.75 or 1
-- clone.lengthFactor = clone.lengthFactor * meanLengthFactor * tax
clone.lengthFactor = clone.lengthFactor * meanLengthFactor
end
local substituteVertex1, substituteVertex2 = substituteEdgeEnds[1], substituteEdgeEnds[2]
graph:addEdge(clone, vertexClones[substituteVertex1], vertexClones[substituteVertex2])
end
-- Now the dangling edges.
for patternVertex, dangles in pairs(danglers) do
for _, graphVertexAndEdge in ipairs(dangles) do
local embeddedVertex = vertexClones[map[patternVertex]]
local graphVertex = graphVertexAndEdge.graphVertex
local graphEdge = graphVertexAndEdge.graphEdge
graph:addEdge(graphEdge, embeddedVertex, graphVertex)
end
end
-- Now we move all the non-inserted vertices away from the inserted
-- vertcies. In an attempt to avoid overlaps.
-- NOTE: this makes everything go very wrong...
-- local insertAABB = Vector.keysAABB(insertions)
-- local focus = insertAABB:centre()
-- local scale = 1.25
-- for graphVertex, _ in pairs(graph.vertices) do
-- if not insertions[graphVertex] then
-- local disp = Vector.to(focus, graphVertex)
-- disp:scale(scale)
-- graphVertex[1] = focus[1] + disp[1]
-- graphVertex[2] = focus[2] + disp[2]
-- end
-- end
if params.replaceYield then
while not gProgress do
coroutine.yield(graph)
end
gProgress = false
end
local finish = love.timer.getTime()
printf(' replace:%.4fs', finish-start)
-- Now make it pretty.
local springStrength = params.springStrength
local edgeLength = params.edgeLength
local repulsion = params.repulsion
local maxDelta = params.maxDelta
local convergenceDistance = params.convergenceDistance
local yield = params.drawYield
graph2D.forceDraw(graph, springStrength, edgeLength, repulsion, maxDelta, convergenceDistance, yield)
end
-- TODO: this is only used on substitute vertices, rename to highlight that.
local function _defaultCloneVertex( vertex )
return {
x = vertex.x,
y = vertex.y,
tag = vertex.tag
}
end
-- TODO: this is only used on substitute edges, rename to highlight that.
local function _defaultCloneEdge( edge )
return {
cosmetic = edge.cosmetic,
lengthFactor = edge.lengthFactor,
subdivide = edge.subdivide,
}
end
function GraphGrammar.new( params )
local rules = params.rules
local cloneVertex = params.cloneVertex or _defaultCloneVertex
local cloneEdge = params.cloneEdge or _defaultCloneEdge
local springStrength = params.springStrength or 1
local edgeLength = params.edgeLength or 50
local repulsion = params.repulsion or 1
local maxDelta = params.maxDelta or 1
local convergenceDistance = params.convergenceDistance or 2
local drawYield = params.drawYield or false
local replaceYield = params.replaceYield or false
local numStartRules = 0
local tags = {}
for name, rule in pairs(rules) do
if rule.start then
numStartRules = numStartRules + 1
end
for tag, _ in pairs(rule.tags) do
tags[tag] = true
end
end
assert(numStartRules > 0)
local result = {
rules = rules,
tags = tags,
cloneVertex = cloneVertex,
cloneEdge = cloneEdge,
springStrength = springStrength,
edgeLength = edgeLength,
repulsion = repulsion,
maxDelta = maxDelta,
convergenceDistance = convergenceDistance,
drawYield = drawYield,
replaceYield = replaceYield,
}
setmetatable(result, GraphGrammar)
return result
end
function GraphGrammar:build( maxIterations, minVertices, maxVertices, maxValence, metarules )
assert(0 < minVertices)
assert(minVertices <= maxVertices)
assert(math.floor(minVertices) == minVertices)
assert(math.floor(maxVertices) == maxVertices)
metarules = metarules or {
max = {},
}
local graph = Graph.new()
graph:addVertex { x = 0, y = 0, tag = 's' }
local numVertices = 1
local rules = self.rules
local totalTime = 0
local stats = {}
-- Map of rule names to the number of times the rule has been applied.
local numUses = {}
for name, rule in pairs(rules) do
numUses[name] = 0
end
for iteration = 1, maxIterations do
local start = love.timer.getTime()
local rulesMatches = {}
printf('#%d', iteration)
local totalMatches = 0
local ticker = {}
for name, rule in pairs(rules) do
if numVertices + rule.vertexDelta > maxVertices then
printf(' %s would pop vertex count', name)
elseif numUses[name] == metarules.max[name] then
printf(' %s has reached its quote of %d uses', name, metarules.max[name])
else
local success, matches = rule:matches(graph, maxValence)
if success then
totalMatches = totalMatches + #matches
ticker[#ticker+1] = string.format("%s=%d", name, #matches)
rulesMatches[#rulesMatches+1] = {
name = name,
rule = rule,
matches = matches
}
else
ticker[#ticker+1] = string.format("%s=0", name)
end
printf(' %s #%d', name, not success and 0 or #matches)
end
end
-- If we have zero matches then we cannot progress. Another iteration
-- has no chance of getting more matches.
local stalled = #rulesMatches == 0
local enoughVertices = numVertices >= minVertices
if stalled then
if not enoughVertices then
error('bulidng has stalled without enough vertices')
end
else
local ruleMatch = rulesMatches[math.random(1, #rulesMatches)]
printf(' %s', ruleMatch.name)
local match = ruleMatch.matches[math.random(1, #ruleMatch.matches)]
if self.replaceYield then
while not gProgress do
coroutine.yield(graph)
end
gProgress = false
end
ruleMatch.rule:replace(graph, match, self)
stats[#stats+1] = {
rule = ruleMatch.name,
ticker = table.concat(ticker, ","),
totalMatches = totalMatches,
}
numUses[ruleMatch.name] = numUses[ruleMatch.name] + 1
numVertices = numVertices + ruleMatch.rule.vertexDelta
end
local finish = love.timer.getTime()
local duration = finish - start
totalTime = totalTime + duration
for iteration, stat in pairs(stats) do
printf(' #%d %s (%d) - %s', iteration, stat.rule, stat.totalMatches, stat.ticker)
end
printf(' %.2fs', duration)
if numVertices == maxVertices or (stalled and enoughVertices) then
break
end
end
printf(' total:%.2fs', totalTime)
return graph
end
| bsd-3-clause |
dr01d3r/darkstar | scripts/globals/regimeinfo.lua | 35 | 13239 | -------------------------------------------------
--
-- Regime Info Database
--
-- Stores details on the number of monsters to kill
-- as well as the suggested level range.
-- n1,n2,n3,n4 = Number of monsters needed
-- sl = Start Level range
-- el = Level range
--
-- Example:
-- n1=6, n2=0, n3=0, n4=0, sl=1, el=6, Regime ID=1, produces:
-- Defeat the following monsters:
-- 6 Worms
-- Level range 1 ~ 6
-- Area: West Ronfaure
-------------------------------------------------
function getRegimeInfo(regimeid)
local regimeinfo = {
[1] = {6,0,0,0,1,6},
[2] = {6,0,0,0,2,6},
[3] = {5,1,0,0,4,7},
[4] = {4,2,0,0,4,8},
[5] = {3,3,0,0,8,12},
[6] = {8,0,0,0,12,13},
[7] = {7,1,0,0,15,19},
[8] = {6,2,0,0,15,22},
[9] = {5,3,0,0,18,23},
[10] = {4,4,0,0,20,23},
[11] = {9,0,0,0,21,22},
[12] = {8,1,0,0,21,23},
[13] = {7,2,0,0,22,25},
[14] = {6,3,0,0,24,25},
[15] = {4,3,0,0,25,28},
[16] = {6,0,0,0,1,6},
[17] = {6,0,0,0,3,6},
[18] = {5,1,0,0,3,7},
[19] = {4,2,0,0,3,8},
[20] = {3,3,0,0,10,12},
[21] = {9,0,0,0,20,21},
[22] = {8,1,0,0,20,22},
[23] = {7,2,0,0,21,23},
[24] = {6,3,0,0,22,25},
[25] = {4,3,0,0,25,28},
[26] = {6,0,0,0,1,5},
[27] = {6,0,0,0,2,5},
[28] = {5,1,0,0,3,8},
[29] = {4,2,0,0,4,8},
[30] = {3,3,0,0,7,12},
[31] = {8,0,0,0,11,13},
[32] = {7,1,0,0,15,19},
[33] = {6,2,0,0,15,23},
[34] = {5,3,0,0,20,24},
[35] = {4,4,0,0,21,24},
[36] = {9,0,0,0,20,21},
[37] = {8,1,0,0,20,22},
[38] = {7,2,0,0,21,23},
[39] = {6,3,0,0,22,25},
[40] = {4,3,0,0,25,28},
-- Regime between 41-50
[41] = {9,1,0,0,26,29},
[42] = {8,2,0,0,26,29},
[43] = {7,3,0,0,28,29},
[44] = {6,4,0,0,28,30},
[45] = {5,4,1,0,28,34},
[46] = {9,2,0,0,34,38},
[47] = {8,3,0,0,34,39},
[48] = {7,4,0,0,37,42},
[49] = {6,4,1,0,37,43},
[50] = {5,4,2,0,40,43},
[51] = {9,3,0,0,42,46},
[52] = {8,4,0,0,42,45},
[53] = {7,4,1,0,42,48},
[54] = {6,4,2,0,42,48},
[55] = {5,4,3,0,45,52},
[56] = {6,1,0,0,4,8},
[57] = {4,2,0,0,22,25},
[58] = {8,2,0,0,15,18},
[59] = {3,4,0,0,3,8},
[60] = {5,4,1,0,22,25},
[61] = {4,2,0,0,4,8},
[62] = {4,3,0,0,22,27},
[63] = {3,5,0,0,25,27},
[64] = {6,0,0,0,1,5},
[65] = {6,0,0,0,2,5},
[66] = {7,0,0,0,2,6},
[67] = {4,2,0,0,3,6},
[68] = {4,2,0,0,4,8},
[69] = {3,5,0,0,11,13},
[70] = {5,3,0,0,11,14},
[71] = {5,3,0,0,10,15},
[72] = {5,2,0,0,23,26},
[73] = {5,2,0,0,23,28},
[74] = {5,2,2,0,26,32},
[75] = {9,0,0,0,31,32},
[76] = {6,0,0,0,1,6},
[77] = {7,0,0,0,2,5},
[78] = {3,3,0,0,3,6},
[79] = {7,0,0,0,3,6},
[80] = {5,2,0,0,4,8},
[81] = {4,2,0,0,8,11},
[82] = {4,2,0,0,9,12},
[83] = {6,0,0,0,9,15},
[84] = {2,2,2,0,12,14},
[85] = {5,2,0,0,25,26},
[86] = {6,2,0,0,26,32},
[87] = {6,2,0,0,27,33},
[88] = {5,0,0,0,36,37},
[89] = {6,0,0,0,1,6},
[90] = {6,0,0,0,1,8},
-- Regime 91-100
[91] = {6,0,0,0,2,6},
[92] = {4,2,0,0,3,6},
[93] = {4,3,0,0,3,6},
[94] = {4,2,0,0,7,11},
[95] = {3,3,0,0,8,12},
[96] = {3,4,0,0,12,16},
[97] = {4,4,0,0,26,32},
[98] = {2,5,0,0,26,34},
[99] = {3,5,0,0,27,33},
[100] = {5,3,0,0,36,38},
[101] = {3,2,0,0,41,44},
[102] = {3,2,0,0,41,46},
[103] = {3,2,0,0,43,47},
[104] = {4,4,0,0,62,66},
[105] = {4,5,0,0,64,68},
[106] = {4,5,0,0,64,69},
[107] = {7,3,0,0,66,74},
[108] = {4,5,0,0,71,79},
[109] = {10,0,0,0,30,34},
[110] = {3,1,7,0,35,40},
[111] = {3,1,7,0,35,44},
[112] = {5,2,2,1,44,49},
[113] = {3,3,2,1,45,49},
[114] = {7,2,0,0,40,44},
[115] = {7,3,0,0,41,46},
[116] = {7,3,0,0,41,46},
[117] = {7,3,0,0,42,47},
[118] = {3,5,0,0,44,50},
[119] = {3,3,0,0,60,65},
[120] = {7,0,0,0,64,69},
[121] = {7,0,0,0,65,69},
[122] = {6,1,0,0,78,82},
[123] = {6,1,0,0,79,82},
[124] = {4,5,0,0,30,35},
[125] = {7,4,0,0,32,37},
[126] = {10,0,0,0,34,36},
[127] = {4,6,0,0,34,38},
[128] = {4,6,0,0,34,41},
[129] = {3,6,0,0,35,39},
[130] = {3,6,0,0,35,40},
[131] = {10,0,0,0,40,44},
[132] = {7,3,0,0,40,46},
[133] = {10,0,0,0,45,49},
[134] = {7,3,0,0,40,45},
[135] = {5,1,4,0,44,49},
[136] = {10,1,0,0,47,53},
[137] = {2,8,0,0,51,56},
[138] = {4,6,0,0,54,58},
[139] = {5,2,0,0,66,72},
[140] = {5,1,0,0,66,74},
-- Regime 140-146
[141] = {4,1,0,0,69,74},
[142] = {8,3,0,0,72,76},
[143] = {8,3,0,0,73,78},
[144] = {11,0,0,0,75,78},
[145] = {2,2,2,0,78,79},
[146] = {2,2,2,0,78,79},
-- ---------------------------------------------------------
-- I know they prevent FoV/GoV page sign-up and FoV/GoV prevent registry.
-- Need confirmation of retail behavior - Do they display in menu?
-- ---------------------------------------------------------
-- I'm pretty sure you can have an active page and OP at same time.
-- They might still display on the review option though.
-- ---------------------------------------------------------
[602] = {4,1,0,0,3,5},
[603] = {5,1,0,0,25,30},
[604] = {4,2,0,0,26,30},
[605] = {4,2,0,0,26,30},
[606] = {4,2,0,0,30,34},
[607] = {5,2,0,0,87,92},
[608] = {3,3,0,0,88,90},
[609] = {3,3,0,0,88,90},
[610] = {5,0,0,0,52,54},
[611] = {4,2,0,0,52,59},
[612] = {5,1,0,0,56,63},
[613] = {9,0,0,0,65,68},
[614] = {6,1,0,0,94,97},
[615] = {6,1,0,0,95,97},
[616] = {6,0,0,0,96,97},
[617] = {2,5,0,0,95,99},
[618] = {3,3,0,0,47,52},
[619] = {2,2,2,0,52,57},
[620] = {3,3,0,0,53,57},
[621] = {3,4,0,0,60,65},
[622] = {4,3,0,0,95,97},
[623] = {5,2,0,0,95,98},
[624] = {5,2,0,0,96,98},
[625] = {8,2,0,0,94,99},
[626] = {3,0,0,0,1,3},
[627] = {3,0,0,0,2,4},
[628] = {5,2,0,0,75,78},
[629] = {5,2,0,0,75,79},
[630] = {5,2,0,0,75,80},
[631] = {3,3,0,0,3,8},
[632] = {4,2,0,0,5,11},
[633] = {2,2,2,0,12,16},
[634] = {3,3,0,0,14,17},
[635] = {2,2,2,0,21,23},
[636] = {6,1,0,0,78,80},
[637] = {5,2,0,0,77,80},
[638] = {5,2,0,0,80,83},
[639] = {4,1,0,0,3,8},
[640] = {3,2,0,0,5,9},
[641] = {3,2,0,0,11,14},
-- 642-651
[642] = {4,2,0,0,86,89},
[643] = {5,2,0,0,86,90},
[644] = {5,2,0,0,86,90},
[645] = {2,2,2,0,90,91},
[646] = {5,2,0,0,90,93},
[647] = {2,3,0,0,1,6},
[648] = {2,3,0,0,1,7},
[649] = {3,2,0,0,15,20},
[650] = {4,2,0,0,22,26},
[651] = {3,3,0,0,78,82},
[652] = {3,3,0,0,79,82},
[653] = {2,4,0,0,81,83},
[654] = {2,4,0,0,81,84},
[655] = {3,3,0,0,18,21},
[656] = {4,2,0,0,21,27},
[657] = {5,1,0,0,17,26},
[658] = {3,3,0,0,23,26},
[659] = {4,2,0,0,26,28},
[660] = {4,1,0,0,29,34},
[661] = {3,3,0,0,84,86},
[662] = {3,3,0,0,86,88},
[663] = {1,1,1,1,10,14},
[664] = {1,1,1,1,15,19},
[665] = {1,1,1,1,20,24},
[666] = {1,1,1,1,25,29},
[667] = {1,1,1,1,30,34},
[668] = {1,1,1,1,35,39},
[669] = {5,1,0,0,81,85},
[670] = {5,1,0,0,82,85},
[671] = {6,0,0,0,42,46},
[672] = {6,0,0,0,46,49},
[673] = {4,2,0,0,51,54},
[674] = {5,1,0,0,50,55},
[675] = {3,3,0,0,53,56},
[676] = {3,3,0,0,60,63},
[677] = {3,3,0,0,91,95},
[678] = {3,3,0,0,91,95},
[679] = {6,0,0,0,20,27},
[680] = {2,4,0,0,20,24},
[681] = {2,4,0,0,21,26},
[682] = {2,2,2,0,28,31},
[683] = {3,3,0,0,30,34},
[684] = {3,3,0,0,32,36},
[685] = {2,5,0,0,85,87},
[686] = {2,5,0,0,85,89},
[687] = {3,3,0,0,40,44},
[688] = {3,3,0,0,45,49},
[689] = {3,3,0,0,49,52},
[690] = {4,2,0,0,50,54},
[691] = {2,2,2,0,53,58},
-- 691-701
[692] = {3,3,0,0,59,63},
[693] = {4,3,0,0,91,93},
[694] = {4,3,0,0,92,96},
[695] = {3,2,0,0,15,18},
[696] = {4,2,0,0,18,23},
[697] = {2,4,0,0,22,26},
[698] = {2,4,0,0,26,31},
[699] = {4,2,0,0,26,31},
[700] = {5,1,0,0,27,33},
[701] = {3,3,0,0,83,85},
[702] = {3,3,0,0,86,88},
[703] = {4,2,0,0,40,43},
[704] = {4,2,0,0,40,44},
[705] = {2,4,0,0,46,49},
[706] = {4,2,0,0,51,55},
[707] = {3,3,0,0,52,58},
[708] = {2,2,1,0,59,62},
[709] = {5,2,0,0,91,96},
[710] = {4,3,0,0,92,96},
[711] = {4,2,0,0,40,43},
[712] = {4,2,0,0,43,46},
[713] = {5,1,0,0,50,55},
[714] = {4,2,0,0,50,56},
[715] = {5,1,0,0,50,58},
[716] = {3,3,0,0,59,63},
[717] = {4,2,0,0,95,99},
[718] = {4,3,0,0,95,99},
[719] = {3,3,0,0,60,63},
[720] = {4,3,0,0,62,66},
[721] = {4,3,0,0,62,67},
[722] = {4,2,0,0,72,75},
[723] = {3,4,0,0,72,76},
[724] = {4,3,0,0,72,78},
[725] = {3,3,0,0,74,78},
[726] = {2,2,2,0,102,105},
[727] = {2,4,0,0,20,26},
[728] = {3,3,0,0,22,30},
[729] = {4,2,0,0,23,31},
[730] = {6,0,0,0,28,31},
[731] = {3,3,0,0,29,33},
[732] = {4,0,0,0,30,33},
[733] = {6,0,0,0,35,37},
[734] = {4,3,0,0,87,91},
[735] = {3,3,0,0,60,64},
[736] = {5,1,0,0,60,66},
[737] = {3,3,0,0,60,66},
[738] = {4,2,0,0,60,67},
[739] = {3,3,0,0,63,69},
[740] = {3,3,0,0,65,69},
[741] = {3,3,0,0,77,80},
-- 741-751
[742] = {3,3,0,0,99,103},
[743] = {10,0,0,0,72,72},
[744] = {7,0,0,0,74,77},
[745] = {7,0,0,0,75,78},
[746] = {7,0,0,0,76,79},
[747] = {7,0,0,0,77,80},
[748] = {6,0,0,0,79,80},
[749] = {10,0,0,0,71,71},
[750] = {6,0,0,0,71,74},
[751] = {7,0,0,0,75,80},
[752] = {7,0,0,0,77,82},
[753] = {7,0,0,0,79,82},
[754] = {7,0,0,0,81,84},
[755] = {4,1,0,0,61,68},
[756] = {4,1,0,0,61,68},
[757] = {4,1,0,0,62,69},
[758] = {3,2,0,0,62,73},
[759] = {3,2,0,0,62,73},
[760] = {4,2,0,0,69,74},
[761] = {4,2,0,0,71,78},
[762] = {4,2,0,0,71,78},
[763] = {2,2,1,0,44,49},
[764] = {2,2,2,0,45,49},
[765] = {3,2,1,0,65,68},
[766] = {3,3,0,0,73,76},
[767] = {5,1,0,0,75,78},
[768] = {5,1,0,0,75,79},
[769] = {4,2,0,0,76,80},
[770] = {5,2,0,0,100,103},
[771] = {2,3,0,0,45,49},
[772] = {3,2,0,0,50,53},
[773] = {3,2,0,0,50,54},
[774] = {3,2,0,0,55,59},
[775] = {4,1,0,0,70,74},
[776] = {4,2,0,0,95,98},
[777] = {3,3,0,0,25,30},
[778] = {3,3,0,0,25,30},
[779] = {3,3,0,0,25,30},
[780] = {4,2,0,0,25,32},
[781] = {4,2,0,0,25,35},
[782] = {4,3,0,0,25,34},
[783] = {4,3,0,0,25,34},
[784] = {4,4,0,0,30,34},
[785] = {6,0,0,0,34,35},
[786] = {2,2,2,0,62,69},
[787] = {2,2,2,0,62,69},
[788] = {2,2,2,0,65,69},
[789] = {2,2,2,0,65,69},
[790] = {3,3,0,0,51,57},
[791] = {4,2,0,0,51,57},
[792] = {4,2,0,0,51,57},
[793] = {3,3,0,0,61,63},
-- 793-803
[794] = {3,3,0,0,61,67},
[795] = {3,3,0,0,61,68},
[796] = {3,3,0,0,60,64},
[797] = {4,2,0,0,60,67},
[798] = {6,0,0,0,62,69},
[799] = {4,2,0,0,62,69},
[800] = {4,2,0,0,62,76},
[801] = {5,1,0,0,73,81},
[802] = {3,3,0,0,74,79},
[803] = {4,2,0,0,75,80},
[804] = {3,3,0,0,35,39},
[805] = {2,4,0,0,37,41},
[806] = {5,1,0,0,41,45},
[807] = {4,2,0,0,43,48},
[808] = {4,2,0,0,44,48},
[809] = {3,3,0,0,62,67},
[810] = {3,3,0,0,62,69},
[811] = {3,3,0,0,66,69},
[812] = {3,3,0,0,51,55},
[813] = {3,3,0,0,51,58},
[814] = {3,3,0,0,51,59},
[815] = {7,0,0,0,52,59},
[816] = {3,3,0,0,52,59},
[817] = {3,3,0,0,56,59},
[818] = {3,3,0,0,62,65},
[819] = {3,3,0,0,65,69},
};
local a = {0,0,0,0,0,0};
if regimeinfo[regimeid] then
return regimeinfo[regimeid];
else
-- print("Warning: Regime ID not found! Returning blank array.");
return a;
end
end; | gpl-3.0 |
waruqi/xmake | xmake/plugins/project/clang/compile_flags.lua | 1 | 3043 | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author luzhlon
-- @file compile_flags.lua
--
-- imports
import("core.tool.compiler")
import("core.project.project")
import("core.language.language")
-- make the object
function _make_object(target, sourcefile, objectfile)
-- get the source file kind
local sourcekind = language.sourcekind_of(sourcefile)
-- make the object for the *.o/obj? ignore it directly
if sourcekind == "obj" or sourcekind == "lib" then
return
end
-- get compile arguments
local arguments = compiler.compflags(sourcefile, {target = target})
for i, flag in ipairs(arguments) do
-- only export the -I*/-D* flags
if not g_flags[flag] and string.find(flag, '^-[ID]') then
g_flags[flag] = true
table.insert(g_flags, flag)
end
end
-- clear first line marks
_g.firstline = false
end
-- make objects
function _make_objects(target, sourcekind, sourcebatch)
for index, objectfile in ipairs(sourcebatch.objectfiles) do
_make_object(target, sourcebatch.sourcefiles[index], objectfile)
end
end
-- make target
function _make_target(target)
-- TODO
-- disable precompiled header first
target:set("pcheader", nil)
target:set("pcxxheader", nil)
-- build source batches
for _, sourcebatch in pairs(target:sourcebatches()) do
local sourcekind = sourcebatch.sourcekind
if sourcekind then
_make_objects(target, sourcekind, sourcebatch)
end
end
end
-- make all
function _make_all()
-- make flags
_g.firstline = true
for _, target in pairs(project.targets()) do
local isdefault = target:get("default")
if not target:isphony() and (isdefault == nil or isdefault == true) then
_make_target(target)
end
end
end
-- generate compilation databases for clang-based tools(compile_flags.txt)
--
-- references:
-- - https://clang.llvm.org/docs/JSONCompilationDatabase.html
--
function make(outputdir)
-- enter project directory
local oldir = os.cd(os.projectdir())
-- make all
g_flags = {}
_make_all()
-- write to file
local flagfile = io.open(path.join(outputdir, "compile_flags.txt"), "w")
for i, flag in ipairs(g_flags) do
flagfile:write(flag, '\n')
end
flagfile:close()
-- leave project directory
os.cd(oldir)
end
| apache-2.0 |
thegrb93/wire | lua/wire/server/modelplug.lua | 8 | 1037 | ModelPlugInfo = {}
--uncomment line 15 and line 26-34 to enable sending model packs to clients
function ModelPlug_Register(category)
if (not ModelPlugInfo[category]) then
local catinfo = {}
local packs = file.Find("WireModelPacks/*.txt", "DATA")
for _,filename in pairs(packs) do
--resource.AddFile("data/WireModelPacks/" .. filename)
local packtbl = util.KeyValuesToTable(file.Read("WireModelPacks/" .. filename) or {})
for name,entry in pairs(packtbl) do
local categorytable = string.Explode(",", entry.categories or "none") or { "none" }
for _,cat in pairs(categorytable) do
if (cat == category) then
catinfo[name] = entry.model or ""
--[[if (entry.model) then
resource.AddFile(entry.model)
end
if (entry.files) then
for _,extrafilename in pairs(entry.files) do
resource.AddFile(extrafilename)
end
end]]
break
end
end
end
end
ModelPlugInfo[category] = catinfo
end
end
| apache-2.0 |
dr01d3r/darkstar | scripts/zones/Jugner_Forest_[S]/mobs/Lobison.lua | 17 | 1817 | -----------------------------------
-- Area: Jugner Forest (S)
-- NPC: Lobison
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local changeTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if (roamChance > 100-roamMoonPhase) then
if (mob:AnimationSub() == 0 and os.time() - changeTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif (mob:AnimationSub() == 1 and os.time() - changeTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if (chance > 100-moonPhase) then
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
| gpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c73018302.lua | 6 | 1731 | --黒羽を狩る者
function c73018302.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(73018302,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c73018302.descon)
e1:SetCost(c73018302.descost)
e1:SetTarget(c73018302.destg)
e1:SetOperation(c73018302.desop)
c:RegisterEffect(e1)
end
function c73018302.check(tp)
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
if g:GetCount()<2 then return false end
local rac=g:GetFirst():GetRace()
local tc=g:GetNext()
while tc do
if tc:GetRace()~=rac then return false end
tc=g:GetNext()
end
return true
end
function c73018302.descon(e,tp,eg,ep,ev,re,r,rp)
return c73018302.check(tp)
end
function c73018302.descost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsAbleToGraveAsCost,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,Card.IsAbleToGraveAsCost,1,1,REASON_COST)
end
function c73018302.filter(c)
return c:IsFaceup()
end
function c73018302.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c73018302.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c73018302.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c73018302.filter,tp,0,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c73018302.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) and c73018302.check(tp) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
dr01d3r/darkstar | scripts/zones/Altar_Room/npcs/Magicite.lua | 14 | 1682 | -----------------------------------
-- Area: Altar Room
-- NPC: Magicite
-- Involved in Mission: Magicite
-- @zone 152
-- @pos -344 25 43
-----------------------------------
package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Altar_Room/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_ORASTONE) == false) then
if (player:getVar("MissionStatus") < 4) then
player:startEvent(0x002c,1); -- play Lion part of the CS (this is first magicite)
else
player:startEvent(0x002c); -- don't play Lion part of the CS
end
else
player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY);
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 == 0x002c) then
player:setVar("MissionStatus",4);
player:addKeyItem(MAGICITE_ORASTONE);
player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_ORASTONE);
end
end; | gpl-3.0 |
retep998/Vana | scripts/npcs/subway_in.lua | 2 | 4025 | --[[
Copyright (C) 2008-2016 Vana Development Team
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 Street, Fifth Floor, Boston, MA 02110-1301, USA.
--]]
-- The Ticket Gate, collects tickets for Kerning Jump Quests and for NLC Subway
dofile("scripts/utils/boatHelper.lua");
dofile("scripts/utils/npcHelper.lua");
dofile("scripts/utils/tableHelper.lua");
jumpTicketB1 = getItemAmount(4031036);
jumpTicketB2 = getItemAmount(4031037);
jumpTicketB3 = getItemAmount(4031038);
nlcTicketBasic = getItemAmount(4031710);
nlcTicketRegular = getItemAmount(4031711);
addText("Here's the ticket reader. ");
if jumpTicketB1 > 0 or jumpTicketB2 > 0 or jumpTicketB3 > 0 or nlcTicketBasic > 0 or nlcTicketRegular > 0 then
choices = {};
if jumpTicketB1 > 0 then
append(choices, makeChoiceHandler("Construction site B1", function()
giveItem(4031036, -1);
setMap(103000900);
end));
end
if jumpTicketB2 > 0 then
append(choices, makeChoiceHandler("Construction site B2", function()
giveItem(4031037, -1);
setMap(103000903);
end));
end
if jumpTicketB3 > 0 then
append(choices, makeChoiceHandler("Construction site B3", function()
giveItem(4031038, -1);
setMap(103000906);
end));
end
nlcChoice = nil;
if nlcTicketBasic > 0 then
nlcChoice = "New Leaf city (Basic)";
elseif nlcTicketRegular > 0 then
nlcChoice = "New Leaf city (Normal)";
end
if nlcChoice ~= nil then
append(choices, makeChoiceHandler(nlcChoice, function()
if setInstance("kerningToNlcBoarding") then
minutesRemaining = getInstanceMinutes();
if minutesRemaining == 0 then
addText("We will begin boarding 5 minutes before the takeoff. ");
addText("Please be patient and wait for a few minutes. ");
addText("Be aware that the subway will take off right on time, and we stop receiving tickets 1 minute before that, so please make sure to be here on time.");
sendNext();
elseif minutesRemaining == 1 then
addText("This subway is getting ready for takeoff. ");
addText("I'm sorry, but you'll have to get on the next ride. ");
addText("The ride schedule is available through the usher at the ticketing booth.");
sendNext();
else
addText("It looks like there's plenty of room for this ride. ");
addText("Please have your ticket ready so I can let you in. ");
addText("The ride will be long, but you'll get to your destination just fine. ");
addText("What do you think? ");
addText("Do you want to get on this ride?");
answer = askYesNo();
if answer == answer_yes then
item = nil;
if nlcTicketBasic > 0 then item = 4031710;
else item = 4031711;
end
giveItem(item, -1);
setMap(600010004);
elseif answer == answer_no then
addText("You must have some business to take care of here, right?");
sendNext();
end
end
revertInstance();
else
addText("We will begin boarding 5 minutes before the takeoff. ");
addText("Please be patient and wait for a few minutes. ");
addText("Be aware that the subway will take off right on time, and we stop receiving tickets 1 minute before that, so please make sure to be here on time.");
sendNext();
end
end));
end
addText("You will be brought in immediately. ");
addText("Which ticket would you like to use?\r\n");
addText(blue(choiceRef(choices)));
choice = askChoice();
selectChoice(choices, choice);
else
addText("You are not allowed in without the ticket.");
sendOk();
end | gpl-2.0 |
koreader/koreader | plugins/kosync.koplugin/KOSyncClient.lua | 4 | 4837 | local UIManager = require("ui/uimanager")
local DEBUG = require("dbg")
local KOSyncClient = {
service_spec = nil,
custom_url = nil,
}
function KOSyncClient:new(o)
if o == nil then o = {} end
setmetatable(o, self)
self.__index = self
if o.init then o:init() end
return o
end
function KOSyncClient:init()
require("socket.http").TIMEOUT = 1
local Spore = require("Spore")
self.client = Spore.new_from_spec(self.service_spec, {
base_url = self.custom_url,
})
package.loaded['Spore.Middleware.GinClient'] = {}
require('Spore.Middleware.GinClient').call = function(_, req)
req.headers['accept'] = "application/vnd.koreader.v1+json"
end
package.loaded['Spore.Middleware.KOSyncAuth'] = {}
require('Spore.Middleware.KOSyncAuth').call = function(args, req)
req.headers['x-auth-user'] = args.username
req.headers['x-auth-key'] = args.userkey
end
package.loaded['Spore.Middleware.AsyncHTTP'] = {}
require('Spore.Middleware.AsyncHTTP').call = function(args, req)
-- disable async http if Turbo looper is missing
if not UIManager.looper then return end
req:finalize()
local result
require("httpclient"):new():request({
url = req.url,
method = req.method,
body = req.env.spore.payload,
on_headers = function(headers)
for header, value in pairs(req.headers) do
if type(header) == 'string' then
headers:add(header, value)
end
end
end,
}, function(res)
result = res
-- Turbo HTTP client uses code instead of status
-- change to status so that Spore can understand
result.status = res.code
coroutine.resume(args.thread)
end)
return coroutine.create(function() coroutine.yield(result) end)
end
end
function KOSyncClient:register(username, password)
self.client:reset_middlewares()
self.client:enable('Format.JSON')
self.client:enable("GinClient")
local ok, res = pcall(function()
return self.client:register({
username = username,
password = password,
})
end)
if ok then
return res.status == 201, res.body
else
DEBUG(ok, res)
return false, res.body
end
end
function KOSyncClient:authorize(username, password)
self.client:reset_middlewares()
self.client:enable('Format.JSON')
self.client:enable("GinClient")
self.client:enable("KOSyncAuth", {
username = username,
userkey = password,
})
local ok, res = pcall(function()
return self.client:authorize()
end)
if ok then
return res.status == 200, res.body
else
DEBUG("err:", res)
return false, res.body
end
end
function KOSyncClient:update_progress(
username,
password,
document,
progress,
percentage,
device,
device_id,
callback)
self.client:reset_middlewares()
self.client:enable('Format.JSON')
self.client:enable("GinClient")
self.client:enable("KOSyncAuth", {
username = username,
userkey = password,
})
local co = coroutine.create(function()
local ok, res = pcall(function()
return self.client:update_progress({
document = document,
progress = tostring(progress),
percentage = percentage,
device = device,
device_id = device_id,
})
end)
if ok then
callback(res.status == 200, res.body)
else
DEBUG("err:", res)
callback(false, res.body)
end
end)
self.client:enable("AsyncHTTP", {thread = co})
coroutine.resume(co)
if UIManager.looper then UIManager:setInputTimeout() end
end
function KOSyncClient:get_progress(
username,
password,
document,
callback)
self.client:reset_middlewares()
self.client:enable('Format.JSON')
self.client:enable("GinClient")
self.client:enable("KOSyncAuth", {
username = username,
userkey = password,
})
local co = coroutine.create(function()
local ok, res = pcall(function()
return self.client:get_progress({
document = document,
})
end)
if ok then
callback(res.status == 200, res.body)
else
DEBUG("err:", res)
callback(false, res.body)
end
end)
self.client:enable("AsyncHTTP", {thread = co})
coroutine.resume(co)
if UIManager.looper then UIManager:setInputTimeout() end
end
return KOSyncClient
| agpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c71934924.lua | 5 | 1597 | --疾風!凶殺陣
function c71934924.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--damage cal
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_BATTLED)
e2:SetOperation(c71934924.atop)
c:RegisterEffect(e2)
--atkup
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_DAMAGE_STEP_END)
e3:SetOperation(c71934924.upop)
c:RegisterEffect(e3)
end
function c71934924.check(c,tp)
return c and c:IsSetCard(0x3d) and c:IsControler(tp)
end
function c71934924.atop(e,tp,eg,ep,ev,re,r,rp)
if c71934924.check(Duel.GetAttacker(),tp) or c71934924.check(Duel.GetAttackTarget(),tp) then
e:GetHandler():RegisterFlagEffect(71934924,RESET_PHASE+PHASE_DAMAGE,0,1)
end
end
function c71934924.filter(c)
return c:IsFaceup() and c:IsSetCard(0x3d) and c:GetFlagEffect(71934924)==0
end
function c71934924.upop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:GetFlagEffect(71934924)==0 then return end
local g=Duel.GetMatchingGroup(c71934924.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(300)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
tc:RegisterFlagEffect(71934924,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
tc=g:GetNext()
end
end
| gpl-2.0 |
soundsrc/premake-stable | tests/project/test_vpaths.lua | 51 | 3834 | --
-- tests/project/test_vpaths.lua
-- Automated test suite for the project support functions.
-- Copyright (c) 2011-2012 Jason Perkins and the Premake project
--
T.project_vpaths = { }
local suite = T.project_vpaths
local project = premake.project
--
-- Setup and teardown
--
local sln
function suite.setup()
sln = test.createsolution()
end
local function run()
premake.bake.buildconfigs()
local prj = premake.solution.getproject(sln, 1)
local cfg = premake.getconfig(prj, "Debug")
return project.getvpath(prj, cfg.files[1])
end
--
-- Test simple replacements
--
function suite.ReturnsOriginalPath_OnNoVpaths()
files { "hello.c" }
test.isequal("hello.c", run())
end
function suite.ReturnsOriginalPath_OnNoMatches()
files { "hello.c" }
vpaths { ["Headers"] = "**.h" }
test.isequal("hello.c", run())
end
function suite.CanStripPaths()
files { "src/myproject/hello.c" }
vpaths { [""] = "src" }
run()
test.isequal("hello.c", run())
end
function suite.CanTrimLeadingPaths()
files { "src/myproject/hello.c" }
vpaths { ["*"] = "src" }
test.isequal("myproject/hello.c", run())
end
function suite.PatternMayIncludeTrailingSlash()
files { "src/myproject/hello.c" }
vpaths { [""] = "src/myproject/" }
test.isequal("hello.c", run())
end
function suite.SimpleReplacementPatterns()
files { "src/myproject/hello.c" }
vpaths { ["sources"] = "src/myproject" }
test.isequal("sources/hello.c", run())
end
function suite.ExactFilenameMatch()
files { "src/hello.c" }
vpaths { ["sources"] = "src/hello.c" }
test.isequal("sources/hello.c", run())
end
--
-- Test wildcard patterns
--
function suite.MatchFilePattern_ToGroup_Flat()
files { "src/myproject/hello.h" }
vpaths { ["Headers"] = "**.h" }
test.isequal("Headers/hello.h", run())
end
function suite.MatchFilePattern_ToNone_Flat()
files { "src/myproject/hello.h" }
vpaths { [""] = "**.h" }
test.isequal("hello.h", run())
end
function suite.MatchFilePattern_ToNestedGroup_Flat()
files { "src/myproject/hello.h" }
vpaths { ["Source/Headers"] = "**.h" }
test.isequal("Source/Headers/hello.h", run())
end
function suite.MatchFilePattern_ToGroup_WithTrailingSlash()
files { "src/myproject/hello.h" }
vpaths { ["Headers/"] = "**.h" }
test.isequal("Headers/hello.h", run())
end
function suite.MatchFilePattern_ToNestedGroup_Flat()
files { "src/myproject/hello.h" }
vpaths { ["Group/Headers"] = "**.h" }
test.isequal("Group/Headers/hello.h", run())
end
function suite.MatchFilePattern_ToGroup_Nested()
files { "src/myproject/hello.h" }
vpaths { ["Headers/*"] = "**.h" }
test.isequal("Headers/src/myproject/hello.h", run())
end
function suite.MatchFilePattern_ToGroup_Nested_OneStar()
files { "src/myproject/hello.h" }
vpaths { ["Headers/*"] = "**.h" }
test.isequal("Headers/src/myproject/hello.h", run())
end
function suite.MatchFilePatternWithPath_ToGroup_Nested()
files { "src/myproject/hello.h" }
vpaths { ["Headers/*"] = "src/**.h" }
test.isequal("Headers/myproject/hello.h", run())
end
function suite.matchBaseFileName_onWildcardExtension()
files { "hello.cpp" }
vpaths { ["Sources"] = "hello.*" }
test.isequal("Sources/hello.cpp", run())
end
--
-- Test with project locations
--
function suite.MatchPath_OnProjectLocationSet()
location "build"
files "src/hello.h"
vpaths { [""] = "src" }
test.isequal("hello.h", run())
end
function suite.MatchFilePattern_OnProjectLocationSet()
location "build"
files "src/hello.h"
vpaths { ["Headers"] = "**.h" }
test.isequal("Headers/hello.h", run())
end
function suite.MatchFilePatternWithPath_OnProjectLocationSet()
location "build"
files "src/hello.h"
vpaths { ["Headers"] = "src/**.h" }
test.isequal("Headers/hello.h", run())
end
| bsd-3-clause |
k20human/domoticz-lua | script_device_tv_source.lua | 1 | 1551 | -----------------------------------------
-- Gestion de la source de la TV
-----------------------------------------
commandArray = {}
tvIp = '192.168.1.36'
tvPort = '1925'
selector = 'Source TV'
sourceTv = 'TV'
sourceShield = 'Shield'
sourceNeutral = 'Neutre'
package.path = package.path .. ';' .. '/home/k20/domoticz/scripts/lua/?.lua'
Library = require('Library')
if (devicechanged[selector] and otherdevices[selector] ~= sourceNeutral) then
if (otherdevices[selector] == sourceShield or otherdevices[selector] == sourceTv) then
Library.setTvKey(tvIp, tvPort, 'Source')
os.execute("sleep 2")
if (otherdevices[selector] == sourceShield) then
Library.setTvKey(tvIp, tvPort, 'CursorDown')
Library.setTvKey(tvIp, tvPort, 'CursorDown')
Library.setTvKey(tvIp, tvPort, 'CursorDown')
Library.setTvKey(tvIp, tvPort, 'CursorDown')
Library.setTvKey(tvIp, tvPort, 'CursorDown')
Library.setTvKey(tvIp, tvPort, 'CursorDown')
elseif (otherdevices[selector] == sourceTv) then
Library.setTvKey(tvIp, tvPort, 'CursorUp')
Library.setTvKey(tvIp, tvPort, 'CursorUp')
Library.setTvKey(tvIp, tvPort, 'CursorUp')
Library.setTvKey(tvIp, tvPort, 'CursorUp')
Library.setTvKey(tvIp, tvPort, 'CursorUp')
Library.setTvKey(tvIp, tvPort, 'CursorUp')
end
Library.setTvKey(tvIp, tvPort, 'Confirm')
commandArray[selector] = 'Set Level: 30'
end
end
return commandArray | mit |
koreader/koreader | spec/unit/document_registry_spec.lua | 8 | 2568 | describe("document registry module", function()
local DocSettings, DocumentRegistry
setup(function()
require("commonrequire")
DocSettings = require("docsettings")
DocumentRegistry = require("document/documentregistry")
end)
it("should get preferred rendering engine", function()
assert.is_equal("crengine",
DocumentRegistry:getProvider("bla.epub").provider)
assert.is_equal("mupdf",
DocumentRegistry:getProvider("bla.pdf").provider)
end)
it("should return all supported rendering engines", function()
local providers = DocumentRegistry:getProviders("bla.epub")
assert.is_equal("crengine",
providers[1].provider.provider)
assert.is_equal("mupdf",
providers[2].provider.provider)
end)
it("should set per-document setting for rendering engine", function()
local path = "../../foo.epub"
local pdf_provider = DocumentRegistry:getProvider("bla.pdf")
DocumentRegistry:setProvider(path, pdf_provider, false)
local provider = DocumentRegistry:getProvider(path)
assert.is_equal("mupdf", provider.provider)
local docsettings = DocSettings:open(path)
docsettings:purge()
end)
it("should set global setting for rendering engine", function()
local path = "../../foo.fb2"
local pdf_provider = DocumentRegistry:getProvider("bla.pdf")
DocumentRegistry:setProvider(path, pdf_provider, true)
local provider = DocumentRegistry:getProvider(path)
assert.is_equal("mupdf", provider.provider)
G_reader_settings:delSetting("provider")
end)
it("should return per-document setting for rendering engine", function()
local path = "../../foofoo.epub"
local docsettings = DocSettings:open(path)
docsettings:saveSetting("provider", "mupdf")
docsettings:flush()
local provider = DocumentRegistry:getProvider(path)
assert.is_equal("mupdf", provider.provider)
docsettings:purge()
end)
it("should return global setting for rendering engine", function()
local path = "../../foofoo.fb2"
local provider_setting = {}
provider_setting.fb2 = "mupdf"
G_reader_settings:saveSetting("provider", provider_setting)
local provider = DocumentRegistry:getProvider(path)
assert.is_equal("mupdf", provider.provider)
G_reader_settings:delSetting("provider")
end)
end)
| agpl-3.0 |
dr01d3r/darkstar | scripts/globals/items/shrimp_cracker_+1.lua | 12 | 1497 | -----------------------------------------
-- ID: 5636
-- Item: shrimp_cracker_+1
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Vitality 2
-- Defense +10
-- Amorph Killer 12
-- Resist Virus 12
-- HP Recovered While Healing 9
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5636);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, 2);
target:addMod(MOD_DEF, 10);
target:addMod(MOD_AMORPH_KILLER, 12);
target:addMod(MOD_VIRUSRES, 12);
target:addMod(MOD_HPHEAL, 9);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, 2);
target:delMod(MOD_DEF, 10);
target:delMod(MOD_AMORPH_KILLER, 12);
target:delMod(MOD_VIRUSRES, 12);
target:delMod(MOD_HPHEAL, 9);
end;
| gpl-3.0 |
koreader/koreader | frontend/ui/widget/confirmbox.lua | 4 | 7032 | --[[--
Widget that shows a confirmation alert with a message and Cancel/OK buttons.
Example:
UIManager:show(ConfirmBox:new{
text = _("Save the document?"),
ok_text = _("Save"), -- ok_text defaults to _("OK")
ok_callback = function()
-- save document
end,
})
It is strongly recommended to set a custom `ok_text` describing the action to be
confirmed, as demonstrated in the example above. No ok_text should be specified
if the resulting phrase would be longer than three words.
]]
local Blitbuffer = require("ffi/blitbuffer")
local ButtonTable = require("ui/widget/buttontable")
local CenterContainer = require("ui/widget/container/centercontainer")
local Device = require("device")
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local GestureRange = require("ui/gesturerange")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local IconWidget = require("ui/widget/iconwidget")
local InputContainer = require("ui/widget/container/inputcontainer")
local MovableContainer = require("ui/widget/container/movablecontainer")
local Size = require("ui/size")
local TextBoxWidget = require("ui/widget/textboxwidget")
local UIManager = require("ui/uimanager")
local VerticalGroup = require("ui/widget/verticalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local _ = require("gettext")
local Input = Device.input
local Screen = Device.screen
local ConfirmBox = InputContainer:extend{
modal = true,
keep_dialog_open = false,
text = _("no text"),
face = Font:getFace("infofont"),
ok_text = _("OK"),
cancel_text = _("Cancel"),
ok_callback = function() end,
cancel_callback = function() end,
other_buttons = nil,
other_buttons_first = false, -- set to true to place other buttons above Cancel-OK row
margin = Size.margin.default,
padding = Size.padding.default,
dismissable = true, -- set to false if any button callback is required
flush_events_on_show = false, -- set to true when it might be displayed after
-- some processing, to avoid accidental dismissal
}
function ConfirmBox:init()
if self.dismissable then
if Device:isTouchDevice() then
self.ges_events.TapClose = {
GestureRange:new{
ges = "tap",
range = Geom:new{
x = 0, y = 0,
w = Screen:getWidth(),
h = Screen:getHeight(),
}
}
}
end
if Device:hasKeys() then
self.key_events.Close = { { Device.input.group.Back } }
end
end
local text_widget = TextBoxWidget:new{
text = self.text,
face = self.face,
width = math.floor(math.min(Screen:getWidth(), Screen:getHeight()) * 2/3),
}
local content = HorizontalGroup:new{
align = "center",
IconWidget:new{
icon = "notice-question",
},
HorizontalSpan:new{ width = Size.span.horizontal_default },
text_widget,
}
local buttons = {{
text = self.cancel_text,
callback = function()
self.cancel_callback()
UIManager:close(self)
end,
}, {
text = self.ok_text,
callback = function()
self.ok_callback()
if self.keep_dialog_open then return end
UIManager:close(self)
end,
},}
buttons = { buttons } -- single row
if self.other_buttons ~= nil then
-- additional rows
local rownum = self.other_buttons_first and 0 or 1
for i, buttons_row in ipairs(self.other_buttons) do
local row = {}
table.insert(buttons, rownum + i, row)
for ___, button in ipairs(buttons_row) do
table.insert(row, {
text = button.text,
callback = function()
if button.callback ~= nil then
button.callback()
end
if self.keep_dialog_open then return end
UIManager:close(self)
end,
})
end
end
end
local button_table = ButtonTable:new{
width = content:getSize().w,
button_font_face = "cfont",
button_font_size = 20,
buttons = buttons,
zero_sep = true,
show_parent = self,
}
local frame = FrameContainer:new{
background = Blitbuffer.COLOR_WHITE,
margin = self.margin,
radius = Size.radius.window,
padding = self.padding,
padding_bottom = 0, -- no padding below buttontable
VerticalGroup:new{
align = "left",
content,
-- Add same vertical space after than before content
VerticalSpan:new{ width = self.margin + self.padding },
button_table,
}
}
self.movable = MovableContainer:new{
frame,
}
self[1] = CenterContainer:new{
dimen = Screen:getSize(),
self.movable,
}
-- Reduce font size until widget fit screen height if needed
local cur_size = frame:getSize()
if cur_size and cur_size.h > 0.95 * Screen:getHeight() then
local orig_font = text_widget.face.orig_font
local orig_size = text_widget.face.orig_size
local real_size = text_widget.face.size
if orig_size > 10 then -- don't go too small
while true do
orig_size = orig_size - 1
self.face = Font:getFace(orig_font, orig_size)
-- scaleBySize() in Font:getFace() may give the same
-- real font size even if we decreased orig_size,
-- so check we really got a smaller real font size
if self.face.size < real_size then
break
end
end
-- re-init this widget
self:free()
self:init()
end
end
end
function ConfirmBox:onShow()
UIManager:setDirty(self, function()
return "ui", self[1][1].dimen
end)
if self.flush_events_on_show then
-- Discard queued and upcoming input events to avoid accidental dismissal
Input:inhibitInputUntil(true)
end
end
function ConfirmBox:onCloseWidget()
UIManager:setDirty(nil, function()
return "ui", self[1][1].dimen
end)
end
function ConfirmBox:onClose()
-- Call cancel_callback, parent may expect a choice
self.cancel_callback()
UIManager:close(self)
return true
end
function ConfirmBox:onTapClose(arg, ges)
if ges.pos:notIntersectWith(self[1][1].dimen) then
self:onClose()
end
-- Don't let it propagate to underlying widgets
return true
end
return ConfirmBox
| agpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c48422921.lua | 2 | 2123 | --猪突猛進
function c48422921.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCondition(c48422921.condition)
e1:SetTarget(c48422921.target)
e1:SetOperation(c48422921.operation)
c:RegisterEffect(e1)
end
function c48422921.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsAbleToEnterBP() or (Duel.GetCurrentPhase()>=PHASE_BATTLE_START and Duel.GetCurrentPhase()<=PHASE_BATTLE)
end
function c48422921.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end
if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
local g=Duel.SelectTarget(tp,Card.IsFaceup,tp,LOCATION_MZONE,0,1,1,nil)
local val=0xff
local reg=g:GetFirst():GetFlagEffectLabel(48422921)
if reg then val=val-reg end
Duel.Hint(HINT_SELECTMSG,tp,562)
local att=Duel.AnnounceAttribute(tp,1,val)
e:SetLabel(att)
end
function c48422921.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and tc:IsFaceup() then
local att=e:GetLabel()
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BATTLE_START)
e1:SetLabel(att)
e1:SetOwnerPlayer(tp)
e1:SetCondition(c48422921.descon)
e1:SetOperation(c48422921.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1,true)
local reg=tc:GetFlagEffectLabel(48422921)
if reg then
reg=bit.bor(reg,att)
tc:SetFlagEffectLabel(48422921,reg)
else
tc:RegisterFlagEffect(48422921,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1,att)
end
end
end
function c48422921.descon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetBattleTarget()
return tp==e:GetOwnerPlayer() and tc and tc:IsControler(1-tp) and tc:IsAttribute(e:GetLabel())
end
function c48422921.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetBattleTarget()
Duel.Destroy(tc,REASON_EFFECT)
end
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c31476755.lua | 5 | 1455 | --砂塵の結界
function c31476755.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c31476755.target)
c:RegisterEffect(e1)
--immune
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_IMMUNE_EFFECT)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetTarget(aux.TargetBoolFunction(Card.IsType,TYPE_NORMAL))
e2:SetValue(c31476755.efilter)
c:RegisterEffect(e2)
end
function c31476755.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local c=e:GetHandler()
c:SetTurnCounter(0)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetCondition(c31476755.descon)
e1:SetOperation(c31476755.desop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,2)
c:RegisterEffect(e1)
end
function c31476755.descon(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer()
end
function c31476755.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local ct=c:GetTurnCounter()
ct=ct+1
c:SetTurnCounter(ct)
if ct==2 then
Duel.Destroy(c,REASON_EFFECT)
end
end
function c31476755.efilter(e,re)
return e:GetHandlerPlayer()~=re:GetOwnerPlayer() and re:IsActiveType(TYPE_SPELL)
end
| gpl-2.0 |
Herve-M/OpenRA | mods/cnc/maps/nod08a/nod08a-AI.lua | 2 | 5752 | --[[
Copyright 2007-2022 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.
]]
AttackPaths = { { AttackPath1 }, { AttackPath2 }, { AttackPath3 } }
GDIBase = { GDICYard, GDIPyle, GDIWeap, GDIHQ, GDIProc, GDINuke1, GDINuke2, GDINuke3, GDIBuilding1, GDIBuilding2, GDIBuilding3, GDIBuilding4, GDIBuilding5, GDIBuilding6, GDIBuilding7, GDIBuilding8, GDIBuilding9 }
GDIOrcas = { GDIOrca1, GDIOrca2 }
InfantryAttackGroup = { }
InfantryGroupSize = 4
InfantryProductionCooldown = DateTime.Minutes(3)
InfantryProductionTypes = { "e1", "e1", "e2" }
HarvesterProductionType = { "harv" }
VehicleAttackGroup = { }
VehicleGroupSize = 4
VehicleProductionCooldown = DateTime.Minutes(4)
VehicleProductionTypes = { "jeep", "jeep", "mtnk", "mtnk", "mtnk" }
StartingCash = 4000
BaseProc = { type = "proc", pos = CPos.New(50, 16), cost = 1500 }
BaseNuke1 = { type = "nuke", pos = CPos.New(60, 17), cost = 500 }
BaseNuke2 = { type = "nuke", pos = CPos.New(59, 19), cost = 500 }
BaseNuke3 = { type = "nuke", pos = CPos.New(57, 18), cost = 500 }
BaseNuke4 = { type = "nuke", pos = CPos.New(58, 16), cost = 500 }
InfantryProduction = { type = "pyle", pos = CPos.New(53, 14), cost = 500 }
VehicleProduction = { type = "weap", pos = CPos.New(48, 13), cost = 2000 }
BaseBuildings = { BaseProc, BaseNuke1, BaseNuke2, BaseNuke3, BaseNuke4, InfantryProduction, VehicleProduction }
AutoGuard = function(guards)
Utils.Do(guards, function(guard)
Trigger.OnDamaged(guard, IdleHunt)
end)
end
BuildBuilding = function(building, cyard)
if CyardIsBuilding or GDI.Cash < building.cost then
Trigger.AfterDelay(DateTime.Seconds(10), function() BuildBuilding(building, cyard) end)
return
end
CyardIsBuilding = true
GDI.Cash = GDI.Cash - building.cost
Trigger.AfterDelay(Actor.BuildTime(building.type), function()
CyardIsBuilding = false
if cyard.IsDead or cyard.Owner ~= GDI then
GDI.Cash = GDI.Cash + building.cost
return
end
local actor = Actor.Create(building.type, true, { Owner = GDI, Location = building.pos })
if actor.Type == 'pyle' or actor.Type == 'hand' then
Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(actor) end)
elseif actor.Type == 'weap' or actor.Type == 'afld' then
Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(actor) end)
end
Trigger.OnKilled(actor, function()
BuildBuilding(building, cyard)
end)
RepairBuilding(GDI, actor, 0.75)
end)
end
CheckForHarvester = function()
local harv = GDI.GetActorsByType("harv")
return #harv > 0
end
GuardBase = function()
Utils.Do(GDIBase, function(building)
Trigger.OnDamaged(building, function()
Utils.Do(GDIOrcas, function(guard)
if not guard.IsDead and not building.IsDead then
guard.Stop()
guard.Guard(building)
end
end)
end)
end)
end
ProduceHarvester = function(building)
if not buildingHarvester then
buildingHarvester = true
building.Build(HarvesterProductionType, function()
buildingHarvester = false
end)
end
end
ProduceInfantry = function(building)
if building.IsDead or building.Owner ~= GDI then
return
elseif not CheckForHarvester() then
Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceInfantry(building) end)
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9))
local toBuild = { Utils.Random(InfantryProductionTypes) }
local Path = Utils.Random(AttackPaths)
building.Build(toBuild, function(unit)
InfantryAttackGroup[#InfantryAttackGroup + 1] = unit[1]
if #InfantryAttackGroup >= InfantryGroupSize then
MoveAndHunt(InfantryAttackGroup, Path)
InfantryAttackGroup = { }
Trigger.AfterDelay(InfantryProductionCooldown, function() ProduceInfantry(building) end)
else
Trigger.AfterDelay(delay, function() ProduceInfantry(building) end)
end
end)
end
ProduceVehicle = function(building)
if building.IsDead or building.Owner ~= GDI then
return
elseif not CheckForHarvester() then
ProduceHarvester(building)
Trigger.AfterDelay(DateTime.Seconds(10), function() ProduceVehicle(building) end)
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(12), DateTime.Seconds(17))
local toBuild = { Utils.Random(VehicleProductionTypes) }
local Path = Utils.Random(AttackPaths)
building.Build(toBuild, function(unit)
VehicleAttackGroup[#VehicleAttackGroup + 1] = unit[1]
if #VehicleAttackGroup >= VehicleGroupSize then
MoveAndHunt(VehicleAttackGroup, Path)
VehicleAttackGroup = { }
Trigger.AfterDelay(VehicleProductionCooldown, function() ProduceVehicle(building) end)
else
Trigger.AfterDelay(delay, function() ProduceVehicle(building) end)
end
end)
end
StartAI = function()
RepairNamedActors(GDI, 0.75)
GDI.Cash = StartingCash
GuardBase()
end
Trigger.OnAllKilledOrCaptured(GDIBase, function()
Utils.Do(GDI.GetGroundAttackers(), IdleHunt)
end)
Trigger.OnKilled(GDIProc, function(building)
BuildBuilding(BaseProc, GDICYard)
end)
Trigger.OnKilled(GDINuke1, function(building)
BuildBuilding(BaseNuke1, GDICYard)
end)
Trigger.OnKilled(GDINuke2, function(building)
BuildBuilding(BaseNuke2, GDICYard)
end)
Trigger.OnKilled(GDINuke3, function(building)
BuildBuilding(BaseNuke3, GDICYard)
end)
Trigger.OnKilled(GDINuke4, function(building)
BuildBuilding(BaseNuke4, GDICYard)
end)
Trigger.OnKilled(GDIPyle, function(building)
BuildBuilding(InfantryProduction, GDICYard)
end)
Trigger.OnKilled(GDIWeap, function(building)
BuildBuilding(VehicleProduction, GDICYard)
end)
| gpl-3.0 |
dr01d3r/darkstar | scripts/zones/Bhaflau_Thickets/mobs/Sea_Puk.lua | 12 | 1367 | -----------------------------------
-- Area: Bhaflau Thickets
-- MOB: Sea Puk
-- Note: Place holder Nis Puk
-----------------------------------
require("scripts/zones/Bhaflau_Thickets/MobIDs");
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
-- Get Sea Puk ID and check if it is a PH of NP
local mobID = mob:getID();
-- Check if Sea Puk is within the Nis_Puk_PH table
if (Nis_Puk_PH[mobID] ~= nil) then
-- printf("%u is a PH",mobID);
-- Get NP's previous ToD
local NP_ToD = GetServerVariable("[POP]Nis_Puk");
-- Check if NP window is open, and there is not an NP popped already(ACTION_NONE = 0)
if (NP_ToD <= os.time(t) and GetMobAction(Nis_Puk) == 0) then
-- printf("NP window open");
-- Give Sea Puk 5 percent chance to pop NP
if (math.random(1,20) >= 1) then
-- printf("NP will pop");
UpdateNMSpawnPoint(Nis_Puk);
GetMobByID(Nis_Puk):setRespawnTime(GetMobRespawnTime(mobID));
SetServerVariable("[PH]Nis_Puk", mobID);
DeterMob(mobID, true);
end
end
end
end; | gpl-3.0 |
sempiternum/telegram-bot | plugins/face.lua | 641 | 3073 | local https = require("ssl.https")
local ltn12 = require "ltn12"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function request(imageUrl)
local api_key = mashape.api_key
if api_key:isempty() then
return nil, 'Configure your Mashape API Key'
end
local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?"
local parameters = "attribute=gender%2Cage%2Crace"
parameters = parameters .. "&url="..(URL.escape(imageUrl) or "")
local url = api..parameters
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "Accept: application/json"
}
print(url)
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return "", code end
local body = table.concat(respbody)
return body, code
end
local function parseData(data)
local jsonBody = json:decode(data)
local response = ""
if jsonBody.error ~= nil then
if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then
response = response .. "The image is too big. Provide a smaller image."
elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then
response = response .. "Is that a valid url for an image?"
else
response = response .. jsonBody.error
end
elseif jsonBody.face == nil or #jsonBody.face == 0 then
response = response .. "No faces found"
else
response = response .. #jsonBody.face .." face(s) found:\n\n"
for k,face in pairs(jsonBody.face) do
local raceP = ""
if face.attribute.race.confidence > 85.0 then
raceP = face.attribute.race.value:lower()
elseif face.attribute.race.confidence > 50.0 then
raceP = "(probably "..face.attribute.race.value:lower()..")"
else
raceP = "(posibly "..face.attribute.race.value:lower()..")"
end
if face.attribute.gender.confidence > 85.0 then
response = response .. "There is a "
else
response = response .. "There may be a "
end
response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " "
response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n"
end
end
return response
end
local function run(msg, matches)
--return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg')
local data, code = request(matches[1])
if code ~= 200 then return "There was an error. "..code end
return parseData(data)
end
return {
description = "Who is in that photo?",
usage = {
"!face [url]",
"!recognise [url]"
},
patterns = {
"^!face (.*)$",
"^!recognise (.*)$"
},
run = run
}
| gpl-2.0 |
soundsrc/premake-stable | tests/actions/vstudio/sln2005/header.lua | 51 | 1327 | --
-- tests/actions/vstudio/sln2005/header.lua
-- Validate generation of Visual Studio 2005+ solution header.
-- Copyright (c) 2009-2011 Jason Perkins and the Premake project
--
T.vstudio_sln2005_header = { }
local suite = T.vstudio_sln2005_header
local sln2005 = premake.vstudio.sln2005
--
-- Setup
--
local sln, prj
function suite.setup()
sln = test.createsolution()
end
local function prepare()
premake.bake.buildconfigs()
sln2005.header()
end
--
-- Tests
--
function suite.On2005()
_ACTION = "vs2005"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 9.00
# Visual Studio 2005
]]
end
function suite.On2008()
_ACTION = "vs2008"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 10.00
# Visual Studio 2008
]]
end
function suite.On2010()
_ACTION = "vs2010"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 11.00
# Visual Studio 2010
]]
end
function suite.On2012()
_ACTION = "vs2012"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2012
]]
end
function suite.On2013()
_ACTION = "vs2013"
prepare()
test.capture [[
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 2013
]]
end
| bsd-3-clause |
delaram16/Avvvv | plugins/weather.lua | 3 | 5045 | local function temps(K)
local F = (K*1.8)-459.67
local C = K-273.15
return F,C
end
local function run(msg, matches)
local res = http.request("http://api.openweathermap.org/data/2.5/weather?q="..URL.escape(matches[2]).."&appid=269ed82391822cc692c9afd59f4aabba")
local jtab = JSON.decode(res)
if jtab.name then
if jtab.list[i].weather[1].main == "Thunderstorm" then
status = "⛈طوفاني"
elseif jtab.list[i].weather[1].main == "Drizzle" then
status = "🌦نمنم باران"
elseif jtab.list[i].weather[1].main == "Rain" then
status = "🌧باراني"
elseif jtab.list[i].weather[1].main == "Snow" then
status = "🌨برفي"
elseif jtab.list[i].weather[1].main == "Atmosphere" then
status = "🌫مه - غباز آلود"
elseif jtab.list[i].weather[1].main == "Clear" then
status = "🌤️صاف"
elseif jtab.list[i].weather[1].main == "Clouds" then
status = "☁️ابري"
elseif jtab.list[i].weather[1].main == "Extreme" then
status = "-------"
elseif jtab.list[i].weather[1].main == "Additional" then
status = "-------"
else
status = "-------"
end
local F1,C1 = temps(jtab.main.temp)
local F2,C2 = temps(jtab.main.temp_min)
local F3,C3 = temps(jtab.main.temp_max)
send_document(get_receiver(msg), "file/weatherIcon/"..jtab.weather[1].icon..".webp", ok_cb, false)
if jtab.rain then
rain = jtab.rain["3h"].." ميليمتر"
else
rain = "-----"
end
if jtab.snow then
snow = jtab.snow["3h"].." ميليمتر"
else
snow = "-----"
end
today = "هم اکنون دماي هوا در "..jtab.name.."\n"
.." "..C1.."° درجه سانتيگراد (سلسيوس)\n"
.." "..F1.."° فارنهايت\n"
.." "..jtab.main.temp.."° کلوين\n"
.."بوده و هوا "..status.." ميباشد\n\n"
.."حداقل دماي امروز: C"..C2.."° F"..F2.."° K"..jtab.main.temp_min.."°\n"
.."حداکثر دماي امروز: C"..C3.."° F"..F3.."° K"..jtab.main.temp_max.."°\n"
.."رطوبت هوا: "..jtab.main.humidity.."% درصد\n"
.."مقدار ابر آسمان: "..jtab.clouds.all.."% درصد\n"
.."سرعت باد: "..(jtab.wind.speed or "------").."m/s متر بر ثانيه\n"
.."جهت باد: "..(jtab.wind.deg or "------").."° درجه\n"
.."فشار هوا: "..(jtab.main.pressure/1000).." بار (اتمسفر)\n"
.."بارندگي 3ساعت اخير: "..rain.."\n"
.."بارش برف 3ساعت اخير: "..snow.."\n\n"
after = ""
local res = http.request("http://api.openweathermap.org/data/2.5/forecast?q="..URL.escape(matches[2]).."&appid=269ed82391822cc692c9afd59f4aabba")
local jtab = JSON.decode(res)
for i=1,5 do
local F1,C1 = temps(jtab.list[i].main.temp_min)
local F2,C2 = temps(jtab.list[i].main.temp_max)
if jtab.list[i].weather[1].main == "Thunderstorm" then
status = "⛈طوفاني"
elseif jtab.list[i].weather[1].main == "Drizzle" then
status = "🌦نمنم باران"
elseif jtab.list[i].weather[1].main == "Rain" then
status = "🌧باراني"
elseif jtab.list[i].weather[1].main == "Snow" then
status = "🌨برفي"
elseif jtab.list[i].weather[1].main == "Atmosphere" then
status = "🌫مه - غباز آلود"
elseif jtab.list[i].weather[1].main == "Clear" then
status = "🌤️صاف"
elseif jtab.list[i].weather[1].main == "Clouds" then
status = "☁️ابري"
elseif jtab.list[i].weather[1].main == "Extreme" then
status = "-------"
elseif jtab.list[i].weather[1].main == "Additional" then
status = "-------"
else
status = "-------"
end
local file = io.open("./file/weatherIcon/"..jtab.list[i].weather[1].icon..".char")
if file then
local file = io.open("./file/weatherIcon/"..jtab.list[i].weather[1].icon..".char", "r")
icon = file:read("*all")
else
icon = ""
end
if i == 1 then
day = "فردا هوا "
elseif i == 2 then
day = "پس فردا هوا "
elseif i == 3 then
day = "3⃣روز بعد هوا "
elseif i == 4 then
day = "4⃣روز بعد هوا "
elseif i == 5 then
day = "5⃣روز بعد هوا "
end
after = after.."- "..day..status.." ميباشد. "..icon.."\n🔺C"..C2.."° - F"..F2.."°\n🔻C"..C1.."° - F"..F1.."°\n"
end
return today.."وضعيت آب و هوا در پنج روز آينده:\n"..after
else
return "مکان وارد شده صحيح نيست"
end
end
return {
description = "Weather Status",
usagehtm = '<tr><td align="center">weather شهر</td><td align="right">اين پلاگين به شما اين امکان را ميدهد که به کاملترين شکل ممکن از وضعيت آب و هواي شهر مورد نظر آگاه شويد همپنين اطلاعات آب و هواي پنجج روز آينده نيز اراه ميشود. دقت کنيد نام شهر را لاتين وارد کنيد</td></tr>',
usage = {"weather (city) : وضعيت آب و هوا"},
patterns = {"^([Ww]eather) (.*)$"},
run = run,
}
| gpl-2.0 |
waruqi/xmake | xmake/core/base/emoji.lua | 1 | 32767 | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file emoji.lua
--
-- define module
local emoji = emoji or {}
-- the emoji keys
--
-- from http://www.emoji-cheat-sheet.com/
-- and https://weechat.org/files/scripts/pending/emoji.lua
--
emoji.keys =
{
four="4⃣",kiss_ww="👩❤💋👩",maple_leaf="🍁",waxing_gibbous_moon="🌔",bike="🚲",recycle="♻",family_mwgb="👨👩👧👦",flag_dk="🇩🇰",thought_balloon="💭",oncoming_automobile="🚘",guardsman_tone5="💂🏿",tickets="🎟",school="🏫",house_abandoned="🏚",blue_book="📘",video_game="🎮",triumph="😤",suspension_railway="🚟",umbrella="☔",levitate="🕴",cactus="🌵",monorail="🚝",stars="🌠",new="🆕",herb="🌿",pouting_cat="😾",blue_heart="💙",["100"]="💯",leaves="🍃",family_mwbb="👨👩👦👦",information_desk_person_tone2="💁🏼",dragon_face="🐲",track_next="⏭",cloud_snow="🌨",flag_jp="🇯🇵",children_crossing="🚸",information_desk_person_tone1="💁🏻",arrow_up_down="↕",mount_fuji="🗻",massage_tone1="💆🏻",flag_mq="🇲🇶",massage_tone3="💆🏽",massage_tone2="💆🏼",massage_tone5="💆🏿",flag_je="🇯🇪",flag_jm="🇯🇲",flag_jo="🇯🇴",red_car="🚗",hospital="🏥",red_circle="🔴",princess="👸",tm="™",curly_loop="➰",boy_tone5="👦🏿",pouch="👝",boy_tone3="👦🏽",boy_tone1="👦🏻",izakaya_lantern="🏮",fist_tone5="✊🏿",fist_tone4="✊🏾",fist_tone1="✊🏻",fist_tone3="✊🏽",fist_tone2="✊🏼",arrow_lower_left="↙",game_die="🎲",pushpin="📌",dividers="🗂",dolphin="🐬",night_with_stars="🌃",cruise_ship="🛳",white_medium_small_square="◽",kissing_closed_eyes="😚",earth_americas="🌎",["end"]="🔚",mouse="🐭",rewind="⏪",beach="🏖",pizza="🍕",briefcase="💼",customs="🛃",heartpulse="💗",sparkler="🎇",sparkles="✨",hand_splayed_tone1="🖐🏻",snowman2="☃",tulip="🌷",speaking_head="🗣",ambulance="🚑",office="🏢",clapper="🎬",keyboard="⌨",japan="🗾",post_office="🏣",dizzy_face="😵",imp="👿",flag_ve="🇻🇪",coffee="☕",flag_vg="🇻🇬",flag_va="🇻🇦",flag_vc="🇻🇨",flag_vn="🇻🇳",flag_vi="🇻🇮",open_mouth="😮",flag_vu="🇻🇺",page_with_curl="📃",bank="🏦",bread="🍞",oncoming_police_car="🚔",capricorn="♑",point_left="👈",tokyo_tower="🗼",fishing_pole_and_fish="🎣",thumbsdown="👎",telescope="🔭",spider="🕷",u7121="🈚",camera_with_flash="📸",lifter="🏋",sweet_potato="🍠",lock_with_ink_pen="🔏",ok_woman_tone2="🙆🏼",ok_woman_tone3="🙆🏽",smirk="😏",baggage_claim="🛄",cherry_blossom="🌸",sparkle="❇",zap="⚡",construction_site="🏗",dancers="👯",flower_playing_cards="🎴",hatching_chick="🐣",free="🆓",bullettrain_side="🚄",poultry_leg="🍗",grapes="🍇",smirk_cat="😼",lollipop="🍭",water_buffalo="🐃",black_medium_small_square="◾",atm="🏧",gift_heart="💝",older_woman_tone5="👵🏿",older_woman_tone4="👵🏾",older_woman_tone1="👵🏻",older_woman_tone3="👵🏽",older_woman_tone2="👵🏼",scissors="✂",woman_tone2="👩🏼",basketball="🏀",hammer_pick="⚒",top="🔝",clock630="🕡",raising_hand_tone5="🙋🏿",railway_track="🛤",nail_care="💅",crossed_flags="🎌",minibus="🚐",white_sun_cloud="🌥",shower="🚿",smile_cat="😸",dog2="🐕",loud_sound="🔊",kaaba="🕋",runner="🏃",ram="🐏",writing_hand="✍",rat="🐀",rice_scene="🎑",milky_way="🌌",vulcan_tone5="🖖🏿",necktie="👔",kissing_cat="😽",snowflake="❄",paintbrush="🖌",crystal_ball="🔮",mountain_bicyclist_tone4="🚵🏾",mountain_bicyclist_tone3="🚵🏽",mountain_bicyclist_tone2="🚵🏼",mountain_bicyclist_tone1="🚵🏻",koko="🈁",flag_it="🇮🇹",flag_iq="🇮🇶",flag_is="🇮🇸",flag_ir="🇮🇷",flag_im="🇮🇲",flag_il="🇮🇱",flag_io="🇮🇴",flag_in="🇮🇳",flag_ie="🇮🇪",flag_id="🇮🇩",flag_ic="🇮🇨",ballot_box_with_check="☑",mountain_bicyclist_tone5="🚵🏿",metal="🤘",dog="🐶",pineapple="🍍",no_good_tone3="🙅🏽",no_good_tone2="🙅🏼",no_good_tone1="🙅🏻",scream="😱",no_good_tone5="🙅🏿",no_good_tone4="🙅🏾",flag_ua="🇺🇦",bomb="💣",flag_ug="🇺🇬",flag_um="🇺🇲",flag_us="🇺🇸",construction_worker_tone1="👷🏻",radio="📻",flag_uy="🇺🇾",flag_uz="🇺🇿",person_with_blond_hair_tone1="👱🏻",cupid="💘",mens="🚹",rice="🍚",point_right_tone1="👉🏻",point_right_tone3="👉🏽",point_right_tone2="👉🏼",sunglasses="😎",point_right_tone4="👉🏾",watch="⌚",frowning="😦",watermelon="🍉",wedding="💒",person_frowning_tone4="🙍🏾",person_frowning_tone5="🙍🏿",person_frowning_tone2="🙍🏼",person_frowning_tone3="🙍🏽",person_frowning_tone1="🙍🏻",flag_gw="🇬🇼",flag_gu="🇬🇺",flag_gt="🇬🇹",flag_gs="🇬🇸",flag_gr="🇬🇷",flag_gq="🇬🇶",flag_gp="🇬🇵",flag_gy="🇬🇾",flag_gg="🇬🇬",flag_gf="🇬🇫",microscope="🔬",flag_gd="🇬🇩",flag_gb="🇬🇧",flag_ga="🇬🇦",flag_gn="🇬🇳",flag_gm="🇬🇲",flag_gl="🇬🇱",japanese_ogre="👹",flag_gi="🇬🇮",flag_gh="🇬🇭",man_with_turban="👳",star_and_crescent="☪",writing_hand_tone3="✍🏽",dromedary_camel="🐪",hash="#⃣",hammer="🔨",hourglass="⌛",postbox="📮",writing_hand_tone5="✍🏿",writing_hand_tone4="✍🏾",wc="🚾",aquarius="♒",couple_with_heart="💑",ok_woman="🙆",raised_hands_tone4="🙌🏾",cop="👮",raised_hands_tone1="🙌🏻",cow="🐮",raised_hands_tone3="🙌🏽",white_large_square="⬜",pig_nose="🐽",ice_skate="⛸",hotsprings="♨",tone5="🏿",three="3⃣",beer="🍺",stadium="🏟",airplane_departure="🛫",heavy_division_sign="➗",flag_black="🏴",mushroom="🍄",record_button="⏺",vulcan="🖖",dash="💨",wind_chime="🎐",anchor="⚓",seven="7⃣",flag_hr="🇭🇷",roller_coaster="🎢",pen_ballpoint="🖊",sushi="🍣",flag_ht="🇭🇹",flag_hu="🇭🇺",flag_hk="🇭🇰",dizzy="💫",flag_hn="🇭🇳",flag_hm="🇭🇲",arrow_forward="▶",violin="🎻",orthodox_cross="☦",id="🆔",heart_decoration="💟",first_quarter_moon="🌓",satellite="📡",tone3="🏽",christmas_tree="🎄",unicorn="🦄",broken_heart="💔",ocean="🌊",hearts="♥",snowman="⛄",person_with_blond_hair_tone4="👱🏾",person_with_blond_hair_tone5="👱🏿",person_with_blond_hair_tone2="👱🏼",person_with_blond_hair_tone3="👱🏽",yen="💴",straight_ruler="📏",sleepy="😪",green_apple="🍏",white_medium_square="◻",flag_fr="🇫🇷",grey_exclamation="❕",innocent="😇",flag_fm="🇫🇲",flag_fo="🇫🇴",flag_fi="🇫🇮",flag_fj="🇫🇯",flag_fk="🇫🇰",menorah="🕎",yin_yang="☯",clock130="🕜",gift="🎁",prayer_beads="📿",stuck_out_tongue="😛",om_symbol="🕉",city_dusk="🌆",massage_tone4="💆🏾",couple_ww="👩❤👩",crown="👑",sparkling_heart="💖",clubs="♣",person_with_pouting_face="🙎",newspaper2="🗞",fog="🌫",dango="🍡",large_orange_diamond="🔶",flag_tn="🇹🇳",flag_to="🇹🇴",point_up="☝",flag_tm="🇹🇲",flag_tj="🇹🇯",flag_tk="🇹🇰",flag_th="🇹🇭",flag_tf="🇹🇫",flag_tg="🇹🇬",corn="🌽",flag_tc="🇹🇨",flag_ta="🇹🇦",flag_tz="🇹🇿",flag_tv="🇹🇻",flag_tw="🇹🇼",flag_tt="🇹🇹",flag_tr="🇹🇷",eight_spoked_asterisk="✳",trophy="🏆",black_small_square="▪",o="⭕",no_bell="🔕",curry="🍛",alembic="⚗",sob="😭",waxing_crescent_moon="🌒",tiger2="🐅",two="2⃣",sos="🆘",compression="🗜",heavy_multiplication_x="✖",tennis="🎾",fireworks="🎆",skull_crossbones="☠",astonished="😲",congratulations="㊗",grey_question="❔",arrow_upper_left="↖",arrow_double_up="⏫",triangular_flag_on_post="🚩",gemini="♊",door="🚪",ship="🚢",point_down_tone3="👇🏽",point_down_tone4="👇🏾",point_down_tone5="👇🏿",movie_camera="🎥",ng="🆖",couple_mm="👨❤👨",football="🏈",asterisk="*⃣",taurus="♉",articulated_lorry="🚛",police_car="🚓",flushed="😳",spades="♠",cloud_lightning="🌩",wine_glass="🍷",clock830="🕣",punch_tone2="👊🏼",punch_tone3="👊🏽",punch_tone1="👊🏻",department_store="🏬",punch_tone4="👊🏾",punch_tone5="👊🏿",crocodile="🐊",white_square_button="🔳",hole="🕳",boy_tone2="👦🏼",mountain_cableway="🚠",melon="🍈",persevere="😣",trident="🔱",head_bandage="🤕",u7a7a="🈳",cool="🆒",high_brightness="🔆",deciduous_tree="🌳",white_flower="💮",gun="🔫",flag_sk="🇸🇰",flag_sj="🇸🇯",flag_si="🇸🇮",flag_sh="🇸🇭",flag_so="🇸🇴",flag_sn="🇸🇳",flag_sm="🇸🇲",flag_sl="🇸🇱",flag_sc="🇸🇨",flag_sb="🇸🇧",flag_sa="🇸🇦",flag_sg="🇸🇬",flag_tl="🇹🇱",flag_se="🇸🇪",arrow_left="⬅",flag_sz="🇸🇿",flag_sy="🇸🇾",small_orange_diamond="🔸",flag_ss="🇸🇸",flag_sr="🇸🇷",flag_sv="🇸🇻",flag_st="🇸🇹",file_folder="📁",flag_td="🇹🇩",["1234"]="🔢",smiling_imp="😈",surfer_tone2="🏄🏼",surfer_tone3="🏄🏽",surfer_tone4="🏄🏾",surfer_tone5="🏄🏿",amphora="🏺",baseball="⚾",boy="👦",flag_es="🇪🇸",raised_hands="🙌",flag_eu="🇪🇺",flag_et="🇪🇹",heavy_plus_sign="➕",bow="🙇",flag_ea="🇪🇦",flag_ec="🇪🇨",flag_ee="🇪🇪",light_rail="🚈",flag_eg="🇪🇬",flag_eh="🇪🇭",massage="💆",man_with_gua_pi_mao_tone4="👲🏾",man_with_gua_pi_mao_tone3="👲🏽",outbox_tray="📤",clock330="🕞",projector="📽",sake="🍶",confounded="😖",angry="😠",iphone="📱",sweat_smile="😅",aries="♈",ear_of_rice="🌾",mouse2="🐁",bicyclist_tone4="🚴🏾",bicyclist_tone5="🚴🏿",guardsman="💂",bicyclist_tone1="🚴🏻",bicyclist_tone2="🚴🏼",bicyclist_tone3="🚴🏽",envelope="✉",money_with_wings="💸",beers="🍻",heart_exclamation="❣",notepad_spiral="🗒",cat="🐱",running_shirt_with_sash="🎽",ferry="⛴",spy="🕵",chart_with_upwards_trend="📈",green_heart="💚",confused="😕",angel_tone4="👼🏾",scorpius="♏",sailboat="⛵",elephant="🐘",map="🗺",disappointed_relieved="😥",flag_xk="🇽🇰",motorway="🛣",sun_with_face="🌞",birthday="🎂",mag="🔍",date="📅",dove="🕊",man="👨",octopus="🐙",wheelchair="♿",truck="🚚",sa="🈂",shield="🛡",haircut="💇",last_quarter_moon_with_face="🌜",rosette="🏵",currency_exchange="💱",mailbox_with_no_mail="📭",bath="🛀",clock930="🕤",bowling="🎳",turtle="🐢",pause_button="⏸",construction_worker="👷",unlock="🔓",anger_right="🗯",beetle="🐞",girl="👧",sunrise="🌅",exclamation="❗",flag_dz="🇩🇿",family_mmgg="👨👨👧👧",factory="🏭",flag_do="🇩🇴",flag_dm="🇩🇲",flag_dj="🇩🇯",mouse_three_button="🖱",flag_dg="🇩🇬",flag_de="🇩🇪",star_of_david="✡",reminder_ribbon="🎗",grimacing="😬",thumbsup_tone3="👍🏽",thumbsup_tone2="👍🏼",thumbsup_tone1="👍🏻",musical_note="🎵",thumbsup_tone5="👍🏿",thumbsup_tone4="👍🏾",high_heel="👠",green_book="📗",headphones="🎧",flag_aw="🇦🇼",stop_button="⏹",yum="😋",flag_aq="🇦🇶",warning="⚠",cheese="🧀",ophiuchus="⛎",revolving_hearts="💞",one="1⃣",ring="💍",point_right="👉",sheep="🐑",bookmark="🔖",spider_web="🕸",eyes="👀",flag_ro="🇷🇴",flag_re="🇷🇪",flag_rs="🇷🇸",sweat_drops="💦",flag_ru="🇷🇺",flag_rw="🇷🇼",middle_finger="🖕",race_car="🏎",evergreen_tree="🌲",biohazard="☣",girl_tone3="👧🏽",scream_cat="🙀",computer="💻",hourglass_flowing_sand="⏳",flag_lb="🇱🇧",tophat="🎩",clock1230="🕧",tractor="🚜",u6709="🈶",u6708="🈷",crying_cat_face="😿",angel="👼",ant="🐜",information_desk_person="💁",anger="💢",mailbox_with_mail="📬",pencil2="✏",wink="😉",thermometer="🌡",relaxed="☺",printer="🖨",credit_card="💳",checkered_flag="🏁",family_mmg="👨👨👧",pager="📟",family_mmb="👨👨👦",radioactive="☢",fried_shrimp="🍤",link="🔗",walking="🚶",city_sunset="🌇",shopping_bags="🛍",hockey="🏒",arrow_up="⬆",gem="💎",negative_squared_cross_mark="❎",worried="😟",walking_tone5="🚶🏿",walking_tone1="🚶🏻",hear_no_evil="🙉",convenience_store="🏪",seat="💺",girl_tone1="👧🏻",cloud_rain="🌧",girl_tone2="👧🏼",girl_tone5="👧🏿",girl_tone4="👧🏾",parking="🅿",pisces="♓",calendar="📆",loudspeaker="📢",camping="🏕",bicyclist="🚴",label="🏷",diamonds="♦",older_man_tone1="👴🏻",older_man_tone3="👴🏽",older_man_tone2="👴🏼",older_man_tone5="👴🏿",older_man_tone4="👴🏾",microphone2="🎙",raising_hand="🙋",hot_pepper="🌶",guitar="🎸",tropical_drink="🍹",upside_down="🙃",restroom="🚻",pen_fountain="🖋",comet="☄",cancer="♋",jeans="👖",flag_qa="🇶🇦",boar="🐗",turkey="🦃",person_with_blond_hair="👱",oden="🍢",stuck_out_tongue_closed_eyes="😝",helicopter="🚁",control_knobs="🎛",performing_arts="🎭",tiger="🐯",foggy="🌁",sound="🔉",flag_cz="🇨🇿",flag_cy="🇨🇾",flag_cx="🇨🇽",speech_balloon="💬",seedling="🌱",flag_cr="🇨🇷",envelope_with_arrow="📩",flag_cp="🇨🇵",flag_cw="🇨🇼",flag_cv="🇨🇻",flag_cu="🇨🇺",flag_ck="🇨🇰",flag_ci="🇨🇮",flag_ch="🇨🇭",flag_co="🇨🇴",flag_cn="🇨🇳",flag_cm="🇨🇲",u5408="🈴",flag_cc="🇨🇨",flag_ca="🇨🇦",flag_cg="🇨🇬",flag_cf="🇨🇫",flag_cd="🇨🇩",purse="👛",telephone="☎",sleeping="😴",point_down_tone1="👇🏻",frowning2="☹",point_down_tone2="👇🏼",muscle_tone4="💪🏾",muscle_tone5="💪🏿",synagogue="🕍",muscle_tone1="💪🏻",muscle_tone2="💪🏼",muscle_tone3="💪🏽",clap_tone5="👏🏿",clap_tone4="👏🏾",clap_tone1="👏🏻",train2="🚆",clap_tone2="👏🏼",oil="🛢",diamond_shape_with_a_dot_inside="💠",barber="💈",metal_tone3="🤘🏽",ice_cream="🍨",rowboat_tone4="🚣🏾",burrito="🌯",metal_tone1="🤘🏻",joystick="🕹",rowboat_tone1="🚣🏻",taxi="🚕",u7533="🈸",racehorse="🐎",snowboarder="🏂",thinking="🤔",wave_tone1="👋🏻",wave_tone2="👋🏼",wave_tone3="👋🏽",wave_tone4="👋🏾",wave_tone5="👋🏿",desktop="🖥",stopwatch="⏱",pill="💊",skier="⛷",orange_book="📙",dart="🎯",disappointed="😞",grin="😁",place_of_worship="🛐",japanese_goblin="👺",arrows_counterclockwise="🔄",laughing="😆",clap="👏",left_right_arrow="↔",japanese_castle="🏯",nail_care_tone4="💅🏾",nail_care_tone5="💅🏿",nail_care_tone2="💅🏼",nail_care_tone3="💅🏽",nail_care_tone1="💅🏻",raised_hand_tone4="✋🏾",raised_hand_tone5="✋🏿",raised_hand_tone1="✋🏻",raised_hand_tone2="✋🏼",raised_hand_tone3="✋🏽",point_left_tone3="👈🏽",point_left_tone2="👈🏼",tanabata_tree="🎋",point_left_tone5="👈🏿",point_left_tone4="👈🏾",o2="🅾",knife="🔪",volcano="🌋",kissing_heart="😘",on="🔛",ok="🆗",package="📦",island="🏝",arrow_right="➡",chart_with_downwards_trend="📉",haircut_tone3="💇🏽",wolf="🐺",ox="🐂",dagger="🗡",full_moon_with_face="🌝",syringe="💉",flag_by="🇧🇾",flag_bz="🇧🇿",flag_bq="🇧🇶",flag_br="🇧🇷",flag_bs="🇧🇸",flag_bt="🇧🇹",flag_bv="🇧🇻",flag_bw="🇧🇼",flag_bh="🇧🇭",flag_bi="🇧🇮",flag_bj="🇧🇯",flag_bl="🇧🇱",flag_bm="🇧🇲",flag_bn="🇧🇳",flag_bo="🇧🇴",flag_ba="🇧🇦",flag_bb="🇧🇧",flag_bd="🇧🇩",flag_be="🇧🇪",flag_bf="🇧🇫",flag_bg="🇧🇬",satellite_orbital="🛰",radio_button="🔘",arrow_heading_down="⤵",rage="😡",whale2="🐋",vhs="📼",hand_splayed_tone3="🖐🏽",strawberry="🍓",["non-potable_water"]="🚱",hand_splayed_tone5="🖐🏿",star2="🌟",toilet="🚽",ab="🆎",cinema="🎦",floppy_disk="💾",princess_tone4="👸🏾",princess_tone5="👸🏿",princess_tone2="👸🏼",nerd="🤓",telephone_receiver="📞",princess_tone1="👸🏻",arrow_double_down="⏬",clock1030="🕥",flag_pr="🇵🇷",flag_ps="🇵🇸",poop="💩",flag_pw="🇵🇼",flag_pt="🇵🇹",flag_py="🇵🇾",pear="🍐",m="Ⓜ",flag_pa="🇵🇦",flag_pf="🇵🇫",flag_pg="🇵🇬",flag_pe="🇵🇪",flag_pk="🇵🇰",flag_ph="🇵🇭",flag_pn="🇵🇳",flag_pl="🇵🇱",flag_pm="🇵🇲",mask="😷",hushed="😯",sunrise_over_mountains="🌄",partly_sunny="⛅",dollar="💵",helmet_with_cross="⛑",smoking="🚬",no_bicycles="🚳",man_with_gua_pi_mao="👲",tv="📺",open_hands="👐",rotating_light="🚨",information_desk_person_tone4="💁🏾",information_desk_person_tone5="💁🏿",part_alternation_mark="〽",pray_tone5="🙏🏿",pray_tone4="🙏🏾",pray_tone3="🙏🏽",pray_tone2="🙏🏼",pray_tone1="🙏🏻",smile="😄",large_blue_circle="🔵",man_tone4="👨🏾",man_tone5="👨🏿",fax="📠",woman="👩",man_tone1="👨🏻",man_tone2="👨🏼",man_tone3="👨🏽",eye_in_speech_bubble="👁🗨",blowfish="🐡",card_box="🗃",ticket="🎫",ramen="🍜",twisted_rightwards_arrows="🔀",swimmer_tone4="🏊🏾",swimmer_tone5="🏊🏿",swimmer_tone1="🏊🏻",swimmer_tone2="🏊🏼",swimmer_tone3="🏊🏽",saxophone="🎷",bath_tone1="🛀🏻",notebook_with_decorative_cover="📔",bath_tone3="🛀🏽",ten="🔟",raising_hand_tone4="🙋🏾",tea="🍵",raising_hand_tone1="🙋🏻",raising_hand_tone2="🙋🏼",raising_hand_tone3="🙋🏽",zero="0⃣",ribbon="🎀",santa_tone1="🎅🏻",abc="🔤",clock="🕰",purple_heart="💜",bow_tone1="🙇🏻",no_smoking="🚭",flag_cl="🇨🇱",surfer="🏄",newspaper="📰",busstop="🚏",new_moon="🌑",traffic_light="🚥",thumbsup="👍",no_entry="⛔",name_badge="📛",classical_building="🏛",hamster="🐹",pick="⛏",two_women_holding_hands="👭",family_mmbb="👨👨👦👦",family="👪",rice_cracker="🍘",wind_blowing_face="🌬",inbox_tray="📥",tired_face="😫",carousel_horse="🎠",eye="👁",poodle="🐩",chestnut="🌰",slight_smile="🙂",mailbox_closed="📪",cloud_tornado="🌪",jack_o_lantern="🎃",lifter_tone3="🏋🏽",lifter_tone2="🏋🏼",lifter_tone1="🏋🏻",lifter_tone5="🏋🏿",lifter_tone4="🏋🏾",nine="9⃣",chocolate_bar="🍫",v="✌",man_with_turban_tone4="👳🏾",man_with_turban_tone5="👳🏿",man_with_turban_tone2="👳🏼",man_with_turban_tone3="👳🏽",man_with_turban_tone1="👳🏻",family_wwbb="👩👩👦👦",hamburger="🍔",accept="🉑",airplane="✈",dress="👗",speedboat="🚤",ledger="📒",goat="🐐",flag_ae="🇦🇪",flag_ad="🇦🇩",flag_ag="🇦🇬",flag_af="🇦🇫",flag_ac="🇦🇨",flag_am="🇦🇲",flag_al="🇦🇱",flag_ao="🇦🇴",flag_ai="🇦🇮",flag_au="🇦🇺",flag_at="🇦🇹",fork_and_knife="🍴",fast_forward="⏩",flag_as="🇦🇸",flag_ar="🇦🇷",cow2="🐄",flag_ax="🇦🇽",flag_az="🇦🇿",a="🅰",volleyball="🏐",dragon="🐉",wrench="🔧",point_up_2="👆",egg="🍳",small_red_triangle="🔺",soon="🔜",bow_tone4="🙇🏾",joy_cat="😹",pray="🙏",dark_sunglasses="🕶",rugby_football="🏉",soccer="⚽",dolls="🎎",monkey_face="🐵",clap_tone3="👏🏽",bar_chart="📊",european_castle="🏰",military_medal="🎖",frame_photo="🖼",rice_ball="🍙",trolleybus="🚎",older_woman="👵",information_source="ℹ",postal_horn="📯",house="🏠",fish="🐟",bride_with_veil="👰",fist="✊",lipstick="💄",fountain="⛲",cyclone="🌀",thumbsdown_tone2="👎🏼",thumbsdown_tone3="👎🏽",thumbsdown_tone1="👎🏻",thumbsdown_tone4="👎🏾",thumbsdown_tone5="👎🏿",cookie="🍪",heartbeat="💓",blush="😊",fire_engine="🚒",feet="🐾",horse="🐴",blossom="🌼",crossed_swords="⚔",station="🚉",clock730="🕢",banana="🍌",relieved="😌",hotel="🏨",park="🏞",aerial_tramway="🚡",flag_sd="🇸🇩",panda_face="🐼",b="🅱",flag_sx="🇸🇽",six_pointed_star="🔯",shaved_ice="🍧",chipmunk="🐿",mountain="⛰",koala="🐨",white_small_square="▫",open_hands_tone2="👐🏼",open_hands_tone3="👐🏽",u55b6="🈺",open_hands_tone1="👐🏻",open_hands_tone4="👐🏾",open_hands_tone5="👐🏿",baby_tone5="👶🏿",baby_tone4="👶🏾",baby_tone3="👶🏽",baby_tone2="👶🏼",baby_tone1="👶🏻",chart="💹",beach_umbrella="⛱",basketball_player_tone5="⛹🏿",basketball_player_tone4="⛹🏾",basketball_player_tone1="⛹🏻",basketball_player_tone3="⛹🏽",basketball_player_tone2="⛹🏼",mans_shoe="👞",shinto_shrine="⛩",ideograph_advantage="🉐",airplane_arriving="🛬",golf="⛳",minidisc="💽",hugging="🤗",crayon="🖍",point_down="👇",copyright="©",person_with_pouting_face_tone2="🙎🏼",person_with_pouting_face_tone3="🙎🏽",person_with_pouting_face_tone1="🙎🏻",person_with_pouting_face_tone4="🙎🏾",person_with_pouting_face_tone5="🙎🏿",busts_in_silhouette="👥",alarm_clock="⏰",couplekiss="💏",circus_tent="🎪",sunny="☀",incoming_envelope="📨",yellow_heart="💛",cry="😢",x="❌",arrow_up_small="🔼",art="🎨",surfer_tone1="🏄🏻",bride_with_veil_tone4="👰🏾",bride_with_veil_tone5="👰🏿",bride_with_veil_tone2="👰🏼",bride_with_veil_tone3="👰🏽",bride_with_veil_tone1="👰🏻",hibiscus="🌺",black_joker="🃏",raised_hand="✋",no_mouth="😶",basketball_player="⛹",champagne="🍾",no_entry_sign="🚫",older_man="👴",moyai="🗿",mailbox="📫",slight_frown="🙁",statue_of_liberty="🗽",mega="📣",eggplant="🍆",rose="🌹",bell="🔔",battery="🔋",wastebasket="🗑",dancer="💃",page_facing_up="📄",church="⛪",underage="🔞",secret="㊙",clock430="🕟",fork_knife_plate="🍽",u7981="🈲",fire="🔥",cold_sweat="😰",flag_er="🇪🇷",family_mwgg="👨👩👧👧",heart_eyes="😍",guardsman_tone1="💂🏻",guardsman_tone2="💂🏼",guardsman_tone3="💂🏽",guardsman_tone4="💂🏾",earth_africa="🌍",arrow_right_hook="↪",spy_tone2="🕵🏼",closed_umbrella="🌂",bikini="👙",vertical_traffic_light="🚦",kissing="😗",loop="➿",potable_water="🚰",pound="💷",["fleur-de-lis"]="⚜",key2="🗝",heavy_dollar_sign="💲",shamrock="☘",boy_tone4="👦🏾",shirt="👕",kimono="👘",left_luggage="🛅",meat_on_bone="🍖",ok_woman_tone4="🙆🏾",ok_woman_tone5="🙆🏿",arrow_heading_up="⤴",calendar_spiral="🗓",snail="🐌",ok_woman_tone1="🙆🏻",arrow_down_small="🔽",leopard="🐆",paperclips="🖇",cityscape="🏙",woman_tone1="👩🏻",slot_machine="🎰",woman_tone3="👩🏽",woman_tone4="👩🏾",woman_tone5="👩🏿",euro="💶",musical_score="🎼",triangular_ruler="📐",flags="🎏",five="5⃣",love_hotel="🏩",hotdog="🌭",speak_no_evil="🙊",eyeglasses="👓",dancer_tone4="💃🏾",dancer_tone5="💃🏿",vulcan_tone4="🖖🏾",bridge_at_night="🌉",writing_hand_tone1="✍🏻",couch="🛋",vulcan_tone1="🖖🏻",vulcan_tone2="🖖🏼",vulcan_tone3="🖖🏽",womans_hat="👒",sandal="👡",cherries="🍒",full_moon="🌕",flag_om="🇴🇲",play_pause="⏯",couple="👫",money_mouth="🤑",womans_clothes="👚",globe_with_meridians="🌐",bath_tone5="🛀🏿",bangbang="‼",stuck_out_tongue_winking_eye="😜",heart="❤",bamboo="🎍",mahjong="🀄",waning_gibbous_moon="🌖",back="🔙",point_up_2_tone4="👆🏾",point_up_2_tone5="👆🏿",lips="👄",point_up_2_tone1="👆🏻",point_up_2_tone2="👆🏼",point_up_2_tone3="👆🏽",candle="🕯",middle_finger_tone3="🖕🏽",middle_finger_tone2="🖕🏼",middle_finger_tone1="🖕🏻",middle_finger_tone5="🖕🏿",middle_finger_tone4="🖕🏾",heavy_minus_sign="➖",nose="👃",zzz="💤",stew="🍲",santa="🎅",tropical_fish="🐠",point_up_tone1="☝🏻",point_up_tone3="☝🏽",point_up_tone2="☝🏼",point_up_tone5="☝🏿",point_up_tone4="☝🏾",field_hockey="🏑",school_satchel="🎒",womens="🚺",baby_symbol="🚼",baby_chick="🐤",ok_hand_tone2="👌🏼",ok_hand_tone3="👌🏽",ok_hand_tone1="👌🏻",ok_hand_tone4="👌🏾",ok_hand_tone5="👌🏿",family_mmgb="👨👨👧👦",last_quarter_moon="🌗",tada="🎉",clock530="🕠",question="❓",registered="®",level_slider="🎚",black_circle="⚫",atom="⚛",penguin="🐧",electric_plug="🔌",skull="💀",kiss_mm="👨❤💋👨",walking_tone4="🚶🏾",fries="🍟",up="🆙",walking_tone3="🚶🏽",walking_tone2="🚶🏼",athletic_shoe="👟",hatched_chick="🐥",black_nib="✒",black_large_square="⬛",bow_and_arrow="🏹",rainbow="🌈",metal_tone5="🤘🏿",metal_tone4="🤘🏾",lemon="🍋",metal_tone2="🤘🏼",peach="🍑",peace="☮",steam_locomotive="🚂",oncoming_bus="🚍",heart_eyes_cat="😻",smiley="😃",haircut_tone1="💇🏻",haircut_tone2="💇🏼",u6e80="🈵",haircut_tone4="💇🏾",haircut_tone5="💇🏿",black_medium_square="◼",closed_book="📕",desert="🏜",expressionless="😑",dvd="📀",construction_worker_tone2="👷🏼",construction_worker_tone3="👷🏽",construction_worker_tone4="👷🏾",construction_worker_tone5="👷🏿",mag_right="🔎",bento="🍱",scroll="📜",flag_nl="🇳🇱",flag_no="🇳🇴",flag_ni="🇳🇮",european_post_office="🏤",flag_ne="🇳🇪",flag_nf="🇳🇫",flag_ng="🇳🇬",flag_na="🇳🇦",flag_nc="🇳🇨",alien="👽",first_quarter_moon_with_face="🌛",flag_nz="🇳🇿",flag_nu="🇳🇺",golfer="🏌",flag_np="🇳🇵",flag_nr="🇳🇷",anguished="😧",mosque="🕌",point_left_tone1="👈🏻",ear_tone1="👂🏻",ear_tone2="👂🏼",ear_tone3="👂🏽",ear_tone4="👂🏾",ear_tone5="👂🏿",eight_pointed_black_star="✴",wave="👋",runner_tone5="🏃🏿",runner_tone4="🏃🏾",runner_tone3="🏃🏽",runner_tone2="🏃🏼",runner_tone1="🏃🏻",railway_car="🚃",notes="🎶",no_good="🙅",trackball="🖲",spaghetti="🍝",love_letter="💌",clipboard="📋",baby_bottle="🍼",bird="🐦",card_index="📇",punch="👊",leo="♌",house_with_garden="🏡",family_wwgg="👩👩👧👧",family_wwgb="👩👩👧👦",see_no_evil="🙈",metro="🚇",popcorn="🍿",apple="🍎",scales="⚖",sleeping_accommodation="🛌",clock230="🕝",tools="🛠",cloud="☁",honey_pot="🍯",ballot_box="🗳",frog="🐸",camera="📷",crab="🦀",video_camera="📹",pencil="📝",thunder_cloud_rain="⛈",mountain_bicyclist="🚵",tangerine="🍊",train="🚋",rabbit="🐰",baby="👶",palm_tree="🌴",capital_abcd="🔠",put_litter_in_its_place="🚮",coffin="⚰",abcd="🔡",lock="🔒",pig2="🐖",family_mwg="👨👩👧",point_right_tone5="👉🏿",trumpet="🎺",film_frames="🎞",six="6⃣",leftwards_arrow_with_hook="↩",earth_asia="🌏",heavy_check_mark="✔",notebook="📓",taco="🌮",tomato="🍅",robot="🤖",mute="🔇",symbols="🔣",motorcycle="🏍",thermometer_face="🤒",paperclip="📎",moneybag="💰",neutral_face="😐",white_sun_rain_cloud="🌦",snake="🐍",kiss="💋",blue_car="🚙",confetti_ball="🎊",tram="🚊",repeat_one="🔂",smiley_cat="😺",beginner="🔰",mobile_phone_off="📴",books="📚",["8ball"]="🎱",cocktail="🍸",flag_ge="🇬🇪",horse_racing_tone2="🏇🏼",flag_mh="🇲🇭",flag_mk="🇲🇰",flag_mm="🇲🇲",flag_ml="🇲🇱",flag_mo="🇲🇴",flag_mn="🇲🇳",flag_ma="🇲🇦",flag_mc="🇲🇨",flag_me="🇲🇪",flag_md="🇲🇩",flag_mg="🇲🇬",flag_mf="🇲🇫",flag_my="🇲🇾",flag_mx="🇲🇽",flag_mz="🇲🇿",mountain_snow="🏔",flag_mp="🇲🇵",flag_ms="🇲🇸",flag_mr="🇲🇷",flag_mu="🇲🇺",flag_mt="🇲🇹",flag_mw="🇲🇼",flag_mv="🇲🇻",timer="⏲",passport_control="🛂",small_blue_diamond="🔹",lion_face="🦁",white_check_mark="✅",bouquet="💐",track_previous="⏮",monkey="🐒",tone4="🏾",closed_lock_with_key="🔐",family_wwb="👩👩👦",family_wwg="👩👩👧",tone1="🏻",crescent_moon="🌙",shell="🐚",gear="⚙",tone2="🏼",small_red_triangle_down="🔻",nut_and_bolt="🔩",umbrella2="☂",unamused="😒",fuelpump="⛽",bed="🛏",bee="🐝",round_pushpin="📍",flag_white="🏳",microphone="🎤",bus="🚌",eight="8⃣",handbag="👜",medal="🏅",arrows_clockwise="🔃",urn="⚱",bookmark_tabs="📑",new_moon_with_face="🌚",fallen_leaf="🍂",horse_racing="🏇",chicken="🐔",ear="👂",wheel_of_dharma="☸",arrow_lower_right="↘",man_with_gua_pi_mao_tone5="👲🏿",scorpion="🦂",waning_crescent_moon="🌘",man_with_gua_pi_mao_tone2="👲🏼",man_with_gua_pi_mao_tone1="👲🏻",bug="🐛",virgo="♍",libra="♎",angel_tone1="👼🏻",angel_tone3="👼🏽",angel_tone2="👼🏼",angel_tone5="👼🏿",sagittarius="♐",bear="🐻",information_desk_person_tone3="💁🏽",no_mobile_phones="📵",hand_splayed="🖐",motorboat="🛥",calling="📲",interrobang="⁉",oncoming_taxi="🚖",flag_lt="🇱🇹",flag_lu="🇱🇺",flag_lr="🇱🇷",flag_ls="🇱🇸",flag_ly="🇱🇾",bellhop="🛎",arrow_down="⬇",flag_lc="🇱🇨",flag_la="🇱🇦",flag_lk="🇱🇰",flag_li="🇱🇮",ferris_wheel="🎡",hand_splayed_tone2="🖐🏼",large_blue_diamond="🔷",cat2="🐈",icecream="🍦",tent="⛺",joy="😂",hand_splayed_tone4="🖐🏾",file_cabinet="🗄",key="🔑",weary="😩",bath_tone2="🛀🏼",flag_lv="🇱🇻",low_brightness="🔅",rowboat_tone5="🚣🏿",rowboat_tone2="🚣🏼",rowboat_tone3="🚣🏽",four_leaf_clover="🍀",space_invader="👾",cl="🆑",cd="💿",bath_tone4="🛀🏾",flag_za="🇿🇦",swimmer="🏊",wavy_dash="〰",flag_zm="🇿🇲",flag_zw="🇿🇼",raised_hands_tone5="🙌🏿",two_hearts="💕",bulb="💡",cop_tone4="👮🏾",cop_tone5="👮🏿",cop_tone2="👮🏼",cop_tone3="👮🏽",cop_tone1="👮🏻",open_file_folder="📂",homes="🏘",raised_hands_tone2="🙌🏼",fearful="😨",grinning="😀",bow_tone5="🙇🏿",santa_tone3="🎅🏽",santa_tone2="🎅🏼",santa_tone5="🎅🏿",santa_tone4="🎅🏾",bow_tone2="🙇🏼",bow_tone3="🙇🏽",bathtub="🛁",ping_pong="🏓",u5272="🈹",rooster="🐓",vs="🆚",bullettrain_front="🚅",airplane_small="🛩",white_circle="⚪",balloon="🎈",cross="✝",princess_tone3="👸🏽",speaker="🔈",zipper_mouth="🤐",u6307="🈯",whale="🐳",pensive="😔",signal_strength="📶",muscle="💪",rocket="🚀",camel="🐫",boot="👢",flashlight="🔦",spy_tone4="🕵🏾",spy_tone5="🕵🏿",ski="🎿",spy_tone3="🕵🏽",musical_keyboard="🎹",spy_tone1="🕵🏻",rolling_eyes="🙄",clock1="🕐",clock2="🕑",clock3="🕒",clock4="🕓",clock5="🕔",clock6="🕕",clock7="🕖",clock8="🕗",clock9="🕘",doughnut="🍩",dancer_tone1="💃🏻",dancer_tone2="💃🏼",dancer_tone3="💃🏽",candy="🍬",two_men_holding_hands="👬",badminton="🏸",bust_in_silhouette="👤",writing_hand_tone2="✍🏼",sunflower="🌻",["e-mail"]="📧",chains="⛓",kissing_smiling_eyes="😙",fish_cake="🍥",no_pedestrians="🚷",v_tone4="✌🏾",v_tone5="✌🏿",v_tone1="✌🏻",v_tone2="✌🏼",v_tone3="✌🏽",arrow_backward="◀",clock12="🕛",clock10="🕙",clock11="🕚",sweat="😓",mountain_railway="🚞",tongue="👅",black_square_button="🔲",do_not_litter="🚯",nose_tone4="👃🏾",nose_tone5="👃🏿",nose_tone2="👃🏼",nose_tone3="👃🏽",nose_tone1="👃🏻",horse_racing_tone5="🏇🏿",horse_racing_tone4="🏇🏾",horse_racing_tone3="🏇🏽",ok_hand="👌",horse_racing_tone1="🏇🏻",custard="🍮",rowboat="🚣",white_sun_small_cloud="🌤",flag_kr="🇰🇷",cricket="🏏",flag_kp="🇰🇵",flag_kw="🇰🇼",flag_kz="🇰🇿",flag_ky="🇰🇾",construction="🚧",flag_kg="🇰🇬",flag_ke="🇰🇪",flag_ki="🇰🇮",flag_kh="🇰🇭",flag_kn="🇰🇳",flag_km="🇰🇲",cake="🍰",flag_wf="🇼🇫",mortar_board="🎓",pig="🐷",flag_ws="🇼🇸",person_frowning="🙍",arrow_upper_right="↗",book="📖",clock1130="🕦",boom="💥",["repeat"]="🔁",star="⭐",rabbit2="🐇",footprints="👣",ghost="👻",droplet="💧",vibration_mode="📳",flag_ye="🇾🇪",flag_yt="🇾🇹",
}
-- translate the string to emoji
function emoji.translate(str)
-- translate it
local chars = emoji.keys[str]
-- ok?
return chars
end
-- return module
return emoji
| apache-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c46181000.lua | 5 | 1314 | --前線基地
function c46181000.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(46181000,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetCountLimit(1)
e1:SetRange(LOCATION_SZONE)
e1:SetTarget(c46181000.target)
e1:SetOperation(c46181000.operation)
c:RegisterEffect(e1)
end
function c46181000.filter(c,e,sp)
return c:IsType(TYPE_UNION) and c:GetLevel()<=4 and c:IsCanBeSpecialSummoned(e,0,sp,false,false)
end
function c46181000.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c46181000.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c46181000.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c46181000.filter,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-2.0 |
dr01d3r/darkstar | scripts/zones/Bastok_Markets/npcs/Gwill.lua | 26 | 2969 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Gwill
-- Starts & Ends Quest: The Return of the Adventurer
-- Involved in Quests: The Cold Light of Day, Riding on the Clouds
-- @zone 235
-- @pos 0 0 0
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
returnOfAdven = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
if (returnOfAdven == QUEST_ACCEPTED and trade:hasItemQty(628,1) and trade:getItemCount() == 1) then
player:startEvent(0x00f3);
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 2) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
pFame = player:getFameLevel(BASTOK);
FatherFigure = player:getQuestStatus(BASTOK,FATHER_FIGURE);
TheReturn = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
if (FatherFigure == QUEST_COMPLETED and TheReturn == QUEST_AVAILABLE and pFame >= 3) then
player:startEvent(0x00f2);
elseif (player:getQuestStatus(BASTOK,THE_COLD_LIGHT_OF_DAY) == QUEST_ACCEPTED) then
player:startEvent(0x0067);
else
player:startEvent(0x0071);
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 == 0x00f2) then
player:addQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
elseif (csid == 0x00f3) then
if (player:getFreeSlotsCount() >= 1) then
player:tradeComplete();
player:addTitle(KULATZ_BRIDGE_COMPANION);
player:addItem(12498);
player:messageSpecial(ITEM_OBTAINED,12498);
player:addFame(BASTOK,80);
player:completeQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12498);
end
end
end; | gpl-3.0 |
HHmmominion/basemmominion | LuaMods/Dev/WayPoint/166.lua | 1 | 1353 | -- Persistent Data
local multiRefObjects = {
} -- multiRefObjects
local obj1 = {
[1] = {
["y"] = 9;
["x"] = -7.05111;
["name"] = "Manor Claviger-kill";
["z"] = -1.568203;
["h"] = -0.821861;
};
[2] = {
["y"] = -3.779982;
["x"] = -3.865242;
["name"] = "Manor Claviger-tank";
["z"] = 1.604352;
["h"] = 1.696882;
};
[3] = {
["y"] = -18.80011;
["x"] = -15.197601;
["name"] = "Yellow key";
["z"] = 49.99987;
["h"] = -0.248174;
};
[4] = {
["y"] = -11.800003;
["x"] = -14.571776;
["name"] = "Manor Jester-Kill";
["z"] = 5.624331;
["h"] = 1.65092;
};
[5] = {
["y"] = -21.800003;
["x"] = -3.754817;
["name"] = "Manor Jester-Tank";
["z"] = 6.12519;
["h"] = 1.488133;
};
[6] = {
["y"] = 25;
["x"] = 41.689537;
["name"] = "Manor Sentry";
["z"] = 7.065102;
["h"] = -2.009449;
};
[7] = {
["y"] = 23;
["x"] = 4.639065;
["name"] = "Lady Amandine-kill";
["z"] = -1.823925;
["h"] = -1.550776;
};
[8] = {
["y"] = 15;
["x"] = 3.09897;
["name"] = "Lady Amandine-tank";
["z"] = -1.793088;
["h"] = -1.586381;
};
[9] = {
["y"] = 26;
["x"] = -11.240426;
["name"] = "Lady Amandine-kill-B";
["z"] = 10.5865;
["h"] = -2.708864;
};
[10] = {
["y"] = 23;
["x"] = 4.438878;
["name"] = "Lady Amandine-kill-c";
["z"] = -11.821922;
["h"] = -1.550776;
};
}
return obj1
| gpl-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c91819979.lua | 6 | 2234 | --マジックブラスト
function c91819979.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c91819979.damtg)
e1:SetOperation(c91819979.damop)
c:RegisterEffect(e1)
--salvage
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(91819979,0))
e2:SetCategory(CATEGORY_TOHAND)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_PREDRAW)
e2:SetRange(LOCATION_GRAVE)
e2:SetCondition(c91819979.thcon)
e2:SetTarget(c91819979.thtg)
e2:SetOperation(c91819979.thop)
c:RegisterEffect(e2)
end
function c91819979.cfilter(c)
return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER)
end
function c91819979.damtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c91819979.cfilter,tp,LOCATION_MZONE,0,1,nil) end
local ct=Duel.GetMatchingGroupCount(c91819979.cfilter,tp,LOCATION_MZONE,0,nil)
Duel.SetTargetPlayer(1-tp)
Duel.SetTargetParam(ct*200)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,ct*200)
end
function c91819979.damop(e,tp,eg,ep,ev,re,r,rp)
local p=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER)
local ct=Duel.GetMatchingGroupCount(c91819979.cfilter,tp,LOCATION_MZONE,0,nil)
Duel.Damage(p,ct*200,REASON_EFFECT)
end
function c91819979.thcon(e,tp,eg,ep,ev,re,r,rp)
return tp==Duel.GetTurnPlayer() and Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)>0
and Duel.GetDrawCount(tp)>0
end
function c91819979.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToHand() end
local dt=Duel.GetDrawCount(tp)
if dt~=0 then
_replace_count=0
_replace_max=dt
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_DRAW_COUNT)
e1:SetTargetRange(1,0)
e1:SetReset(RESET_PHASE+PHASE_DRAW)
e1:SetValue(0)
Duel.RegisterEffect(e1,tp)
end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0)
end
function c91819979.thop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
_replace_count=_replace_count+1
if _replace_count<=_replace_max and c:IsRelateToEffect(e) then
Duel.SendtoHand(c,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,c)
end
end
| gpl-2.0 |
waruqi/xmake | xmake/modules/detect/tools/find_qmake.lua | 1 | 1374 | --!A cross-platform build utility based on Lua
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--
-- Copyright (C) 2015-2020, TBOOX Open Source Group.
--
-- @author ruki
-- @file find_qmake.lua
--
-- imports
import("lib.detect.find_program")
import("lib.detect.find_programver")
-- find qmake
--
-- @param opt the argument options, e.g. {version = true}
--
-- @return program, version
--
-- @code
--
-- local qmake = find_qmake()
-- local qmake, version = find_qmake({version = true})
--
-- @endcode
--
function main(opt)
-- init options
opt = opt or {}
-- find program
local program = find_program(opt.program or "qmake", opt)
-- find program version
local version = nil
if program and opt and opt.version then
version = find_programver(program, opt)
end
-- ok?
return program, version
end
| apache-2.0 |
SalvationDevelopment/Salvation-Scripts-Production | c17536995.lua | 5 | 1294 | --紋章変換
function c17536995.initial_effect(c)
--end battle phase
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetCondition(c17536995.condition)
e1:SetTarget(c17536995.target)
e1:SetOperation(c17536995.operation)
c:RegisterEffect(e1)
end
function c17536995.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetAttacker():IsControler(1-tp)
end
function c17536995.filter(c,e,tp)
return c:IsSetCard(0x76) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c17536995.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 Duel.IsExistingMatchingCard(c17536995.filter,tp,LOCATION_HAND,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c17536995.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c17536995.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp)
if g:GetCount()>0 and Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)>0 then
Duel.BreakEffect()
Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE,1)
end
end
| gpl-2.0 |
dr01d3r/darkstar | scripts/globals/mobskills/Flat_Blade.lua | 9 | 1360 | ---------------------------------------------
-- Flat Blade
--
-- Description: Stuns enemy. Chance of stunning varies with TP.
-- Type: Physical
-- Utsusemi/Blink absorb: Shadow per hit
-- Range: Melee
---------------------------------------------
require("scripts/globals/monstertpmoves");
require("scripts/globals/settings");
require("scripts/globals/status");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:getPool() ~= 4006) then
mob:messageBasic(43, 0, 35);
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
if (mob:getPool() == 4006) then -- Trion@Qubia_Arena only
require("scripts/zones/Qubia_Arena/TextIDs");
target:showText(mob,FLAT_LAND);
end
local numhits = 1;
local accmod = 1;
local dmgmod = 1.25;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1.1,1.2,1.3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
skill:setSkillchain(35);
if (math.random(1,100) < skill:getTP()/3) then
MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_STUN, 1, 0, 4);
end
-- AA EV: Approx 900 damage to 75 DRG/35 THF. 400 to a NIN/WAR in Arhat, but took shadows.
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
fir3element/forgottenserver036 | data/npc/scripts/loot.lua | 7 | 2677 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
-- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions!
keywordHandler:addKeyword({'helmets'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy royal (40k), warrior (6k), crusader (9k), crown (5k), devil (4k), chain (35gp) and iron helmets (30gp), also mystic turbans (500gp).'})
keywordHandler:addKeyword({'boots'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy golden boots (100k), steel boots (40k) and boots of haste (40k).'})
keywordHandler:addKeyword({'armors'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy golden (30k), crown (20k), knight (5k), lady (7,5k), plate (400gp), brass (200gp) and chain armors (100gp), also mpa (100k), dsm (60k) and blue robes (15k).'})
keywordHandler:addKeyword({'legs'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy golden (80k), crown (15k), knight (6k), plate (500gp) and brass legs (100gp).'})
keywordHandler:addKeyword({'shields'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy blessed (150k), great (100k), demon (40k), vampire (25k), medusa (8k), amazon (4k), crown (5k), tower (4k), dragon (3k), guardian (2k), beholder (1k), and dwarven shields (100gp), also mms (80k).'})
keywordHandler:addKeyword({'swords'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy giant (10k), bright (6k), fire (3k) serpent (1.5k), spike (800gp) and two handed swords (400gp), also ice rapiers (4k), magic longswords (150k), magic swords (90k), warlord swords (100k) broad swords (70gp), short swords (30gp), sabres (25gp) and swords (25gp).'})
keywordHandler:addKeyword({'axes'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy fire (10k), guardian halberds (7,5k) knight (2k), double (200gp) and battle axes (100gp), also dragon lances (10k), stonecutters axes (90k), halberds (200gp) and hatchets (20gp).'})
keywordHandler:addKeyword({'clubs'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I buy thunder hammers (90k), war (6k), dragon (2k) and battle hammers (60gp), also skull staffs (10k) and clerical maces (200gp).'})
npcHandler:addModule(FocusModule:new())
| gpl-2.0 |
dwmw2/domoticz | dzVents/runtime/device-adapters/rgbw_device.lua | 3 | 7614 | local TimedCommand = require('TimedCommand')
return {
baseType = 'device',
name = 'RGB(W) device adapter',
matches = function (device, adapterManager)
local res = device.deviceType == 'Color Switch'
adapterManager.addDummyMethod(device, 'setKelvin')
adapterManager.addDummyMethod(device, 'setWhiteMode')
adapterManager.addDummyMethod(device, 'increaseBrightness')
adapterManager.addDummyMethod(device, 'decreaseBrightness')
adapterManager.addDummyMethod(device, 'setNightMode')
adapterManager.addDummyMethod(device, 'setRGB')
adapterManager.addDummyMethod(device, 'setHex')
adapterManager.addDummyMethod(device, 'setHue')
adapterManager.addDummyMethod(device, 'setColor')
adapterManager.addDummyMethod(device, 'setColorBrightness')
adapterManager.addDummyMethod(device, 'setHue')
adapterManager.addDummyMethod(device, 'getColor')
adapterManager.addDummyMethod(device, 'setDiscoMode')
return res
end,
process = function (device, data, domoticz, utils, adapterManager)
local function methodNotAvailableMessage(device, methodName)
domoticz.log('Method ' .. methodName .. ' is not available for device ' .. ' "' .. device.name .. '"' , utils.LOG_ERROR)
domoticz.log('(id=' .. device.id .. ', type=' .. device.deviceType .. ', subtype=' .. device.deviceSubType .. ', hardwareType=' .. device.hardwareType .. ')', utils.LOG_ERROR)
domoticz.log('If you believe this is not correct, please report on the forum.', utils.LOG_ERROR)
end
if (device.deviceSubType == 'RGBWW') or (device.deviceSubType == 'WW') then
function device.setKelvin(kelvin)
local url
url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=setkelvinlevel&type=command&idx=' .. device.id .. '&kelvin=' .. tonumber(kelvin)
return domoticz.openURL(url)
end
end
function device.setWhiteMode()
local url
url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=whitelight&type=command&idx=' .. device.id
return domoticz.openURL(url)
end
function device.increaseBrightness()
-- API will be removed; kept here until then to get user reports (if any)
if false and device.hardwareType and device.hardwareType == 'YeeLight LED' then
local url
url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=brightnessup&type=command&idx=' .. device.id
return domoticz.openURL(url)
else
methodNotAvailableMessage(device, 'increaseBrightness')
end
end
function device.decreaseBrightness()
-- API will be removed; kept here until then to get user reports (if any)
if false and device.hardwareType and device.hardwareType == 'YeeLight LED' then
local url
url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=brightnessdown&type=command&idx=' .. device.id
return domoticz.openURL(url)
else
methodNotAvailableMessage(device, 'decreaseBrightness')
end
end
function device.setNightMode()
local url
url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=nightlight&type=command&idx=' .. device.id
return domoticz.openURL(url)
end
function device.setDiscoMode(modeNum)
if false then -- API will be removed; kept here until then to get user reports (if any)
if (type(modeNum) ~= 'number' or modeNum < 1 or modeNum > 9) then
domoticz.log('Mode number needs to be a number from 1-9', utils.LOG_ERROR)
end
local url
url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=discomodenum' .. tonumber(modeNum) .. '&type=command&idx=' .. device.id
return domoticz.openURL(url)
else
methodNotAvailableMessage(device, 'setDiscoMode')
end
end
local function inRange(value, low, high)
return (value >= low and value <= high )
end
local function validRGB(r, g, b)
return (
type(r) == 'number' and
type(b) == 'number' and
type(g) == 'number' and
inRange(r, 0, 255) and
inRange(b, 0, 255) and
inRange(g, 0, 255)
)
end
local function RGBError()
domoticz.log('RGB values need to be numbers from 0-255', utils.LOG_ERROR)
end
function device.setRGB(r, g, b)
if not(validRGB(r, g, b)) then RGBError() return false end
local h, s, b, isWhite = domoticz.utils.rgbToHSB(r, g, b)
local url = domoticz.settings['Domoticz url'] ..
'/json.htm?param=setcolbrightnessvalue&type=command' ..
'&idx=' .. device.id ..
'&hue=' .. math.floor(tonumber(h) + 0.5) ..
'&brightness=' .. math.floor(tonumber(b) + 0.5) ..
'&iswhite=' .. tostring(isWhite)
return domoticz.openURL(url)
end
function device.setColor(r, g, b, br, cw, ww, m, t)
if not(validRGB(r, g, b)) then RGBError() return false end
if br and not(inRange(br, 0, 100)) then
domoticz.log('Brightness value need to be number from 0-100', utils.LOG_ERROR)
return false
end
if m == nil then m = 3 end
local colors = domoticz.utils.fromJSON(device.color,{ t=0, cw=0, ww=0})
local brightness = br or 100
if br == nil then
local _ , _ , brightness = domoticz.utils.rgbToHSB(r, g, b)
end
if cw == nil then cw = colors.cw end
if ww == nil then ww = colors.ww end
if t == nil then t = colors.t end
local url = domoticz.settings['Domoticz url'] ..
'/json.htm?type=command¶m=setcolbrightnessvalue' ..
'&idx=' .. device.id ..
'&brightness=' .. brightness ..
'&color={"m":' .. m ..
',"t":' .. t ..
',"cw":' .. cw ..
',"ww":' .. ww ..
',"r":' .. r ..
',"g":' .. g ..
',"b":' .. b .. '}'
return domoticz.openURL(url)
end
function device.setColorBrightness(r, g, b, br, cw, ww, m, t)
return device.setColor(r, g, b, br, cw, ww, m, t)
end
function device.setHex(r,g,b)
local _ , _ , brightness = domoticz.utils.rgbToHSB(r, g, b)
local hex = string.format("%02x",r) .. string.format("%02x", g) .. string.format("%02x", b)
local url = domoticz.settings['Domoticz url'] .. '/json.htm?type=command¶m=setcolbrightnessvalue' ..
'&idx=' .. device.id ..
'&brightness=' .. brightness ..
'&hex=' .. hex ..
'&iswhite=false'
return domoticz.openURL(url)
end
function device.setHue(hue,brightness,isWhite)
if not(brightness) or not(inRange(brightness, 0, 100)) then
domoticz.log('Brightness value need to be number from 0-100', utils.LOG_ERROR)
return false
end
if not(hue) or not(inRange(hue, 0, 360)) then
domoticz.log('hue value need to be number from 0-360', utils.LOG_ERROR)
return false
end
if isWhite and type(isWhite) ~= "boolean" then
domoticz.log('isWhite need to be of boolean type', utils.LOG_ERROR)
return false
end
if not(isWhite) then isWhite = false end
local url = domoticz.settings['Domoticz url'] .. '/json.htm?type=command¶m=setcolbrightnessvalue' ..
'&idx=' .. device.id ..
'&brightness=' .. brightness ..
'&hue=' .. hue ..
'&iswhite=' .. tostring(isWhite)
return domoticz.openURL(url)
end
function device.getColor()
if not(device.color) or device.color == "" then
domoticz.log('Color field not set for this device', utils.LOG_ERROR)
return nil
end
local ct = domoticz.utils.fromJSON(device.color, {})
ct.hue, ct.saturation, ct.value, ct.isWhite = domoticz.utils.rgbToHSB(ct.r, ct.g, ct.b)
ct.red = ct.r
ct.blue = ct.b
ct.green = ct.g
ct["warm white"] = ct.ww
ct["cold white"] = ct.cw
ct.temperature = ct.t
ct.mode = ct.m
ct.brightness = ct.value
return (ct)
end
end
} | gpl-3.0 |
SalvationDevelopment/Salvation-Scripts-Production | c19163116.lua | 4 | 1503 | --ジェムナイト・オブシディア
function c19163116.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(19163116,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c19163116.spcon)
e1:SetTarget(c19163116.sptg)
e1:SetOperation(c19163116.spop)
c:RegisterEffect(e1)
end
function c19163116.spcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetPreviousLocation()==LOCATION_HAND
end
function c19163116.filter(c,e,tp)
return c:IsLevelBelow(4) and c:IsType(TYPE_NORMAL) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c19163116.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c19163116.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c19163116.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c19163116.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c19163116.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
dr01d3r/darkstar | scripts/zones/AlTaieu/Zone.lua | 32 | 2324 | -----------------------------------
--
-- Zone: AlTaieu (33)
--
-----------------------------------
package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/AlTaieu/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-25,-1 ,-620 ,33);
end
if (player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus")==0) then
cs=0x0001;
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==0) then
cs=0x00A7;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0001) then
player:setVar("PromathiaStatus",1);
player:addKeyItem(LIGHT_OF_ALTAIEU);
player:messageSpecial(KEYITEM_OBTAINED,LIGHT_OF_ALTAIEU);
player:addTitle(SEEKER_OF_THE_LIGHT);
elseif (csid == 0x00A7) then
player:setVar("PromathiaStatus",1);
end
end;
| gpl-3.0 |
githubmereza/jackreza | plugins/stats.lua | 236 | 3989 | do
-- 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 = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
local file = io.open("./groups/"..chat_id.."stats.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..chat_id,"./groups/"..chat_id.."stats.txt", ok_cb, false)
return --text
end
local function chat_stats2(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 = 'users in this chat \n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
-- Save stats, ban user
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nGroups: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == 'teleseed' then -- Put everything you like :)
local about = _config.about_text
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ")
return about
end
if matches[1]:lower() == "statslist" then
if not is_momod(msg) then
return "For mods only !"
end
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats2(chat_id)
end
if matches[1]:lower() == "stats" then
if not matches[2] then
if not is_momod(msg) then
return "For mods only !"
end
if msg.to.type == 'chat' then
local chat_id = msg.to.id
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ")
return chat_stats(chat_id)
else
return
end
end
if matches[2] == "teleseed" then -- Put everything you like :)
if not is_admin(msg) then
return "For admins only !"
else
return bot_stats()
end
end
if matches[2] == "group" then
if not is_admin(msg) then
return "For admins only !"
else
return chat_stats(matches[3])
end
end
end
end
return {
patterns = {
"^[!/]([Ss]tats)$",
"^[!/]([Ss]tatslist)$",
"^[!/]([Ss]tats) (group) (%d+)",
"^[!/]([Ss]tats) (teleseed)",-- Put everything you like :)
"^[!/]([Tt]eleseed)"-- Put everything you like :)
},
run = run
}
end
| gpl-2.0 |
Squeakz/darkstar | scripts/globals/items/faerie_apple.lua | 18 | 1190 | -----------------------------------------
-- ID: 4363
-- Item: faerie_apple
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility -4
-- Intelligence 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true 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,4363);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, -4);
target:addMod(MOD_INT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, -4);
target:delMod(MOD_INT, 2);
end;
| gpl-3.0 |
Squeakz/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5c5.lua | 13 | 2051 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Gate: Magical Gizmo
-- Involved In Mission: The Horutoto Ruins Experiment
-- @pos 419 0 -27 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 1) then
player:startEvent(0x002A);
else
player:showText(npc,DOOR_FIRMLY_CLOSED);
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 == 0x002A) then
player:setVar("MissionStatus",2);
-- Generate a random value to use for the next part of the mission
-- where you have to examine 6 Magical Gizmo's, each of them having
-- a number from 1 to 6 (Remember, setting 0 deletes the var)
local random_value = math.random(1,6);
player:setVar("MissionStatus_rv",random_value); -- 'rv' = random value
player:setVar("MissionStatus_op1",1);
player:setVar("MissionStatus_op2",1);
player:setVar("MissionStatus_op3",1);
player:setVar("MissionStatus_op4",1);
player:setVar("MissionStatus_op5",1);
player:setVar("MissionStatus_op6",1);
end
end; | gpl-3.0 |
Squeakz/darkstar | scripts/zones/Kuftal_Tunnel/mobs/Guivre.lua | 4 | 14754 | ----------------------------------
-- Area: Gustav Tunnel
-- NM: Guivre
-----------------------------------
local path =
{
106.836830, 0.753614, -3.944333,
106.991020, 0.588184, -4.941793,
107.207207, 0.424275, -5.923915,
107.583046, 0.424275, -6.866960,
108.040382, 0.424275, -7.778655,
108.482483, 0.364732, -8.695824,
108.921669, 0.289885, -9.613388,
109.362129, 0.184958, -10.528788,
109.805786, 0.066048, -11.439518,
111.644989, 0.000000, -15.198928,
112.081032, 0.000000, -16.120642,
112.434616, 0.000000, -17.077393,
112.794510, 0.000000, -18.031784,
113.158630, 0.000000, -18.984592,
113.525223, 0.000000, -19.936440,
114.229553, 0.244860, -21.829271,
114.874275, 0.575834, -23.735594,
115.086800, 0.689463, -24.726152,
115.305222, 0.831800, -25.712254,
115.528206, 0.948544, -26.699181,
115.763580, 0.948544, -27.691650,
116.812645, 0.518518, -32.313782,
117.069260, 0.307952, -33.614750,
117.273041, 0.230719, -34.943283,
117.261650, 0.231090, -35.962982,
117.248177, 0.183139, -36.982887,
117.241623, -0.012887, -37.983841,
117.127762, 0.000000, -38.990234,
116.862022, 0.000000, -39.974133,
116.454262, 0.000000, -40.908192,
115.965675, 0.000000, -41.803535,
115.494179, 0.000000, -42.708023,
115.027023, 0.000000, -43.614761,
114.560127, 0.000000, -44.521637,
113.998978, -0.028513, -45.372234,
113.334190, 0.141798, -46.132935,
112.618889, 0.297568, -46.837734,
111.879662, 0.246952, -47.539852,
111.145302, 0.213181, -48.244881,
110.412346, 0.200519, -48.953037,
109.682579, 0.073200, -49.655846,
108.882729, 0.020027, -50.276154,
107.993965, -0.039275, -50.770645,
107.107376, -0.301162, -51.243320,
105.984108, -0.589100, -51.903667,
105.087524, -0.668489, -52.384327,
104.193001, -0.826998, -52.856438,
103.029999, -1.119595, -53.479015,
101.524078, -1.681683, -54.232483,
100.346069, -1.856236, -54.810303,
98.258423, -2.653062, -55.809986,
94.811630, -4.113267, -57.345276,
93.531342, -4.535689, -57.660553,
92.303452, -5.021625, -58.021339,
91.044044, -5.413645, -58.356346,
89.792992, -5.828867, -58.690666,
88.552742, -6.587278, -58.856159,
87.239265, -6.773692, -59.040783,
85.931122, -7.440585, -59.237297,
84.642632, -7.863066, -59.336357,
83.338280, -8.219630, -59.348583,
82.016800, -8.541007, -59.371071,
80.700005, -8.776169, -59.386993,
79.000061, -8.750005, -59.404205,
75.644821, -9.149647, -59.397270,
74.634064, -9.014733, -59.423302,
71.920708, -8.945028, -59.504490,
70.921768, -8.986447, -59.703518,
69.957237, -8.910275, -60.032097,
69.040680, -8.792699, -60.478394,
68.176872, -8.801409, -61.020370,
67.313622, -8.812502, -61.563572,
66.445267, -8.827121, -62.098515,
65.604500, -8.832716, -62.673820,
64.853836, -8.886011, -63.361320,
64.048332, -9.189323, -64.424530,
63.529961, -9.094744, -65.302437,
63.013744, -9.063213, -66.181328,
62.505089, -9.077284, -67.065010,
62.115822, -9.144894, -68.006805,
61.831207, -9.180872, -68.982086,
61.554005, -9.231291, -69.962242,
61.276596, -9.179898, -70.942604,
60.999046, -9.140337, -71.922745,
60.722118, -9.005057, -72.907417,
58.999298, -8.769359, -78.349106,
58.492390, -8.750000, -79.462196,
58.175842, -8.750000, -80.431839,
57.852287, -8.788690, -81.397903,
56.975307, -8.838920, -83.970108,
55.606792, -9.225280, -88.166565,
54.969444, -9.224050, -90.099770,
53.838299, -9.223946, -93.303070,
53.306873, -8.978403, -94.172638,
52.650906, -8.965917, -94.952515,
51.887714, -8.996368, -95.627831,
51.039528, -9.026613, -96.188911,
50.129826, -9.014540, -96.649712,
49.222870, -8.981197, -97.115295,
48.318565, -8.911366, -97.583122,
47.407032, -8.808225, -98.034767,
46.444683, -8.756307, -98.366364,
45.445477, -8.719460, -98.562843,
44.439350, -8.698065, -98.728958,
43.434891, -8.691673, -98.905418,
42.430725, -8.697237, -99.084343,
41.420193, -8.729889, -99.213470,
40.401783, -8.750000, -99.201477,
39.386082, -8.750000, -99.108139,
38.369362, -8.608469, -99.026604,
37.361057, -8.409928, -98.944649,
36.363045, -8.166966, -98.861526,
35.034431, -7.813974, -98.752487,
32.699688, -6.851008, -98.521561,
31.706427, -6.493926, -98.351158,
30.710039, -6.000926, -98.189049,
29.718033, -5.638355, -98.035667,
27.425087, -4.956075, -97.658463,
26.132277, -4.406496, -97.462463,
24.151098, -3.967233, -97.131180,
23.171007, -3.334724, -96.848778,
21.888128, -2.891352, -96.503868,
20.588747, -2.189068, -96.150612,
19.361200, -1.888149, -95.630508,
18.459362, -1.703711, -95.191124,
17.273445, -1.238759, -94.619148,
16.358973, -1.074295, -94.199028,
14.863462, -0.812591, -93.437744,
13.995891, -0.681874, -92.918854,
13.124660, -0.652185, -92.401703,
11.981263, -0.068438, -91.754562,
8.189893, 0.131953, -89.508270,
7.381987, 0.088618, -88.886955,
6.571380, 0.027514, -88.269890,
5.766691, -0.002299, -87.654968,
4.945962, 0.000000, -87.049316,
3.883574, 0.000000, -86.202354,
3.126469, 0.000000, -85.518845,
2.370068, -0.119624, -84.843323,
1.614515, -0.303587, -84.175644,
0.857115, 0.000000, -83.495300,
-0.870769, 0.000000, -81.862190,
-1.568556, 0.000000, -81.118217,
-2.269822, 0.000000, -80.377510,
-3.194349, 0.000000, -79.380562,
-3.819240, 0.000000, -78.574409,
-4.449546, 0.000000, -77.772438,
-5.086962, 0.137702, -76.984360,
-7.210657, 0.175519, -74.355286,
-8.692932, -0.185115, -72.536095,
-16.493408, 0.013434, -63.163830,
-26.895781, 0.139084, -51.041916,
-33.461296, 0.306640, -43.713573,
-36.005562, 0.000000, -41.001808,
-38.542736, -0.120660, -38.256161,
-39.083927, 0.000000, -37.397449,
-39.555202, 0.000000, -36.492863,
-40.037514, 0.000000, -35.594105,
-40.526558, 0.000000, -34.698994,
-41.019489, -0.022164, -33.806004,
-41.652416, 0.180338, -32.609749,
-42.016624, 0.293460, -31.678379,
-42.271152, 0.542783, -30.701290,
-42.519249, 0.681291, -29.722433,
-42.795589, 0.826644, -28.744770,
-43.079948, 0.948544, -27.772430,
-45.149635, 0.238260, -20.630129,
-46.271828, 0.000000, -16.723400,
-47.862793, 0.000000, -11.521264,
-48.733509, 0.256991, -8.609860,
-48.896648, 0.324526, -7.606351,
-49.057713, 0.338616, -6.599248,
-49.223305, 0.363505, -5.593130,
-49.390556, 0.374511, -4.587783,
-49.684200, 0.370477, -2.916082,
-49.903740, 0.449262, -0.893895,
-49.922726, 0.454472, 0.125913,
-49.948883, 0.286609, 1.145556,
-50.102844, -0.115937, 2.402715,
-50.156853, 0.000000, 3.761640,
-50.159981, 0.000000, 5.120244,
-50.007885, -0.015259, 6.128576,
-49.857365, -0.045265, 7.137108,
-49.713821, 0.039034, 8.146688,
-49.585705, 0.186338, 9.147921,
-49.455704, 0.302599, 10.150855,
-49.203857, 0.323244, 11.138046,
-48.910267, 0.347195, 12.114579,
-48.625202, 0.370449, 13.093660,
-48.342144, 0.385329, 14.073327,
-48.052616, 0.332701, 15.049960,
-47.667847, 0.274040, 16.352327,
-44.511124, 0.252378, 26.755022,
-43.121750, -0.012623, 30.935074,
-42.260540, -0.049747, 33.517990,
-43.056217, -0.026659, 32.881931,
-43.706509, -0.045365, 32.098381,
-44.169453, 0.000000, 31.191624,
-44.416973, 0.000000, 30.204136,
-44.437744, 0.028373, 29.187935,
-44.234550, 0.147605, 28.197554,
-44.150120, 0.298818, 26.919199,
-44.269028, 0.420611, 25.913910,
-44.344677, 0.461140, 24.897463,
-44.417439, 0.485243, 23.880436,
-44.792072, 0.547829, 18.456495,
-44.909702, 0.520047, 16.761114,
-44.984016, 0.546042, 15.743969,
-45.293648, 0.529866, 11.335310,
-45.466782, -0.292093, 7.003008,
-45.295456, -0.350010, 6.017503,
-45.133808, -0.306995, 5.010587,
-44.979404, -0.288531, 4.002648,
-44.838799, -0.137383, 2.999915,
-44.591873, 0.000000, 1.326093,
-43.541481, -0.290097, -5.380277,
-42.848728, -0.040544, -9.723336,
-42.292336, 0.642154, -13.730497,
-41.547997, 0.916541, -19.108713,
-39.144688, -0.110269, -34.782520,
-38.852798, -0.151156, -35.757435,
-38.562496, -0.267764, -36.734951,
-38.282818, -0.267764, -37.714661,
-37.983608, -0.143293, -38.683777,
-37.691250, 0.000000, -39.649914,
-36.961990, 0.000000, -41.913502,
-36.474354, 0.028213, -42.808399,
-35.971992, 0.226432, -43.673664,
-35.457680, 0.299082, -44.547100,
-34.948200, 0.307759, -45.430702,
-34.437958, 0.280654, -46.312672,
-33.832745, 0.208592, -47.129368,
-33.109161, 0.152678, -47.845551,
-32.362976, 0.178447, -48.540161,
-31.625460, 0.193057, -49.244442,
-30.888935, 0.191501, -49.950066,
-30.152180, 0.191501, -50.655468,
-28.682632, 0.327592, -52.052853,
-22.999739, -0.021864, -57.395721,
-14.951417, 0.053770, -64.715271,
-9.587814, -0.283296, -69.405060,
0.201969, 0.000000, -77.739349,
8.018144, 0.474488, -84.227051,
8.810593, 0.500000, -84.869247,
13.446918, -0.556004, -88.735023,
18.700258, -1.617588, -93.300865,
20.009169, -1.854144, -94.364220,
20.871933, -2.079291, -94.879112,
22.090717, -2.734235, -95.349945,
23.265066, -3.198344, -95.600243,
24.519112, -3.769525, -95.944420,
25.734962, -4.197329, -96.323906,
29.720675, -5.662676, -97.632629,
35.058762, -7.760355, -99.350182,
36.351494, -8.138969, -99.480362,
37.667927, -8.463923, -99.614883,
38.980259, -8.754398, -99.752815,
39.995571, -8.750000, -99.850632,
41.014687, -8.750000, -99.843651,
42.021122, -8.699507, -99.690598,
43.023811, -8.693951, -99.503616,
44.028286, -8.689321, -99.326424,
45.033279, -8.710691, -99.153366,
46.038563, -8.734357, -98.981979,
47.019447, -8.787255, -98.710304,
47.952656, -8.849693, -98.303986,
48.873344, -8.868368, -97.866592,
49.800724, -8.926785, -97.446609,
50.729198, -8.935081, -97.024788,
51.655121, -8.995463, -96.601227,
52.530022, -9.002600, -96.084099,
53.332405, -8.989055, -95.456009,
54.045231, -9.004202, -94.727470,
54.733864, -8.960525, -93.976273,
55.427677, -8.901531, -93.232239,
56.115280, -8.872164, -92.479927,
56.703072, -8.870046, -91.647278,
57.171017, -8.860332, -90.741814,
57.512268, -8.862024, -89.781326,
57.717064, -8.850554, -88.782913,
57.890076, -8.844110, -87.777725,
58.075729, -8.838920, -86.774788,
58.212158, -8.838920, -85.764946,
58.190685, -8.838920, -84.746010,
58.132496, -8.838920, -83.727676,
58.085430, -8.838920, -82.708755,
58.041931, -8.813974, -81.679680,
57.999989, -8.750000, -80.664566,
58.055069, -8.750000, -79.308144,
58.276073, -8.768729, -78.313454,
58.640610, -8.784549, -77.361809,
59.035458, -8.795819, -76.421379,
59.419872, -8.905950, -75.481468,
59.803303, -9.013034, -74.545952,
60.183582, -8.999618, -73.599487,
60.564983, -9.003467, -72.653481,
61.039726, -9.136139, -71.761078,
61.552238, -9.214413, -70.882713,
62.009228, -9.447116, -69.991959,
62.537430, -9.467735, -69.120331,
63.044746, -9.363365, -68.235588,
63.564800, -9.289007, -67.360374,
64.135468, -9.226895, -66.518372,
64.748192, -9.076785, -65.716934,
65.346390, -9.028047, -64.891052,
65.945122, -8.860834, -64.065323,
66.588593, -8.817420, -63.275833,
67.349281, -8.807837, -62.598480,
68.201759, -8.825143, -62.040005,
69.123352, -8.814865, -61.604710,
70.094444, -8.811885, -61.294819,
71.097076, -8.893328, -61.111229,
72.411018, -9.004781, -60.921368,
73.416824, -9.037530, -60.751774,
74.414474, -9.141319, -60.565445,
75.411049, -9.250545, -60.377529,
76.421310, -9.308679, -59.907219,
77.726753, -8.834991, -59.683815,
78.722717, -8.752763, -59.499489,
79.723335, -8.750000, -59.305267,
80.724586, -8.750000, -59.110531,
88.836075, -6.541266, -57.393227,
92.434395, -5.028264, -56.656715,
97.030624, -3.152335, -55.771854,
101.635529, -1.743830, -54.859383,
102.837372, -1.193740, -54.311890,
103.735199, -1.036099, -53.857418,
104.636528, -0.850292, -53.415447,
105.552078, -0.709825, -52.989338,
107.340843, -0.442860, -52.125702,
108.163712, -0.043214, -51.529591,
108.909218, -0.021570, -50.838665,
109.567856, 0.069812, -50.065910,
110.118469, 0.173837, -49.215237,
110.574730, 0.253699, -48.307762,
111.032120, 0.303196, -47.397114,
111.502792, 0.414660, -46.499710,
111.953445, 0.485286, -45.515354,
112.334724, 0.390197, -44.109322,
112.585159, 0.327591, -43.019482,
112.847252, 0.262069, -41.922249,
113.124084, 0.192864, -40.787575,
113.286522, 0.152224, -39.620495,
113.299835, 0.148355, -38.440830,
113.325317, 0.228800, -37.375103,
113.384865, 0.355033, -36.367905,
113.412315, 0.350082, -35.351025,
113.442711, 0.387855, -34.332180,
113.472527, 0.555494, -32.634743,
113.514076, 0.948544, -29.250244,
113.557159, 0.900203, -27.552439,
113.667038, -0.037840, -20.129488,
113.447464, 0.000000, -19.133646,
113.228622, 0.000000, -18.137411,
113.017487, 0.000000, -17.139507,
112.808426, 0.000000, -16.141161,
112.599602, 0.000000, -15.142765,
110.949753, 0.337926, -7.520249,
110.637054, 0.365284, -6.549754,
110.331459, 0.402835, -5.577313,
110.028595, 0.448456, -4.604719,
109.324074, 0.563950, -2.333729,
109.049179, 0.694935, -1.362919,
108.008881, 0.504658, 1.822723,
107.542999, 0.261044, 3.065771
};
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
onMobRoam(mob);
end;
-----------------------------------
-- onPath
-----------------------------------
function onPath(mob)
pathfind.patrol(mob, path);
end;
-----------------------------------
-- onMobRoam
-----------------------------------
function onMobRoam(mob)
-- move to start position if not moving
if (mob:isFollowingPath() == false) then
mob:pathThrough(pathfind.first(path));
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
-- Set Guivre's spawnpoint and respawn time (18-24 hours)
UpdateNMSpawnPoint(mob:getID());
mob:setRespawnTime(math.random(64800,86400));
end; | gpl-3.0 |
smartdevicelink/sdl_atf_test_scripts | test_scripts/Defects/4_5/Trigger_PTU_NO_Certificate/1888_4_secure_video_force_on.lua | 1 | 1506 | ---------------------------------------------------------------------------------------------------
-- Issue: https://github.com/SmartDeviceLink/sdl_core/issues/1888
---------------------------------------------------------------------------------------------------
--[[ Required Shared libraries ]]
local common = require('test_scripts/Defects/4_5/Trigger_PTU_NO_Certificate/common')
local runner = require('user_modules/script_runner')
--[[ Test Configuration ]]
runner.testSettings.isSelfIncluded = false
--[[ Local Variables ]]
local serviceId = 11
local appHMIType = "NAVIGATION"
--[[ General configuration parameters ]]
config.application1.registerAppInterfaceParams.appHMIType = { appHMIType }
--[[ Scenario ]]
runner.Title("Preconditions")
runner.Step("Clean environment", common.preconditions)
runner.Step("Set ForceProtectedService ON", common.setForceProtectedServiceParam, { "0x0B" })
runner.Step("Init SDL certificates", common.initSDLCertificates,
{ "./files/Security/client_credential_expired.pem", false })
runner.Step("Start SDL, HMI, connect Mobile, start Session", common.start)
runner.Step("Register App", common.registerApp)
runner.Step("PolicyTableUpdate without certificate", common.policyTableUpdate, { common.ptUpdateWOcert })
runner.Step("Activate App", common.activateApp)
runner.Title("Test")
runner.Step("StartService Secured ACK", common.startServiceSecured, { serviceId, common.ackData })
runner.Title("Postconditions")
runner.Step("Stop SDL", common.postconditions)
| bsd-3-clause |
Squeakz/darkstar | scripts/zones/Port_Bastok/npcs/Kurando.lua | 12 | 2343 | -----------------------------------
-- Area: Port Bastok
-- NPC: Kurando
-- Type: Quest Giver
-- @zone: 236
-- @pos -23.887 3.898 0.870
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Bastok/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,FEAR_OF_FLYING) == QUEST_ACCEPTED) then
if (trade:hasItemQty(4526,1) and trade:getItemCount() == 1) then
player:startEvent(0x00AB); -- Quest Completion Dialogue
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local FearofFlying = player:getQuestStatus(BASTOK,FEAR_OF_FLYING);
-- csid 0x00Ad ?
if (FearofFlying == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >=3) then
player:startEvent(0x00AA); -- Quest Start Dialogue
elseif (FearofFlying == QUEST_COMPLETED) then
player:startEvent(0x00AC); -- Dialogue after Completion
else
player:startEvent(0x001c); -- Default Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00AA) then
player:addQuest(BASTOK,FEAR_OF_FLYING);
elseif (csid == 0x00AB) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13113);
else
player:tradeComplete();
player:addItem(13113,1);
player:messageSpecial(ITEM_OBTAINED,13113);
player:setTitle(AIRSHIP_DENOUNCER);
player:completeQuest(BASTOK,FEAR_OF_FLYING);
player:addFame(BASTOK,30);
end
end
end; | gpl-3.0 |
ddumont/darkstar | scripts/zones/Kuftal_Tunnel/mobs/Phantom_Worm.lua | 23 | 1639 | -----------------------------------
-- Area: Kuftal Tunnel (173)
-- Mob: Phantom Worm
-----------------------------------
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local npc = GetNPCByID(17490253);
npc:updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME);
local randpos = math.random(1,16);
switch (randpos): caseof
{
[1] = function (x) npc:setPos(75.943,29.969,118.854); end,
[2] = function (x) npc:setPos(75.758,30.000,125.815); end,
[3] = function (x) npc:setPos(65.222,29.364,131.645); end,
[4] = function (x) npc:setPos(53.088,25.033,138.725); end,
[5] = function (x) npc:setPos(85.658,30.155,123.941); end,
[6] = function (x) npc:setPos(91.153,30.146,113.657); end,
[7] = function (x) npc:setPos(86.549,29.875,107.232); end,
[8] = function (x) npc:setPos(94.763,29.054,105.138); end,
[9] = function (x) npc:setPos(102.719,26.751,102.816); end,
[10] = function (x) npc:setPos(71.571,30.241,110.704); end,
[11] = function (x) npc:setPos(65.642,28.018,99.2442); end,
[12] = function (x) npc:setPos(62.090,25.421,93.4702); end,
[13] = function (x) npc:setPos(60.740,22.638,86.1781); end,
[14] = function (x) npc:setPos(80.460,30.293,112.721); end,
[15] = function (x) npc:setPos(76.929,30.050,127.630); end,
[16] = function (x) npc:setPos(68.810,30.175,123.516); end,
}
end; | gpl-3.0 |
ff-kbu/fff-luci | contrib/luadoc/lua/luadoc/taglet/standard.lua | 93 | 16319 | -------------------------------------------------------------------------------
-- @release $Id: standard.lua,v 1.39 2007/12/21 17:50:48 tomas Exp $
-------------------------------------------------------------------------------
local assert, pairs, tostring, type = assert, pairs, tostring, type
local io = require "io"
local posix = require "nixio.fs"
local luadoc = require "luadoc"
local util = require "luadoc.util"
local tags = require "luadoc.taglet.standard.tags"
local string = require "string"
local table = require "table"
module 'luadoc.taglet.standard'
-------------------------------------------------------------------------------
-- Creates an iterator for an array base on a class type.
-- @param t array to iterate over
-- @param class name of the class to iterate over
function class_iterator (t, class)
return function ()
local i = 1
return function ()
while t[i] and t[i].class ~= class do
i = i + 1
end
local v = t[i]
i = i + 1
return v
end
end
end
-- Patterns for function recognition
local identifiers_list_pattern = "%s*(.-)%s*"
local identifier_pattern = "[^%(%s]+"
local function_patterns = {
"^()%s*function%s*("..identifier_pattern..")%s*%("..identifiers_list_pattern.."%)",
"^%s*(local%s)%s*function%s*("..identifier_pattern..")%s*%("..identifiers_list_pattern.."%)",
"^()%s*("..identifier_pattern..")%s*%=%s*function%s*%("..identifiers_list_pattern.."%)",
}
-------------------------------------------------------------------------------
-- Checks if the line contains a function definition
-- @param line string with line text
-- @return function information or nil if no function definition found
local function check_function (line)
line = util.trim(line)
local info = table.foreachi(function_patterns, function (_, pattern)
local r, _, l, id, param = string.find(line, pattern)
if r ~= nil then
return {
name = id,
private = (l == "local"),
param = { } --util.split("%s*,%s*", param),
}
end
end)
-- TODO: remove these assert's?
if info ~= nil then
assert(info.name, "function name undefined")
assert(info.param, string.format("undefined parameter list for function `%s'", info.name))
end
return info
end
-------------------------------------------------------------------------------
-- Checks if the line contains a module definition.
-- @param line string with line text
-- @param currentmodule module already found, if any
-- @return the name of the defined module, or nil if there is no module
-- definition
local function check_module (line, currentmodule)
line = util.trim(line)
-- module"x.y"
-- module'x.y'
-- module[[x.y]]
-- module("x.y")
-- module('x.y')
-- module([[x.y]])
-- module(...)
local r, _, modulename = string.find(line, "^module%s*[%s\"'(%[]+([^,\"')%]]+)")
if r then
-- found module definition
logger:debug(string.format("found module `%s'", modulename))
return modulename
end
return currentmodule
end
-- Patterns for constant recognition
local constant_patterns = {
"^()%s*([A-Z][A-Z0-9_]*)%s*=",
"^%s*(local%s)%s*([A-Z][A-Z0-9_]*)%s*=",
}
-------------------------------------------------------------------------------
-- Checks if the line contains a constant definition
-- @param line string with line text
-- @return constant information or nil if no constant definition found
local function check_constant (line)
line = util.trim(line)
local info = table.foreachi(constant_patterns, function (_, pattern)
local r, _, l, id = string.find(line, pattern)
if r ~= nil then
return {
name = id,
private = (l == "local"),
}
end
end)
-- TODO: remove these assert's?
if info ~= nil then
assert(info.name, "constant name undefined")
end
return info
end
-------------------------------------------------------------------------------
-- Extracts summary information from a description. The first sentence of each
-- doc comment should be a summary sentence, containing a concise but complete
-- description of the item. It is important to write crisp and informative
-- initial sentences that can stand on their own
-- @param description text with item description
-- @return summary string or nil if description is nil
local function parse_summary (description)
-- summary is never nil...
description = description or ""
-- append an " " at the end to make the pattern work in all cases
description = description.." "
-- read until the first period followed by a space or tab
local summary = string.match(description, "(.-%.)[%s\t]")
-- if pattern did not find the first sentence, summary is the whole description
summary = summary or description
return summary
end
-------------------------------------------------------------------------------
-- @param f file handle
-- @param line current line being parsed
-- @param modulename module already found, if any
-- @return current line
-- @return code block
-- @return modulename if found
local function parse_code (f, line, modulename)
local code = {}
while line ~= nil do
if string.find(line, "^[\t ]*%-%-%-") then
-- reached another luadoc block, end this parsing
return line, code, modulename
else
-- look for a module definition
modulename = check_module(line, modulename)
table.insert(code, line)
line = f:read()
end
end
-- reached end of file
return line, code, modulename
end
-------------------------------------------------------------------------------
-- Parses the information inside a block comment
-- @param block block with comment field
-- @return block parameter
local function parse_comment (block, first_line, modulename)
-- get the first non-empty line of code
local code = table.foreachi(block.code, function(_, line)
if not util.line_empty(line) then
-- `local' declarations are ignored in two cases:
-- when the `nolocals' option is turned on; and
-- when the first block of a file is parsed (this is
-- necessary to avoid confusion between the top
-- local declarations and the `module' definition.
if (options.nolocals or first_line) and line:find"^%s*local" then
return
end
return line
end
end)
-- parse first line of code
if code ~= nil then
local func_info = check_function(code)
local module_name = check_module(code)
local const_info = check_constant(code)
if func_info then
block.class = "function"
block.name = func_info.name
block.param = func_info.param
block.private = func_info.private
elseif const_info then
block.class = "constant"
block.name = const_info.name
block.private = const_info.private
elseif module_name then
block.class = "module"
block.name = module_name
block.param = {}
else
block.param = {}
end
else
-- TODO: comment without any code. Does this means we are dealing
-- with a file comment?
end
-- parse @ tags
local currenttag = "description"
local currenttext
table.foreachi(block.comment, function (_, line)
line = util.trim_comment(line)
local r, _, tag, text = string.find(line, "@([_%w%.]+)%s+(.*)")
if r ~= nil then
-- found new tag, add previous one, and start a new one
-- TODO: what to do with invalid tags? issue an error? or log a warning?
tags.handle(currenttag, block, currenttext)
currenttag = tag
currenttext = text
else
currenttext = util.concat(currenttext, line)
assert(string.sub(currenttext, 1, 1) ~= " ", string.format("`%s', `%s'", currenttext, line))
end
end)
tags.handle(currenttag, block, currenttext)
-- extracts summary information from the description
block.summary = parse_summary(block.description)
assert(string.sub(block.description, 1, 1) ~= " ", string.format("`%s'", block.description))
if block.name and block.class == "module" then
modulename = block.name
end
return block, modulename
end
-------------------------------------------------------------------------------
-- Parses a block of comment, started with ---. Read until the next block of
-- comment.
-- @param f file handle
-- @param line being parsed
-- @param modulename module already found, if any
-- @return line
-- @return block parsed
-- @return modulename if found
local function parse_block (f, line, modulename, first)
local block = {
comment = {},
code = {},
}
while line ~= nil do
if string.find(line, "^[\t ]*%-%-") == nil then
-- reached end of comment, read the code below it
-- TODO: allow empty lines
line, block.code, modulename = parse_code(f, line, modulename)
-- parse information in block comment
block, modulename = parse_comment(block, first, modulename)
return line, block, modulename
else
table.insert(block.comment, line)
line = f:read()
end
end
-- reached end of file
-- parse information in block comment
block, modulename = parse_comment(block, first, modulename)
return line, block, modulename
end
-------------------------------------------------------------------------------
-- Parses a file documented following luadoc format.
-- @param filepath full path of file to parse
-- @param doc table with documentation
-- @return table with documentation
function parse_file (filepath, doc, handle, prev_line, prev_block, prev_modname)
local blocks = { prev_block }
local modulename = prev_modname
-- read each line
local f = handle or io.open(filepath, "r")
local i = 1
local line = prev_line or f:read()
local first = true
while line ~= nil do
if string.find(line, "^[\t ]*%-%-%-") then
-- reached a luadoc block
local block, newmodname
line, block, newmodname = parse_block(f, line, modulename, first)
if modulename and newmodname and newmodname ~= modulename then
doc = parse_file( nil, doc, f, line, block, newmodname )
else
table.insert(blocks, block)
modulename = newmodname
end
else
-- look for a module definition
local newmodname = check_module(line, modulename)
if modulename and newmodname and newmodname ~= modulename then
parse_file( nil, doc, f )
else
modulename = newmodname
end
-- TODO: keep beginning of file somewhere
line = f:read()
end
first = false
i = i + 1
end
if not handle then
f:close()
end
if filepath then
-- store blocks in file hierarchy
assert(doc.files[filepath] == nil, string.format("doc for file `%s' already defined", filepath))
table.insert(doc.files, filepath)
doc.files[filepath] = {
type = "file",
name = filepath,
doc = blocks,
-- functions = class_iterator(blocks, "function"),
-- tables = class_iterator(blocks, "table"),
}
--
local first = doc.files[filepath].doc[1]
if first and modulename then
doc.files[filepath].author = first.author
doc.files[filepath].copyright = first.copyright
doc.files[filepath].description = first.description
doc.files[filepath].release = first.release
doc.files[filepath].summary = first.summary
end
end
-- if module definition is found, store in module hierarchy
if modulename ~= nil then
if modulename == "..." then
assert( filepath, "Can't determine name for virtual module from filepatch" )
modulename = string.gsub (filepath, "%.lua$", "")
modulename = string.gsub (modulename, "/", ".")
end
if doc.modules[modulename] ~= nil then
-- module is already defined, just add the blocks
table.foreachi(blocks, function (_, v)
table.insert(doc.modules[modulename].doc, v)
end)
else
-- TODO: put this in a different module
table.insert(doc.modules, modulename)
doc.modules[modulename] = {
type = "module",
name = modulename,
doc = blocks,
-- functions = class_iterator(blocks, "function"),
-- tables = class_iterator(blocks, "table"),
author = first and first.author,
copyright = first and first.copyright,
description = "",
release = first and first.release,
summary = "",
}
-- find module description
for m in class_iterator(blocks, "module")() do
doc.modules[modulename].description = util.concat(
doc.modules[modulename].description,
m.description)
doc.modules[modulename].summary = util.concat(
doc.modules[modulename].summary,
m.summary)
if m.author then
doc.modules[modulename].author = m.author
end
if m.copyright then
doc.modules[modulename].copyright = m.copyright
end
if m.release then
doc.modules[modulename].release = m.release
end
if m.name then
doc.modules[modulename].name = m.name
end
end
doc.modules[modulename].description = doc.modules[modulename].description or (first and first.description) or ""
doc.modules[modulename].summary = doc.modules[modulename].summary or (first and first.summary) or ""
end
-- make functions table
doc.modules[modulename].functions = {}
for f in class_iterator(blocks, "function")() do
if f and f.name then
table.insert(doc.modules[modulename].functions, f.name)
doc.modules[modulename].functions[f.name] = f
end
end
-- make tables table
doc.modules[modulename].tables = {}
for t in class_iterator(blocks, "table")() do
if t and t.name then
table.insert(doc.modules[modulename].tables, t.name)
doc.modules[modulename].tables[t.name] = t
end
end
-- make constants table
doc.modules[modulename].constants = {}
for c in class_iterator(blocks, "constant")() do
if c and c.name then
table.insert(doc.modules[modulename].constants, c.name)
doc.modules[modulename].constants[c.name] = c
end
end
end
if filepath then
-- make functions table
doc.files[filepath].functions = {}
for f in class_iterator(blocks, "function")() do
if f and f.name then
table.insert(doc.files[filepath].functions, f.name)
doc.files[filepath].functions[f.name] = f
end
end
-- make tables table
doc.files[filepath].tables = {}
for t in class_iterator(blocks, "table")() do
if t and t.name then
table.insert(doc.files[filepath].tables, t.name)
doc.files[filepath].tables[t.name] = t
end
end
end
return doc
end
-------------------------------------------------------------------------------
-- Checks if the file is terminated by ".lua" or ".luadoc" and calls the
-- function that does the actual parsing
-- @param filepath full path of the file to parse
-- @param doc table with documentation
-- @return table with documentation
-- @see parse_file
function file (filepath, doc)
local patterns = { "%.lua$", "%.luadoc$" }
local valid = table.foreachi(patterns, function (_, pattern)
if string.find(filepath, pattern) ~= nil then
return true
end
end)
if valid then
logger:info(string.format("processing file `%s'", filepath))
doc = parse_file(filepath, doc)
end
return doc
end
-------------------------------------------------------------------------------
-- Recursively iterates through a directory, parsing each file
-- @param path directory to search
-- @param doc table with documentation
-- @return table with documentation
function directory (path, doc)
for f in posix.dir(path) do
local fullpath = path .. "/" .. f
local attr = posix.stat(fullpath)
assert(attr, string.format("error stating file `%s'", fullpath))
if attr.type == "reg" then
doc = file(fullpath, doc)
elseif attr.type == "dir" and f ~= "." and f ~= ".." then
doc = directory(fullpath, doc)
end
end
return doc
end
-- Recursively sorts the documentation table
local function recsort (tab)
table.sort (tab)
-- sort list of functions by name alphabetically
for f, doc in pairs(tab) do
if doc.functions then
table.sort(doc.functions)
end
if doc.tables then
table.sort(doc.tables)
end
end
end
-------------------------------------------------------------------------------
function start (files, doc)
assert(files, "file list not specified")
-- Create an empty document, or use the given one
doc = doc or {
files = {},
modules = {},
}
assert(doc.files, "undefined `files' field")
assert(doc.modules, "undefined `modules' field")
table.foreachi(files, function (_, path)
local attr = posix.stat(path)
assert(attr, string.format("error stating path `%s'", path))
if attr.type == "reg" then
doc = file(path, doc)
elseif attr.type == "dir" then
doc = directory(path, doc)
end
end)
-- order arrays alphabetically
recsort(doc.files)
recsort(doc.modules)
return doc
end
| apache-2.0 |
Squeakz/darkstar | scripts/globals/mobskills/Corrosive_ooze.lua | 34 | 1192 | ---------------------------------------------------
-- Corrosive Ooze
-- Family: Slugs
-- Description: Deals water damage to an enemy. Additional Effect: Attack Down and Defense Down.
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Radial
-- Notes:
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffectOne = EFFECT_ATTACK_DOWN;
local typeEffectTwo = EFFECT_DEFENSE_DOWN;
local duration = 120;
MobStatusEffectMove(mob, target, typeEffectOne, 15, 0, duration);
MobStatusEffectMove(mob, target, typeEffectTwo, 15, 0, duration);
local dmgmod = 1;
local baseDamage = mob:getWeaponDmg()*4.2;
local info = MobMagicalMove(mob,target,skill,baseDamage,ELE_WATER,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end; | gpl-3.0 |
ff-kbu/fff-luci | contrib/luadoc/lua/luadoc/util.lua | 93 | 5826 | -------------------------------------------------------------------------------
-- General utilities.
-- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local posix = require "nixio.fs"
local type, table, string, io, assert, tostring, setmetatable, pcall = type, table, string, io, assert, tostring, setmetatable, pcall
-------------------------------------------------------------------------------
-- Module with several utilities that could not fit in a specific module
module "luadoc.util"
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string
-- @param s string to be trimmed
-- @return trimmed string
function trim (s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string, considering the
-- string is inside a lua comment.
-- @param s string to be trimmed
-- @return trimmed string
-- @see trim
-- @see string.gsub
function trim_comment (s)
s = string.gsub(s, "%-%-+(.*)$", "%1")
return trim(s)
end
-------------------------------------------------------------------------------
-- Checks if a given line is empty
-- @param line string with a line
-- @return true if line is empty, false otherwise
function line_empty (line)
return (string.len(trim(line)) == 0)
end
-------------------------------------------------------------------------------
-- Appends two string, but if the first one is nil, use to second one
-- @param str1 first string, can be nil
-- @param str2 second string
-- @return str1 .. " " .. str2, or str2 if str1 is nil
function concat (str1, str2)
if str1 == nil or string.len(str1) == 0 then
return str2
else
return str1 .. " " .. str2
end
end
-------------------------------------------------------------------------------
-- Split text into a list consisting of the strings in text,
-- separated by strings matching delim (which may be a pattern).
-- @param delim if delim is "" then action is the same as %s+ except that
-- field 1 may be preceeded by leading whitespace
-- @usage split(",%s*", "Anna, Bob, Charlie,Dolores")
-- @usage split(""," x y") gives {"x","y"}
-- @usage split("%s+"," x y") gives {"", "x","y"}
-- @return array with strings
-- @see table.concat
function split(delim, text)
local list = {}
if string.len(text) > 0 then
delim = delim or ""
local pos = 1
-- if delim matches empty string then it would give an endless loop
if string.find("", delim, 1) and delim ~= "" then
error("delim matches empty string!")
end
local first, last
while 1 do
if delim ~= "" then
first, last = string.find(text, delim, pos)
else
first, last = string.find(text, "%s+", pos)
if first == 1 then
pos = last+1
first, last = string.find(text, "%s+", pos)
end
end
if first then -- found?
table.insert(list, string.sub(text, pos, first-1))
pos = last+1
else
table.insert(list, string.sub(text, pos))
break
end
end
end
return list
end
-------------------------------------------------------------------------------
-- Comments a paragraph.
-- @param text text to comment with "--", may contain several lines
-- @return commented text
function comment (text)
text = string.gsub(text, "\n", "\n-- ")
return "-- " .. text
end
-------------------------------------------------------------------------------
-- Wrap a string into a paragraph.
-- @param s string to wrap
-- @param w width to wrap to [80]
-- @param i1 indent of first line [0]
-- @param i2 indent of subsequent lines [0]
-- @return wrapped paragraph
function wrap(s, w, i1, i2)
w = w or 80
i1 = i1 or 0
i2 = i2 or 0
assert(i1 < w and i2 < w, "the indents must be less than the line width")
s = string.rep(" ", i1) .. s
local lstart, len = 1, string.len(s)
while len - lstart > w do
local i = lstart + w
while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end
local j = i
while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end
s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) ..
string.sub(s, i + 1, -1)
local change = i2 + 1 - (i - j)
lstart = j + change
len = len + change
end
return s
end
-------------------------------------------------------------------------------
-- Opens a file, creating the directories if necessary
-- @param filename full path of the file to open (or create)
-- @param mode mode of opening
-- @return file handle
function posix.open (filename, mode)
local f = io.open(filename, mode)
if f == nil then
filename = string.gsub(filename, "\\", "/")
local dir = ""
for d in string.gfind(filename, ".-/") do
dir = dir .. d
posix.mkdir(dir)
end
f = io.open(filename, mode)
end
return f
end
----------------------------------------------------------------------------------
-- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger.
-- @param options a table with options for the logging mechanism
-- @return logger object that will implement log methods
function loadlogengine(options)
local logenabled = pcall(function()
require "logging"
require "logging.console"
end)
local logging = logenabled and logging
if logenabled then
if options.filelog then
logger = logging.file("luadoc.log") -- use this to get a file log
else
logger = logging.console("[%level] %message\n")
end
if options.verbose then
logger:setLevel(logging.INFO)
else
logger:setLevel(logging.WARN)
end
else
noop = {__index=function(...)
return function(...)
-- noop
end
end}
logger = {}
setmetatable(logger, noop)
end
return logger
end
| apache-2.0 |
jlcvp/otxserver | data/monster/humanoids/elf_arcanist.lua | 2 | 4030 | local mType = Game.createMonsterType("Elf Arcanist")
local monster = {}
monster.description = "an elf arcanist"
monster.experience = 175
monster.outfit = {
lookType = 63,
lookHead = 0,
lookBody = 0,
lookLegs = 0,
lookFeet = 0,
lookAddons = 0,
lookMount = 0
}
monster.raceId = 63
monster.Bestiary = {
class = "Humanoid",
race = BESTY_RACE_HUMANOID,
toKill = 500,
FirstUnlock = 25,
SecondUnlock = 250,
CharmsPoints = 15,
Stars = 2,
Occurrence = 0,
Locations = "Yalahar Foreigner Quarter, Demona, Shadowthorn, northwest of Ab'Dendriel, Maze of Lost Souls, \z
Cyclopolis, Elvenbane, near Mount Sternum."
}
monster.health = 220
monster.maxHealth = 220
monster.race = "blood"
monster.corpse = 6011
monster.speed = 220
monster.manaCost = 0
monster.changeTarget = {
interval = 4000,
chance = 10
}
monster.strategiesTarget = {
nearest = 100,
}
monster.flags = {
summonable = false,
attackable = true,
hostile = true,
convinceable = false,
pushable = false,
rewardBoss = false,
illusionable = false,
canPushItems = true,
canPushCreatures = false,
staticAttackChance = 90,
targetDistance = 4,
runHealth = 0,
healthHidden = false,
isBlockable = false,
canWalkOnEnergy = false,
canWalkOnFire = false,
canWalkOnPoison = false
}
monster.light = {
level = 0,
color = 0
}
monster.voices = {
interval = 5000,
chance = 10,
{text = "Feel my wrath!", yell = false},
{text = "For the Daughter of the Stars!", yell = false},
{text = "I'll bring balance upon you!", yell = false},
{text = "Tha'shi Cenath", yell = false},
{text = "Vihil Ealuel", yell = false}
}
monster.loot = {
{id = 2815, chance = 31000}, -- scroll
{name = "candlestick", chance = 2100},
{name = "gold coin", chance = 37000, maxCount = 47},
{name = "yellow gem", chance = 50},
{name = "life crystal", chance = 970},
{name = "wand of cosmic energy", chance = 1160},
{name = "elven amulet", chance = 1999},
{name = "blank rune", chance = 18000},
{name = "arrow", chance = 6000, maxCount = 3},
{id = 3509, chance = 1000}, -- inkwell
{name = "sandals", chance = 950},
{name = "green tunic", chance = 7000},
{name = "melon", chance = 22000},
{name = "bread", chance = 14000},
{name = "grave flower", chance = 880},
{name = "sling herb", chance = 5000},
{name = "holy orchid", chance = 2100},
{name = "strong mana potion", chance = 3000},
{name = "health potion", chance = 4000},
{name = "elvish talisman", chance = 10000},
{name = "elven astral observer", chance = 7710}
}
monster.attacks = {
{name ="melee", interval = 2000, chance = 100, minDamage = 0, maxDamage = -35},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_PHYSICALDAMAGE, minDamage = 0, maxDamage = -70, range = 7, shootEffect = CONST_ANI_ARROW, target = false},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_ENERGYDAMAGE, minDamage = -30, maxDamage = -50, range = 7, shootEffect = CONST_ANI_ENERGY, effect = CONST_ME_ENERGYHIT, target = false},
{name ="combat", interval = 2000, chance = 10, type = COMBAT_DEATHDAMAGE, minDamage = -70, maxDamage = -85, range = 7, shootEffect = CONST_ANI_SUDDENDEATH, effect = CONST_ME_MORTAREA, target = false}
}
monster.defenses = {
defense = 15,
armor = 15,
{name ="combat", interval = 2000, chance = 15, type = COMBAT_HEALING, minDamage = 40, maxDamage = 60, effect = CONST_ME_MAGIC_BLUE, target = false}
}
monster.elements = {
{type = COMBAT_PHYSICALDAMAGE, percent = 0},
{type = COMBAT_ENERGYDAMAGE, percent = 20},
{type = COMBAT_EARTHDAMAGE, percent = 0},
{type = COMBAT_FIREDAMAGE, percent = 50},
{type = COMBAT_LIFEDRAIN, percent = 0},
{type = COMBAT_MANADRAIN, percent = 0},
{type = COMBAT_DROWNDAMAGE, percent = 0},
{type = COMBAT_ICEDAMAGE, percent = 0},
{type = COMBAT_HOLYDAMAGE , percent = -10},
{type = COMBAT_DEATHDAMAGE , percent = 20}
}
monster.immunities = {
{type = "paralyze", condition = false},
{type = "outfit", condition = false},
{type = "invisible", condition = true},
{type = "bleed", condition = false}
}
mType:register(monster)
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.