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
gfgtdf/wesnoth-old
data/ai/micro_ais/mai-defs/animals.lua
4
6717
local AH = wesnoth.require "ai/lua/ai_helper.lua" local MAIH = wesnoth.require("ai/micro_ais/micro_ai_helper.lua") function wesnoth.micro_ais.big_animals(cfg) local required_keys = { "[filter]"} local optional_keys = { "[avoid_unit]", "[filter_location]", "[filter_location_wander]" } local CA_parms = { ai_id = 'mai_big_animals', { ca_id = "move", location = 'ca_big_animals.lua', score = cfg.ca_score or 300000 } } return required_keys, optional_keys, CA_parms end function wesnoth.micro_ais.wolves(cfg) local required_keys = { "[filter]", "[filter_second]" } local optional_keys = { "attack_only_prey", "avoid_type" } local score = cfg.ca_score or 90000 local CA_parms = { ai_id = 'mai_wolves', { ca_id = "move", location = 'ca_wolves_move.lua', score = score }, { ca_id = "wander", location = 'ca_wolves_wander.lua', score = score - 1 } } if cfg.attack_only_prey then local wolves_aspects = { { aspect = "attacks", facet = { name = "ai_default_rca::aspect_attacks", id = "mai_wolves_" .. (cfg.ca_id or "default") .. "_dont_attack", invalidate_on_gamestate_change = "yes", { "filter_enemy", { { "and", wml.get_child(cfg, "filter_second") } } } } } } if (cfg.action == "delete") then MAIH.delete_aspects(cfg.side, wolves_aspects) else MAIH.add_aspects(cfg.side, wolves_aspects) end elseif cfg.avoid_type then local wolves_aspects = { { aspect = "attacks", facet = { name = "ai_default_rca::aspect_attacks", id = "mai_wolves_" .. (cfg.ca_id or "default") .. "_dont_attack", invalidate_on_gamestate_change = "yes", { "filter_enemy", { { "not", { type=cfg.avoid_type } } } } } } } if (cfg.action == "delete") then MAIH.delete_aspects(cfg.side, wolves_aspects) else MAIH.add_aspects(cfg.side, wolves_aspects) end end return required_keys, optional_keys, CA_parms end function wesnoth.micro_ais.herding(cfg) if (cfg.action ~= 'delete') then AH.get_named_loc_xy('herd', cfg, 'Herding [micro_ai] tag') end local required_keys = { "[filter_location]", "[filter]", "[filter_second]" } local optional_keys = { "attention_distance", "attack_distance", "herd_loc", "herd_x", "herd_y" } local score = cfg.ca_score or 300000 local CA_parms = { ai_id = 'mai_herding', { ca_id = "attack_close_enemy", location = 'ca_herding_attack_close_enemy.lua', score = score }, { ca_id = "sheep_runs_enemy", location = 'ca_herding_sheep_runs_enemy.lua', score = score - 1 }, { ca_id = "sheep_runs_dog", location = 'ca_herding_sheep_runs_dog.lua', score = score - 2 }, { ca_id = "herd_sheep", location = 'ca_herding_herd_sheep.lua', score = score - 3 }, { ca_id = "sheep_move", location = 'ca_herding_sheep_move.lua', score = score - 4 }, { ca_id = "dog_move", location = 'ca_herding_dog_move.lua', score = score - 5 }, { ca_id = "dog_stopmove", location = 'ca_herding_dog_stopmove.lua', score = score - 6 } } return required_keys, optional_keys, CA_parms end local rabbit_registry_counter = 0; local save_rabbit_spawn, save_rabbit_despawn local function register_rabbit_commands() function wesnoth.custom_synced_commands.rabbit_despawn(cfg) --TODO: maybe we only want to allow erasing of unit of certain types/sides/locations? wesnoth.units.erase(cfg.x, cfg.y) end function wesnoth.custom_synced_commands.rabbit_spawn(cfg) --TODO: maybe we only want to allow creation of unit of certain types/sides/locations? wesnoth.units.to_map({ side = wesnoth.current.side, type = cfg.rabbit_type}, cfg.x, cfg.y) end end function wesnoth.persistent_tags.micro_ai_rabbits.read(cfg) rabbit_registry_counter = cfg.counter or 0 register_rabbit_commands() end function wesnoth.persistent_tags.micro_ai_rabbits.write(add) if rabbit_registry_counter > 0 then add{counter = rabbit_registry_counter} end end function wesnoth.micro_ais.forest_animals(cfg) local optional_keys = { "rabbit_type", "rabbit_number", "rabbit_enemy_distance", "rabbit_hole_img", "tusker_type", "tusklet_type", "deer_type", "[filter_location]" } local score = cfg.ca_score or 300000 local CA_parms = { ai_id = 'mai_forest_animals', { ca_id = "new_rabbit", location = 'ca_forest_animals_new_rabbit.lua', score = score }, { ca_id = "tusker_attack", location = 'ca_forest_animals_tusker_attack.lua', score = score - 1 }, { ca_id = "move", location = 'ca_forest_animals_move.lua', score = score - 2 }, { ca_id = "tusklet_move", location = 'ca_forest_animals_tusklet_move.lua', score = score - 3 } } -- Register custom synced commands for the rabbit AI if cfg.action == "delete" then rabbit_registry_counter = rabbit_registry_counter - 1 if rabbit_registry_counter == 0 then wesnoth.custom_synced_commands.rabbit_spawn = save_rabbit_spawn wesnoth.custom_synced_commands.rabbit_despawn = save_rabbit_despawn end else if rabbit_registry_counter == 0 then save_rabbit_spawn = wesnoth.custom_synced_commands.rabbit_spawn save_rabbit_despawn = wesnoth.custom_synced_commands.rabbit_despawn end rabbit_registry_counter = rabbit_registry_counter + 1 register_rabbit_commands() end return {}, optional_keys, CA_parms end function wesnoth.micro_ais.swarm(cfg) local optional_keys = { "[avoid]", "scatter_distance", "vision_distance", "enemy_distance" } local score = cfg.ca_score or 300000 local CA_parms = { ai_id = 'mai_swarm', { ca_id = "scatter", location = 'ca_swarm_scatter.lua', score = score }, { ca_id = "move", location = 'ca_swarm_move.lua', score = score - 1 } } return {}, optional_keys, CA_parms end function wesnoth.micro_ais.wolves_multipacks(cfg) local optional_keys = { "[avoid]", "type", "pack_size", "show_pack_number" } local score = cfg.ca_score or 300000 local CA_parms = { ai_id = 'mai_wolves_multipacks', { ca_id = "attack", location = 'ca_wolves_multipacks_attack.lua', score = score }, { ca_id = "wander", location = 'ca_wolves_multipacks_wander.lua', score = score - 1 } } return {}, optional_keys, CA_parms end function wesnoth.micro_ais.hunter(cfg) if (cfg.action ~= 'delete') then if (not cfg.id) and (not wml.get_child(cfg, "filter")) then wml.error("Hunter [micro_ai] tag requires either id= key or [filter] tag") end AH.get_named_loc_xy('home', cfg, 'Hunter [micro_ai] tag') end local required_keys = {} local optional_keys = { "id", "[filter]", "[filter_location]", "home_loc", "home_x", "home_y", "rest_turns", "show_messages" } local CA_parms = { ai_id = 'mai_hunter', { ca_id = "move", location = 'ca_hunter.lua', score = cfg.ca_score or 300000 } } return required_keys, optional_keys, CA_parms end
gpl-2.0
waytim/darkstar
scripts/zones/Arrapago_Reef/TextIDs.lua
6
1141
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7045; -- You can't fish here -- Assault CANNOT_ENTER = 8433; -- You cannot enter at this time. Please wait a while before trying again. AREA_FULL = 8434; -- This area is fully occupied. You were unable to enter. MEMBER_NO_REQS = 8438; -- Not all of your party members meet the requirements for this objective. Unable to enter area. MEMBER_TOO_FAR = 8442; -- One or more party members are too far away from the entrance. Unable to enter area. -- Other Texts NOTHING_HAPPENS = 119; -- Nothing happens... RESPONSE = 7320; -- There is no response... -- Medusa MEDUSA_ENGAGE = 8544; -- Foolish two-legs... Have you forgotten the terrible power of the gorgons you created? It is time you were reminded... MEDUSA_DEATH = 8545; -- No... I cannot leave my sisters...
gpl-3.0
drxspace/cronoconky
cronograph_blk/scripts/clock_rings.lua
1
10950
--[[ Clock Rings by londonali1010 (2009) This script draws percentage meters as rings, and also draws clock hands if you want! It is fully customisable; all options are described in the script. This script is based off a combination of my clock.lua script and my rings.lua script. IMPORTANT: if you are using the 'cpu' function, it will cause a segmentation fault if it tries to draw a ring straight away. The if statement near the end of the script uses a delay to make sure that this doesn't happen. It calculates the length of the delay by the number of updates since Conky started. Generally, a value of 5s is long enough, so if you update Conky every 1s, use update_num > 5 in that if statement (the default). If you only update Conky every 2s, you should change it to update_num > 3; conversely if you update Conky every 0.5s, you should use update_num > 10. ALSO, if you change your Conky, is it best to use "killall conky; conky" to update it, otherwise the update_num will not be reset and you will get an error. To call this script in Conky, use the following (assuming that you save this script to ~/scripts/rings.lua): lua_load ~/scripts/clock_rings-v1.1.1.lua lua_draw_hook_pre clock_rings Changelog: + v1.1.1 -- Fixed minor bug that caused the script to crash if conky_parse() returns a nil value (20.10.2009) + v1.1 -- Added colour option for clock hands (07.10.2009) + v1.0 -- Original release (30.09.2009) ]] require 'cairo' local settings_table = { { -- Edit this table to customise your rings. -- You can create more rings simply by adding more elements to settings_table. -- "name" is the type of stat to display; you can choose from 'cpu', -- 'memperc', 'fs_used_perc', 'battery_used_perc'. name='time', -- "arg" is the argument to the stat type, e.g. if in Conky you -- would write ${cpu cpu0}, 'cpu0' would be the argument. If you -- would not use an argument in the Conky variable, use ''. arg='%I', -- .%M', -- "max" is the maximum value of the ring. If the Conky variable outputs a percentage, use 100. max=12, -- "bg_colour" is the colour of the base ring. bg_colour=0x333333, -- "bg_alpha" is the alpha value of the base ring. bg_alpha=0.6, -- "fg_colour" is the colour of the indicator part of the ring. fg_colour=0x000000, -- "fg_alpha" is the alpha value of the indicator part of the ring. fg_alpha=0.9, -- "x" and "y" are the x and y coordinates of the centre of the ring, relative to the top left corner of the Conky window. x=150, y=150, -- "radius" is the radius of the ring. radius=145, -- "thickness" is the thickness of the ring, centred around the radius. thickness=4, -- "start_angle" is the starting angle of the ring, in degrees, clockwise from top. Value can be either positive or negative. start_angle=0, -- "end_angle" is the ending angle of the ring, in degrees, clockwise from top. Value can be either positive or negative, but must be larger than start_angle. end_angle=360 }, { name='time', arg='%M', -- .%S', max=60, bg_colour=0x555555, bg_alpha=0.6, fg_colour=0x000000, fg_alpha=0.7, x=150, y=150, radius=140, thickness=4, start_angle=0, end_angle=360 }, { name='time', arg='%S', max=60, bg_colour=0x777777, bg_alpha=0.6, fg_colour=0x000000, fg_alpha=0.5, x=150, y=150, radius=135, thickness=4, start_angle=0, end_angle=360 }, --[[ -- due to background circle image { -- Watch inside drawing name='', arg='', max=100, --bg_colour=0x404040, --bg_alpha=0.2, bg_colour=0xFFFFFF, bg_alpha=0.0, fg_colour=0xFFFFFF, fg_alpha=0.0, x=150, y=150, radius=66, thickness=130, start_angle=0, end_angle=360 }, { -- Watch center circle name='', arg='', max=100, bg_colour=0xFFD700, bg_alpha=0.3, fg_colour=0x000000, fg_alpha=0.0, x=150, y=150, radius=1, thickness=40, start_angle=0, end_angle=360 },]] { -- cpu outline name='', arg='', max=100, bg_colour=0x000000, bg_alpha=1.0, fg_colour=0x000000, fg_alpha=0.0, x=85, y=150, radius=30, thickness=1, start_angle=0, end_angle=360 }, { -- cpu inside name='', arg='', max=100, bg_colour=0xF3F9FF, bg_alpha=0.33, fg_colour=0xFFFFFF, fg_alpha=0.0, x=85, y=150, radius=16, thickness=27, start_angle=0, end_angle=360 }, { -- cpu inside dot name='', arg='', max=100, bg_colour=0xFFD700, bg_alpha=0.9, fg_colour=0x000000, fg_alpha=0.0, x=85, y=150, radius=1, thickness=3, start_angle=0, end_angle=360 }, { -- mem outline name='', arg='', max=100, bg_colour=0x000000, bg_alpha=1.0, fg_colour=0x000000, fg_alpha=0.0, x=215, y=150, radius=30, thickness=1, start_angle=0, end_angle=360 }, { -- mem inside name='', arg='', max=100, bg_colour=0xF3F9FF, bg_alpha=0.33, fg_colour=0xFFFFFF, fg_alpha=0.0, x=215, y=150, radius=16, thickness=27, start_angle=0, end_angle=360 }, { -- mem inside dot name='', arg='', max=100, bg_colour=0xFFD700, bg_alpha=0.9, fg_colour=0x000000, fg_alpha=0.0, x=215, y=150, radius=1, thickness=3, start_angle=0, end_angle=360 }, { -- hdd outline name='', arg='', max=100, bg_colour=0x000000, bg_alpha=1.0, fg_colour=0x000000, fg_alpha=0.0, x=150, y=75, radius=25, thickness=1, start_angle=0, end_angle=360 }, { -- hdd inside name='', arg='', max=100, bg_colour=0xF3FFFF, bg_alpha=0.33, fg_colour=0xFFFFFF, fg_alpha=0.0, x=150, y=75, radius=14, thickness=22, start_angle=0, end_angle=360 }, { -- hdd inside dot name='', arg='', max=100, bg_colour=0xFFD700, bg_alpha=0.9, fg_colour=0xFFFFFF, fg_alpha=0.0, x=150, y=75, radius=1, thickness=3, start_angle=0, end_angle=360 }, } -- Use these settings to define the origin and extent of your clock. local clock_r=128 -- "clock_x" and "clock_y" are the coordinates of the centre of the clock, in pixels, from the top left of the Conky window. local clock_x=150 local clock_y=150 -- Colour & alpha of the clock hands local hours_colour=0x383436 local mins_colour=0x202020 local secs_colour=0x830000 local secs_shd_colour=0x888888 local secs_shade_off=4 local clock_alpha=0.7 -- Do you want to show the seconds hand? local show_seconds=true local function rgb_to_r_g_b(colour,alpha) return ((colour / 0x10000) % 0x100) / 255., ((colour / 0x100) % 0x100) / 255., (colour % 0x100) / 255., alpha end local function draw_ring(cr,t,pt) local w,h=conky_window.width,conky_window.height local xc,yc,ring_r,ring_w,sa,ea=pt['x'],pt['y'],pt['radius'],pt['thickness'],pt['start_angle'],pt['end_angle'] local bgc, bga, fgc, fga=pt['bg_colour'], pt['bg_alpha'], pt['fg_colour'], pt['fg_alpha'] local angle_0=sa*(2*math.pi/360)-math.pi/2 local angle_f=ea*(2*math.pi/360)-math.pi/2 local t_arc=t*(angle_f-angle_0) cairo_set_line_width(cr,ring_w) -- Draw ring cairo_set_source_rgba(cr,rgb_to_r_g_b(bgc,bga)) cairo_arc(cr,xc,yc,ring_r,angle_0,angle_f) cairo_stroke(cr) -- Draw indicator ring cairo_set_source_rgba(cr,rgb_to_r_g_b(fgc,fga)) cairo_arc(cr,xc,yc,ring_r,angle_0,angle_0+t_arc) cairo_stroke(cr) end local function draw_clock_hands(cr,xc,yc) local secs,mins,hours,secs_arc,mins_arc,hours_arc local xh,yh,xm,ym,xs,ys local xxh,yyh,xxm,yym,xxs,yys local saved_lc secs=os.date("%S") mins=os.date("%M") hours=os.date("%I") secs_arc=(2*math.pi/60)*secs mins_arc=(2*math.pi/60)*mins+secs_arc/60 hours_arc=(2*math.pi/12)*hours+mins_arc/12 saved_lc=cairo_get_line_cap (cr); cairo_set_line_cap(cr,CAIRO_LINE_CAP_ROUND) -- Draw hour hand xh=xc+0.55*clock_r*math.sin(hours_arc) yh=yc-0.55*clock_r*math.cos(hours_arc) -- and hour backhand xxh=xc-0.12*clock_r*math.sin(hours_arc) yyh=yc+0.12*clock_r*math.cos(hours_arc) cairo_set_line_width(cr,11) cairo_set_source_rgba(cr,rgb_to_r_g_b(hours_colour,clock_alpha)) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xh,yh) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xxh,yyh) cairo_stroke(cr) -- Draw minute hand xm=xc+0.80*clock_r*math.sin(mins_arc) ym=yc-0.80*clock_r*math.cos(mins_arc) -- and minute backhand xxm=xc-0.20*clock_r*math.sin(mins_arc) yym=yc+0.20*clock_r*math.cos(mins_arc) cairo_set_line_width(cr,7) cairo_set_source_rgba(cr,rgb_to_r_g_b(mins_colour,clock_alpha)) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xm,ym) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xxm,yym) cairo_stroke(cr) if show_seconds then xs=xc+0.92*clock_r*math.sin(secs_arc) ys=yc-0.92*clock_r*math.cos(secs_arc) xxs=xc-0.31*clock_r*math.sin(secs_arc) yys=yc+0.31*clock_r*math.cos(secs_arc) -- Draw seconds hand shade -- and seconds backhand shade cairo_set_line_width(cr,1) cairo_set_source_rgba(cr,rgb_to_r_g_b(secs_shd_colour,clock_alpha)) cairo_move_to(cr,xc+secs_shade_off,yc+secs_shade_off) cairo_line_to(cr,xs+secs_shade_off,ys+secs_shade_off) cairo_move_to(cr,xc+secs_shade_off,yc+secs_shade_off) cairo_line_to(cr,xxs+secs_shade_off,yys+secs_shade_off) cairo_stroke(cr) -- Draw seconds hand -- and seconds backhand cairo_set_line_width(cr,2) cairo_set_source_rgba(cr,rgb_to_r_g_b(secs_colour,clock_alpha)) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xs,ys) cairo_move_to(cr,xc,yc) cairo_line_to(cr,xxs,yys) cairo_stroke(cr) end -- Draw center dot/screw cairo_set_source_rgba(cr,rgb_to_r_g_b(0xFFD700,0.9)) cairo_set_line_width(cr,3) cairo_arc(cr,xc,yc,1,0,360) cairo_stroke(cr) -- Restore line cap cairo_set_line_cap (cr,saved_lc) end function conky_clock_rings() local function setup_rings(cr,pt) local str, value = '', 0 local pct str = string.format('${%s %s}', pt['name'], pt['arg']) if pt['name'] == '' then str = 0 value = 0 else str=conky_parse(str) value = tonumber(str) end if (pt['arg'] == '%I' and value > 12) then value = value - 12 elseif ((pt['arg'] == '%M' or pt['arg'] == '%S') and value == 0) then value = 60 end pct=value/pt['max'] draw_ring(cr,pct,pt) end -- Check that Conky has been running for at least 2s -- We use the lua_loader script that makes wait for this if (conky_window == nil) or (tonumber(conky_parse('${updates}')) < 2) then return end local cs = cairo_xlib_surface_create(conky_window.display, conky_window.drawable, conky_window.visual, conky_window.width, conky_window.height) local cr = cairo_create(cs) -- This function references surface, so you can immediately call -- cairo_surface_destroy() on it if you don't need to maintain a separate reference to it. cairo_surface_destroy(cs) cs = nil for i in pairs(settings_table) do setup_rings(cr, settings_table[i]) end draw_clock_hands(cr, clock_x, clock_y) cairo_destroy(cr) cr = nil -- #419 memory leak when calling top objects with conky_parse in lua -- http://sourceforge.net/p/conky/bugs/419/ collectgarbage() return end
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c121200111.lua
2
5095
--Guardian of the Flora - Colwrath -- Idea: Aslan -- Script: Shad3 --[[ This card is treated as a Normal Monster while face-up on the field or in the Graveyard or Extra Deck. While this card is a Normal Monster on the field, you can Normal Summon it to have it become an Effect Monster with these effects. ● Once per turn: You can Tribute other monsters you control (max. 2); increase this card's Level by twice the amount of the Tributed monsters, as long as this card is face-up on the field. ● This Level 5 or higher card can attack twice during each Battle Phase. ● While this Level 7 or higher card is face-up on the field, any card that would be sent to your opponent's Extra Deck is banished instead. --]] local function getID() local str=string.match(debug.getinfo(2,'S')['source'],"c%d+%.lua") str=string.sub(str,1,string.len(str)-4) local scard=_G[str] local s_id=tonumber(string.sub(str,2)) return scard,s_id end local scard,s_id=getID() --common Flora functions & effects if not Auxiliary.FloraCommons then Auxiliary.FloraCommons=true --Normalmonster in PZone local cgt=Card.GetType Card.GetType=function(c) if c:IsLocation(LOCATION_EXTRA) and c:IsHasEffect(121200100) then return bit.bxor(cgt(c),TYPE_EFFECT+TYPE_NORMAL) else return cgt(c) end end local cit=Card.IsType Card.IsType=function(c,ty) if c:IsLocation(LOCATION_EXTRA) and c:IsHasEffect(121200100) then return bit.band(c:GetType(),ty)~=0 else return cit(c,ty) end end --Flora Set card function Auxiliary.SetCardFlora(c) return c:IsSetCard(0xa8b) or c:IsCode(36318200,500000142,500000143,511000002) end --mentions Gemini in Extra Deck function Auxiliary.GeminiMentionExtra(c) if c.mention_gemini then return true end local cd=c:GetOriginalCode() return cd==64463828 or cd==96029574 or cd==38026562 end end --redirectfunction if not scard.gl_reg then scard.gl_reg=true local f1=Card.IsAbleToExtraAsCost Card.IsAbleToExtraAsCost=function(c) if Duel.IsPlayerAffectedByEffect(c:GetOwner(),s_id) then return false end return f1(c) end local f2=Card.IsAbleToDeckOrExtraAsCost Card.IsAbleToDeckOrExtraAsCost=function(c) if bit.band(c:GetOriginalType(),TYPE_SYNCHRO+TYPE_FUSION+TYPE_XYZ)~=0 and Duel.IsPlayerAffectedByEffect(c:GetOwner(),s_id) then return false end return f2(c) end end function scard.initial_effect(c) aux.EnableDualAttribute(c) aux.EnablePendulumAttribute(c) --norpendulum local e0=Effect.CreateEffect(c) e0:SetType(EFFECT_TYPE_SINGLE) e0:SetCode(121200100) c:RegisterEffect(e0) --level increase local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetDescription(aux.Stringid(s_id,0)) e1:SetCondition(aux.IsDualState) e1:SetCost(scard.a_cs) e1:SetOperation(scard.a_op) c:RegisterEffect(e1) --DblATK local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_EXTRA_ATTACK) e2:SetDescription(aux.Stringid(s_id,1)) e2:SetCondition(scard.b_cd) e2:SetValue(1) c:RegisterEffect(e2) --SendRep local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetCode(EFFECT_SEND_REPLACE) e3:SetRange(LOCATION_MZONE) e3:SetDescription(aux.Stringid(s_id,2)) e3:SetCondition(scard.c_cd) e3:SetTarget(scard.c_tg) e3:SetValue(scard.c_val) e3:SetOperation(scard.c_op) c:RegisterEffect(e3) local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD) e4:SetCode(s_id) e4:SetRange(LOCATION_MZONE) e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e4:SetTargetRange(0,1) e4:SetCondition(scard.c_cd) c:RegisterEffect(e4) end function scard.a_cs(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.CheckReleaseGroup(tp,aux.TRUE,1,e:GetHandler()) end local g=Duel.SelectReleaseGroup(tp,aux.TRUE,1,2,e:GetHandler()) Duel.Release(g,REASON_COST) e:GetHandler():RegisterFlagEffect(s_id,RESET_EVENT+0x1fe0000+RESET_CHAIN,0,0,g:GetCount()) end function scard.a_op(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() and c:GetFlagEffect(s_id)~=0 then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_LEVEL) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetValue(c:GetFlagEffectLabel(s_id)*2) c:RegisterEffect(e1) end end function scard.b_cd(e) return aux.IsDualState(e) and e:GetHandler():IsLevelAbove(5) end function scard.c_fil(c,p) return c:GetOwner()==p and c:GetDestination()==LOCATION_EXTRA and c:IsAbleToRemove() end function scard.c_cd(e) return aux.IsDualState(e) and e:GetHandler():IsLevelAbove(7) end function scard.c_tg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(scard.c_fil,1,nil,1-tp) end local g=eg:Filter(scard.c_fil,nil,1-tp) g:KeepAlive() e:SetLabelObject(g) return true end function scard.c_val(e,c) local g=e:GetLabelObject() return g and g:IsContains(c) end function scard.c_op(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() if g then Duel.Remove(g,POS_FACEUP,REASON_EFFECT+REASON_REPLACE) g:DeleteGroup() end end
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Metalworks/npcs/Chantain.lua
5
1050
----------------------------------- -- Area: Metalworks -- NPC: Chantain -- Type: Consulate Representative -- @zone: 237 -- @pos: 21.729 -17 -30.888 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00cb); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
waytim/darkstar
scripts/globals/items/plate_of_squid_sushi_+1.lua
17
1540
----------------------------------------- -- ID: 5162 -- Item: plate_of_squid_sushi_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Health 30 -- Dexterity 6 -- Agility 5 -- Accuracy % 16 -- Ranged ACC % 16 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5162); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 30); target:addMod(MOD_DEX, 6); target:addMod(MOD_AGI, 5); target:addMod(MOD_FOOD_ACCP, 16); target:addMod(MOD_FOOD_RACCP, 16); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 30); target:delMod(MOD_DEX, 6); target:delMod(MOD_AGI, 5); target:delMod(MOD_FOOD_ACCP, 16); target:delMod(MOD_FOOD_RACCP, 16); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
waytim/darkstar
scripts/globals/effects/afflatus_misery.lua
33
1221
----------------------------------- -- -- EFFECT_AFFLATUS_MISERY -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:setMod(MOD_AFFLATUS_MISERY,0); if (target:hasStatusEffect(EFFECT_AUSPICE)) then local power = target:getStatusEffect(EFFECT_AUSPICE):getPower(); target:addMod(MOD_ENSPELL,18); target:addMod(MOD_ENSPELL_DMG, power); end end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:setMod(MOD_AFFLATUS_MISERY,0); --Clean Up Afflatus Misery Bonuses local accuracyBonus = effect:getSubPower(); --printf("AUSPICE: Removing Accuracy Bonus +%d!", accuracyBonus); target:delMod(MOD_ACC, accuracyBonus); if (target:hasStatusEffect(EFFECT_AUSPICE)) then target:setMod(MOD_ENSPELL,0); target:setMod(MOD_ENSPELL_DMG, 0); end end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c66666607.lua
2
2868
--Aetherius function c66666607.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --atkup local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetRange(LOCATION_FZONE) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x144)) e2:SetValue(500) c:RegisterEffect(e2) --indes local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e3:SetRange(LOCATION_SZONE) e3:SetTargetRange(LOCATION_MZONE,0) e3:SetTarget(aux.TargetBoolFunction(Card.IsSetCard,0x144)) e3:SetValue(1) c:RegisterEffect(e3) --Destroy replace local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(66666607,0)) e4:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_DESTROY_REPLACE) e4:SetTarget(c66666607.desreptg) e4:SetOperation(c66666607.desrepop) c:RegisterEffect(e4) --Destroy Pendulums local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(57554544,2)) e5:SetCategory(CATEGORY_DESTROY) e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e5:SetCode(EVENT_TO_GRAVE) e5:SetCondition(c66666607.descon) e5:SetTarget(c66666607.destg) e5:SetOperation(c66666607.desop) c:RegisterEffect(e5) end function c66666607.repfilter(c) return c:IsType(TYPE_MONSTER) and c:IsSetCard(0x144) and not c:IsStatus(STATUS_LEAVE_CONFIRMED) end function c66666607.desreptg(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return not c:IsReason(REASON_REPLACE) and c:IsOnField() and Duel.IsExistingMatchingCard(c66666607.repfilter,tp,LOCATION_MZONE,0,1,c) end if Duel.SelectYesNo(tp,aux.Stringid(66666607,0)) then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE) local g=Duel.SelectMatchingCard(tp,c66666607.repfilter,tp,LOCATION_MZONE,0,1,1,c) Duel.SetTargetCard(g) g:GetFirst():SetStatus(STATUS_LEAVE_CONFIRMED,true) return true else return false end end function c66666607.desrepop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS) g:GetFirst():SetStatus(STATUS_LEAVE_CONFIRMED,false) Duel.Release(g,REASON_EFFECT+REASON_REPLACE) end function c66666607.desfilter(c) return c:IsType(TYPE_PENDULUM) and c:IsDestructable() end function c66666607.descon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousLocation(LOCATION_SZONE) and c:GetPreviousSequence()==5 end function c66666607.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(c66666607.desfilter,tp,LOCATION_MZONE,0,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c66666607.desop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetMatchingGroup(c66666607.desfilter,tp,LOCATION_MZONE,0,nil) Duel.Destroy(g,REASON_EFFECT) end
gpl-3.0
waytim/darkstar
scripts/globals/items/bowl_of_oceanfin_soup.lua
18
1891
----------------------------------------- -- ID: 6070 -- Item: Bowl of Oceanfin Soup -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- Accuracy % 15 Cap 95 -- Ranged Accuracy % 15 Cap 95 -- Attack % 19 Cap 85 -- Ranged Attack % 19 Cap 85 -- Amorph Killer 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,6070); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 95); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 95); target:addMod(MOD_FOOD_ATTP, 19); target:addMod(MOD_FOOD_ATT_CAP, 85); target:addMod(MOD_FOOD_RATTP, 19); target:addMod(MOD_FOOD_RATT_CAP, 85); target:addMod(MOD_AMORPH_KILLER, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 95); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 95); target:delMod(MOD_FOOD_ATTP, 19); target:delMod(MOD_FOOD_ATT_CAP, 85); target:delMod(MOD_FOOD_RATTP, 19); target:delMod(MOD_FOOD_RATT_CAP, 85); target:delMod(MOD_AMORPH_KILLER, 6); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Labyrinth_of_Onzozo/MobIDs.lua
31
2026
----------------------------------- -- Area: Labyrinth of Onzozo (213) -- Comments: -- posX, posY, posZ --(Taken from 'mob_spawn_points' table) ----------------------------------- -- Mysticmaker Profblix Mysticmaker_Profblix=17649693; -- Lord of Onzozo Lord_of_Onzozo=17649731; Lord_of_Onzozo_PH={ [17649730] = '1', -- -39.356, 14.265, -60.406 }; -- Ose Ose=17649822; Ose_PH={ [17649813] = '1', -- -1.758, 4.982, 153.412 [17649814] = '1', -- 8.113, 5.055, 159.197 [17649824] = '1', -- 9.000, 4.000, 176.000 [17649819] = '1', -- -7.000, 4.467, 184.000 [17649820] = '1', -- -7.233, 4.976, 204.202 [17649823] = '1', -- 26.971, 4.440, 216.229 [17649816] = '1', -- 48.440, 5.070, 174.352 [17649815] = '1', -- 39.858, 4.364, 164.961 }; -- Soulstealer Skullnix Soulstealer_Skullnix=17649818; Soulstealer_Skullnix_PH={ [17649838] = '1', -- 38.347, 5.500, 178.050 [17649834] = '1', -- 43.103, 5.677, 181.977 [17649843] = '1', -- 41.150, 5.026, 204.483 [17649825] = '1', -- 24.384, 5.471, 197.938 [17649829] = '1', -- 13.729, 4.814, 166.295 [17649831] = '1', -- 5.096, 3.930, 166.865 }; -- Narasimha Narasimha=17649784; Narasimha_PH={ [17649783] = '1', -- -119.897, 0.275, 127.060 [17649787] = '1', -- -126.841, -0.554, 129.681 [17649790] = '1', -- -140.000, -0.955, 144.000 }; -- Hellion Hellion=17649795; Hellion_PH={ [17649797] = '1', -- 136.566, 14.708, 70.077 [17649810] = '1', -- 127.523, 14.327, 210.258 }; -- Peg Powler Peg_Powler=17649761; Peg_Powler_PH={ [17649755] = '1', -- -100.912, 4.263, -21.983 [17649759] = '1', -- -128.471, 4.952, 0.489 [17649760] = '1', -- -104.000, 4.000, 28.000 [17649758] = '1', -- -111.183, 5.357, 44.411 [17649762] = '1', -- -81.567, 5.013, 37.186 [17649763] = '1', -- -72.956, 4.943, 39.293 [17649770] = '1', -- -33.112, 4.735, 34.742 [17649769] = '1', -- -51.745, 4.288, 46.295 [17649774] = '1', -- -54.100, 5.462, 81.680 [17649773] = '1', -- -65.089, 5.386, 81.363 [17649766] = '1', -- -64.269, 5.441, 72.382 };
gpl-3.0
mehrpouya81/gamerspm
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
DevPGSV/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
siktirmirza/uzz
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
RockySeven3161/PRO
plugins/groupmanager.lua
14
16269
-- data saved to data/moderation.json do local function gpadd(msg) -- because sudo are always has privilege if not is_sudo(msg) then return nil end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end -- create data array in moderation.json data[tostring(msg.to.id)] = { moderators ={}, settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_bots = 'no', lock_name = 'no', lock_photo = 'no', lock_member = 'no', anti_flood = 'no', welcome = 'no' } } save_data(_config.moderation.data, data) return 'Group has been added.' end local function gprem(msg) -- because sudo are always has privilege if not is_sudo(msg) then return nil end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if not data[tostring(msg.to.id)] then return 'Group is not added.' end data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return 'Group has been removed' end local function export_chat_link_callback(extra, success, result) local receiver = extra.receiver local data = extra.data local chat_id = extra.chat_id local group_name = extra.group_name if success == 0 then return send_large_msg(receiver, "Can't generate invite link for this group.\nMake sure you're the admin or sudoer.") end data[tostring(chat_id)]['link'] = result save_data(_config.moderation.data, data) return send_large_msg(receiver,'Newest generated invite link for '..group_name..' is:\n'..result) end local function set_description(msg, data) if not is_sudo(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set group description to:\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] return string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about end local function set_rules(msg, data) if not is_sudo(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules return rules end -- dis/allow APIs bots to enter group. Spam prevention. local function allow_api_bots(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots'] if group_bot_lock == 'no' then return 'Bots allowed to enter group.' else data[tostring(msg.to.id)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Group is open for bots.' end end local function disallow_api_bots(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bots'] if group_bot_lock == 'yes' then return 'Group already locked from bots.' else data[tostring(msg.to.id)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Group is locked from bots.' end end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name has been locked' end end local function unlock_group_name(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(msg.to.id)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data) if not is_sudo(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_sudo(msg) then return "For moderators only!" end local settings = data[tostring(msg.to.id)]['settings'] if settings.lock_bots == 'yes' then lock_bots_state = '🔒' elseif settings.lock_bots == 'no' then lock_bots_state = '🔓' end if settings.lock_name == 'yes' then lock_name_state = '🔒' elseif settings.lock_name == 'no' then lock_name_state = '🔓' end if settings.lock_photo == 'yes' then lock_photo_state = '🔒' elseif settings.lock_photo == 'no' then lock_photo_state = '🔓' end if settings.lock_member == 'yes' then lock_member_state = '🔒' elseif settings.lock_member == 'no' then lock_member_state = '🔓' end if settings.anti_flood ~= 'no' then antiflood_state = '🔒' elseif settings.anti_flood == 'no' then antiflood_state = '🔓' end if settings.welcome ~= 'no' then greeting_state = '🔒' elseif settings.welcome == 'no' then greeting_state = '🔓' end local text = 'Group settings:\n' ..'\n'..lock_bots_state..' Lock group from bot : '..settings.lock_bots ..'\n'..lock_name_state..' Lock group name : '..settings.lock_name ..'\n'..lock_photo_state..' Lock group photo : '..settings.lock_photo ..'\n'..lock_member_state..' Lock group member : '..settings.lock_member ..'\n'..antiflood_state..' Flood protection : '..settings.anti_flood ..'\n'..greeting_state..' Welcome message : '..settings.welcome return text end -- media handler. needed by group_photo_lock local function pre_process(msg) if not msg.text and msg.media then msg.text = '['..msg.media.type..']' end return msg end function run(msg, matches) if not is_chat_msg(msg) then return "This is not a group chat." end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) -- add a group to be moderated if matches[1] == 'gpadd' then return gpadd(msg) end -- remove group from moderation if matches[1] == 'gprem' then return gprem(msg) end if msg.media and is_chat_msg(msg) and is_sudo(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end -- group link {get|set} if matches[1] == 'link' then local chat = 'chat#id'..msg.to.id if matches[2] == 'get' then if data[tostring(msg.to.id)]['link'] then local about = get_description(msg, data) local link = data[tostring(msg.to.id)]['link'] return about.."\n\n"..link else return "Invite link is not exist.\nTry !link set to generate it." end end if matches[2] == 'set' and is_sudo(msg) then msgr = export_chat_link('chat#id'..msg.to.id, export_chat_link_callback, {receiver=receiver, data=data, chat_id=msg.to.id, group_name=msg.to.print_name}) end end -- lock {bot|name|member|photo} if matches[1] == 'group' and matches[2] == 'lock' then if matches[3] == 'bot' then return disallow_api_bots(msg, data) end if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end end -- unlock {bot|name|member|photo} if matches[1] == 'group' and matches[2] == 'unlock' then if matches[3] == 'bot' then return allow_api_bots(msg, data) end if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end end -- view group settings if matches[1] == 'group' and matches[2] == 'settings' then return show_group_settings(msg, data) end -- if group name is renamed if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end -- set group name if matches[1] == 'setname' and is_sudo(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end -- set group photo if matches[1] == 'setphoto' and is_sudo(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end -- if a user is added to group if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local group_bot_lock = settings.lock_bots local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) -- no APIs bot are allowed to enter chat group. elseif group_bot_lock == 'yes' and msg.action.user.flags == 4352 then chat_del_user(chat, user, ok_cb, true) elseif group_bot_lock == 'no' or group_member_lock == 'no' then return nil end end -- if group photo is deleted if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end -- if group photo is changed if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Plugin to manage group chat.", usage = { "!about : Read group description", "!gpadd : Add group to moderation list.", "!gprem : Remove group from moderation list.", "!group <lock|unlock> bot : {Dis}allow APIs bots", "!group <lock|unlock> member : Lock/unlock group member", "!group <lock|unlock> name : Lock/unlock group name", "!group <lock|unlock> photo : Lock/unlock group photo", "!group settings : Show group settings", "!link <get|set> : Get or revoke invite link", "!rules : Read group rules", "!setabout <description> : Set group description", "!setname <new_name> : Set group name", "!setphoto : Set group photo", "!setrules <rules> : Set group rules" }, patterns = { "^!(about)$", "%[(audio)%]", "%[(document)%]", "^!(gpadd)$", "^!(gprem)$", "^!(group) (lock) (.*)$", "^!(group) (settings)$", "^!(group) (unlock) (.*)$", "^!(link) (.*)$", "%[(photo)%]", "%[(photo)%]", "^!(rules)$", "^!(setabout) (.*)$", "^!(setname) (.*)$", "^!(setphoto)$", "^!(setrules) (.*)$", "^!!tgservice (.+)$", "%[(video)%]" }, run = run, privileged = true, hide = true, pre_process = pre_process } end
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c1143227.lua
2
3939
--ANTI-MATTER Dark Being, Rokkr function c1143227.initial_effect(c) c:SetUniqueOnField(1,0,1143227) --self destruct local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetOperation(c1143227.effop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_SPSUMMON_SUCCESS) c:RegisterEffect(e2) --battle indestructable local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e3:SetValue(1) c:RegisterEffect(e3) --actlimit local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_FIELD) e4:SetCode(EFFECT_CANNOT_ACTIVATE) e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e4:SetRange(LOCATION_MZONE) e4:SetTargetRange(1,1) e4:SetCondition(c1143227.actcon) e4:SetValue(c1143227.actlimit) c:RegisterEffect(e4) --spsummon local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(1143227,2)) e5:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_DRAW) e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e5:SetCode(EVENT_DESTROYED) e5:SetCountLimit(1,1143227) e5:SetCondition(c1143227.spcon) e5:SetTarget(c1143227.sptg) e5:SetOperation(c1143227.spop) c:RegisterEffect(e5) if not c1143227.global_check then c1143227.global_check=true local ge1=Effect.GlobalEffect() ge1:SetType(EFFECT_TYPE_FIELD) ge1:SetCode(EFFECT_TO_GRAVE_REDIRECT) ge1:SetTargetRange(LOCATION_DECK+LOCATION_HAND+LOCATION_MZONE+LOCATION_OVERLAY,LOCATION_DECK+LOCATION_HAND+LOCATION_MZONE+LOCATION_OVERLAY) ge1:SetTarget(aux.TargetBoolFunction(Card.IsCode,1143227)) ge1:SetValue(LOCATION_REMOVED) Duel.RegisterEffect(ge1,0) end end function c1143227.effop(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetRange(LOCATION_MZONE) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetOperation(c1143227.desop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,2) e1:SetLabel(0) e1:SetCountLimit(1) e:GetHandler():RegisterEffect(e1) end function c1143227.desop(e,tp,eg,ep,ev,re,r,rp) if e:GetLabel()>0 then Duel.Destroy(e:GetHandler(),REASON_EFFECT) else e:SetLabel(1) end end function c1143227.actcon(e) local ph=Duel.GetCurrentPhase() return ph>=PHASE_BATTLE_START and ph<=PHASE_BATTLE end function c1143227.actlimit(e,re,tp) return re:IsHasType(EFFECT_TYPE_ACTIVATE) or re:IsActiveType(TYPE_MONSTER) and not re:GetHandler():IsImmuneToEffect(e) end function c1143227.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsReason(REASON_DESTROY) and c:IsPreviousLocation(LOCATION_ONFIELD) end function c1143227.spfilter1(c,e,tp) local lv=c:GetLevel() return lv>0 and lv<8 and c:IsSetCard(0xaf75) and not c:IsCode(1143227) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.IsExistingMatchingCard(c1143227.spfilter2,tp,LOCATION_DECK,0,1,c,e,tp,8-lv) end function c1143227.spfilter2(c,e,tp,lv) return c:IsSetCard(0xaf75) and c:GetLevel()==lv and not c:IsCode(1143227) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c1143227.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c1143227.spfilter1,tp,LOCATION_DECK,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1) end function c1143227.spop(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g1=Duel.SelectMatchingCard(tp,c1143227.spfilter1,tp,LOCATION_DECK,0,1,1,nil,e,tp) local tc1=g1:GetFirst() if not tc1 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g2=Duel.SelectMatchingCard(tp,c1143227.spfilter2,tp,LOCATION_DECK,0,1,1,tc1,e,tp,8-tc1:GetLevel()) g1:Merge(g2) Duel.SpecialSummon(g1,0,tp,tp,false,false,POS_FACEUP) Duel.Draw(tp,1,REASON_EFFECT) end
gpl-3.0
waytim/darkstar
scripts/zones/Windurst_Waters/npcs/Qhum_Knaidjn.lua
13
2728
----------------------------------- -- Area: Windurst Waters -- NPC: Qhum_Knaidjn -- Type: Guildworker's Union Representative -- @zone: 238 -- @pos -112.561 -2 55.205 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/globals/keyitems"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Waters/TextIDs"); local keyitems = { [0] = { id = RAW_FISH_HANDLING, rank = 3, cost = 30000 }, [1] = { id = NOODLE_KNEADING, rank = 3, cost = 30000 }, [2] = { id = PATISSIER, rank = 3, cost = 8000 }, [3] = { id = STEWPOT_MASTERY, rank = 3, cost = 30000 }, [4] = { id = WAY_OF_THE_CULINARIAN, rank = 9, cost = 20000 } }; local items = { [2] = { id = 15451, -- Culinarian's Belt rank = 4, cost = 10000 }, [3] = { id = 13948, -- Chef's Hat rank = 5, cost = 70000 }, [4] = { id = 14399, -- Culinarian's Apron rank = 7, cost = 100000 }, [5] = { id = 137, -- Cordon Bleu Cooking Set rank = 9, cost = 150000 }, [6] = { id = 338, -- Culinarian's Signboard rank = 9, cost = 200000 }, [7] = { id = 15826, -- Chef's Ring rank = 6, cost = 80000 }, [8] = { id = 3667, -- Brass Crock rank = 7, cost = 50000 }, [9] = { id = 3328, -- Culinarian's Emblem rank = 9, cost = 15000 } }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) unionRepresentativeTrade(player, npc, trade, 0x2729, 8); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) unionRepresentativeTrigger(player, 8, 0x2728, "guild_cooking", keyitems); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,target) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2728) then unionRepresentativeTriggerFinish(player, option, target, 8, "guild_cooking", keyitems, items); elseif (csid == 0x2729) then player:messageSpecial(GP_OBTAINED, option); end end;
gpl-3.0
waytim/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
waytim/darkstar
scripts/zones/Upper_Jeuno/npcs/Deadly_Minnow.lua
13
1826
----------------------------------- -- Area: Upper Jeuno -- NPC: Deadly Minnow -- Standard Merchant NPC -- Involved in Quest: Borghertz's Hands (1st quest only) -- @zone 244 -- @pos -5 1 48 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BorghertzHandsFirstTime") == 1) then player:startEvent(0x0018); player:setVar("BorghertzHandsFirstTime",2); else player:showText(npc,DEADLYMINNOW_SHOP_DIALOG); stock = {0x309A,13179, --Studded Bandana 0x3089,22800, --Silver Mask 0x308A,47025, --Banded Helm 0x311A,20976, --Studded Vest 0x3109,35200, --Silver Mail 0x310A,66792, --Banded Mail 0x319A,11012, --Studded Gloves 0x3189,18800, --Silver Mittens 0x3180,23846, --Gauntlets 0x318A,35673} --Mufflers showShop(player, STATIC, stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
db260179/openwrt-bpi-r1-luci
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrd6.lua
68
16296
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. require("luci.tools.webadmin") local fs = require "nixio.fs" local util = require "luci.util" local ip = require "luci.ip" local has_ipip = fs.glob("/etc/modules.d/[0-9]*-ipip")() m = Map("olsrd6", translate("OLSR Daemon"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) function m.on_parse() local has_defaults = false m.uci:foreach("olsrd6", "InterfaceDefaults", function(s) has_defaults = true return false end) if not has_defaults then m.uci:section("olsrd6", "InterfaceDefaults") end end function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end s = m:section(TypedSection, "olsrd6", translate("General settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("lquality", translate("Link Quality Settings")) s:tab("smartgw", translate("SmartGW"), not has_ipip and translate("Warning: kmod-ipip is not installed. Without kmod-ipip SmartGateway will not work, please install it.")) s:tab("advanced", translate("Advanced Settings")) poll = s:taboption("advanced", Value, "Pollrate", translate("Pollrate"), translate("Polling rate for OLSR sockets in seconds. Default is 0.05.")) poll.optional = true poll.datatype = "ufloat" poll.placeholder = "0.05" nicc = s:taboption("advanced", Value, "NicChgsPollInt", translate("Nic changes poll interval"), translate("Interval to poll network interfaces for configuration changes (in seconds). Default is \"2.5\".")) nicc.optional = true nicc.datatype = "ufloat" nicc.placeholder = "2.5" tos = s:taboption("advanced", Value, "TosValue", translate("TOS value"), translate("Type of service value for the IP header of control traffic. Default is \"16\".")) tos.optional = true tos.datatype = "uinteger" tos.placeholder = "16" fib = s:taboption("general", ListValue, "FIBMetric", translate("FIB metric"), translate ("FIBMetric controls the metric value of the host-routes OLSRd sets. ".. "\"flat\" means that the metric value is always 2. This is the preferred value ".. "because it helps the linux kernel routing to clean up older routes. ".. "\"correct\" uses the hopcount as the metric value. ".. "\"approx\" use the hopcount as the metric value too, but does only update the hopcount if the nexthop changes too. ".. "Default is \"flat\".")) fib:value("flat") fib:value("correct") fib:value("approx") lql = s:taboption("lquality", ListValue, "LinkQualityLevel", translate("LQ level"), translate("Link quality level switch between hopcount and cost-based (mostly ETX) routing.<br />".. "<b>0</b> = do not use link quality<br />".. "<b>2</b> = use link quality for MPR selection and routing<br />".. "Default is \"2\"")) lql:value("2") lql:value("0") lqage = s:taboption("lquality", Value, "LinkQualityAging", translate("LQ aging"), translate("Link quality aging factor (only for lq level 2). Tuning parameter for etx_float and etx_fpm, smaller values ".. "mean slower changes of ETX value. (allowed values are between 0.01 and 1.0)")) lqage.optional = true lqage:depends("LinkQualityLevel", "2") lqa = s:taboption("lquality", ListValue, "LinkQualityAlgorithm", translate("LQ algorithm"), translate("Link quality algorithm (only for lq level 2).<br />".. "<b>etx_float</b>: floating point ETX with exponential aging<br />".. "<b>etx_fpm</b> : same as etx_float, but with integer arithmetic<br />".. "<b>etx_ff</b> : ETX freifunk, an etx variant which use all OLSR traffic (instead of only hellos) for ETX calculation<br />".. "<b>etx_ffeth</b>: incompatible variant of etx_ff that allows ethernet links with ETX 0.1.<br />".. "Defaults to \"etx_ff\"")) lqa.optional = true lqa:value("etx_ff") lqa:value("etx_fpm") lqa:value("etx_float") lqa:value("etx_ffeth") lqa:depends("LinkQualityLevel", "2") lqa.optional = true lqfish = s:taboption("lquality", Flag, "LinkQualityFishEye", translate("LQ fisheye"), translate("Fisheye mechanism for TCs (checked means on). Default is \"on\"")) lqfish.default = "1" lqfish.optional = true hyst = s:taboption("lquality", Flag, "UseHysteresis", translate("Use hysteresis"), translate("Hysteresis for link sensing (only for hopcount metric). Hysteresis adds more robustness to the link sensing ".. "but delays neighbor registration. Defaults is \"yes\"")) hyst.default = "yes" hyst.enabled = "yes" hyst.disabled = "no" hyst:depends("LinkQualityLevel", "0") hyst.optional = true hyst.rmempty = true port = s:taboption("general", Value, "OlsrPort", translate("Port"), translate("The port OLSR uses. This should usually stay at the IANA assigned port 698. It can have a value between 1 and 65535.")) port.optional = true port.default = "698" port.rmempty = true mainip = s:taboption("general", Value, "MainIp", translate("Main IP"), translate("Sets the main IP (originator ip) of the router. This IP will NEVER change during the uptime of olsrd. ".. "Default is ::, which triggers usage of the IP of the first interface.")) mainip.optional = true mainip.rmempty = true mainip.datatype = "ipaddr" mainip.placeholder = "::" sgw = s:taboption("smartgw", Flag, "SmartGateway", translate("Enable"), translate("Enable SmartGateway. If it is disabled, then " .. "all other SmartGateway parameters are ignored. Default is \"no\".")) sgw.default="no" sgw.enabled="yes" sgw.disabled="no" sgw.rmempty = true sgwnat = s:taboption("smartgw", Flag, "SmartGatewayAllowNAT", translate("Allow gateways with NAT"), translate("Allow the selection of an outgoing ipv4 gateway with NAT")) sgwnat:depends("SmartGateway", "yes") sgwnat.default="yes" sgwnat.enabled="yes" sgwnat.disabled="no" sgwnat.optional = true sgwnat.rmempty = true sgwuplink = s:taboption("smartgw", ListValue, "SmartGatewayUplink", translate("Announce uplink"), translate("Which kind of uplink is exported to the other mesh nodes. " .. "An uplink is detected by looking for a local HNA6 ::ffff:0:0/96 or 2000::/3. Default setting is \"both\".")) sgwuplink:value("none") sgwuplink:value("ipv4") sgwuplink:value("ipv6") sgwuplink:value("both") sgwuplink:depends("SmartGateway", "yes") sgwuplink.default="both" sgwuplink.optional = true sgwuplink.rmempty = true sgwulnat = s:taboption("smartgw", Flag, "SmartGatewayUplinkNAT", translate("Uplink uses NAT"), translate("If this Node uses NAT for connections to the internet. " .. "Default is \"yes\".")) sgwulnat:depends("SmartGatewayUplink", "ipv4") sgwulnat:depends("SmartGatewayUplink", "both") sgwulnat.default="yes" sgwulnat.enabled="yes" sgwulnat.disabled="no" sgwnat.optional = true sgwnat.rmempty = true sgwspeed = s:taboption("smartgw", Value, "SmartGatewaySpeed", translate("Speed of the uplink"), translate("Specifies the speed of ".. "the uplink in kilobits/s. First parameter is upstream, second parameter is downstream. Default is \"128 1024\".")) sgwspeed:depends("SmartGatewayUplink", "ipv4") sgwspeed:depends("SmartGatewayUplink", "ipv6") sgwspeed:depends("SmartGatewayUplink", "both") sgwspeed.optional = true sgwspeed.rmempty = true sgwprefix = s:taboption("smartgw", Value, "SmartGatewayPrefix", translate("IPv6-Prefix of the uplink"), translate("This can be used " .. "to signal the external IPv6 prefix of the uplink to the clients. This might allow a client to change it's local IPv6 address to " .. "use the IPv6 gateway without any kind of address translation. The maximum prefix length is 64 bits. " .. "Default is \"::/0\" (no prefix).")) sgwprefix:depends("SmartGatewayUplink", "ipv6") sgwprefix:depends("SmartGatewayUplink", "both") sgwprefix.optional = true sgwprefix.rmempty = true willingness = s:taboption("advanced", ListValue, "Willingness", translate("Willingness"), translate("The fixed willingness to use. If not set willingness will be calculated dynamically based on battery/power status. Default is \"3\".")) for i=0,7 do willingness:value(i) end willingness.optional = true willingness.default = "3" natthr = s:taboption("advanced", Value, "NatThreshold", translate("NAT threshold"), translate("If the route to the current gateway is to be changed, the ETX value of this gateway is ".. "multiplied with this value before it is compared to the new one. ".. "The parameter can be a value between 0.1 and 1.0, but should be close to 1.0 if changed.<br />".. "<b>WARNING:</b> This parameter should not be used together with the etx_ffeth metric!<br />".. "Defaults to \"1.0\".")) for i=1,0.1,-0.1 do natthr:value(i) end natthr:depends("LinkQualityAlgorithm", "etx_ff") natthr:depends("LinkQualityAlgorithm", "etx_float") natthr:depends("LinkQualityAlgorithm", "etx_fpm") natthr.default = "1.0" natthr.optional = true natthr.write = write_float i = m:section(TypedSection, "InterfaceDefaults", translate("Interfaces Defaults")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float ifs = m:section(TypedSection, "Interface", translate("Interfaces")) ifs.addremove = true ifs.anonymous = true ifs.extedit = luci.dispatcher.build_url("admin/services/olsrd6/iface/%s") ifs.template = "cbi/tblsection" function ifs.create(...) local sid = TypedSection.create(...) luci.http.redirect(ifs.extedit % sid) end ign = ifs:option(Flag, "ignore", translate("Enable")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = ifs:option(DummyValue, "interface", translate("Network")) network.template = "cbi/network_netinfo" mode = ifs:option(DummyValue, "Mode", translate("Mode")) function mode.cfgvalue(...) return Value.cfgvalue(...) or m.uci:get_first("olsrd6", "InterfaceDefaults", "Mode", "mesh") end hello = ifs:option(DummyValue, "_hello", translate("Hello")) function hello.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "HelloInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloInterval", 5)) local v = tonumber(m.uci:get("olsrd6", section, "HelloValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HelloValidityTime", 40)) return "%.01fs / %.01fs" %{ i, v } end tc = ifs:option(DummyValue, "_tc", translate("TC")) function tc.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "TcInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcInterval", 2)) local v = tonumber(m.uci:get("olsrd6", section, "TcValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "TcValidityTime", 256)) return "%.01fs / %.01fs" %{ i, v } end mid = ifs:option(DummyValue, "_mid", translate("MID")) function mid.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "MidInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidInterval", 18)) local v = tonumber(m.uci:get("olsrd6", section, "MidValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "MidValidityTime", 324)) return "%.01fs / %.01fs" %{ i, v } end hna = ifs:option(DummyValue, "_hna", translate("HNA")) function hna.cfgvalue(self, section) local i = tonumber(m.uci:get("olsrd6", section, "HnaInterval")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaInterval", 18)) local v = tonumber(m.uci:get("olsrd6", section, "HnaValidityTime")) or tonumber(m.uci:get_first("olsrd6", "InterfaceDefaults", "HnaValidityTime", 108)) return "%.01fs / %.01fs" %{ i, v } end return m
apache-2.0
waytim/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/YrvaulairSCousseraux1.lua
19
1186
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Yrvaulair S Cousseraux -- @zone 80 -- @pos 0 1 -78 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, 11692); -- Not once in the four hundred years since the dawn of the Royal Knights has the kingdom found itself in such peril. Let us take up our pikes and stand our ground to ensure another four centuries of prosperity! 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
tenvick/hugular_cstolua
Client/Assets/Lua/begin.lua
1
1286
------------------------------------------------ -- Copyright © 2013-2014 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ require("const.importClass") require("net.netMsgHelper") require("net.netAPIList") require("net.netProtocalPaser") require("net.proxy") require("const.requires") require("registerItemObjects") require("registerState") require("uiInput") local os=os local UPDATECOMPONENTS=UPDATECOMPONENTS local LuaObject=LuaObject local StateManager=StateManager local Net=Net local Msg=Msg local LuaHelper = LuaHelper local delay = delay local pLua = PLua.instance ------------------------------------------------------------------------------- local Proxy=Proxy local NetMsgHelper = NetMsgHelper local NetAPIList = NetAPIList StateManager:setCurrentState(StateManager.welcome) -- require("netGame") local function update() local cmp local len len = #UPDATECOMPONENTS local ostime=os.clock() for i=1,len do cmp=UPDATECOMPONENTS[i] if cmp.enable then cmp:onUpdate(ostime) end end end pLua.updateFn=update --load config require("game.common.loadCSV") delay(function( ... ) print(getValue("level_name_001")) --language key print(Model.getUnit(200001).name) --read config -- Loader:clearSharedAB() end,0.5,nil)
mit
MinFu/luci
protocols/luci-proto-ipv6/luasrc/model/cbi/admin_network/proto_6rd.lua
72
2039
-- Copyright 2011-2012 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, peeraddr, ip6addr, tunnelid, username, password local defaultroute, metric, ttl, mtu ipaddr = s:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Leave empty to use the current WAN address")) ipaddr.datatype = "ip4addr" peeraddr = s:taboption("general", Value, "peeraddr", translate("Remote IPv4 address"), translate("This IPv4 address of the relay")) peeraddr.rmempty = false peeraddr.datatype = "ip4addr" ip6addr = s:taboption("general", Value, "ip6prefix", translate("IPv6 prefix"), translate("The IPv6 prefix assigned to the provider, usually ends with <code>::</code>")) ip6addr.rmempty = false ip6addr.datatype = "ip6addr" ip6prefixlen = s:taboption("general", Value, "ip6prefixlen", translate("IPv6 prefix length"), translate("The length of the IPv6 prefix in bits")) ip6prefixlen.placeholder = "16" ip6prefixlen.datatype = "range(0,128)" ip6prefixlen = s:taboption("general", Value, "ip4prefixlen", translate("IPv4 prefix length"), translate("The length of the IPv4 prefix in bits, the remainder is used in the IPv6 addresses.")) ip6prefixlen.placeholder = "0" ip6prefixlen.datatype = "range(0,32)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) ttl = section:taboption("advanced", Value, "ttl", translate("Use TTL on tunnel interface")) ttl.placeholder = "64" ttl.datatype = "range(1,255)" mtu = section:taboption("advanced", Value, "mtu", translate("Use MTU on tunnel interface")) mtu.placeholder = "1280" mtu.datatype = "max(9200)"
apache-2.0
TienHP/Aquaria
files/scripts/maps/_unused/node_naija_minimap.lua
6
1097
-- Copyright (C) 2007, 2010 - Bit-Blot -- -- This file is part of Aquaria. -- -- Aquaria is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; either version 2 -- of the License, or (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. -- -- See the GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program; if not, write to the Free Software -- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. if not v then v = {} end if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end function init(me) end function update(me, dt) if isFlag(FLAG_NAIJA_MINIMAP, 0) then if node_isEntityIn(me, getNaija()) then voice("naija_minimap") setFlag(FLAG_NAIJA_MINIMAP, 1) end end end
gpl-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/East_Ronfaure/npcs/Croteillard.lua
4
1081
----------------------------------- -- Area: East Ronfaure -- NPC: Croteillard -- Type: Gate Guard -- @zone: 101 -- @pos: 87.426 -62.999 266.709 -- -- Auto-Script: Requires Verification ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, CROTEILLARD_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
waytim/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Porter_Moogle.lua
41
1547
----------------------------------- -- Area: Tavnazian_Safehold -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 26 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Tavnazian_Safehold/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 619, STORE_EVENT_ID = 620, RETRIEVE_EVENT_ID = 621, ALREADY_STORED_ID = 622, MAGIAN_TRIAL_ID = 623 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
waytim/darkstar
scripts/zones/Batallia_Downs/npcs/qm1.lua
15
1500
----------------------------------- -- Area: Batallia Downs -- NPC: qm1 (???) -- @pos -407.526 -23.507 412.544 105 -- Notes: Spawns Vegnix Greenthumb for ACP mission "Gatherer of Light (I)" ----------------------------------- package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Batallia_Downs/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Gob = GetMobAction(17207710); if ( (Gob == ACTION_NONE or Gob == ACTION_SPAWN) and (player:hasKeyItem(BOWL_OF_BLAND_GOBLIN_SALAD) == true) and (player:hasKeyItem(SEEDSPALL_ROSEUM) == false) and (player:hasKeyItem(VIRIDIAN_KEY) == false) ) then SpawnMob(17207710,180):updateClaim(player); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Em30-tm-lua/Emc
.luarocks/lib/luarocks/rocks/luasocket/3.0rc1-2/test/ftptest.lua
26
3156
local socket = require("socket") local ftp = require("socket.ftp") local url = require("socket.url") local ltn12 = require("ltn12") -- override protection to make sure we see all errors --socket.protect = function(s) return s end dofile("testsupport.lua") local host, port, index_file, index, back, err, ret local t = socket.gettime() host = host or "localhost" index_file = "index.html" -- a function that returns a directory listing local function nlst(u) local t = {} local p = url.parse(u) p.command = "nlst" p.sink = ltn12.sink.table(t) local r, e = ftp.get(p) return r and table.concat(t), e end -- function that removes a remote file local function dele(u) local p = url.parse(u) p.command = "dele" p.argument = string.gsub(p.path, "^/", "") if p.argumet == "" then p.argument = nil end p.check = 250 return ftp.command(p) end -- read index with CRLF convention index = readfile(index_file) io.write("testing wrong scheme: ") back, err = ftp.get("wrong://banana.com/lixo") assert(not back and err == "wrong scheme 'wrong'", err) print("ok") io.write("testing invalid url: ") back, err = ftp.get("localhost/dir1/index.html;type=i") assert(not back and err) print("ok") io.write("testing anonymous file download: ") back, err = socket.ftp.get("ftp://" .. host .. "/pub/index.html;type=i") assert(not err and back == index, err) print("ok") io.write("erasing before upload: ") ret, err = dele("ftp://luasocket:pedrovian@" .. host .. "/index.up.html") if not ret then print(err) else print("ok") end io.write("testing upload: ") ret, err = ftp.put("ftp://luasocket:pedrovian@" .. host .. "/index.up.html;type=i", index) assert(ret and not err, err) print("ok") io.write("downloading uploaded file: ") back, err = ftp.get("ftp://luasocket:pedrovian@" .. host .. "/index.up.html;type=i") assert(ret and not err and index == back, err) print("ok") io.write("erasing after upload/download: ") ret, err = dele("ftp://luasocket:pedrovian@" .. host .. "/index.up.html") assert(ret and not err, err) print("ok") io.write("testing weird-character translation: ") back, err = ftp.get("ftp://luasocket:pedrovian@" .. host .. "/%23%3f;type=i") assert(not err and back == index, err) print("ok") io.write("testing parameter overriding: ") local back = {} ret, err = ftp.get{ url = "//stupid:mistake@" .. host .. "/index.html", user = "luasocket", password = "pedrovian", type = "i", sink = ltn12.sink.table(back) } assert(ret and not err and table.concat(back) == index, err) print("ok") io.write("testing upload denial: ") ret, err = ftp.put("ftp://" .. host .. "/index.up.html;type=a", index) assert(not ret and err, "should have failed") print(err) io.write("testing authentication failure: ") ret, err = ftp.get("ftp://luasocket:wrong@".. host .. "/index.html;type=a") assert(not ret and err, "should have failed") print(err) io.write("testing wrong file: ") back, err = ftp.get("ftp://".. host .. "/index.wrong.html;type=a") assert(not back and err, "should have failed") print(err) print("passed all tests") print(string.format("done in %.2fs", socket.gettime() - t))
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c9821000.lua
2
1827
--Soleil - Song of the Ascending Raven function c9821000.initial_effect(c) --Negate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e1:SetCondition(c9821000.condition) e1:SetTarget(c9821000.target) e1:SetOperation(c9821000.operation) c:RegisterEffect(e1) --act in hand local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(EFFECT_TRAP_ACT_IN_HAND) e2:SetCondition(c9821000.handcon) c:RegisterEffect(e2) end function c9821000.filter(c) return c:IsFaceup() and c:IsRace(RACE_MACHINE) and c:IsType(TYPE_SYNCHRO) end function c9821000.condition(e,tp,eg,ep,ev,re,r,rp) if not Duel.IsExistingMatchingCard(c9821000.filter,tp,LOCATION_MZONE,0,1,nil) then return false end if tp==ep or not Duel.IsChainNegatable(ev) then return false end if not re:IsActiveType(TYPE_MONSTER) and not re:IsHasType(EFFECT_TYPE_ACTIVATE) then return false end local ex,tg,tc=Duel.GetOperationInfo(ev,CATEGORY_DESTROY) return ex and tg~=nil and tc>0 end function c9821000.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,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 c9821000.operation(e,tp,eg,ep,ev,re,r,rp) Duel.NegateActivation(ev) if re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end function c9821000.filter(c) return c:IsFaceup() and c:IsSetCard(0x0dac402) and c:IsType(TYPE_SYNCHRO) and c:IsLevelAbove(5) end function c9821000.handcon(e) return Duel.IsExistingMatchingCard(c9821000.filter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) end
gpl-3.0
GregSatre/nn
SparseJacobian.lua
61
8618
nn.SparseJacobian = {} function nn.SparseJacobian.backward (module, input, param, dparam) local doparam = 0 if param then doparam = 1 end -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(), 1, dout:nElement()) -- jacobian matrix to calculate local jacobian if doparam == 1 then jacobian = torch.Tensor(param:nElement(), dout:nElement()):zero() else jacobian = torch.Tensor(input:size(1), dout:nElement()):zero() end for i=1,sdout:nElement() do dout:zero() sdout[i] = 1 module:zeroGradParameters() local din = module:updateGradInput(input, dout) module:accGradParameters(input, dout) if doparam == 1 then jacobian:select(2,i):copy(dparam) else jacobian:select(2,i):copy(din:select(2,2)) end end return jacobian end function nn.SparseJacobian.backwardUpdate (module, input, param) -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(),1,dout:nElement()) -- jacobian matrix to calculate local jacobian = torch.Tensor(param:nElement(),dout:nElement()):zero() -- original param local params = module:parameters() local origparams = {} for j=1,#params do table.insert(origparams, params[j]:clone()) end for i=1,sdout:nElement() do -- Reset parameters for j=1,#params do params[j]:copy(origparams[j]) end dout:zero() sdout[i] = 1 module:zeroGradParameters() module:updateGradInput(input, dout) module:accUpdateGradParameters(input, dout, 1) jacobian:select(2,i):copy(param) end for j=1,#params do params[j]:copy(origparams[j]) end return jacobian end function nn.SparseJacobian.forward(module, input, param) local doparam = 0 if param then doparam = 1 end param = param or input -- perturbation amount local small = 1e-6 -- 1D view of input --local tst = param:storage() local sin if doparam == 1 then sin = param.new(param):resize(param:nElement()) else sin = input.new(input):select(2,2) end local out = module:forward(input) -- jacobian matrix to calculate local jacobian if doparam == 1 then jacobian = torch.Tensor():resize(param:nElement(), out:nElement()) else jacobian = torch.Tensor():resize(input:size(1), out:nElement()) end local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do sin[i] = sin[i] - small outa:copy(module:forward(input)) sin[i] = sin[i] + 2*small outb:copy(module:forward(input)) sin[i] = sin[i] - small outb:add(-1,outa):div(2*small) jacobian:select(1,i):copy(outb) end return jacobian end function nn.SparseJacobian.forwardUpdate(module, input, param) -- perturbation amount local small = 1e-6 -- 1D view of input --local tst = param:storage() local sin = param.new(param):resize(param:nElement())--param.new(tst,1,tst:size()) -- jacobian matrix to calculate local jacobian = torch.Tensor():resize(param:nElement(),module:forward(input):nElement()) local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do sin[i] = sin[i] - small outa:copy(module:forward(input)) sin[i] = sin[i] + 2*small outb:copy(module:forward(input)) sin[i] = sin[i] - small outb:add(-1,outa):div(2*small) jacobian:select(1,i):copy(outb) jacobian:select(1,i):mul(-1) jacobian:select(1,i):add(sin[i]) end return jacobian end function nn.SparseJacobian.testJacobian (module, input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) local jac_fprop = nn.SparseJacobian.forward(module,input) local jac_bprop = nn.SparseJacobian.backward(module,input) local error = jac_fprop-jac_bprop return error:abs():max() end function nn.SparseJacobian.testJacobianParameters (module, input, param, dparam, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local jac_bprop = nn.SparseJacobian.backward(module, input, param, dparam) local jac_fprop = nn.SparseJacobian.forward(module, input, param) local error = jac_fprop - jac_bprop return error:abs():max() end function nn.SparseJacobian.testJacobianUpdateParameters (module, input, param, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local params_bprop = nn.SparseJacobian.backwardUpdate(module, input, param) local params_fprop = nn.SparseJacobian.forwardUpdate(module, input, param) local error = params_fprop - params_bprop return error:abs():max() end function nn.SparseJacobian.testIO(module,input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval -- run module module:forward(input) local go = module.output:clone():copy(torch.rand(module.output:nElement()):mul(inrange):add(minval)) module:zeroGradParameters() module:updateGradInput(input,go) module:accGradParameters(input,go) local fo = module.output:clone() local bo = module.gradInput:clone() -- write module local f = torch.DiskFile('tmp.bin','w'):binary() f:writeObject(module) f:close() -- read module local m = torch.DiskFile('tmp.bin'):binary():readObject() m:forward(input) m:zeroGradParameters() m:updateGradInput(input,go) m:accGradParameters(input,go) -- cleanup os.remove('tmp.bin') local fo2 = m.output:clone() local bo2 = m.gradInput:clone() local errf = fo - fo2 local errb = bo - bo2 return errf:abs():max(), errb:abs():max() end function nn.SparseJacobian.testAllUpdate(module, input, weight, gradWeight) local gradOutput local lr = torch.uniform(0.1, 1) local errors = {} -- accGradParameters local maccgp = module:clone() local weightc = maccgp[weight]:clone() maccgp:forward(input) gradOutput = torch.rand(maccgp.output:size()) maccgp:zeroGradParameters() maccgp:updateGradInput(input, gradOutput) maccgp:accGradParameters(input, gradOutput) maccgp:updateParameters(lr) errors["accGradParameters"] = (weightc-maccgp[gradWeight]*lr-maccgp[weight]):norm() -- accUpdateGradParameters local maccugp = module:clone() maccugp:forward(input) maccugp:updateGradInput(input, gradOutput) maccugp:accUpdateGradParameters(input, gradOutput, lr) errors["accUpdateGradParameters"] = (maccugp[weight]-maccgp[weight]):norm() -- shared, accGradParameters local macsh1 = module:clone() local macsh2 = module:clone() macsh2:share(macsh1, weight) macsh1:forward(input) macsh2:forward(input) macsh1:zeroGradParameters() macsh2:zeroGradParameters() macsh1:updateGradInput(input, gradOutput) macsh2:updateGradInput(input, gradOutput) macsh1:accGradParameters(input, gradOutput) macsh2:accGradParameters(input, gradOutput) macsh1:updateParameters(lr) macsh2:updateParameters(lr) local err = (weightc-maccgp[gradWeight]*(lr*2)-macsh1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macsh2[weight]):norm() errors["accGradParameters [shared]"] = err -- shared, accUpdateGradParameters local macshu1 = module:clone() local macshu2 = module:clone() macshu2:share(macshu1, weight) macshu1:forward(input) macshu2:forward(input) macshu1:updateGradInput(input, gradOutput) macshu2:updateGradInput(input, gradOutput) macshu1:accUpdateGradParameters(input, gradOutput, lr) macshu2:accUpdateGradParameters(input, gradOutput, lr) err = (weightc-maccgp[gradWeight]*(lr*2)-macshu1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macshu2[weight]):norm() errors["accUpdateGradParameters [shared]"] = err return errors end
bsd-3-clause
TheOnePharaoh/YGOPro-Custom-Cards
script/c44646223.lua
2
1187
--Vocaloid Luo Tianyi/Modified function c44646223.initial_effect(c) c:EnableReviveLimit() --Cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.FALSE) c:RegisterEffect(e1) --atk local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetRange(LOCATION_MZONE) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetTarget(c44646223.efilter) e2:SetValue(300) c:RegisterEffect(e2) --avoid battle damage local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_AVOID_BATTLE_DAMAGE) e2:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e2:SetRange(LOCATION_MZONE) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetTarget(c44646223.efilter) e2:SetValue(1) c:RegisterEffect(e2) end function c44646223.efilter(e,c) return c:IsFaceup() and c:IsCode(44646216) or c:IsCode(44646219) or c:IsCode(44646220) or c:IsCode(44646221) or c:IsCode(44646222) or c:IsCode(44646223) or c:IsCode(13739085) or c:IsCode(54759291) or c:IsCode(75963559) or c:IsCode(75963528) or c:IsCode(44646228) end
gpl-3.0
waytim/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
db260179/openwrt-bpi-r1-luci
libs/luci-lib-nixio/docsrc/nixio.bit.lua
171
2044
--- Bitfield operators and mainpulation functions. -- Can be used as a drop-in replacement for bitlib. module "nixio.bit" --- Bitwise OR several numbers. -- @class function -- @name bor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Invert given number. -- @class function -- @name bnot -- @param oper Operand -- @return number --- Bitwise AND several numbers. -- @class function -- @name band -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Bitwise XOR several numbers. -- @class function -- @name bxor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Left shift a number. -- @class function -- @name lshift -- @param oper number -- @param shift bits to shift -- @return number --- Right shift a number. -- @class function -- @name rshift -- @param oper number -- @param shift bits to shift -- @return number --- Arithmetically right shift a number. -- @class function -- @name arshift -- @param oper number -- @param shift bits to shift -- @return number --- Integer division of 2 or more numbers. -- @class function -- @name div -- @param oper1 Operand 1 -- @param oper2 Operand 2 -- @param ... More Operands -- @return number --- Cast a number to the bit-operating range. -- @class function -- @name cast -- @param oper number -- @return number --- Sets one or more flags of a bitfield. -- @class function -- @name set -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Unsets one or more flags of a bitfield. -- @class function -- @name unset -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Checks whether given flags are set in a bitfield. -- @class function -- @name check -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return true when all flags are set, otherwise false
apache-2.0
PotcFdk/nBAM
server/packages/nbamTimer.lua
1
2393
--[[ Copyright 2014 - The nBAM Team Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- local isfunction = function (func) return type(func) == 'function' end local isstring = function (str) return type(str) == 'string' end local isnumber = function (num) return type(num) == 'number' end local istable = function (tab) return type(tab) == 'table' end local function errmsg (paramNum, expectedType) return string.format('Parameter #%d expected to be %s!', paramNum, expectedType) end package.loaded.nbamTimer = {} local timer = package.loaded.nbamTimer local timers = {} local tim = Timer() local function time () return tim:GetSeconds() end function timer.Create (id, delay, count, callback) assert(isstring(id), errmsg(1, 'string')) assert(isnumber(delay), errmsg(2, 'number')) assert(isnumber(count), errmsg(3, 'number')) assert(isfunction(callback), errmsg(4, 'function')) timers[id] = { delay = delay, last = time(), count = count, callback = callback } end function timer.Destroy (id) assert(isstring(id), errmsg(1, 'string')) timers[id] = nil end timer.Remove = timer.Destroy function timer.Simple (delay, callback) assert(isnumber(delay), errmsg(1, 'number')) assert(isfunction(callback), errmsg(2, 'function')) table.insert(timers, { delay = delay, last = time(), count = 1, callback = callback }) end function timer.Think () local t = time() for k, v in next, timers do if t >= v.last + v.delay then local ok, err = pcall(v.callback) if not ok then timers[k] = nil print(string.format("[timer] Timer '%s' errored: %s\nRemoved timer '%s'!", k, err, k)) else if err ~= nil then return err end end v.count = v.count - 1 if v.count == 0 then timers[k] = nil else v.last = t end end end end Events:Subscribe("PreTick", timer.Think)
apache-2.0
Contatta/prosody-modules
mod_turncredentials/mod_turncredentials.lua
36
1415
-- XEP-0215 implementation for time-limited turn credentials -- Copyright (C) 2012-2013 Philipp Hancke -- This file is MIT/X11 licensed. local st = require "util.stanza"; local hmac_sha1 = require "util.hashes".hmac_sha1; local base64 = require "util.encodings".base64; local os_time = os.time; local secret = module:get_option_string("turncredentials_secret"); local host = module:get_option_string("turncredentials_host"); -- use ip addresses here to avoid further dns lookup latency local port = module:get_option_number("turncredentials_port", 3478); local ttl = module:get_option_number("turncredentials_ttl", 86400); if not (secret and host) then module:log("error", "turncredentials not configured"); return; end module:add_feature("urn:xmpp:extdisco:1"); module:hook("iq-get/host/urn:xmpp:extdisco:1:services", function(event) local origin, stanza = event.origin, event.stanza; if origin.type ~= "c2s" then return; end local now = os_time() + ttl; local userpart = tostring(now); local nonce = base64.encode(hmac_sha1(secret, tostring(userpart), false)); origin.send(st.reply(stanza):tag("services", {xmlns = "urn:xmpp:extdisco:1"}) :tag("service", { type = "stun", host = host, port = port }):up() :tag("service", { type = "turn", host = host, port = port, username = userpart, password = nonce, ttl = ttl}):up() ); return true; end);
mit
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Upper_Jeuno/npcs/Ilumida.lua
2
4850
----------------------------------- -- Area: Upper Jeuno -- NPC: Ilumida -- Starts and Finishes Quest: A Candlelight Vigil -- @zone : 244 -- @pos : -75 -1 58 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local aCandlelightVigil = player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL); local SearchingForWords = player:getQuestStatus(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS); --this variable implicitly stores: JFame >= 7 and ACandlelightVigil == QUEST_COMPLETED and RubbishDay == QUEST_COMPLETED and --NeverToReturn == QUEST_COMPLETED and SearchingForTheRightWords == QUEST_AVAILABLE and prereq CS complete local SearchingForWords_prereq = player:getVar("QuestSearchRightWords_prereq"); if (player:getFameLevel(JEUNO) >= 4 and aCandlelightVigil == QUEST_AVAILABLE) then player:startEvent(0x00c0); --Start quest : Ilumida asks you to obtain a candle ... elseif (aCandlelightVigil == QUEST_ACCEPTED) then if (player:hasKeyItem(HOLY_CANDLE) == true) then player:startEvent(0x00c2); --Finish quest : CS NOT FOUND. else player:startEvent(0x00bf); --quest accepted dialog end elseif (player:getVar("QuestACandlelightVigil_denied") == 1) then player:startEvent(0x00c1); --quest denied dialog, asks again for A Candlelight Vigil elseif (SearchingForWords_prereq == 1) then --has player completed prerequisite cutscene with Kurou-Morou? player:startEvent(0x00c5); --SearchingForTheRightWords intro CS elseif (player:getVar("QuestSearchRightWords_denied") == 1) then player:startEvent(0x00c9); --asks player again, SearchingForTheRightWords accept/deny elseif (SearchingForWords == QUEST_ACCEPTED) then if (player:hasKeyItem(MOONDROP) == true) then player:startEvent(0x00c6); else player:startEvent(0x00c7); -- SearchingForTheRightWords quest accepted dialog end elseif (player:getVar("SearchingForRightWords_postcs") == -1) then player:startEvent(0x00c4); elseif(SearchingForWords == QUEST_COMPLETED) then player:startEvent(0x00c8); else player:startEvent(0x00BD); --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 == 0x00c0 and option == 1) or (csid == 0x00c1 and option == 1)) then --just start quest player:addQuest(JEUNO,A_CANDLELIGHT_VIGIL); player:setVar("QuestACandlelightVigil_denied", 0); elseif(csid == 0x00c0 and option == 0) then --quest denied, special eventIDs available player:setVar("QuestACandlelightVigil_denied", 1); elseif(csid == 0x00c2) then --finish quest if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13094); else player:addTitle(ACTIVIST_FOR_KINDNESS); player:delKeyItem(HOLY_CANDLE); player:addItem(13094); player:messageSpecial(ITEM_OBTAINED,13094); player:needToZone(true); player:addFame(JEUNO,30); player:completeQuest(JEUNO,A_CANDLELIGHT_VIGIL); end elseif(csid == 0x00c5 and option == 0) then --quest denied, special eventIDs available player:setVar("QuestSearchRightWords_prereq", 0); --remove charVar from memory player:setVar("QuestSearchRightWords_denied", 1); elseif((csid == 0x00c5 and option == 1) or (csid == 0x00c9 and option == 1)) then player:setVar("QuestSearchRightWords_prereq", 0); --remove charVar from memory player:setVar("QuestSearchRightWords_denied", 0); player:addQuest(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS); elseif(csid == 0x00c6) then --finish quest, note: no title granted if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4882); else player:delKeyItem(MOONDROP); player:messageSpecial(GIL_OBTAINED, GIL_RATE*3000) player:addItem(4882); player:messageSpecial(ITEM_OBTAINED,4882); player:addFame(JEUNO,30); player:completeQuest(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS); player:setVar("SearchingForRightWords_postcs", -2); end elseif(csid == 0x00c4) then player:setVar("SearchingForRightWords_postcs", 0); end end;
gpl-3.0
sevanteri/shootaround
main.lua
1
1173
require 'bullet' require 'movable' require 'gun' function love.load() Bullets = {} gun = Gun:new() love.graphics.setBackgroundColor(0,0,0) end function love.draw(dt) gun:draw(dt) for _, db in ipairs(Bullets) do db:draw(dt) end love.graphics.print("Bullets: " .. #Bullets, 10, 10) love.graphics.print("Gun power: " .. gun.power, 10, 24) end function love.update(dt) Wwidth, Wheight = love.window.getDimensions() CenterX, CenterY = Wwidth/2, Wheight/2 -- mouse stuff MouseX, MouseY = love.mouse.getPosition() local abs = math.abs local centerToX, centerToY = abs(CenterX - MouseX), abs(CenterY - MouseY) CenterToMouse = math.sqrt(centerToX^2 + centerToY^2) if gun.shooting then gun.power = CenterToMouse end for _, ub in ipairs(Bullets) do ub:update(dt) end local isDown = love.keyboard.isDown if love.keyboard.isDown('escape') then love.event.push('quit') end end function love.mousepressed(x, y, b) if CenterToMouse <= gun.size then gun.shooting = true end end function love.mousereleased(x, y, b) gun:shootFrom(x, y) end
mit
Em30-tm-lua/Emc
.luarocks/share/lua/5.2/luarocks/upload/multipart.lua
4
2794
local multipart = {} local File = {} local unpack = unpack or table.unpack math.randomseed(os.time()) -- socket.url.escape(s) from LuaSocket 3.0rc1 function multipart.url_escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end)) end function File:mime() if not self.mimetype then local mimetypes_ok, mimetypes = pcall(require, "mimetypes") if mimetypes_ok then self.mimetype = mimetypes.guess(self.fname) end self.mimetype = self.mimetype or "application/octet-stream" end return self.mimetype end function File:content() local fd = io.open(self.fname) if not fd then return nil, "Failed to open file: "..self.fname end local data = fd:read("*a") fd:close() return data end local function rand_string(len) local shuffled = {} for i = 1, len do local r = math.random(97, 122) if math.random() >= 0.5 then r = r - 32 end shuffled[i] = r end return string.char(unpack(shuffled)) end -- multipart encodes params -- returns encoded string,boundary -- params is an a table of tuple tables: -- params = { -- {key1, value2}, -- {key2, value2}, -- key3: value3 -- } function multipart.encode(params) local tuples = { } for i = 1, #params do tuples[i] = params[i] end for k,v in pairs(params) do if type(k) == "string" then table.insert(tuples, {k, v}) end end local chunks = {} for _, tuple in ipairs(tuples) do local k,v = unpack(tuple) k = multipart.url_escape(k) local buffer = { 'Content-Disposition: form-data; name="' .. k .. '"' } local content if type(v) == "table" and v.__class == File then buffer[1] = buffer[1] .. ('; filename="' .. v.fname:gsub(".*/", "") .. '"') table.insert(buffer, "Content-type: " .. v:mime()) content = v:content() else content = v end table.insert(buffer, "") table.insert(buffer, content) table.insert(chunks, table.concat(buffer, "\r\n")) end local boundary while not boundary do boundary = "Boundary" .. rand_string(16) for _, chunk in ipairs(chunks) do if chunk:find(boundary) then boundary = nil break end end end local inner = "\r\n--" .. boundary .. "\r\n" return table.concat({ "--", boundary, "\r\n", table.concat(chunks, inner), "\r\n", "--", boundary, "--", "\r\n" }), boundary end function multipart.new_file(fname, mime) local self = {} setmetatable(self, { __index = File }) self.__class = File self.fname = fname self.mimetype = mime return self end return multipart
gpl-2.0
wanmaple/MWFrameworkForCocosLua
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/UserDefault.lua
10
3039
-------------------------------- -- @module UserDefault -- @parent_module cc -------------------------------- -- brief Set integer value by key.<br> -- js NA -- @function [parent=#UserDefault] setIntegerForKey -- @param self -- @param #char pKey -- @param #int value -------------------------------- -- @overload self, char, float -- @overload self, char -- @function [parent=#UserDefault] getFloatForKey -- @param self -- @param #char pKey -- @param #float defaultValue -- @return float#float ret (return value: float) -------------------------------- -- @overload self, char, bool -- @overload self, char -- @function [parent=#UserDefault] getBoolForKey -- @param self -- @param #char pKey -- @param #bool defaultValue -- @return bool#bool ret (return value: bool) -------------------------------- -- brief Set double value by key.<br> -- js NA -- @function [parent=#UserDefault] setDoubleForKey -- @param self -- @param #char pKey -- @param #double value -------------------------------- -- brief Set float value by key.<br> -- js NA -- @function [parent=#UserDefault] setFloatForKey -- @param self -- @param #char pKey -- @param #float value -------------------------------- -- @overload self, char, string -- @overload self, char -- @function [parent=#UserDefault] getStringForKey -- @param self -- @param #char pKey -- @param #string defaultValue -- @return string#string ret (return value: string) -------------------------------- -- brief Set string value by key.<br> -- js NA -- @function [parent=#UserDefault] setStringForKey -- @param self -- @param #char pKey -- @param #string value -------------------------------- -- brief Save content to xml file<br> -- js NA -- @function [parent=#UserDefault] flush -- @param self -------------------------------- -- @overload self, char, int -- @overload self, char -- @function [parent=#UserDefault] getIntegerForKey -- @param self -- @param #char pKey -- @param #int defaultValue -- @return int#int ret (return value: int) -------------------------------- -- @overload self, char, double -- @overload self, char -- @function [parent=#UserDefault] getDoubleForKey -- @param self -- @param #char pKey -- @param #double defaultValue -- @return double#double ret (return value: double) -------------------------------- -- brief Set bool value by key.<br> -- js NA -- @function [parent=#UserDefault] setBoolForKey -- @param self -- @param #char pKey -- @param #bool value -------------------------------- -- js NA -- @function [parent=#UserDefault] destroyInstance -- @param self -------------------------------- -- js NA -- @function [parent=#UserDefault] getXMLFilePath -- @param self -- @return string#string ret (return value: string) -------------------------------- -- js NA -- @function [parent=#UserDefault] isXMLFileExist -- @param self -- @return bool#bool ret (return value: bool) return nil
apache-2.0
waytim/darkstar
scripts/zones/Riverne-Site_A01/npcs/_0u2.lua
13
1348
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x11); else player:messageSpecial(SD_VERY_SMALL); end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
waytim/darkstar
scripts/globals/abilities/eagle_eye_shot.lua
26
2067
----------------------------------- -- Ability: Eagle Eye Shot -- Delivers a powerful and accurate ranged attack. -- Obtained: Ranger Level 1 -- Recast Time: 1:00:00 -- Duration: Instant ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/weaponskills"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local ranged = player:getStorageItem(0, 0, SLOT_RANGED); local ammo = player:getStorageItem(0, 0, SLOT_AMMO); if ranged and ranged:isType(ITEM_WEAPON) then local skilltype = ranged:getSkillType(); if skilltype == SKILL_ARC or skilltype == SKILL_MRK or skilltype == SKILL_THR then if ammo and (ammo:isType(ITEM_WEAPON) or skilltype == SKILL_THR) then return 0, 0; end; end; end; return MSGBASIC_NO_RANGED_WEAPON, 0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability,action) if (player:getWeaponSkillType(SLOT_RANGED) == SKILL_MRK) then action:animation(target:getID(), action:animation(target:getID()) + 1); end local params = {}; params.numHits = 1; local ftp = 5 params.ftp100 = ftp; params.ftp200 = ftp; params.ftp300 = ftp; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1 params.enmityMult = 0.5 local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, 0, params, 0, true) if not (tpHits + extraHits > 0) then ability:setMsg(MSGBASIC_USES_BUT_MISSES) action:speceffect(target:getID(), 0) end return damage; end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Jugner_Forest/npcs/Chaplion_RK.lua
2
2891
----------------------------------- -- Area: Jugner Forest -- NPC: Chaplion, R.K. -- Outpost Conquest Guards -- @pos 54 0 -11 104 ------------------------------------- package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Jugner_Forest/TextIDs"); guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border region = NORVALLEN; csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
pvvx/EspLua
lua_examples/yet-another-ds18b20.lua
79
1924
------------------------------------------------------------------------------ -- DS18B20 query module -- -- LICENCE: http://opensource.org/licenses/MIT -- Vladimir Dronnikov <dronnikov@gmail.com> -- -- Example: -- dofile("ds18b20.lua").read(4, function(r) for k, v in pairs(r) do print(k, v) end end) ------------------------------------------------------------------------------ local M do local bit = bit local format_addr = function(a) return ("%02x-%02x%02x%02x%02x%02x%02x"):format( a:byte(1), a:byte(7), a:byte(6), a:byte(5), a:byte(4), a:byte(3), a:byte(2) ) end local read = function(pin, cb, delay) local ow = require("ow") -- get list of relevant devices local d = { } ow.setup(pin) ow.reset_search(pin) while true do tmr.wdclr() local a = ow.search(pin) if not a then break end if ow.crc8(a) == 0 and (a:byte(1) == 0x10 or a:byte(1) == 0x28) then d[#d + 1] = a end end -- conversion command for all ow.reset(pin) ow.skip(pin) ow.write(pin, 0x44, 1) -- wait a bit tmr.alarm(0, delay or 100, 0, function() -- iterate over devices local r = { } for i = 1, #d do tmr.wdclr() -- read rom command ow.reset(pin) ow.select(pin, d[i]) ow.write(pin, 0xBE, 1) -- read data local x = ow.read_bytes(pin, 9) if ow.crc8(x) == 0 then local t = (x:byte(1) + x:byte(2) * 256) -- negatives? if bit.isset(t, 15) then t = 1 - bit.bxor(t, 0xffff) end -- NB: temperature in Celsius * 10^4 t = t * 625 -- NB: due 850000 means bad pullup. ignore if t ~= 850000 then r[format_addr(d[i])] = t end d[i] = nil end end cb(r) end) end -- expose M = { read = read, } end return M
mit
TheOnePharaoh/YGOPro-Custom-Cards
script/c78219337.lua
1
3786
--Colossal Warrior - Red Armor function c78219337.initial_effect(c) --pendulum summon aux.EnablePendulumAttribute(c) --splimit local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetRange(LOCATION_PZONE) e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CANNOT_DISABLE) e1:SetTargetRange(1,0) e1:SetCondition(c78219337.splimcon) e1:SetTarget(c78219337.splimit) c:RegisterEffect(e1) --self destroy local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_PZONE) e2:SetCode(EFFECT_SELF_DESTROY) e2:SetCondition(c78219337.descon) c:RegisterEffect(e2) --atk plus local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e3:SetRange(LOCATION_MZONE) e3:SetCost(c78219337.atkcost) e3:SetOperation(c78219337.atkup) c:RegisterEffect(e3) --place card local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(78219337,0)) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_DESTROYED) e4:SetTarget(c78219337.sgtg) e4:SetOperation(c78219337.sgop) c:RegisterEffect(e4) --indes local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e5:SetCode(EFFECT_DESTROY_REPLACE) e5:SetRange(LOCATION_PZONE) e5:SetCountLimit(1) e5:SetTarget(c78219337.indtg) e5:SetValue(c78219337.indval) c:RegisterEffect(e5) end function c78219337.splimcon(e) return not e:GetHandler():IsForbidden() end function c78219337.splimit(e,c,tp,sumtp,sumpos) return not c:IsSetCard(0x7ad30) and bit.band(sumtp,SUMMON_TYPE_PENDULUM)==SUMMON_TYPE_PENDULUM end function c78219337.descon(e) return not Duel.IsEnvironment(78219337) end function c78219337.atkcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsCanRemoveCounter(tp,1,1,0x1115,4,REASON_COST) end Duel.RemoveCounter(tp,1,1,0x1115,4,REASON_COST) end function c78219337.atkup(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() local d=Duel.GetAttackTarget() if not a:IsSetCard(0x7ad30) or not d or a:GetAttack()>=d:GetAttack() then return end local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_PHASE+PHASE_DAMAGE_CAL) e1:SetValue(1500) a:RegisterEffect(e1) end function c78219337.indfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsOnField() and c:IsReason(REASON_EFFECT) and c:IsLocation(LOCATION_SZONE) and c:IsSetCard(0x7ad30) and not c:IsCode(78219328) end function c78219337.indtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return eg:IsExists(c78219337.indfilter,1,nil,tp) end return true end function c78219337.indval(e,c) return c78219337.indfilter(c,e:GetHandlerPlayer()) end function c78219337.tgfilter(c) return c:IsSetCard(0x7ad30) and not c:IsType(TYPE_PENDULUM) end function c78219337.sgtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c78219337.tgfilter,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,nil) and Duel.GetLocationCount(tp,LOCATION_SZONE)>0 end end function c78219337.sgop(e,tp,eg,ep,ev,re,r,rp,chk) if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOFIELD) local g=Duel.SelectMatchingCard(tp,c78219337.tgfilter,tp,LOCATION_HAND+LOCATION_DECK+LOCATION_GRAVE,0,1,1,nil) if g:GetCount()>0 then local tc=g:GetFirst() Duel.MoveToField(tc,tp,tp,LOCATION_SZONE,POS_FACEUP,true) local e1=Effect.CreateEffect(tc) e1:SetCode(EFFECT_CHANGE_TYPE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+0x1fc0000) e1:SetValue(TYPE_SPELL+TYPE_CONTINUOUS) tc:RegisterEffect(e1) Duel.RaiseEvent(tc,78219337,e,0,tp,0,0) end end
gpl-3.0
niegenug/wesnoth
join.lua
27
3343
-- join.lua -- -- Try to join a game called "Test" local function plugin() local function log(text) std_print("join: " .. text) end local counter = 0 local events, context, info local helper = wesnoth.require("lua/helper.lua") local function find_test_game(info) local g = info.game_list() if g then local gamelist = helper.get_child(g, "gamelist") if gamelist then for i = 1, #gamelist do local t = gamelist[i] if t[1] == "game" then local game = t[2] if game.scenario == "Test" then return game.id end end end end end return nil end local function idle_text(text) counter = counter + 1 if counter >= 100 then counter = 0 log("idling " .. text) end end log("hello world") repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for titlescreen or lobby") until info.name == "titlescreen" or info.name == "Multiplayer Lobby" while info.name == "titlescreen" do context.play_multiplayer({}) log("playing multiplayer...") events, context, info = coroutine.yield() end repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for lobby") until info.name == "Multiplayer Lobby" events, context, info = coroutine.yield() context.chat({message = "waiting for test game to join..."}) local test_game = nil repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for test game") for i,v in ipairs(events) do if v[1] == "chat" then std_print("chat:", v[2].message) end end test_game = find_test_game(info) until test_game log("found a test game, joining... id = " .. test_game) context.chat({message = "found test game"}) context.select_game({id = test_game}) events, context, info = coroutine.yield() context.join({}) events, context, info = coroutine.yield() repeat if context.join then context.join({}) else std_print("did not find join...") end events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for leader select dialog") until info.name == "Dialog" or info.name == "Multiplayer Wait" if info.name == "Dialog" then log("got a leader select dialog...") context.set_result({result = 0}) events, context, info = coroutine.yield() repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for mp wait") until info.name == "Multiplayer Wait" end log("got to multiplayer wait...") context.chat({message = "ready"}) repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for game") until info.name == "Game" log("got to a game context...") repeat events, context, info = coroutine.yield() idle_text("in " .. info.name .. " waiting for not game") until info.name ~= "Game" log("left a game context...") repeat context.quit({}) log("quitting a " .. info.name .. " context...") events, context, info = coroutine.yield() until info.name == "titlescreen" context.exit({code = 0}) coroutine.yield() end return plugin
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c20162005.lua
2
3726
--Lizardfolk Resting Place function c20162005.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCost(c20162005.cost) e1:SetTarget(c20162005.target) e1:SetOperation(c20162005.operation) c:RegisterEffect(e1) --destroy replace local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EFFECT_DESTROY_REPLACE) e2:SetRange(LOCATION_GRAVE) e2:SetTarget(c20162005.reptg) e2:SetValue(c20162005.repval) c:RegisterEffect(e2) end function c20162005.cfilter(c) return c:IsRace(RACE_REPTILE) and c:IsAbleToDeckAsCost() end function c20162005.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c20162005.cfilter,tp,LOCATION_HAND+LOCATION_MZONE,0,3,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK) local g=Duel.SelectMatchingCard(tp,c20162005.cfilter,tp,LOCATION_HAND+LOCATION_MZONE,0,3,3,nil) Duel.SendtoDeck(g,nil,1,REASON_COST) end function c20162005.spfilter(c,e,tp) return c:IsType(TYPE_MONSTER) and c:IsSetCard(0xab90) or c:IsSetCard(0xab91) or c:IsSetCard(0xab92) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c20162005.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingMatchingCard(c20162005.spfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_GRAVE) end function c20162005.operation(e,tp,eg,ep,ev,re,r,rp) local ft1=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft1<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c20162005.spfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,ft1,ft1,nil,e,tp) if g:GetCount()>0 then local fid=e:GetHandler():GetFieldID() local tc=g:GetFirst() while tc do Duel.SpecialSummonStep(tc,0,tp,tp,false,false,POS_FACEUP) tc:RegisterFlagEffect(20162005,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1,fid) tc=g:GetNext() end Duel.SpecialSummonComplete() g:KeepAlive() local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetProperty(EFFECT_FLAG_IGNORE_IMMUNE) e1:SetCountLimit(1) e1:SetLabel(fid) e1:SetLabelObject(g) e1:SetCondition(c20162005.tdcon) e1:SetOperation(c20162005.tdsop) Duel.RegisterEffect(e1,tp) end end function c20162005.tdfilter(c,fid) return c:GetFlagEffectLabel(20162005)==fid end function c20162005.tdcon(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() if not g:IsExists(c20162005.tdfilter,1,nil,e:GetLabel()) then g:DeleteGroup() e:Reset() return false else return true end end function c20162005.tdsop(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() local tg=g:Filter(c20162005.tdfilter,nil,e:GetLabel()) Duel.SendtoDeck(tg,nil,1,REASON_EFFECT) end function c20162005.repfilter(c,tp) return c:IsFaceup() and c:IsControler(tp) and c:IsLocation(LOCATION_MZONE) and c:IsRace(RACE_REPTILE) end function c20162005.reptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemove() and eg:IsExists(c20162005.repfilter,1,nil,tp) end if Duel.SelectYesNo(tp,aux.Stringid(20162005,0)) then local g=eg:Filter(c20162005.repfilter,nil,tp) if g:GetCount()==1 then e:SetLabelObject(g:GetFirst()) else Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESREPLACE) local cg=g:Select(tp,1,1,nil) e:SetLabelObject(cg:GetFirst()) end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_EFFECT) return true else return false end end function c20162005.repval(e,c) return c==e:GetLabelObject() end
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c100000894.lua
2
4821
--Created and coded by Rising Phoenix function c100000894.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetDescription(aux.Stringid(100000894,1)) e1:SetTarget(c100000894.target) e1:SetOperation(c100000894.activate) c:RegisterEffect(e1) --search local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(100000894,0)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetRange(LOCATION_HAND) e2:SetCost(c100000894.costh) e2:SetTarget(c100000894.targeth) e2:SetOperation(c100000894.operationh) c:RegisterEffect(e2) --counter local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_IGNITION) e3:SetRange(LOCATION_GRAVE) e3:SetProperty(EFFECT_FLAG_CARD_TARGET) e3:SetCost(c100000894.ctcost) e3:SetTarget(c100000894.cttg) e3:SetOperation(c100000894.ctop) c:RegisterEffect(e3) end c100000894.fit_monster={100000901} function c100000894.costh(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsDiscardable() end Duel.SendtoGrave(c,REASON_COST+REASON_DISCARD) end function c100000894.filterh(c) return c:IsSetCard(0x110) and c:IsAbleToHand() end function c100000894.targeth(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chk==0 then return Duel.IsExistingMatchingCard(c100000894.filterh,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c100000894.operationh(e,tp,eg,ep,ev,re,r,rp,chk) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c100000894.filterh,tp,LOCATION_DECK,0,1,2,nil) if g:GetCount()>0 then end Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_TO_HAND) e1:SetTargetRange(LOCATION_DECK,0) e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN) Duel.RegisterEffect(e1,tp) end function c100000894.ctcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c100000894.ctfilter(c) return c:IsFaceup() and c:IsCanAddCounter(0x50,1) and c:IsSetCard(0x110) end function c100000894.cttg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsControler(tp) and c100000894.ctfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c100000894.ctfilter,tp,LOCATION_ONFIELD,0,1,nil) end Duel.SelectTarget(tp,c100000894.ctfilter,tp,LOCATION_ONFIELD,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_COUNTER,nil,1,0,0x50) end function c100000894.ctop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsFaceup() and tc:IsRelateToEffect(e) then tc:AddCounter(0x50,1) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_CANNOT_REMOVE) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e1:SetTargetRange(1,0) e1:SetTarget(c100000894.rmlimit) e1:SetReset(RESET_PHASE+PHASE_END+RESET_SELF_TURN) Duel.RegisterEffect(e1,tp) end end function c100000894.rmlimit(e,c,p) return c:IsLocation(LOCATION_GRAVE) end function c100000894.filter(c,e,tp,m) if bit.band(c:GetType(),0x81)~=0x81 or not c:IsCode(100000901) or not c:IsCanBeSpecialSummoned(e,SUMMON_TYPE_RITUAL,tp,false,true) then return false end if c.mat_filter then m=m:Filter(c.mat_filter,nil) end return m:CheckWithSumEqual(Card.GetRitualLevel,c:GetLevel(),1,99,c) end function c100000894.matfilter(c) return c:IsAbleToGrave() and c:IsType(TYPE_MONSTER) and c:IsSetCard(0x110) end function c100000894.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return false end local mg=Duel.GetMatchingGroup(c100000894.matfilter,tp,LOCATION_DECK,0,nil) return Duel.IsExistingMatchingCard(c100000894.filter,tp,LOCATION_HAND,0,1,nil,e,tp,mg) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND) end function c100000894.activate(e,tp,eg,ep,ev,re,r,rp) if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end local mg=Duel.GetMatchingGroup(c100000894.matfilter,tp,LOCATION_DECK,0,nil) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local tg=Duel.SelectMatchingCard(tp,c100000894.filter,tp,LOCATION_HAND,0,1,1,nil,e,tp,mg) if tg:GetCount()>0 then local tc=tg:GetFirst() if tc.mat_filter then mg=mg:Filter(tc.mat_filter,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local mat=mg:SelectWithSumEqual(tp,Card.GetRitualLevel,tc:GetLevel(),1,99,tc) tc:SetMaterial(mat) Duel.SendtoGrave(mat,REASON_EFFECT+REASON_MATERIAL+REASON_RITUAL) Duel.BreakEffect() Duel.SpecialSummon(tc,SUMMON_TYPE_RITUAL,tp,tp,false,true,POS_FACEUP) tc:CompleteProcedure() end end
gpl-3.0
X-Raym/REAPER-ReaScripts
Items Editing/X-Raym_Stutter edit selected media items.lua
1
3640
--[[ * ReaScript Name: Stutter edit selected media items * About: Divide selected items length and duplicate * Instructions: Select items. Run. * Screenshot: https://youtu.be/Uz09ifB7atg * Author: X-Raym * Author URI: https://www.extremraym.com * Repository: GitHub > X-Raym > REAPER-ReaScripts * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts * Licence: GPL v3 * Forum Thread: Scripts: Items Editing (various) * Forum Thread URI: http://forum.cockos.com/showthread.php?t=163363 * REAPER: 5.0 * Version: 1.0 --]] --[[ * Changelog: * v1.0 (2016-02-29) + Initial Release --]] -- Notes : it doesn't work with groups items -- USER CONFIG AREA ----------------------------------------------------------- console = true -- true/false: display debug messages in the console divider = 2 ------------------------------------------------------- END OF USER CONFIG AREA -- UTILITIES ------------------------------------------------------------- -- Save item selection function SaveSelectedItems (table) for i = 0, reaper.CountSelectedMediaItems(0)-1 do table[i+1] = reaper.GetSelectedMediaItem(0, i) end end function RestoreSelectedItems (table) for i, item in ipairs(table) do reaper.SetMediaItemSelected(item, true) end end -- Display a message in the console for debugging function Msg(value) if console then reaper.ShowConsoleMsg(tostring(value) .. "\n") end end -- Copy selected media items function CopySelectedMediaItems(track, pos) local cursor_pos = reaper.GetCursorPosition() reaper.SetOnlyTrackSelected(track) reaper.Main_OnCommand(40914, 0) -- Select first track as last touched reaper.SetEditCurPos(pos, false, false) reaper.Main_OnCommand(40698, 0) -- Copy Items reaper.Main_OnCommand(40058, 0) -- Paste Items new_item = reaper.GetSelectedMediaItem(0, 0) -- Get First Selected Item reaper.SetEditCurPos(cursor_pos, false, false) return new_item end -- VIEW -- SAVE INITIAL VIEW function SaveView() start_time_view, end_time_view = reaper.BR_GetArrangeView(0) end -- RESTORE INITIAL VIEW function RestoreView() reaper.BR_SetArrangeView(0, start_time_view, end_time_view) end --------------------------------------------------------- END OF UTILITIES -- Main function function main() new_items = {} for i, item in ipairs(init_sel_items) do reaper.SelectAllMediaItems(0, false) -- Unselect all media items reaper.SetMediaItemSelected(item, true) -- Select only desired item new_len = reaper.GetMediaItemInfo_Value(item, "D_LENGTH") / divider reaper.SetMediaItemInfo_Value(item, "D_LENGTH", new_len) -- Set item to its new length pos = reaper.GetMediaItemInfo_Value(item, "D_POSITION") track = reaper.GetMediaItemTrack(item) -- Get destination track (in this case, item parent track) for j = 1, divider - 1 do new_pos = pos + new_len * j new_item = CopySelectedMediaItems(track, new_pos) table.insert(new_items, new_item) end end end -- INIT -- See if there is items selected count_sel_items = reaper.CountSelectedMediaItems(0) if count_sel_items > 0 then reaper.PreventUIRefresh(1) SaveView() reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function. init_sel_items = {} SaveSelectedItems(init_sel_items) main() RestoreSelectedItems(init_sel_items) RestoreSelectedItems(new_items) reaper.Undo_EndBlock("Stutter edit selected media items", -1) -- End of the undo block. Leave it at the bottom of your main function. reaper.UpdateArrange() RestoreView() reaper.PreventUIRefresh(-1) end
gpl-3.0
mehrpouya81/gamerspm
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
MinFu/luci
modules/luci-base/luasrc/http/protocol.lua
34
15539
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- This class contains several functions useful for http message- and content -- decoding and to retrive form data from raw http messages. module("luci.http.protocol", package.seeall) local ltn12 = require("luci.ltn12") HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size -- the "+" sign to " " - and return the decoded string. function urldecode( str, no_plus ) local function __chrdec( hex ) return string.char( tonumber( hex, 16 ) ) end if type(str) == "string" then if not no_plus then str = str:gsub( "+", " " ) end str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec ) end return str end -- from given url or string. Returns a table with urldecoded values. -- Simple parameters are stored as string values associated with the parameter -- name within the table. Parameters with multiple values are stored as array -- containing the corresponding values. function urldecode_params( url, tbl ) local params = tbl or { } if url:find("?") then url = url:gsub( "^.+%?([^?]+)", "%1" ) end for pair in url:gmatch( "[^&;]+" ) do -- find key and value local key = urldecode( pair:match("^([^=]+)") ) local val = urldecode( pair:match("^[^=]+=(.+)$") ) -- store if type(key) == "string" and key:len() > 0 then if type(val) ~= "string" then val = "" end if not params[key] then params[key] = val elseif type(params[key]) ~= "table" then params[key] = { params[key], val } else table.insert( params[key], val ) end end end return params end function urlencode( str ) local function __chrenc( chr ) return string.format( "%%%02x", string.byte( chr ) ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.!*'(),])", __chrenc ) end return str end -- separated by "&". Tables are encoded as parameters with multiple values by -- repeating the parameter name with each value. function urlencode_params( tbl ) local enc = "" for k, v in pairs(tbl) do if type(v) == "table" then for i, v2 in ipairs(v) do enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v2) end else enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v) end end return enc end -- (Internal function) -- Initialize given parameter and coerce string into table when the parameter -- already exists. local function __initval( tbl, key ) if tbl[key] == nil then tbl[key] = "" elseif type(tbl[key]) == "string" then tbl[key] = { tbl[key], "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Append given data to given parameter, either by extending the string value -- or by appending it to the last string in the parameter's value table. local function __appendval( tbl, key, chunk ) if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk else tbl[key] = tbl[key] .. chunk end end -- (Internal function) -- Finish the value of given parameter, either by transforming the string value -- or - in the case of multi value parameters - the last element in the -- associated values table. local function __finishval( tbl, key, handler ) if handler then if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] ) else tbl[key] = handler( tbl[key] ) end end end -- Table of our process states local process_states = { } -- Extract "magic", the first line of a http message. -- Extracts the message type ("get", "post" or "response"), the requested uri -- or the status code if the line descripes a http response. process_states['magic'] = function( msg, chunk, err ) if chunk ~= nil then -- ignore empty lines before request if #chunk == 0 then return true, nil end -- Is it a request? local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$") -- Yup, it is if method then msg.type = "request" msg.request_method = method:lower() msg.request_uri = uri msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end -- Is it a response? else local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$") -- Is a response if code then msg.type = "response" msg.status_code = code msg.status_message = message msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end end end end -- Can't handle it return nil, "Invalid HTTP message magic" end -- Extract headers from given string. process_states['headers'] = function( msg, chunk ) if chunk ~= nil then -- Look for a valid header format local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" ) if type(hdr) == "string" and hdr:len() > 0 and type(val) == "string" and val:len() > 0 then msg.headers[hdr] = val -- Valid header line, proceed return true, nil elseif #chunk == 0 then -- Empty line, we won't accept data anymore return false, nil else -- Junk data return nil, "Invalid HTTP header received" end else return nil, "Unexpected EOF" end end -- data line by line with the trailing \r\n stripped of. function header_source( sock ) return ltn12.source.simplify( function() local chunk, err, part = sock:receive("*l") -- Line too long if chunk == nil then if err ~= "timeout" then return nil, part and "Line exceeds maximum allowed length" or "Unexpected EOF" else return nil, err end -- Line ok elseif chunk ~= nil then -- Strip trailing CR chunk = chunk:gsub("\r$","") return chunk, nil end end ) end -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- If an optional file callback function is given then it is feeded with the -- file contents chunk by chunk and only the extracted file name is stored -- within the params table. The callback function will be called subsequently -- with three arguments: -- o Table containing decoded (name, file) and raw (headers) mime header data -- o String value containing a chunk of the file data -- o Boolean which indicates wheather the current chunk is the last one (eof) function mimedecode_message_body( src, msg, filecb ) if msg and msg.env.CONTENT_TYPE then msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$") end if not msg.mime_boundary then return nil, "Invalid Content-Type found" end local tlen = 0 local inhdr = false local field = nil local store = nil local lchunk = nil local function parse_headers( chunk, field ) local stat repeat chunk, stat = chunk:gsub( "^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n", function(k,v) field.headers[k] = v return "" end ) until stat == 0 chunk, stat = chunk:gsub("^\r\n","") -- End of headers if stat > 0 then if field.headers["Content-Disposition"] then if field.headers["Content-Disposition"]:match("^form%-data; ") then field.name = field.headers["Content-Disposition"]:match('name="(.-)"') field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$') end end if not field.headers["Content-Type"] then field.headers["Content-Type"] = "text/plain" end if field.name and field.file and filecb then __initval( msg.params, field.name ) __appendval( msg.params, field.name, field.file ) store = filecb elseif field.name then __initval( msg.params, field.name ) store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end else store = nil end return chunk, true end return chunk, false end local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" end if chunk and not lchunk then lchunk = "\r\n" .. chunk elseif lchunk then local data = lchunk .. ( chunk or "" ) local spos, epos, found repeat spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true ) if not spos then spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true ) end if spos then local predata = data:sub( 1, spos - 1 ) if inhdr then predata, eof = parse_headers( predata, field ) if not eof then return nil, "Invalid MIME section header" elseif not field.name then return nil, "Invalid Content-Disposition header" end end if store then store( field, predata, true ) end field = { headers = { } } found = found or true data, eof = parse_headers( data:sub( epos + 1, #data ), field ) inhdr = not eof end until not spos if found then -- We found at least some boundary. Save -- the unparsed remaining data for the -- next chunk. lchunk, data = data, nil else -- There was a complete chunk without a boundary. Parse it as headers or -- append it as data, depending on our current state. if inhdr then lchunk, eof = parse_headers( data, field ) inhdr = not eof else -- We're inside data, so append the data. Note that we only append -- lchunk, not all of data, since there is a chance that chunk -- contains half a boundary. Assuming that each chunk is at least the -- boundary in size, this should prevent problems store( field, lchunk, false ) lchunk, chunk = chunk, nil end end end return true end return ltn12.pump.all( src, snk ) end -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. function urldecode_message_body( src, msg ) local tlen = 0 local lchunk = nil local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" elseif tlen > HTTP_MAX_CONTENT then return nil, "Message body size exceeds maximum allowed length" end if not lchunk and chunk then lchunk = chunk elseif lchunk then local data = lchunk .. ( chunk or "&" ) local spos, epos repeat spos, epos = data:find("^.-[;&]") if spos then local pair = data:sub( spos, epos - 1 ) local key = pair:match("^(.-)=") local val = pair:match("=([^%s]*)%s*$") if key and #key > 0 then __initval( msg.params, key ) __appendval( msg.params, key, val ) __finishval( msg.params, key, urldecode ) end data = data:sub( epos + 1, #data ) end until not spos lchunk = data end return true end return ltn12.pump.all( src, snk ) end -- version, message headers and resulting CGI environment variables from the -- given ltn12 source. function parse_message_header( src ) local ok = true local msg = { } local sink = ltn12.sink.simplify( function( chunk ) return process_states['magic']( msg, chunk ) end ) -- Pump input data... while ok do -- get data ok, err = ltn12.pump.step( src, sink ) -- error if not ok and err then return nil, err -- eof elseif not ok then -- Process get parameters if ( msg.request_method == "get" or msg.request_method == "post" ) and msg.request_uri:match("?") then msg.params = urldecode_params( msg.request_uri ) else msg.params = { } end -- Populate common environment variables msg.env = { CONTENT_LENGTH = msg.headers['Content-Length']; CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type']; REQUEST_METHOD = msg.request_method:upper(); REQUEST_URI = msg.request_uri; SCRIPT_NAME = msg.request_uri:gsub("?.+$",""); SCRIPT_FILENAME = ""; -- XXX implement me SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version); QUERY_STRING = msg.request_uri:match("?") and msg.request_uri:gsub("^.+?","") or "" } -- Populate HTTP_* environment variables for i, hdr in ipairs( { 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Connection', 'Cookie', 'Host', 'Referer', 'User-Agent', } ) do local var = 'HTTP_' .. hdr:upper():gsub("%-","_") local val = msg.headers[hdr] msg.env[var] = val end end end return msg end -- This function will examine the Content-Type within the given message object -- to select the appropriate content decoder. -- Currently the application/x-www-urlencoded and application/form-data -- mime types are supported. If the encountered content encoding can't be -- handled then the whole message body will be stored unaltered as "content" -- property within the given message object. function parse_message_body( src, msg, filecb ) -- Is it multipart/mime ? if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^multipart/form%-data") then return mimedecode_message_body( src, msg, filecb ) -- Is it application/x-www-form-urlencoded ? elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded") then return urldecode_message_body( src, msg, filecb ) -- Unhandled encoding -- If a file callback is given then feed it chunk by chunk, else -- store whole buffer in message.content else local sink -- If we have a file callback then feed it if type(filecb) == "function" then local meta = { name = "raw", encoding = msg.env.CONTENT_TYPE } sink = function( chunk ) if chunk then return filecb(meta, chunk, false) else return filecb(meta, nil, true) end end -- ... else append to .content else msg.content = "" msg.content_length = 0 sink = function( chunk ) if chunk then if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then msg.content = msg.content .. chunk msg.content_length = msg.content_length + #chunk return true else return nil, "POST data exceeds maximum allowed length" end end return true end end -- Pump data... while true do local ok, err = ltn12.pump.step( src, sink ) if not ok and err then return nil, err elseif not ok then -- eof return true end end return true end end statusmsg = { [200] = "OK", [206] = "Partial Content", [301] = "Moved Permanently", [302] = "Found", [304] = "Not Modified", [400] = "Bad Request", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [408] = "Request Time-out", [411] = "Length Required", [412] = "Precondition Failed", [416] = "Requested range not satisfiable", [500] = "Internal Server Error", [503] = "Server Unavailable", }
apache-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c77777881.lua
2
3707
--Lady of the Glade function c77777881.initial_effect(c) function aux.AddXyzProcedure(c,f,lv,ct,alterf,desc,maxct,op) local code=c:GetOriginalCode() local mt=_G["c" .. code] if f then mt.xyz_filter=function(mc) return mc and f(mc) end else mt.xyz_filter=function(mc) return true end end mt.minxyzct=ct if not maxct then mt.maxxyzct=ct else if maxct==5 and code~=14306092 and code~=63504681 and code~=23776077 then mt.maxxyzct=99 else mt.maxxyzct=maxct end end local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_EXTRA) if not maxct then maxct=ct end if alterf then e1:SetCondition(Auxiliary.XyzCondition2(f,lv,ct,maxct,alterf,desc,op)) e1:SetTarget(Auxiliary.XyzTarget2(f,lv,ct,maxct,alterf,desc,op)) e1:SetOperation(Auxiliary.XyzOperation2(f,lv,ct,maxct,alterf,desc,op)) else e1:SetCondition(Auxiliary.XyzCondition(f,lv,ct,maxct)) e1:SetTarget(Auxiliary.XyzTarget(f,lv,ct,maxct)) e1:SetOperation(Auxiliary.XyzOperation(f,lv,ct,maxct)) end e1:SetValue(SUMMON_TYPE_XYZ) c:RegisterEffect(e1) end --To hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(77777881,0)) e1:SetCategory(CATEGORY_TOGRAVE) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP+EFFECT_TYPE_TRIGGER_F) e1:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP) e1:SetTarget(c77777881.target) e1:SetOperation(c77777881.operation) c:RegisterEffect(e1) c77777881.xyzlimit2=function(mc) return mc:IsRace(RACE_FAIRY) end local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetCode(511001225) c:RegisterEffect(e2) if not c77777881.global_check then c77777881.global_check=true local ge2=Effect.CreateEffect(c) ge2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) ge2:SetCode(EVENT_ADJUST) ge2:SetCountLimit(1) ge2:SetProperty(EFFECT_FLAG_NO_TURN_RESET) ge2:SetOperation(c77777881.xyzchk) Duel.RegisterEffect(ge2,0) end --attack limit local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e5:SetCode(EVENT_FLIP) e5:SetOperation(c77777881.flipop) c:RegisterEffect(e5) end function c77777881.flipop(e,tp,eg,ep,ev,re,r,rp) e:GetHandler():RegisterFlagEffect(77777876,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) end function c77777881.dccon(c) return c:IsRace(RACE_FAIRY) end function c77777881.tgfilter(c) return c:IsSetCard(0x40c) and c:IsAbleToGrave() and c:IsType(TYPE_MONSTER) end function c77777881.xyzfilter(c) return c:IsXyzSummonable() and c:IsRace(RACE_FAIRY) end function c77777881.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c77777881.tgfilter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK) end function c77777881.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE) local g=Duel.SelectMatchingCard(tp,c77777881.tgfilter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 and Duel.SendtoGrave(g,REASON_EFFECT) and Duel.IsExistingMatchingCard(Card.IsXyzSummonable,tp,LOCATION_EXTRA,0,1,nil,nil) and Duel.SelectYesNo(tp,aux.Stringid(77777881,1)) then Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_EXTRA) local g2=Duel.GetMatchingGroup(Card.IsXyzSummonable,tp,LOCATION_EXTRA,0,nil,nil) if g2:GetCount()>0 then Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g2:Select(tp,1,1,nil) Duel.XyzSummon(tp,sg:GetFirst(),nil) end end end function c77777881.xyzchk(e,tp,eg,ep,ev,re,r,rp) Duel.CreateToken(tp,419) Duel.CreateToken(1-tp,419) end
gpl-3.0
waytim/darkstar
scripts/globals/mobskills/Typhoon.lua
34
1116
--------------------------------------------- -- Typhoon -- -- Description: Spins around dealing damage to targets in an area of effect. -- Type: Physical -- Utsusemi/Blink absorb: 2-4 shadows -- Range: 10' 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 numhits = 4; local accmod = 1; local dmgmod = 0.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); if (mob:getName() == "Faust") then if (mob:getLocalVar("Typhoon") == 0) then mob:useMobAbility(539); mob:setLocalVar("Typhoon", 1); else mob:setLocalVar("Typhoon", 0); end end return dmg; end;
gpl-3.0
behnam98/SmartRobot
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
waytim/darkstar
scripts/zones/Dangruf_Wadi/npcs/Grounds_Tome.lua
30
1091
----------------------------------- -- Area: Dangruf Wadi -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_DANGRUF_WADI,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,639,640,641,642,643,644,645,646,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,639,640,641,642,643,644,645,646,0,0,GOV_MSG_DANGRUF_WADI); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/weaponskills/blade_yu.lua
4
1416
----------------------------------- -- Blade Yu -- Katana weapon skill -- Skill Level: 290 -- Delivers a water elemental attack. Additional effect Poison. Durration varies with TP. -- Aligned with the Aqua Gorget & Soil Gorget. -- Aligned with the Aqua Belt & Soil Belt. -- Element: Water -- Modifiers: DEX:50% ; INT:50% -- 100%TP 200%TP 300%TP -- 2.25 2.25 2.25 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25; params.str_wsc = 0.0; params.dex_wsc = 0.5; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.5; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 15) + 75; if(target:hasStatusEffect(EFFECT_POISON) == false) then target:addStatusEffect(EFFECT_POISON, 10, 0, duration); end end return tpHits, extraHits, damage; end
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c494476157.lua
2
2384
function c494476157.initial_effect(c) --end battle phase local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(494476157,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_ATTACK_ANNOUNCE) e1:SetRange(LOCATION_HAND) e1:SetCondition(c494476157.condition) e1:SetTarget(c494476157.target) e1:SetOperation(c494476157.operation) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(494476157,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_LEAVE_FIELD) e2:SetCondition(c494476157.spcon) e2:SetTarget(c494476157.sptg) e2:SetOperation(c494476157.spop) c:RegisterEffect(e2) end function c494476157.condition(e,tp,eg,ep,ev,re,r,rp) local at=Duel.GetAttacker() return at:GetControler()~=tp and Duel.GetAttackTarget()==nil end function c494476157.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,c,1,0,0) end function c494476157.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)>0 then Duel.BreakEffect() Duel.SkipPhase(1-tp,PHASE_BATTLE,RESET_PHASE+PHASE_BATTLE,1) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_LEAVE_FIELD_REDIRECT) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetReset(RESET_EVENT+0xfe0000) e1:SetValue(LOCATION_REMOVED) c:RegisterEffect(e1) end end function c494476157.spcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() return c:IsPreviousPosition(POS_FACEUP) and not c:IsLocation(LOCATION_DECK) end function c494476157.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK) end function c494476157.spfilter(c,e,tp) return c:IsCode(494476151) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c494476157.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstMatchingCard(c494476157.spfilter,tp,LOCATION_DECK,0,nil,e,tp) if tc then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/weaponskills/ground_strike.lua
4
1448
----------------------------------- -- Ground Strike -- Great Sword weapon skill -- Skill level: 250 QUESTED -- Delivers a single-hit attack. Damage varies with TP. -- Modifiers: STR:50% INT:50% -- 100%TP 200%TP 300%TP -- 1.5 1.75 3.0 ----------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/weaponskills"); function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; --ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp100 = 1.5; params.ftp200 = 1.75; params.ftp300 = 3.0; --wscs are in % so 0.2=20% params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.5; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; --critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP) params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0; params.canCrit = false; --accuracy mods (ONLY USE FOR ACCURACY VARIES WITH TP) , should be the params.acc at those %s NOT the penalty values. Leave 0 if params.acc doesnt vary with tp. params.acc100 = 0; params.acc200=0; params.acc300=0; --attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default. params.atkmulti = 1.75; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
amostalong/SSFS
Assets/LuaFramework/ToLua/Lua/socket/url.lua
16
11058
----------------------------------------------------------------------------- -- URI parsing, composition and relative URL resolution -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local base = _G local table = require("table") local socket = require("socket") socket.url = {} local _M = socket.url ----------------------------------------------------------------------------- -- Module version ----------------------------------------------------------------------------- _M._VERSION = "URL 1.0.3" ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function _M.escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end)) end ----------------------------------------------------------------------------- -- Protects a path segment, to prevent it from interfering with the -- url parsing. -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end -- these are allowed withing a path segment, along with alphanum -- other characters must be escaped local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end ----------------------------------------------------------------------------- -- Encodes a string into its escaped hexadecimal representation -- Input -- s: binary string to be encoded -- Returns -- escaped representation of string binary ----------------------------------------------------------------------------- function _M.unescape(s) return (string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end)) end ----------------------------------------------------------------------------- -- Builds a path from a base path and a relative path -- Input -- base_path -- relative_path -- Returns -- corresponding absolute path ----------------------------------------------------------------------------- local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function _M.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query string url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:%]]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then -- IPv6? parsed.host = string.match(authority, "^%[(.+)%]$") or authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function _M.build(parsed) local ppath = _M.parse_path(parsed.path or "") local url = _M.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if string.find(authority, ":") then -- IPv6? authority = "[" .. authority .. "]" end if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end ----------------------------------------------------------------------------- -- Builds a absolute URL from a base and a relative URL according to RFC 2396 -- Input -- base_url -- relative_url -- Returns -- corresponding absolute url ----------------------------------------------------------------------------- function _M.absolute(base_url, relative_url) local base_parsed if base.type(base_url) == "table" then base_parsed = base_url base_url = _M.build(base_parsed) else base_parsed = _M.parse(base_url) end local relative_parsed = _M.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return _M.build(relative_parsed) end end ----------------------------------------------------------------------------- -- Breaks a path into its segments, unescaping the segments -- Input -- path -- Returns -- segment: a table with one entry per segment ----------------------------------------------------------------------------- function _M.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = _M.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end ----------------------------------------------------------------------------- -- Builds a path component from its segments, escaping protected characters. -- Input -- parsed: path segments -- unsafe: if true, segments are not protected before path is built -- Returns -- path: corresponding path stringing ----------------------------------------------------------------------------- function _M.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return _M
mit
X-Raym/REAPER-ReaScripts
Text Items and Item Notes/Formatting/X-Raym_Delete musical notes from selected items notes.lua
1
1803
--[[ * ReaScript Name: Delete musical notes from selected items notes * About: Delete musical notes from selected items notes * Instructions: Here is how to use it. (optional) * Author: X-Raym * Author URI: https://www.extremraym.com * Repository: GitHub > X-Raym > REAPER-ReaScripts * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts * Licence: GPL v3 * Forum Thread: Scripts (LUA): Text Items Formatting Actions (various) * Forum Thread URI: http://forum.cockos.com/showthread.php?t=156757 * REAPER: 5.0 pre 15 * Extensions: SWS/S&M 2.7.3 #0 * Version: 1.1 --]] --[[ * Changelog: * v1.1 (2015-07-29) # Better Set Notes * v1.0 (2015-03-06) + Initial Release --]] function delete_background() reaper.Undo_BeginBlock() -- Begining of the undo block. Leave it at the top of your main function. -- LOOP THROUGH SELECTED ITEMS selected_items_count = reaper.CountSelectedMediaItems(0) -- INITIALIZE loop through selected items for i = 0, selected_items_count-1 do -- GET ITEMS item = reaper.GetSelectedMediaItem(0, i) -- Get selected item i -- GET NOTES note = reaper.ULT_GetMediaItemNote(item) -- MODIFY NOTES note = note:gsub(" ♪", "") note = note:gsub("♪ ", "") -- SET NOTES reaper.ULT_SetMediaItemNote(item, note) end -- ENDLOOP through selected items reaper.Undo_EndBlock("Delete musical notes from selected items notes", 0) -- End of the undo block. Leave it at the bottom of your main function. end reaper.PreventUIRefresh(1) -- Prevent UI refreshing. Uncomment it only if the script works. delete_background() -- Execute your main function reaper.PreventUIRefresh(-1) -- Restore UI Refresh. Uncomment it only if the script works. reaper.UpdateArrange() -- Update the arrangement (often needed)
gpl-3.0
waytim/darkstar
scripts/zones/Chocobo_Circuit/Zone.lua
17
1068
----------------------------------- -- -- Zone: Chocobo_Circuit -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Chocobo_Circuit/TextIDs"] = nil; require("scripts/zones/Chocobo_Circuit/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
waytim/darkstar
scripts/zones/Port_Windurst/npcs/Kucha_Malkobhi.lua
17
1473
----------------------------------- -- Area: Port Windurst -- NPC: Kucha Malkobhi -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,KUCHAMALKOBHI_SHOP_DIALOG); stock = { 0x315b, 273, --Tarutaru Kaftan 0x31d4, 163, --Tarutaru Mitts 0x3256, 236, --Tarutaru Braccae 0x32cf, 163, --Tarutaru Clomps 0x315c, 273, --Mithran Separates 0x31d5, 163, --Mithran Gauntlets 0x3257, 236, --Mithran Loincloth 0x32d0, 163 --Mithran Gaiters } showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
waytim/darkstar
scripts/zones/Northern_San_dOria/npcs/Aivedoir.lua
13
1041
----------------------------------- -- Area: Northern San d'Oria -- NPC: Aivedoir -- Type: Standard Dialogue NPC -- @zone: 231 -- @pos -123.119 7.999 134.490 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,AIVEDOIR_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/npcs/_l10.lua
6
1495
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -19 0 -4.625 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); if (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (player:getVar("cService") == 1) then player:setVar("cService",2); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 14) then player:setVar("cService",15); end end end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
waytim/darkstar
scripts/zones/Eastern_Altepa_Desert/npcs/qm.lua
13
1620
----------------------------------- -- Area: Eastern Altepa Desert -- NPC: ??? -- Involved In Quest: A Craftsman's Work -- @pos 113 -7.972 -72 114 ----------------------------------- package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Eastern_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Decurio_I_IIIKilled = player:getVar("Decurio_I_IIIKilled"); if (player:getVar("aCraftsmanWork") == 1 and Decurio_I_IIIKilled == 0) then SpawnMob(17244523,300):updateClaim(player); elseif (Decurio_I_IIIKilled == 1) then player:addKeyItem(ALTEPA_POLISHING_STONE); player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_POLISHING_STONE); player:setVar("aCraftsmanWork",2); player:setVar("Decurio_I_IIIKilled",0); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Em30-tm-lua/Emc
.luarocks/share/lua/5.2/luarocks/build/builtin.lua
3
10879
--- A builtin build system: back-end to provide a portable way of building C-based Lua modules. --module("luarocks.build.builtin", package.seeall) local builtin = {} local unpack = unpack or table.unpack local fs = require("luarocks.fs") local path = require("luarocks.path") local util = require("luarocks.util") local cfg = require("luarocks.cfg") local dir = require("luarocks.dir") --- Run a command displaying its execution on standard output. -- @return boolean: true if command succeeds (status code 0), false -- otherwise. local function execute(...) io.stdout:write(table.concat({...}, " ").."\n") return fs.execute(...) end --- Makes an RC file with an embedded Lua script, for building .exes on Windows -- @return nil if could open files, error otherwise local function make_rc(luafilename, rcfilename) --TODO EXEWRAPPER local rcfile = io.open(rcfilename, "w") if not rcfile then error("Could not open "..rcfilename.." for writing.") end rcfile:write("STRINGTABLE\r\nBEGIN\r\n") local i = 1 for line in io.lines(luafilename) do if not line:match("^#!") then rcfile:write(i .. " \"") line = line:gsub("\\", "\\\\"):gsub('"', '""'):gsub("[\r\n]+", "") rcfile:write(line .. "\\r\\n\"\r\n") i = i + 1 end end rcfile:write("END\r\n") rcfile:close() end --- Driver function for the builtin build back-end. -- @param rockspec table: the loaded rockspec. -- @return boolean or (nil, string): true if no errors ocurred, -- nil and an error message otherwise. function builtin.run(rockspec) assert(type(rockspec) == "table") local compile_object, compile_library, compile_wrapper_binary --TODO EXEWRAPPER local build = rockspec.build local variables = rockspec.variables local function add_flags(extras, flag, flags) if flags then if type(flags) ~= "table" then flags = { tostring(flags) } end util.variable_substitutions(flags, variables) for _, v in ipairs(flags) do table.insert(extras, flag:format(v)) end end end if cfg.is_platform("mingw32") then compile_object = function(object, source, defines, incdirs) local extras = {} add_flags(extras, "-D%s", defines) add_flags(extras, "-I%s", incdirs) return execute(variables.CC.." "..variables.CFLAGS, "-c", "-o", object, "-I"..variables.LUA_INCDIR, source, unpack(extras)) end compile_library = function(library, objects, libraries, libdirs) local extras = { unpack(objects) } add_flags(extras, "-L%s", libdirs) add_flags(extras, "-l%s", libraries) extras[#extras+1] = dir.path(variables.LUA_LIBDIR, variables.LUALIB) extras[#extras+1] = "-l" .. (variables.MSVCRT or "m") local ok = execute(variables.LD.." "..variables.LIBFLAG, "-o", library, unpack(extras)) return ok end compile_wrapper_binary = function(fullname, name) --TODO EXEWRAPPER local fullbasename = fullname:gsub("%.lua$", ""):gsub("/", "\\") local basename = name:gsub("%.lua$", ""):gsub("/", "\\") local rcname = basename..".rc" local resname = basename..".o" local wrapname = basename..".exe" make_rc(fullname, fullbasename..".rc") local ok = execute(variables.RC, "-o", resname, rcname) if not ok then return ok end ok = execute(variables.CC.." "..variables.CFLAGS, "-I"..variables.LUA_INCDIR, "-o", wrapname, resname, variables.WRAPPER, dir.path(variables.LUA_LIBDIR, variables.LUALIB), "-l" .. (variables.MSVCRT or "m"), "-luser32") return ok, wrapname end elseif cfg.is_platform("win32") then compile_object = function(object, source, defines, incdirs) local extras = {} add_flags(extras, "-D%s", defines) add_flags(extras, "-I%s", incdirs) return execute(variables.CC.." "..variables.CFLAGS, "-c", "-Fo"..object, "-I"..variables.LUA_INCDIR, source, unpack(extras)) end compile_library = function(library, objects, libraries, libdirs, name) local extras = { unpack(objects) } add_flags(extras, "-libpath:%s", libdirs) add_flags(extras, "%s.lib", libraries) local basename = dir.base_name(library):gsub(".[^.]*$", "") local deffile = basename .. ".def" local def = io.open(dir.path(fs.current_dir(), deffile), "w+") def:write("EXPORTS\n") def:write("luaopen_"..name:gsub("%.", "_").."\n") def:close() local ok = execute(variables.LD, "-dll", "-def:"..deffile, "-out:"..library, dir.path(variables.LUA_LIBDIR, variables.LUALIB), unpack(extras)) local basedir = "" if name:find("%.") ~= nil then basedir = name:gsub("%.%w+$", "\\") basedir = basedir:gsub("%.", "\\") end local manifestfile = basedir .. basename..".dll.manifest" if ok and fs.exists(manifestfile) then ok = execute(variables.MT, "-manifest", manifestfile, "-outputresource:"..basedir..basename..".dll;2") end return ok end compile_wrapper_binary = function(fullname, name) --TODO EXEWRAPPER local fullbasename = fullname:gsub("%.lua$", ""):gsub("/", "\\") local basename = name:gsub("%.lua$", ""):gsub("/", "\\") local object = basename..".obj" local rcname = basename..".rc" local resname = basename..".res" local wrapname = basename..".exe" make_rc(fullname, fullbasename..".rc") local ok = execute(variables.RC, "-r", "-fo"..resname, rcname) if not ok then return ok end ok = execute(variables.CC.." "..variables.CFLAGS, "-c", "-Fo"..object, "-I"..variables.LUA_INCDIR, variables.WRAPPER) if not ok then return ok end ok = execute(variables.LD, "-out:"..wrapname, resname, object, dir.path(variables.LUA_LIBDIR, variables.LUALIB), "user32.lib") local manifestfile = wrapname..".manifest" if ok and fs.exists(manifestfile) then ok = execute(variables.MT, "-manifest", manifestfile, "-outputresource:"..wrapname..";1") end return ok, wrapname end else compile_object = function(object, source, defines, incdirs) local extras = {} add_flags(extras, "-D%s", defines) add_flags(extras, "-I%s", incdirs) return execute(variables.CC.." "..variables.CFLAGS, "-I"..variables.LUA_INCDIR, "-c", source, "-o", object, unpack(extras)) end compile_library = function (library, objects, libraries, libdirs) local extras = { unpack(objects) } add_flags(extras, "-L%s", libdirs) if cfg.gcc_rpath then add_flags(extras, "-Wl,-rpath,%s:", libdirs) end add_flags(extras, "-l%s", libraries) if cfg.is_platform("cygwin") then add_flags(extras, "-l%s", {"lua"}) end return execute(variables.LD.." "..variables.LIBFLAG, "-o", library, "-L"..variables.LUA_LIBDIR, unpack(extras)) end compile_wrapper_binary = function(_, name) return true, name end --TODO EXEWRAPPER end local ok = true local built_modules = {} local luadir = path.lua_dir(rockspec.name, rockspec.version) local libdir = path.lib_dir(rockspec.name, rockspec.version) --TODO EXEWRAPPER -- On Windows, compiles an .exe for each Lua file in build.install.bin, and -- replaces the filename with the .exe name. Strips the .lua extension if it exists, -- otherwise just appends .exe to the name. Only if `cfg.exewrapper = true` if build.install and build.install.bin then for key, name in pairs(build.install.bin) do local fullname = dir.path(fs.current_dir(), name) if cfg.exewrapper and fs.is_lua(fullname) then ok, name = compile_wrapper_binary(fullname, name) if ok then build.install.bin[key] = name else return nil, "Build error in wrapper binaries" end end end end if not build.modules then return nil, "Missing build.modules table" end for name, info in pairs(build.modules) do local moddir = path.module_to_path(name) if type(info) == "string" then local ext = info:match(".([^.]+)$") if ext == "lua" then local filename = dir.base_name(info) if info:match("init%.lua$") and not name:match("%.init$") then moddir = path.module_to_path(name..".init") else local basename = name:match("([^.]+)$") local baseinfo = filename:gsub("%.lua$", "") if basename ~= baseinfo then filename = basename..".lua" end end local dest = dir.path(luadir, moddir, filename) built_modules[info] = dest else info = {info} end end if type(info) == "table" then local objects = {} local sources = info.sources if info[1] then sources = info end if type(sources) == "string" then sources = {sources} end for _, source in ipairs(sources) do local object = source:gsub(".[^.]*$", "."..cfg.obj_extension) if not object then object = source.."."..cfg.obj_extension end ok = compile_object(object, source, info.defines, info.incdirs) if not ok then return nil, "Failed compiling object "..object end table.insert(objects, object) end if not ok then break end local module_name = name:match("([^.]*)$").."."..util.matchquote(cfg.lib_extension) if moddir ~= "" then module_name = dir.path(moddir, module_name) local ok, err = fs.make_dir(moddir) if not ok then return nil, err end end built_modules[module_name] = dir.path(libdir, module_name) ok = compile_library(module_name, objects, info.libraries, info.libdirs, name) if not ok then return nil, "Failed compiling module "..module_name end end end for name, dest in pairs(built_modules) do fs.make_dir(dir.dir_name(dest)) ok = fs.copy(name, dest) if not ok then return nil, "Failed installing "..name.." in "..dest end end if fs.is_dir("lua") then local ok, err = fs.copy_contents("lua", luadir) if not ok then return nil, "Failed copying contents of 'lua' directory: "..err end end return true end return builtin
gpl-2.0
MinFu/luci
protocols/luci-proto-3g/luasrc/model/cbi/admin_network/proto_3g.lua
52
4346
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, apn, service, pincode, username, password, dialnumber local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty[A-Z]*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end service = section:taboption("general", Value, "service", translate("Service Type")) service:value("", translate("-- Please choose --")) service:value("umts", "UMTS/GPRS") service:value("umts_only", translate("UMTS only")) service:value("gprs_only", translate("GPRS only")) service:value("evdo", "CDMA/EV-DO") apn = section:taboption("general", Value, "apn", translate("APN")) pincode = section:taboption("general", Value, "pincode", translate("PIN")) username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true dialnumber = section:taboption("general", Value, "dialnumber", translate("Dial number")) dialnumber.placeholder = "*99***1#" if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end maxwait = section:taboption("advanced", Value, "maxwait", translate("Modem init timeout"), translate("Maximum amount of seconds to wait for the modem to become ready")) maxwait.placeholder = "20" maxwait.datatype = "min(1)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger"
apache-2.0
waytim/darkstar
scripts/zones/Western_Adoulin/npcs/Porter_Moogle.lua
41
1534
----------------------------------- -- Area: Western Adoulin -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 256 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Adoulin/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 41, STORE_EVENT_ID = 42, RETRIEVE_EVENT_ID = 43, ALREADY_STORED_ID = 44, MAGIAN_TRIAL_ID = 45 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
waytim/darkstar
scripts/globals/items/flask_of_panacea.lua
70
1742
----------------------------------------- -- ID: 4163 -- Item: Panacea -- Item Effect: Removes any number of status effects ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:delStatusEffect(EFFECT_PARALYSIS); target:delStatusEffect(EFFECT_BIND); target:delStatusEffect(EFFECT_WEIGHT); target:delStatusEffect(EFFECT_ADDLE); target:delStatusEffect(EFFECT_BURN); target:delStatusEffect(EFFECT_FROST); target:delStatusEffect(EFFECT_CHOKE); target:delStatusEffect(EFFECT_RASP); target:delStatusEffect(EFFECT_SHOCK); target:delStatusEffect(EFFECT_DROWN); target:delStatusEffect(EFFECT_DIA); target:delStatusEffect(EFFECT_BIO); target:delStatusEffect(EFFECT_STR_DOWN); target:delStatusEffect(EFFECT_DEX_DOWN); target:delStatusEffect(EFFECT_VIT_DOWN); target:delStatusEffect(EFFECT_AGI_DOWN); target:delStatusEffect(EFFECT_INT_DOWN); target:delStatusEffect(EFFECT_MND_DOWN); target:delStatusEffect(EFFECT_CHR_DOWN); target:delStatusEffect(EFFECT_MAX_HP_DOWN); target:delStatusEffect(EFFECT_MAX_MP_DOWN); target:delStatusEffect(EFFECT_ATTACK_DOWN); target:delStatusEffect(EFFECT_EVASION_DOWN); target:delStatusEffect(EFFECT_DEFENSE_DOWN); target:delStatusEffect(EFFECT_MAGIC_DEF_DOWN); target:delStatusEffect(EFFECT_INHIBIT_TP); target:delStatusEffect(EFFECT_MAGIC_ACC_DOWN); target:delStatusEffect(EFFECT_MAGIC_ATK_DOWN); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Lower_Jeuno/npcs/Muckvix.lua
23
1436
----------------------------------- -- Area: Lower Jeuno -- NPC: Muckvix -- Involved in Mission: Magicite -- @zone 245 -- @pos -26.824 3.601 -137.082 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(SILVER_BELL) and player:hasKeyItem(YAGUDO_TORCH) == false) then if(player:getVar("YagudoTorchCS") == 1) then player:startEvent(0x00b8); else player:startEvent(0x0050); end else player:startEvent(0x000f); 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 == 0x00b8) then player:addKeyItem(YAGUDO_TORCH); player:messageSpecial(KEYITEM_OBTAINED,YAGUDO_TORCH); player:setVar("YagudoTorchCS",0); end end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c494476182.lua
2
1926
function c494476182.initial_effect(c) local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --must attack local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_MUST_ATTACK) e2:SetRange(LOCATION_SZONE) e2:SetTargetRange(0,LOCATION_MZONE) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(EFFECT_CANNOT_EP) e3:SetRange(LOCATION_SZONE) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetTargetRange(0,1) e3:SetCondition(c494476182.becon) c:RegisterEffect(e3) --destroy local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(511001028,1)) e4:SetCategory(CATEGORY_DESTROY) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e4:SetRange(LOCATION_SZONE) e4:SetCountLimit(1) e4:SetProperty(EFFECT_FLAG_REPEAT) e4:SetCode(EVENT_PHASE+PHASE_END) e4:SetCondition(c494476182.decon) e4:SetTarget(c494476182.destg) e4:SetOperation(c494476182.desop) c:RegisterEffect(e4) end function c494476182.becon(e) return Duel.IsExistingMatchingCard(Card.IsAttackable,Duel.GetTurnPlayer(),LOCATION_MZONE,0,1,nil) end function c494476182.desfilter(c) return c:IsFaceup() and c:GetAttackAnnouncedCount()==0 and c:IsDestructable() end function c494476182.decon(e,tp,eg,ep,ev,re,r,rp) return tp~=Duel.GetTurnPlayer() end function c494476182.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=Duel.GetMatchingGroup(c494476182.desfilter,Duel.GetTurnPlayer(),LOCATION_MZONE,0,e:GetHandler()) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c494476182.desop(e,tp,eg,ep,ev,re,r,rp) if not e:GetHandler():IsRelateToEffect(e) then return end local g=Duel.GetMatchingGroup(c494476182.desfilter,Duel.GetTurnPlayer(),LOCATION_MZONE,0,e:GetHandler()) Duel.Destroy(g,REASON_EFFECT) end
gpl-3.0
waytim/darkstar
scripts/globals/abilities/aspir_samba.lua
25
1430
----------------------------------- -- Ability: Aspir Samba -- Inflicts the next target you strike with Aspir daze, allowing all those engaged in battle with it to drain its MP. -- Obtained: Dancer Level 25 -- TP Required: 10% -- Recast Time: 1:00 -- Duration: 2:00 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 100) then return MSGBASIC_NOT_ENOUGH_TP,0; else return 0,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(100); end; local duration = 120 + player:getMod(MOD_SAMBA_DURATION); duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100; player:delStatusEffect(EFFECT_HASTE_SAMBA); player:delStatusEffect(EFFECT_DRAIN_SAMBA); player:addStatusEffect(EFFECT_ASPIR_SAMBA,1,0,duration); end;
gpl-3.0
thisishmed/butler
libs/JSON.lua
13
36868
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release -- -- -_-_-_-_-_-_-_-_-_- ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ || ||-_-_-_-_-_ -- || || || || -- || || || || -- || || || || -- || ||-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- -- -- /\ /\ /-_-_-_-_-_ ||-_-_-_-_-_ ||-_-_-_-_-_ -- ||\\ //|| //\\ || //|| //\\ // || || // -- || \\ // || // \\ || // || // \\ // || || // -- || \\ // || // \\ || // || // \\ || || || // -- || \\ // || //______\\ || // || //______\\ || -_-_-_- ||-_-_-_-_-_ || // -- || \\ // || // \\ || // || // \\ || || || || \\ -- || \\ // || // \\ || // || // \\ \\ || || || \\ -- || \\// || // \\ ||// || // \\ \\-_-_-_-_-|| ||-_-_-_-_-_ || \\ -- -- -- ||-_-_-_- || || || //-_-_-_-_-_- -- || || || || || // -- ||_-_-_|| || || || // -- || || || || \\ -- || || \\ // \\ -- || || \\ // // -- || ||-_-_-_-_ \\-_-_-_-// -_-_-_-_-_-// -- --By @ali_ghoghnoos --@telemanager_ch
gpl-2.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c99970180.lua
1
3074
--DAL - Metatron-Angel of Extinction function c99970180.initial_effect(c) --Return To Hand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(99970180,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1,99970180+EFFECT_COUNT_CODE_OATH) e1:SetTarget(c99970180.target) e1:SetOperation(c99970180.operation) c:RegisterEffect(e1) --Banish From Grave local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(99970180,1)) e2:SetCategory(CATEGORY_REMOVE) e2:SetType(EFFECT_TYPE_QUICK_O) e2:SetRange(LOCATION_GRAVE) e2:SetCode(EVENT_FREE_CHAIN) e2:SetCondition(aux.exccon) e2:SetCost(c99970180.bancost) e2:SetTarget(c99970180.bantg) e2:SetOperation(c99970180.banop) c:RegisterEffect(e2) end function c99970180.filter1(c,tp) return c:IsFaceup() and c:IsSetCard(0x997) and c:IsLevelAbove(5) and Duel.IsExistingMatchingCard(c99970180.filter2,tp,0,LOCATION_MZONE,1,c,c:GetAttack()) end function c99970180.filter2(c,atk) return c:IsFaceup() and c:IsAttackBelow(atk) end function c99970180.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c99970180.filter1(chkc) end if chk==0 then return Duel.IsExistingTarget(c99970180.filter1,tp,LOCATION_MZONE,0,1,nil,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c99970180.filter1,tp,LOCATION_MZONE,0,1,1,nil,tp) Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) end function c99970180.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() and not tc:IsImmuneToEffect(e) then local g=Duel.GetMatchingGroup(c99970180.filter2,tp,0,LOCATION_MZONE,tc,tc:GetAttack()) Duel.SendtoHand(g,nil,REASON_EFFECT) end end function c99970180.bancost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c99970180.banfilter1(c) return c:IsFaceup() and c:IsSetCard(0x997) and c:IsLevelAbove(5) end function c99970180.banfilter2(c) return c:IsType(TYPE_MONSTER) and c:IsAbleToRemove() end function c99970180.bantg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c99970180.banfilter1(chkc) end if chk==0 then return Duel.IsExistingTarget(c99970180.banfilter1,tp,LOCATION_MZONE,0,1,nil) and Duel.IsExistingTarget(c99970180.banfilter2,tp,0,LOCATION_GRAVE,1,nil) end local ct=Duel.GetMatchingGroupCount(c99970180.banfilter1,tp,LOCATION_MZONE,0,nil) Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,c99970180.banfilter2,tp,0,LOCATION_GRAVE,1,ct,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,g:GetCount(),0,0) end function c99970180.banop(e,tp,eg,ep,ev,re,r,rp) local g=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e) Duel.Remove(g,POS_FACEUP,REASON_EFFECT) end
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Lower_Delkfutts_Tower/npcs/_545.lua
2
1534
----------------------------------- -- Area: Lower Delkfutt's Tower -- NPC: Cermet Door -- Spawns a mob in CoP. Never opens. ----------------------------------- package.loaded["scripts/zones/Lower_Delkfutts_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Lower_Delkfutts_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 6 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE))then SpawnMob(17531121,180):updateEnmity(player); elseif(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 7 and player:hasKeyItem(DELKFUTT_RECOGNITION_DEVICE))then player:startEvent(0x0019); 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) --print("CSID:",csid); --print("RESULT:",option); if(csid == 0x0019)then player:setVar("COP_Tenzen_s_Path",8); end end;
gpl-3.0
CaptainPRICE/wire
lua/entities/gmod_wire_egp_hud/huddraw.lua
7
4647
hook.Add("Initialize","EGP_HUD_Initialize",function() if (CLIENT) then local EGP_HUD_FirstPrint = true local tbl = {} -------------------------------------------------------- -- Toggle -------------------------------------------------------- local function EGP_Use( um ) local ent = um:ReadEntity() if (!ent or !ent:IsValid()) then return end local bool = um:ReadChar() if (bool == -1) then ent.On = nil elseif (bool == 1) then ent.On = true elseif (bool == 0) then if (ent.On == true) then ent.On = nil LocalPlayer():ChatPrint("[EGP] EGP HUD Disconnected.") else if (!tbl[ent]) then -- strange... this entity should be in the table. Might have gotten removed due to a lagspike. Add it again EGP:AddHUDEGP( ent ) end ent.On = true if (EGP_HUD_FirstPrint) then LocalPlayer():ChatPrint("[EGP] EGP HUD Connected. NOTE: Type 'wire_egp_hud_unlink' in console to disconnect yourself from all EGP HUDs.") EGP_HUD_FirstPrint = nil else LocalPlayer():ChatPrint("[EGP] EGP HUD Connected.") end end end end usermessage.Hook( "EGP_HUD_Use", EGP_Use ) -------------------------------------------------------- -- Disconnect all HUDs -------------------------------------------------------- concommand.Add("wire_egp_hud_unlink",function() local en = ents.FindByClass("gmod_wire_egp_hud") LocalPlayer():ChatPrint("[EGP] Disconnected from all EGP HUDs.") for k,v in ipairs( en ) do en.On = nil end end) -------------------------------------------------------- -- Add / Remove HUD Entities -------------------------------------------------------- function EGP:AddHUDEGP( Ent ) tbl[Ent] = true end function EGP:RemoveHUDEGP( Ent ) tbl[Ent] = nil end -------------------------------------------------------- -- Paint -------------------------------------------------------- hook.Add("HUDPaint","EGP_HUDPaint",function() for Ent,_ in pairs( tbl ) do if (!Ent or !Ent:IsValid()) then EGP:RemoveHUDEGP( Ent ) break else if (Ent.On == true) then if (Ent.RenderTable and #Ent.RenderTable > 0) then for _,object in pairs( Ent.RenderTable ) do local oldtex = EGP:SetMaterial( object.material ) object:Draw(Ent) EGP:FixMaterial( oldtex ) -- Check for 3DTracker parent if (object.parent) then local hasObject, _, parent = EGP:HasObject( Ent, object.parent ) if (hasObject and parent.Is3DTracker) then Ent:EGP_Update() end end end end end end end end) -- HUDPaint hook else local vehiclelinks = {} function EGP:LinkHUDToVehicle( hud, vehicle ) if not hud.LinkedVehicles then hud.LinkedVehicles = {} end if not hud.Marks then hud.Marks = {} end hud.Marks[#hud.Marks+1] = vehicle hud.LinkedVehicles[vehicle] = true vehiclelinks[hud] = hud.LinkedVehicles timer.Simple( 0.1, function() -- timers solve everything (this time, it's the fact that the entity isn't valid on the client after dupe) WireLib.SendMarks( hud ) end) end function EGP:UnlinkHUDFromVehicle( hud, vehicle ) if not vehicle then -- unlink all vehiclelinks[hud] = nil hud.LinkedVehicles = nil hud.Marks = nil else if vehiclelinks[hud] then local bool = vehiclelinks[hud][vehicle] if bool then if vehicle:GetDriver() and vehicle:GetDriver():IsValid() then umsg.Start( "EGP_HUD_Use", vehicle:GetDriver() ) umsg.Entity( hud ) umsg.Char( -1 ) umsg.End() end end if hud.Marks then for i=1,#hud.Marks do if hud.Marks[i] == vehicle then table.remove( hud.Marks, i ) break end end end hud.LinkedVehicles[vehicle] = nil if not next( hud.LinkedVehicles ) then hud.LinkedVehicles = nil hud.Marks = nil end vehiclelinks[hud] = hud.LinkedVehicles end end WireLib.SendMarks( hud ) end hook.Add("PlayerEnteredVehicle","EGP_HUD_PlayerEnteredVehicle",function( ply, vehicle ) for k,v in pairs( vehiclelinks ) do if v[vehicle] ~= nil then umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( k ) umsg.Char( 1 ) umsg.End() end end end) hook.Add("PlayerLeaveVehicle","EGP_HUD_PlayerLeaveVehicle",function( ply, vehicle ) for k,v in pairs( vehiclelinks ) do if v[vehicle] ~= nil then umsg.Start( "EGP_HUD_Use", ply ) umsg.Entity( k ) umsg.Char( -1 ) umsg.End() end end end) end end)
apache-2.0
fernsehmuell/reaper_scripts
Mediacomposer_like_functions/fernsehmuell_Reverse_Play_Shuttle_(J).lua
1
1461
-- @version 1.1 -- @author Udo Sauer -- @changelog -- better way to get commandID of backgroundscript function is_playing_reverse() retval,value=reaper.GetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle") --check if reverse playing if not tonumber(value) then value="0" end if value=="1" then return 1 else return 0 end end function GetPath(str) if reaper.GetOS() == "Win32" or reaper.GetOS() == "Win64" then separator = "\\" else separator = "/" end return str:match("(.*"..separator..")") end function main() reaper.Undo_BeginBlock() is_new_value,filename,sectionID,cmdID,mode,resolution,val = reaper.get_action_context() reverse_function = reaper.AddRemoveReaScript(true, 0, GetPath(filename).."fernsehmuell_Reverse_Play_Shuttle_Background.lua", true) --reverse_function=reaper.NamedCommandLookup("_RS28389260f2e3c333a10d41c8ab150ebee11d2e92") -- fernsehmuell_Reverse_Play_Shuttle_Background.lua if reverse_function ~= 0 then if is_playing_reverse()>0 then reaper.SetProjExtState(0, "Fernsehmuell", "Reverse_Play_Shuttle", 2) --set reverse status to 2 -> button pressed again! else reaper.Main_OnCommand(reverse_function, 0) end else reaper.ShowMessageBox("the script file: "..GetPath(filename).."fernsehmuell_Reverse_Play_Shuttle_Background.lua".. " is missing.", "Warning: LUA Script missing.", 0) end reaper.Undo_EndBlock("PLAY REVERSE fernsehmuell", -1) end main()
mit
waytim/darkstar
scripts/zones/RuLude_Gardens/npcs/Neraf-Najiruf.lua
13
2032
----------------------------------- -- 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
waytim/darkstar
scripts/globals/items/carp_sushi.lua
18
1386
----------------------------------------- -- ID: 4407 -- Item: carp_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 1 -- Accuracy % 10 -- HP Recovered While Healing 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,1800,4407); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_FOOD_ACCP, 10); target:addMod(MOD_FOOD_ACC_CAP, 999); target:addMod(MOD_HPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_FOOD_ACCP, 10); target:delMod(MOD_FOOD_ACC_CAP, 999); target:delMod(MOD_HPHEAL, 2); end;
gpl-3.0
waytim/darkstar
scripts/zones/Nashmau/npcs/Pipiroon.lua
13
1206
----------------------------------- -- Area: Nashmau -- NPC: Pipiroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,PIPIROON_SHOP_DIALOG); stock = {0x43A1,1204, -- Grenade 0x43A3,6000, -- Riot Grenade 0x03A0,515, -- Bomb Ash 0x0b39,10000} -- Nashmau Waystone showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
zorfmorf/loveprojects
colonycontrol/src/lib/quickie/core.lua
15
3418
--[[ Copyright (c) 2012 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local BASE = (...):match("(.-)[^%.]+$") local group = require(BASE .. 'group') local mouse = require(BASE .. 'mouse') local keyboard = require(BASE .. 'keyboard') -- -- Helper functions -- -- evaluates all arguments local function strictAnd(...) local n = select("#", ...) local ret = true for i = 1,n do ret = select(i, ...) and ret end return ret end local function strictOr(...) local n = select("#", ...) local ret = false for i = 1,n do ret = select(i, ...) or ret end return ret end -- -- Widget ID -- local maxid, uids = 0, {} setmetatable(uids, {__index = function(t, i) t[i] = {} return t[i] end}) local function generateID() maxid = maxid + 1 return uids[maxid] end -- -- Drawing / Frame update -- local draw_items = {n = 0} local function registerDraw(id, f, ...) assert(type(f) == 'function' or (getmetatable(f) or {}).__call, 'Drawing function is not a callable type!') local font = love.graphics.getFont() local state = 'normal' if mouse.isHot(id) or keyboard.hasFocus(id) then state = mouse.isActive(id) and 'active' or 'hot' end local rest = {n = select('#', ...), ...} draw_items.n = draw_items.n + 1 draw_items[draw_items.n] = function() if font then love.graphics.setFont(font) end f(state, unpack(rest, 1, rest.n)) end end -- actually update-and-draw local function draw() keyboard.endFrame() mouse.endFrame() group.endFrame() -- save graphics state local c = {love.graphics.getColor()} local f = love.graphics.getFont() local lw = love.graphics.getLineWidth() local ls = love.graphics.getLineStyle() for i = 1,draw_items.n do draw_items[i]() end -- restore graphics state love.graphics.setLineWidth(lw) love.graphics.setLineStyle(ls) if f then love.graphics.setFont(f) end love.graphics.setColor(c) draw_items.n = 0 maxid = 0 group.beginFrame() mouse.beginFrame() keyboard.beginFrame() end -- -- The Module -- return { generateID = generateID, style = require((...):match("(.-)[^%.]+$") .. 'style-default'), registerDraw = registerDraw, draw = draw, strictAnd = strictAnd, strictOr = strictOr, }
apache-2.0
waytim/darkstar
scripts/zones/Rolanberry_Fields/npcs/Cavernous_Maw.lua
27
2925
----------------------------------- -- Area: Rolanberry Fields -- NPC: Cavernous Maw -- @pos -198 8 361 110 -- Teleports Players to Rolanberry Fields [S] ----------------------------------- package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/campaign"); require("scripts/zones/Rolanberry_Fields/TextIDs"); require("scripts/globals/titles"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then player:startEvent(500,1); elseif (ENABLE_WOTG == 1 and hasMawActivated(player,1)) then if (player:getCurrentMission(WOTG) == BACK_TO_THE_BEGINNING and (player:getQuestStatus(CRYSTAL_WAR, CLAWS_OF_THE_GRIFFON) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, THE_TIGRESS_STRIKES) == QUEST_COMPLETED or player:getQuestStatus(CRYSTAL_WAR, FIRES_OF_DISCONTENT) == QUEST_COMPLETED)) then player:startEvent(501); else player:startEvent(904); end else player:messageSpecial(NOTHING_HAPPENS); 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:",csid); -- printf("RESULT:",option); if (csid == 500) then local r = math.random(1,3); player:addKeyItem(PURE_WHITE_FEATHER); player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER); player:completeMission(WOTG,CAVERNOUS_MAWS); player:addMission(WOTG,BACK_TO_THE_BEGINNING); if (r == 1) then player:addNationTeleport(MAW,1); toMaw(player,1); -- go to Batallia_Downs[S] elseif (r == 2) then player:addNationTeleport(MAW,2); toMaw(player,3); -- go to Rolanberry_Fields_[S] elseif (r == 3) then player:addNationTeleport(MAW,4); toMaw(player,5); -- go to Sauromugue_Champaign_[S] end; elseif (csid == 904 and option == 1) then toMaw(player,3); -- go to Rolanberry_Fields_[S] elseif (csid == 501) then player:completeMission(WOTG, BACK_TO_THE_BEGINNING); player:addMission(WOTG, CAIT_SITH); player:addTitle(CAIT_SITHS_ASSISTANT); toMaw(player,3); end; end;
gpl-3.0
X-Raym/REAPER-ReaScripts
Items Editing/X-Raym_Quantize selected items to next marker position.lua
1
3819
--[[ * ReaScript Name: Quantize selected items to next marker position * About: A template script for REAPER ReaScript. * Instructions: Have Regions. Select items. Run. * Author: X-Raym * Author URI: https://www.extremraym.com * Repository: GitHub > X-Raym > REAPER-ReaScripts * Repository URI: https://github.com/X-Raym/REAPER-ReaScripts * Licence: GPL v3 * Forum Thread: Scripts: Items Editing (various) * Forum Thread URI: http://forum.cockos.com/showthread.php?t=163363 * REAPER: 5.0 * Version: 1.0 --]] --[[ * Changelog: * v1.0 (2016-01-14) + Initial release --]] console = false function Msg(variable) if console == true then reaper.ShowConsoleMsg(tostring(variable).."\n") end end function SaveMarkers() markers_pos = {} i=0 repeat iRetval, bIsrgnOut, iPosOut, iRgnendOut, sNameOut, iMarkrgnindexnumberOut, iColorOur = reaper.EnumProjectMarkers3(0,i) if iRetval >= 1 then if bIsrgnOut == false then table.insert(markers_pos, iPosOut) end i = i+1 end until iRetval == 0 table.sort(markers_pos) return markers_pos end function NextValue(table, number) local smallestSoFar, smallestIndex for i, y in ipairs(table) do if y > number then index = i break end end return index, table[index] end function main() groups = {} for i, item in ipairs(sel_items) do -- Check Group group = reaper.GetMediaItemInfo_Value(item, "I_GROUPID") item_pos = reaper.GetMediaItemInfo_Value(item, "D_POSITION") item_snap = reaper.GetMediaItemInfo_Value(item, "D_SNAPOFFSET") item_snap_abs = item_pos + item_snap -- If in Group if group > 0 then -- If group doesn't exist if groups[group] == nil then -- Groups have ID as key and minimum POS as reference groups[group] = item_snap_abs else -- if group exist, set minimum item pos of the group (first selected items in groups in time behave like the leader of the group) if item_snap_abs < groups[group] then groups[group] = item_snap_abs end end else -- no group index, pos = NextValue(markers_pos, item_pos+item_snap) if index ~= nil then reaper.SetMediaItemInfo_Value(item, "D_POSITION", pos-item_snap) end end end offsets = {} -- Transform Min Pos in Groups into Offset Settings for key, min_pos in pairs(groups) do index, closest_grid = NextValue(markers_pos, min_pos) if index ~= nil then offset = closest_grid - min_pos --Msg(closest_grid .. "-" .. min_pos .. "=" .. "offset") offsets[key] = offset end end SaveAllItems(all_items) -- Apply offset of items in groups for i, item in ipairs(all_items) do group = reaper.GetMediaItemInfo_Value(item, "I_GROUPID") -- If in Group if group > 0 then -- If group doesn't exist if groups[group] ~= nil and offsets[group] ~= nil then item_pos = reaper.GetMediaItemInfo_Value(item, "D_POSITION") reaper.SetMediaItemInfo_Value(item, "D_POSITION", item_pos + offsets[group]) end end end end function SaveSelectedItems (table) for i = 0, reaper.CountSelectedMediaItems(0)-1 do table[i+1] = reaper.GetSelectedMediaItem(0, i) end end function SaveAllItems(table) for i = 0, reaper.CountMediaItems(0)-1 do table[i+1] = reaper.GetMediaItem(0, i) end end count_sel_items = reaper.CountSelectedMediaItems(0, 0) retval, count_markers, count_regions = reaper.CountProjectMarkers(0) if count_sel_items > 0 and count_markers > 0 then reaper.PreventUIRefresh(1) SaveMarkers() sel_items = {} all_items = {} SaveSelectedItems(sel_items) reaper.Undo_BeginBlock() main() reaper.Undo_EndBlock("Quantize selected items to next marker position", -1) reaper.UpdateArrange() reaper.PreventUIRefresh(-1) end
gpl-3.0
wanmaple/MWFrameworkForCocosLua
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ProgressTimer.lua
10
4320
-------------------------------- -- @module ProgressTimer -- @extend Node -- @parent_module cc -------------------------------- -- -- @function [parent=#ProgressTimer] isReverseDirection -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- This allows the bar type to move the component at a specific rate<br> -- Set the component to 0 to make sure it stays at 100%.<br> -- For example you want a left to right bar but not have the height stay 100%<br> -- Set the rate to be Vec2(0,1); and set the midpoint to = Vec2(0,.5f); -- @function [parent=#ProgressTimer] setBarChangeRate -- @param self -- @param #vec2_table barChangeRate -------------------------------- -- Percentages are from 0 to 100 -- @function [parent=#ProgressTimer] getPercentage -- @param self -- @return float#float ret (return value: float) -------------------------------- -- -- @function [parent=#ProgressTimer] setSprite -- @param self -- @param #cc.Sprite sprite -------------------------------- -- Change the percentage to change progress. -- @function [parent=#ProgressTimer] getType -- @param self -- @return int#int ret (return value: int) -------------------------------- -- The image to show the progress percentage, retain -- @function [parent=#ProgressTimer] getSprite -- @param self -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- Midpoint is used to modify the progress start position.<br> -- If you're using radials type then the midpoint changes the center point<br> -- If you're using bar type the the midpoint changes the bar growth<br> -- it expands from the center but clamps to the sprites edge so:<br> -- you want a left to right then set the midpoint all the way to Vec2(0,y)<br> -- you want a right to left then set the midpoint all the way to Vec2(1,y)<br> -- you want a bottom to top then set the midpoint all the way to Vec2(x,0)<br> -- you want a top to bottom then set the midpoint all the way to Vec2(x,1) -- @function [parent=#ProgressTimer] setMidpoint -- @param self -- @param #vec2_table point -------------------------------- -- Returns the BarChangeRate -- @function [parent=#ProgressTimer] getBarChangeRate -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- @overload self, bool -- @overload self, bool -- @function [parent=#ProgressTimer] setReverseDirection -- @param self -- @param #bool reverse -------------------------------- -- Returns the Midpoint -- @function [parent=#ProgressTimer] getMidpoint -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- -- @function [parent=#ProgressTimer] setPercentage -- @param self -- @param #float percentage -------------------------------- -- -- @function [parent=#ProgressTimer] setType -- @param self -- @param #int type -------------------------------- -- Creates a progress timer with the sprite as the shape the timer goes through -- @function [parent=#ProgressTimer] create -- @param self -- @param #cc.Sprite sp -- @return ProgressTimer#ProgressTimer ret (return value: cc.ProgressTimer) -------------------------------- -- -- @function [parent=#ProgressTimer] setAnchorPoint -- @param self -- @param #vec2_table anchorPoint -------------------------------- -- -- @function [parent=#ProgressTimer] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table transform -- @param #unsigned int flags -------------------------------- -- -- @function [parent=#ProgressTimer] setColor -- @param self -- @param #color3b_table color -------------------------------- -- -- @function [parent=#ProgressTimer] getColor -- @param self -- @return color3b_table#color3b_table ret (return value: color3b_table) -------------------------------- -- -- @function [parent=#ProgressTimer] setOpacity -- @param self -- @param #unsigned char opacity -------------------------------- -- -- @function [parent=#ProgressTimer] getOpacity -- @param self -- @return unsigned char#unsigned char ret (return value: unsigned char) return nil
apache-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Kazham/npcs/Mumupp.lua
2
1782
----------------------------------- -- Area: Kazham -- NPC: Mumupp -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); path = { 94.732452, -15.000000, -114.034622, 94.210846, -15.000000, -114.989388, 93.508865, -15.000000, -116.274101, 94.584877, -15.000000, -116.522118, 95.646988, -15.000000, -116.468452, 94.613518, -15.000000, -116.616562, 93.791100, -15.000000, -115.858505, 94.841835, -15.000000, -116.108437, 93.823380, -15.000000, -116.712860, 94.986847, -15.000000, -116.571831, 94.165512, -15.000000, -115.965698, 95.005806, -15.000000, -116.519707, 93.935555, -15.000000, -116.706291, 94.943497, -15.000000, -116.578346, 93.996826, -15.000000, -115.932816, 95.060165, -15.000000, -116.180840, 94.081062, -15.000000, -115.923836, 95.246490, -15.000000, -116.215691, 94.234077, -15.000000, -115.960793 }; function onSpawn(npc) npc:setPos(pathfind.first(path)); onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C7); npc:wait(-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); GetNPCByID(17801290):wait(0); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Oldton_Movalpolos/npcs/Bartabaq.lua
2
1048
----------------------------------- -- Area: Oldton Movalpolos -- NPC: Bartabaq -- Type: Outpost Vendor -- @zone: 11 -- @pos: -261.930 6.999 -49.145 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x7ff4); 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
farbod1423/farbod3
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
SEEDTEAM/TeleSeed
plugins/inrealm.lua
850
25085
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do if v.print_name then local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
agpl-3.0
waytim/darkstar
scripts/globals/items/plate_of_tuna_sushi.lua
17
1537
----------------------------------------- -- ID: 5150 -- Item: plate_of_tuna_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 15 -- Ranged ACC % 15 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5150); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_CHR, 5); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_CHR, 5); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/plate_of_dorado_sushi.lua
2
1494
----------------------------------------- -- ID: 5178 -- Item: plate_of_dorado_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 5 -- Accuracy % 15 -- Accuracy Cap 75 -- Ranged ACC % 15 -- Ranged ACC Cap 75 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5178); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 5); target:addMod(MOD_FOOD_ACCP, 15); target:addMod(MOD_FOOD_ACC_CAP, 75); target:addMod(MOD_FOOD_RACCP, 15); target:addMod(MOD_FOOD_RACC_CAP, 75); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 5); target:delMod(MOD_FOOD_ACCP, 15); target:delMod(MOD_FOOD_ACC_CAP, 75); target:delMod(MOD_FOOD_RACCP, 15); target:delMod(MOD_FOOD_RACC_CAP, 75); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
waytim/darkstar
scripts/zones/The_Eldieme_Necropolis/TextIDs.lua
22
2300
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6543; -- Obtained: <item> GIL_OBTAINED = 6544; -- Obtained <number> gil KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem> SOLID_STONE = 7378; -- This door is made of solid stone. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7397; -- You unlock the chest! CHEST_FAIL = 7398; -- Fails to open the chest. CHEST_TRAP = 7399; -- The chest was trapped! CHEST_WEAK = 7400; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7401; -- The chest was a mimic! CHEST_MOOGLE = 7402; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7403; -- The chest was but an illusion... CHEST_LOCKED = 7404; -- The chest appears to be locked. -- Quests NOTHING_OUT_OF_ORDINARY = 6557; -- There is nothing out of the ordinary here. SENSE_OF_FOREBODING = 6558; -- You are suddenly overcome with a sense of foreboding... NOTHING_HAPPENED = 7338; -- Nothing happened... RETURN_RIBBON_TO_HER = 7351; -- You can hear a voice from somewhere. (...return...ribbon to...her...) THE_BRAZIER_IS_LIT = 7365; -- The brazier is lit. REFUSE_TO_LIGHT = 7366; -- Unexpectedly, therefuses to light. LANTERN_GOES_OUT = 7367; -- For some strange reason, the light of thegoes out... THE_LIGHT_DIMLY = 7368; -- lights dimly. It doesn't look like this will be effective yet.?Prompt? THE_LIGHT_HAS_INTENSIFIED = 7369; -- The light of thehas intensified. THE_LIGHT_IS_FULLY_LIT = 7370; -- is fully lit! SPIRIT_INCENSE_EMITS_PUTRID_ODOR = 7407; -- emits a putrid odor and burns up. Your attempt this time has failed...?Prompt? SARCOPHAGUS_CANNOT_BE_OPENED = 7424; -- It is a stone sarcophagus with the lid sealed tight. It cannot be opened. -- conquest Base CONQUEST_BASE = 0; -- Strange Apparatus DEVICE_NOT_WORKING = 7314; -- The device is not working. SYS_OVERLOAD = 7323; -- arning! Sys...verload! Enterin...fety mode. ID eras...d YOU_LOST_THE = 7328; -- You lost the #.
gpl-3.0
EShamaev/ardupilot
libraries/AP_Scripting/examples/rangefinder_test.lua
24
1193
-- This script checks RangeFinder local rotation_downward = 25 local rotation_forward = 0 function update() local sensor_count = rangefinder:num_sensors() gcs:send_text(0, string.format("%d rangefinder sensors found.", sensor_count)) for i = 0, rangefinder:num_sensors() do if rangefinder:has_data_orient(rotation_downward) then info(rotation_downward) elseif rangefinder:has_data_orient(rotation_forward) then info(rotation_forward) end end return update, 1000 -- check again in 1Hz end function info(rotation) local ground_clearance = rangefinder:ground_clearance_cm_orient(rotation) local distance_min = rangefinder:min_distance_cm_orient(rotation) local distance_max = rangefinder:max_distance_cm_orient(rotation) local offset = rangefinder:get_pos_offset_orient(rotation) local distance_cm = rangefinder:distance_cm_orient(rotation) gcs:send_text(0, string.format("Ratation %d %.0f cm range %d - %d offset %.0f %.0f %.0f ground clearance %.0f", rotation, distance_cm, distance_min, distance_max, offset:x(), offset:y(), offset:z(), ground_clearance)) end return update(), 1000 -- first message may be displayed 1 seconds after start-up
gpl-3.0
waytim/darkstar
scripts/zones/Dynamis-Tavnazia/Zone.lua
13
2401
----------------------------------- -- -- Zone: Dynamis-Tavnazia -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Dynamis-Tavnazia/TextIDs"] = nil; require("scripts/zones/Dynamis-Tavnazia/TextIDs"); ----------------------------------- -- 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) cs = -1; local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaTavnazia]UniqueID")) then if (player:isBcnmsFull() == 1) then if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then inst = player:addPlayerToDynamis(1289); if (inst == 1) then player:bcnmEnter(1289); else cs = 0x0065; end else player:bcnmEnter(1289); end else inst = player:bcnmRegister(1289); if (inst == 1) then player:bcnmEnter(1289); else cs = 0x0065; end end else cs = 0x0065; 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 == 0x0065) then player:setPos(0.0,-7,-23,195,26); end end;
gpl-3.0
niegenug/wesnoth
data/lua/location_set.lua
28
3736
local location_set = {} local function index(x, y) -- the 2000 bias ensure that the correct x is recovered for negative y return x * 16384 + y + 2000 end local invscale = 1 / 16384 local function revindex(p) local x = math.floor(p * invscale) return x, p - x * 16384 - 2000 end local methods = {} local locset_meta = { __index = methods } function methods:empty() return (not next(self.values)) end function methods:size() local sz = 0 for p,v in pairs(self.values) do sz = sz + 1 end return sz end function methods:clear() self.values = {} end function methods:get(x, y) return self.values[index(x, y)] end function methods:insert(x, y, v) self.values[index(x, y)] = v or true end function methods:remove(x, y) self.values[index(x, y)] = nil end function methods:union(s) local values = self.values for p,v in pairs(s.values) do values[p] = v end end function methods:union_merge(s, f) local values = self.values for p,v in pairs(s.values) do local x, y = revindex(p) values[p] = f(x, y, values[p], v) end end function methods:inter(s) local values = self.values local nvalues = {} for p,v in pairs(s.values) do nvalues[p] = values[p] end self.values = nvalues end function methods:inter_merge(s, f) local values = s.values local nvalues = {} for p,v in pairs(self.values) do local x, y = revindex(p) nvalues[p] = f(x, y, v, values[p]) end self.values = nvalues end function methods:filter(f) local nvalues = {} for p,v in pairs(self.values) do local x, y = revindex(p) if f(x, y, v) then nvalues[p] = v end end return setmetatable({ values = nvalues }, locset_meta) end function methods:iter(f) for p,v in pairs(self.values) do local x, y = revindex(p) f(x, y, v) end end function methods:stable_iter(f) local indices = {} for p,v in pairs(self.values) do table.insert(indices, p) end table.sort(indices) for i,p in ipairs(indices) do local x, y = revindex(p) f(x, y) end end function methods:of_pairs(t) local values = self.values for i,v in ipairs(t) do local value_table = {} local x_index local y_index if v.x and v.y then x_index = "x" y_index = "y" else x_index = 1 y_index = 2 end for k,val in pairs(v) do if k ~= x_index and k ~= y_index then value_table[k] = val end end if next(value_table) then values[index(v[x_index], v[y_index])] = value_table else values[index(v[x_index], v[y_index])] = true end end end function methods:of_wml_var(name) local values = self.values for i = 0, wesnoth.get_variable(name .. ".length") - 1 do local t = wesnoth.get_variable(string.format("%s[%d]", name, i)) local x, y = t.x, t.y t.x, t.y = nil, nil values[index(x, y)] = next(t) and t or true end end function methods:to_pairs() local res = {} self:iter(function(x, y) table.insert(res, { x, y }) end) return res end function methods:to_stable_pairs() local res = {} self:stable_iter(function(x, y) table.insert(res, { x, y }) end) return res end function methods:to_wml_var(name) local i = 0 wesnoth.set_variable(name) self:stable_iter(function(x, y, v) if type(v) == 'table' then wesnoth.set_variable(string.format("%s[%d]", name, i), v) end wesnoth.set_variable(string.format("%s[%d].x", name, i), x) wesnoth.set_variable(string.format("%s[%d].y", name, i), y) i = i + 1 end) end function location_set.create() local w,h,b = wesnoth.get_map_size() assert(h + 2 * b < 9000) return setmetatable({ values = {} }, locset_meta) end function location_set.of_pairs(t) local s = location_set.create() s:of_pairs(t) return s end function location_set.of_wml_var(name) local s = location_set.create() s:of_wml_var(name) return s end return location_set
gpl-2.0
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/Beaucedine_Glacier/npcs/Ryunchi-Pauchi_WW.lua
4
2917
----------------------------------- -- Area: Beaucedine Glacier -- NPC: Ryunchi-Pauchi, W.W. -- Outpost Conquest Guards -- @pos -24.351 -60.421 -114.215 111 ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Beaucedine_Glacier/TextIDs"); guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border region = FAUREGANDI; csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if(supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else arg1 = getArg1(guardnation, player) - 1; if(arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); if(option == 1) then duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif(option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if(hasOutpost(player, region+5) == 0) then supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif(option == 4) then if(player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
waytim/darkstar
scripts/zones/Southern_San_dOria/npcs/Raimbroy.lua
11
3551
----------------------------------- -- Area: Southern San d'Oria -- NPC: Raimbroy -- Starts and Finishes Quest: The Sweetest Things -- @zone 230 -- @pos ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); -- "The Sweetest Things" quest status var theSweetestThings = player:getQuestStatus(SANDORIA,THE_SWEETEST_THINGS); if (theSweetestThings ~= QUEST_AVAILABLE) then if (trade:hasItemQty(4370,5) and trade:getItemCount() == 5) then player:startEvent(0x0217,GIL_RATE*400); else player:startEvent(0x020a); end end if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) theSweetestThings = player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS); -- "The Sweetest Things" Quest Dialogs if (player:getFameLevel(SANDORIA) >= 2 and theSweetestThings == QUEST_AVAILABLE) then theSweetestThingsVar = player:getVar("theSweetestThings"); if (theSweetestThingsVar == 1) then player:startEvent(0x0215); elseif (theSweetestThingsVar == 2) then player:startEvent(0x0216); else player:startEvent(0x0214); end elseif (theSweetestThings == QUEST_ACCEPTED) then player:startEvent(0x0218); elseif (theSweetestThings == QUEST_COMPLETED) then player:startEvent(0x0219); 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); -- "The Sweetest Things" ACCEPTED if (csid == 0x0214) then player:setVar("theSweetestThings", 1); elseif (csid == 0x0215) then if (option == 0) then player:addQuest(SANDORIA,THE_SWEETEST_THINGS); player:setVar("theSweetestThings", 0); else player:setVar("theSweetestThings", 2); end elseif (csid == 0x0216 and option == 0) then player:addQuest(SANDORIA, THE_SWEETEST_THINGS); player:setVar("theSweetestThings", 0); elseif (csid == 0x0217) then player:tradeComplete(); player:addTitle(APIARIST); player:addGil(GIL_RATE*400); if (player:getQuestStatus(SANDORIA, THE_SWEETEST_THINGS) == QUEST_ACCEPTED) then player:addFame(SANDORIA,30); player:completeQuest(SANDORIA, THE_SWEETEST_THINGS); else player:addFame(SANDORIA, 5); end end end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c11478413.lua
2
4818
--War God of the Bound Creator function c11478413.initial_effect(c) c:EnableReviveLimit() --spsummon condition local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(c11478413.splimit) c:RegisterEffect(e1) --search local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(11478413,0)) e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_BATTLE_DAMAGE) e2:SetCountLimit(1,11478413) e2:SetCondition(c11478413.condition) e2:SetTarget(c11478413.target1) e2:SetOperation(c11478413.operation1) c:RegisterEffect(e2) --search2 local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(11478413,1)) e3:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e3:SetCode(EVENT_BATTLE_DAMAGE) e3:SetCountLimit(1,11478413) e3:SetCondition(c11478413.condition) e3:SetTarget(c11478413.target2) e3:SetOperation(c11478413.operation2) c:RegisterEffect(e3) --negate local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(11478413,2)) e4:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY) e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O) e4:SetCode(EVENT_CHAINING) e4:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DAMAGE_CAL) e4:SetRange(LOCATION_GRAVE) e4:SetCondition(c11478413.negcon) e4:SetCost(c11478413.cost) e4:SetTarget(c11478413.negtg) e4:SetOperation(c11478413.negop) c:RegisterEffect(e4) --disable spsummon local e5=Effect.CreateEffect(c) e5:SetDescription(aux.Stringid(11478413,3)) e5:SetCategory(CATEGORY_DISABLE_SUMMON+CATEGORY_DESTROY) e5:SetType(EFFECT_TYPE_QUICK_O) e5:SetRange(LOCATION_GRAVE) e5:SetCode(EVENT_SPSUMMON) e5:SetCondition(c11478413.discon) e5:SetCost(c11478413.cost) e5:SetTarget(c11478413.distg) e5:SetOperation(c11478413.disop) c:RegisterEffect(e5) end function c11478413.splimit(e,se,sp,st) return bit.band(st,SUMMON_TYPE_RITUAL)==SUMMON_TYPE_RITUAL end function c11478413.condition(e,tp,eg,ep,ev,re,r,rp) return ep~=tp end function c11478413.filter1(c) return c:IsSetCard(0xf2002) and c:IsAbleToHand() end function c11478413.target1(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c11478413.filter1,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c11478413.operation1(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c11478413.filter1,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c11478413.filter2(c) return c:IsSetCard(0xf2001) and c:IsAbleToHand() end function c11478413.target2(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c11478413.filter2,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c11478413.operation2(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c11478413.filter2,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end function c11478413.negcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if ep==tp or c:IsStatus(STATUS_BATTLE_DESTROYED) then return false end return (re:IsActiveType(TYPE_MONSTER) or re:IsHasType(EFFECT_TYPE_ACTIVATE)) and Duel.IsChainNegatable(ev) end function c11478413.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c11478413.negtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,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 c11478413.negop(e,tp,eg,ep,ev,re,r,rp) Duel.NegateActivation(ev) if re:GetHandler():IsRelateToEffect(re) then Duel.Destroy(eg,REASON_EFFECT) end end function c11478413.disfilter(c,tp) return c:GetSummonPlayer()==tp end function c11478413.discon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetCurrentChain()==0 and eg:IsExists(c11478413.disfilter,1,nil,1-tp) end function c11478413.distg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end local g=eg:Filter(c11478413.disfilter,nil,1-tp) Duel.SetOperationInfo(0,CATEGORY_DISABLE_SUMMON,g,g:GetCount(),0,0) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c11478413.disop(e,tp,eg,ep,ev,re,r,rp) local g=eg:Filter(c11478413.disfilter,nil,1-tp) Duel.NegateSummon(g) Duel.Destroy(g,REASON_EFFECT) end
gpl-3.0
waytim/darkstar
scripts/zones/Al_Zahbi/npcs/Chayaya.lua
13
1644
----------------------------------- -- Area: Al Zahbi -- NPC: Chayaya -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,CHAYAYA_SHOP_DIALOG); stock = {0x439B,10, --Dart 0x439C,60, --Hawkeye 0x43A1,1204, --Grenade 0x43A8,8, --Iron Arrow 0x1565,68000, --Warrior Die 0x1566,22400, --Monk Die 0x1567,5000, --White Mage Die 0x1568,108000, --Black Mage Die 0x1569,62000, --Red Mage Die 0x156A,50400, --Thief Die 0x156B,90750, --Paladin Die 0x156C,2205, --Dark Knight Die 0x156D,26600, --Beastmaster Die 0x156E,12780, --Bard Die 0x156F,1300, --Ranger Die 0x1577,63375, --Dancer Die 0x1578,68250} --Scholar Die showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
lusiankaitz/koreader-master
frontend/ui/networkmgr.lua
1
4504
local InfoMessage = require("ui/widget/infomessage") local ConfirmBox = require("ui/widget/confirmbox") local UIManager = require("ui/uimanager") local Device = require("device") local DEBUG = require("dbg") local T = require("ffi/util").template local _ = require("gettext") local NetworkMgr = {} local function kindleEnableWifi(toggle) local lipc = require("liblipclua") local lipc_handle = nil if lipc then lipc_handle = lipc.init("com.github.koreader.networkmgr") end if lipc_handle then lipc_handle:set_int_property("com.lab126.cmd", "wirelessEnable", toggle) lipc_handle:close() end end local function koboEnableWifi(toggle) if toggle == 1 then local path = "/etc/wpa_supplicant/wpa_supplicant.conf" os.execute("insmod /drivers/ntx508/wifi/sdio_wifi_pwr.ko 2>/dev/null") os.execute("insmod /drivers/ntx508/wifi/dhd.ko") os.execute("sleep 1") os.execute("ifconfig eth0 up") os.execute("wlarm_le -i eth0 up") os.execute("wpa_supplicant -s -i eth0 -c "..path.." -C /var/run/wpa_supplicant -B") os.execute("udhcpc -S -i eth0 -s /etc/udhcpc.d/default.script -t15 -T10 -A3 -b -q >/dev/null 2>&1") else os.execute("killall udhcpc wpa_supplicant 2>/dev/null") os.execute("wlarm_le -i eth0 down") os.execute("ifconfig eth0 down") os.execute("rmmod -r dhd") os.execute("rmmod -r sdio_wifi_pwr") end end function NetworkMgr:turnOnWifi() if Device:isKindle() then kindleEnableWifi(1) elseif Device:isKobo() then koboEnableWifi(1) end end function NetworkMgr:turnOffWifi() if Device:isKindle() then kindleEnableWifi(0) elseif Device:isKobo() then koboEnableWifi(0) end end function NetworkMgr:promptWifiOn() UIManager:show(ConfirmBox:new{ text = _("Do you want to turn on Wifi?"), ok_callback = function() self:turnOnWifi() end, }) end function NetworkMgr:promptWifiOff() UIManager:show(ConfirmBox:new{ text = _("Do you want to turn off Wifi?"), ok_callback = function() self:turnOffWifi() end, }) end function NetworkMgr:getWifiStatus() local socket = require("socket") return socket.dns.toip("www.google.com") ~= nil end function NetworkMgr:setHTTPProxy(proxy) local http = require("socket.http") http.PROXY = proxy if proxy then G_reader_settings:saveSetting("http_proxy", proxy) G_reader_settings:saveSetting("http_proxy_enabled", true) else G_reader_settings:saveSetting("http_proxy_enabled", false) end end function NetworkMgr:getWifiMenuTable() return { text = _("Wifi connection"), enabled_func = function() return Device:isKindle() or Device:isKobo() end, checked_func = function() return NetworkMgr:getWifiStatus() end, callback = function() if NetworkMgr:getWifiStatus() then NetworkMgr:promptWifiOff() else NetworkMgr:promptWifiOn() end end } end function NetworkMgr:getProxyMenuTable() local proxy_enabled = function() return G_reader_settings:readSetting("http_proxy_enabled") end local proxy = function() return G_reader_settings:readSetting("http_proxy") end return { text_func = function() return T(_("HTTP proxy %1"), (proxy_enabled() and proxy() or "")) end, checked_func = function() return proxy_enabled() end, callback = function() if not proxy_enabled() and proxy() then NetworkMgr:setHTTPProxy(proxy()) elseif proxy_enabled() then NetworkMgr:setHTTPProxy(nil) end if not proxy() then UIManager:show(InfoMessage:new{ text = _("Tip:\nLong press on this menu entry to configure HTTP proxy."), }) end end, hold_input = { title = _("Enter proxy address"), type = "text", hint = proxy() or "", callback = function(input) if input ~= "" then NetworkMgr:setHTTPProxy(input) end end, } } end -- set network proxy if global variable NETWORK_PROXY is defined if NETWORK_PROXY then NetworkMgr:setHTTPProxy(NETWORK_PROXY) end return NetworkMgr
agpl-3.0
kdakers80/HeaterMeter
openwrt/package/linkmeter/targets/bcm2708/usr/lib/lua/luci/model/cbi/admin_system/rpi.lua
4
1530
require "nixio" require "nixio.util" local function OPT_SPLIT(o) return o:match("(%w+)\.(.+)") end local conf = {} local f = nixio.open("/boot/config.txt", "r") if f then for line in f:linesource() do line = line:match("%s*(.+)") -- Make sure the line isn't a comment if line and line:sub(1, 1) ~= "#" and line:sub(1, 1) ~= ";" then local option = line:match("[%w_]+"):lower() local value = line:match(".+=(.*)") conf[option] = value end -- if line end -- for line f:close() end f = nixio.open("/proc/cpuinfo", "r") if f then for line in f:linesource() do line = line:match("%s*(.+)") if line then local option = line:match("%S+"):lower() local value = line:match(".+:(.*)") if option == "serial" or option == "revision" then conf['cpu_' .. option] = value end end end f:close() end local t = nixio.fs.readfile("/sys/class/thermal/thermal_zone0/temp") conf['cpu_temp'] = tonumber(t) and (t / 1000) .. " C" conf['governor'] = nixio.fs.readfile("/sys/devices/system/cpu/cpu0/cpufreq/scaling_governor") local m = SimpleForm("rpi", "Raspberry Pi Configuration", [[Read-only for now. From /boot/config.txt ]]) local s = m:section(NamedSection, "Boot") function s.cfgvalue(self, section) return true end local function getconf(k) return conf[k.option] end for k,v in pairs(conf) do s:option(DummyValue, k, k).cfgvalue = getconf end -- for account table.sort(s.children, function (a,b) return a.title < b.title end) return m
mit
ffxinfinity/ffxinfinity
FFXI Server-Development/Build Files/scripts/zones/East_Ronfaure/npcs/Cavernous_Maw.lua
4
1362
----------------------------------- -- Cavernous Maw -- Teleports Players to East Ronfaure [S] -- @pos 322 -59 503 101 ----------------------------------- package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/East_Ronfaure/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,6)) then player:startEvent(0x0388); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("CSID:",csid); --print("RESULT:",option); if(csid == 0x0388 and option == 1) then toMaw(player,9); end end;
gpl-3.0
TheOnePharaoh/YGOPro-Custom-Cards
script/c14981498.lua
2
2645
function c14981498.initial_effect(c) c:SetUniqueOnField(1,0,14981498) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) c:RegisterEffect(e1) --special summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(14981498,0)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_IGNITION) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCountLimit(1,14981498+EFFECT_COUNT_CODE_OATH) e2:SetRange(LOCATION_SZONE) e2:SetCost(c14981498.cost) e2:SetTarget(c14981498.target) e2:SetOperation(c14981498.operation) c:RegisterEffect(e2) --negate monster effect local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(14981498,1)) e3:SetCategory(CATEGORY_NEGATE) e3:SetType(EFFECT_TYPE_QUICK_O) e3:SetRange(LOCATION_SZONE) e3:SetCountLimit(1,14981498+EFFECT_COUNT_CODE_OATH) e3:SetCode(EVENT_CHAINING) e3:SetCost(c14981498.negcost) e3:SetCondition(c14981498.negcon) e3:SetTarget(c14981498.negtg) e3:SetOperation(c14981498.negop) c:RegisterEffect(e3) end function c14981498.cost(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 c14981498.cfilter(c,e,tp) return c:IsSetCard(0x5DC) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and c:IsLocation(LOCATION_EXTRA) and c:IsFaceup() end function c14981498.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_EXTRA) and chkc:IsControler(tp) and c14981498.cfilter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c14981498.cfilter,tp,LOCATION_EXTRA,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c14981498.cfilter,tp,LOCATION_EXTRA,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c14981498.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e)then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end function c14981498.negcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToGrave() end Duel.SendtoGrave(e:GetHandler(),REASON_COST) end function c14981498.negcon(e,tp,eg,ep,ev,re,r,rp,chk) local loc=Duel.GetChainInfo(ev,CHAININFO_TRIGGERING_LOCATION) return ep~=tp and loc==LOCATION_MZONE and re:IsActiveType(TYPE_MONSTER) and Duel.IsChainNegatable(ev) end function c14981498.negtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0) end function c14981498.negop(e,tp,eg,ep,ev,re,r,rp) Duel.NegateActivation(ev) end
gpl-3.0