repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
FFXIOrgins/FFXIOrgins
scripts/zones/Rabao/npcs/Shiny_Teeth.lua
36
1675
----------------------------------- -- Area: Rabao -- NPC: Shiny Teeth -- Standard Merchant NPC -- @pos -30 8 99 247 ----------------------------------- package.loaded["scripts/zones/Rabao/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Rabao/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,SHINY_TEETH_SHOP_DIALOG); stock = {0x4042,1867, --Dagger 1867 - 2111 0x404C,11128, --Kris 11128 - 12096 0x4052,2231, --Knife 2231 - 2522 0x40A8,4163, --Scimitar 4163 - 4706 0x40A9,35308, --Tulwar 35308 0x40AE,62560, --Falchion 62560 - 70720 0x42A4,2439, --Rod 2439 - 4680 0x4011,103803, --Jamadhars 103803 - 104944 0x4303,23887, --Composite Bow 23887 - 24150 0x4392,294, --Tathlum 294 - 332 0x43A8,7, --Iron Arrow 7 - 10 0x43BC,92, --Bullet 92 - 174 0x43A3,5460, --Riot Grenade 5460 - 5520 0x4384,8996} --Chakram 8996 - 10995 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
suchipi/pac3
lua/pac3/core/client/libraries/webaudio/streams.lua
1
1339
-- made by Morten and CapsAdmin pac.webaudio = pac.webaudio or {} local webaudio = pac.webaudio webaudio.Streams = webaudio.Streams or {} webaudio.Streams.LastStreamId = 0 webaudio.Streams.Streams = {} function webaudio.Streams.CreateStream(url) --url = url:gsub("http[s?]://", "http://") if url:find("http",1,true) then url = pac.FixupURL(url) else url = "asset://garrysmod/sound/" .. url end local stream = setmetatable({}, webaudio.Streams.STREAM) webaudio.Streams.LastStreamId = webaudio.Streams.LastStreamId + 1 stream:SetId(webaudio.Streams.LastStreamId) stream:SetUrl(url) webaudio.Streams.Streams[stream:GetId()] = stream webaudio.Browser.QueueJavascript(string.format("createStream(%q, %d)", stream:GetUrl(), stream:GetId())) return stream end function webaudio.Streams.GetStream(streamId) return webaudio.Streams.Streams[streamId] end function webaudio.Streams.StreamExists(streamId) return webaudio.Streams.Streams[streamId] ~= nil end function webaudio.Streams.Think() for streamId, stream in pairs(webaudio.Streams.Streams) do if stream:IsValid() then stream:Think() else stream:Stop() webaudio.Streams.Streams[streamId] = nil webaudio.Browser.QueueJavascript(string.format("destroyStream(%i)", stream:GetId())) setmetatable(stream, getmetatable(NULL)) end end end
gpl-3.0
PioneerMakeTeam/Cretaceous
wicker/kernel_extensions/class.lua
5
5095
local GClass = _G.Class local assert, error = assert, error local type = type local rawget, rawset = rawget, rawset local pairs, ipairs = pairs, ipairs local next = next local getmetatable, setmetatable = getmetatable, setmetatable --- local Lambda = wickerrequire "paradigms.functional" pkgrequire "uuids" --- local AddPropertyTo = assert( AddPropertyTo ) --- assert( uuid ) local PROPERTY_KEY = uuid() local ANCESTORS_KEY = uuid() local PROXYCLASS_KEY = uuid() local DUMMY_SELF_KEY = uuid() --- local function get_dummy_object(class) local ret = rawget(class, DUMMY_SELF_KEY) if ret == nil then ret = setmetatable({}, class) rawset(class, DUMMY_SELF_KEY, ret) end return ret end local NewClassMetatable = (function() local basic_mt = { __call = function(class, ...) local obj = {} setmetatable(obj, class) local v = class._ctor(obj, ...) if v ~= nil then obj = v end return obj end, } local function parse_prop_spec(spec) if type(spec) ~= "table" then return end local getter = spec.get or spec.getter local setter = spec.set or spec.setter if not (getter or setter) then return end local k = next(spec) if getter then k = next(spec, k) end if setter then k = next(spec, k) end if k ~= nil then return end return getter, setter end local function add_property(class, k, getter, setter) local props = rawget(class, PROPERTY_KEY) props[k] = {get = getter, set = setter} local dummyself = get_dummy_object(class) AddPropertyTo(dummyself, k, getter, setter) end basic_mt.__newindex = function(class, k, v) local getter, setter = parse_prop_spec(v) if getter or setter then add_property(class, k, getter, setter) return true else -- Implement access control? rawset(class, k, v) end end return function(class) local mt = {} for k, v in pairs(basic_mt) do mt[k] = v end return mt end end)() --- function is_a(self, D) local C = getmetatable(self) if C == D then return true end local proxy_target = rawget(self, PROXYCLASS_KEY) if proxy_target ~= nil then if proxy_target:is_a(D) then return true end end local ancestors = rawget(C, ANCESTORS_KEY) if ancestors ~= nil then return ancestors[D] else if C._base then return get_dummy_object(C._base):is_a(D) end end return false end local Class = function(baseclass, ctor) if type(ctor) ~= "function" then ctor, baseclass = baseclass, nil end assert(baseclass == nil or type(baseclass) == "table") assert(type(ctor) == "function") local C = GClass(baseclass, ctor) setmetatable(C, nil) C.RedirectSetters = nil assert(C._base == baseclass) function C.__index(self, k) return C[k] end C.__newindex = rawset C.is_a = is_a --- local inherited_props = {} if baseclass ~= nil then local ancestors = {} local baseprops, baseancestors = rawget(baseclass, PROPERTY_KEY), rawget(baseclass, ANCESTORS_KEY) if baseprops ~= nil then inherited_props = baseprops end if baseancestors ~= nil then for B in pairs(baseancestors) do ancestors[B] = true end ancestors[baseclass] = true else local ancestor = baseclass repeat ancestors[ancestor] = true ancestor = ancestor._base until ancestor == nil end rawset(C, ANCESTORS_KEY, ancestors) end --- rawset(C, PROPERTY_KEY, {}) --- setmetatable(C, NewClassMetatable(C)) --- for k, v in pairs(inherited_props) do C[k] = v end --- return C end local PROXYMETHOD_CACHE = uuid() local function ProxyMethod(self, fn) local cache = rawget(self, PROXYMETHOD_CACHE) if cache == nil then cache = setmetatable({}, {__mode = "k"}) rawset(self, PROXYMETHOD_CACHE, cache) end local gn = cache[fn] if gn == nil then gn = function(maybeself, ...) if maybeself == self then local targetself = assert( rawget(self, PROXYCLASS_KEY) ) maybeself = targetself end return fn(maybeself, ...) end cache[fn] = gn end return gn end local function proxy_index(self, k) local v = rawget(self, PROXYCLASS_KEY)[k] if type(v) == "function" then return ProxyMethod(self, v) end return v end local function proxy_newindex(self, k, v) rawget(self, PROXYCLASS_KEY)[k] = v return true end local function redirect_setters(class) AttachMetaNewIndexTo(get_dummy_object(class), proxy_newindex) end local function ProxyClass(targetclass, ...) local C = Class(...) local old_ctor = C._ctor function C._ctor(self, targetself, ...) if targetself == nil then return error("Target object of proxy object cannot be nil.", 3) end rawset(self, PROXYCLASS_KEY, targetself) assert( self.targetself == targetself, "Logic error." ) return old_ctor(self, ...) end C.targetself = { get = function(self) return rawget(self, PROXYCLASS_KEY) end, set = Lambda.Error("targetself cannot be set."), } AttachMetaIndexTo(get_dummy_object(C), proxy_index, true) function C.RedirectSetters() redirect_setters(C) C.RedirectSetters = Lambda.Nil end return C end kernel.Class = Class kernel.ProxyClass = ProxyClass
mit
hydna/luahydna
hydna.lua
1
1364
local io = require("io") local http = require("socket.http") local ltn12 = require("ltn12") local hydna = {} function hydna.send(url, data, priority) priority = priority or 0 return do_request(url, data, priority) end function hydna.emit(url, data) return do_request(url, data, nil) end function do_request(url, data, priority) local response_body = {} local headers if url == nil then error("Expected url") end if data == nil or type(data) ~= "string" then error("Expected data as string") end if (string.sub(url, 1, 7) == "http://") == false or (string.sub(url, 1, 8) == "https://") == false then url = "http://"..url end if #data > 0xffff then error("Data to large") end headers = { ["Content-Type"] = "text/plain", ["Content-Length"] = #data } if type(priority) == "number" then headers["X-Priority"] = priority else headers["X-Emit"] = "yes" end local r, code = http.request { method = "POST", headers = headers, url = url, source = ltn12.source.string(data), sink = ltn12.sink.table(response_body) } if r == nil then return code end if code ~= 200 then return table.concat(response_body) end end return hydna
mit
FFXIOrgins/FFXIOrgins
scripts/zones/Metalworks/npcs/Nogga.lua
34
1203
----------------------------------- -- Area: Metalworks -- NPC: Nogga -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NOGGA_SHOP_DIALOG); stock = {0x43A4,675,2, -- Bomb Arm 0x43A1,1083,3, -- Grenade 0x0ae8,92,3} -- Catalytic Oil showNationShop(player, BASTOK, 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
FFXIOrgins/FFXIOrgins
scripts/zones/Aht_Urhgan_Whitegate/npcs/Naja_Salaheem.lua
7
2566
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Naja Salaheem -- Type: Standard NPC -- @pos 22.700 -8.804 -45.591 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TOAUM3_DAY = player:getVar("TOAUM3_STARTDAY"); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local needToZone = player:needToZone(); if(player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES)then if(player:getVar("TOAUM2") == 1 or player:getVar("TOAUM2") == 2) then player:startEvent(0x0BBA,0,0,0,0,0,0,0,0,0); end elseif(player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("TOAUM3") == 1)then player:startEvent(0x0049,0,0,0,0,0,0,0,0,0); elseif(player:getCurrentMission(TOAU) == PRESIDENT_SALAHEEM and player:getVar("TOAUM3") == 2 and TOAUM3_DAY ~= realday and needToZone == true) then player:startEvent(0x0BCC,0,0,0,0,0,0,0,0,0); else player:messageSpecial(0);-- need to find correct normal chat CS.. 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 == 0x0BBA)then player:setVar("TOAUM2",0); player:completeMission(TOAU,IMMORTAL_SENTRIES); player:addMission(TOAU,PRESIDENT_SALAHEEM); player:addImperialStanding(150); player:addTitle(PRIVATE_SECOND_CLASS); player:addKeyItem(PSC_WILDCAT_BADGE); player:messageSpecial(KEYITEM_OBTAINED,PSC_WILDCAT_BADGE); elseif(csid == 0x0BCC)then player:completeMission(TOAU,PRESIDENT_SALAHEEM); player:addMission(TOAU,KNIGHT_OF_GOLD); player:setVar("TOAUM3",0); player:setVar("TOAUM3_DAY", 0); elseif(csid == 0x0049)then player:setVar("TOAUM3",2); player:setVar("TOAUM3_DAY", os.date("%j")); -- %M for next minute, %j for next day end end;
gpl-3.0
Capster/Metro
lua/metro/ui/dcolorcube.lua
2
3343
--[[ _ ( ) _| | __ _ __ ___ ___ _ _ /'_` | /'__`\( '__)/' _ ` _ `\ /'_` ) ( (_| |( ___/| | | ( ) ( ) |( (_| | `\__,_)`\____)(_) (_) (_) (_)`\__,_) DColorCube --]] local PANEL = {} AccessorFunc( PANEL, "m_Hue", "Hue" ) AccessorFunc( PANEL, "m_BaseRGB", "BaseRGB" ) AccessorFunc( PANEL, "m_OutRGB", "RGB" ) --[[--------------------------------------------------------- Name: Init -----------------------------------------------------------]] function PANEL:Init() self:SetImage( "vgui/minixhair" ) self.Knob:NoClipping( false ) self.BGSaturation = vgui.Create( "DImage", self ) self.BGSaturation:SetImage( "vgui/gradient-r" ) self.BGValue = vgui.Create( "DImage", self ) self.BGValue:SetImage( "vgui/gradient-d" ) self.BGValue:SetImageColor( Color( 0, 0, 0, 255 ) ) self:SetBaseRGB( Color( 255, 0, 0 ) ) self:SetRGB( Color( 255, 0, 0 ) ) self:SetColor( Color( 255, 0, 0 ) ) self:SetLockX( nil ) self:SetLockY( nil ) end --[[--------------------------------------------------------- Name: PerformLayout -----------------------------------------------------------]] function PANEL:PerformLayout() DSlider.PerformLayout( self ) self.BGSaturation:StretchToParent( 0,0,0,0 ) self.BGSaturation:SetZPos( -9 ) self.BGValue:StretchToParent( 0,0,0,0 ) self.BGValue:SetZPos( -8 ) end --[[--------------------------------------------------------- Name: Paint -----------------------------------------------------------]] function PANEL:Paint() surface.SetDrawColor( self.m_BaseRGB.r, self.m_BaseRGB.g, self.m_BaseRGB.b, 255 ) self:DrawFilledRect() end --[[--------------------------------------------------------- Name: PaintOver -----------------------------------------------------------]] function PANEL:PaintOver() surface.SetDrawColor( 0, 0, 0, 250 ) self:DrawOutlinedRect() end --[[--------------------------------------------------------- Name: TranslateValues -----------------------------------------------------------]] function PANEL:TranslateValues( x, y ) self:UpdateColor( x, y ) self:OnUserChanged( self.m_OutRGB ) return x, y end --[[--------------------------------------------------------- Name: UpdateColor -----------------------------------------------------------]] function PANEL:UpdateColor( x, y ) x = x or self:GetSlideX() y = y or self:GetSlideY() local value = 1 - y local saturation = 1 - x local h = ColorToHSV( self.m_BaseRGB ) local color = HSVToColor( h, saturation, value ) self:SetRGB( color ) end --[[--------------------------------------------------------- Name: OnUserChanged -----------------------------------------------------------]] function PANEL:OnUserChanged() -- Override me end --[[--------------------------------------------------------- Name: SetColor -----------------------------------------------------------]] function PANEL:SetColor( color ) local h, s, v = ColorToHSV( color ) self:SetBaseRGB( HSVToColor( h, 1, 1 ) ) self:SetSlideY( 1 - v ) self:SetSlideX( 1 - s ) self:UpdateColor() end --[[--------------------------------------------------------- Name: SetBaseRGB -----------------------------------------------------------]] function PANEL:SetBaseRGB( color ) self.m_BaseRGB = color self:UpdateColor() end derma.DefineControl( "DColorCube", "", PANEL, "DSlider" )
apache-2.0
wilbefast/you-ordered-a-pizza
src/debugWorldDraw.lua
2
2709
local seed = 123 local rng = love.math.newRandomGenerator(seed) local function drawFixture(fixture) local shape = fixture:getShape() local shapeType = shape:getType() if (fixture:isSensor()) then love.graphics.setColor(0,0,255,96) else love.graphics.setColor(rng:random(32,255),rng:random(32,255),rng:random(32,255),96) end if (shapeType == "circle") then local x,y = shape:getPoint() local radius = shape:getRadius() love.graphics.circle("fill",x,y,radius,15) love.graphics.setColor(0,0,0,255) love.graphics.circle("line",x,y,radius,15) local eyeRadius = radius/4 love.graphics.setColor(0,0,0,255) love.graphics.circle("fill",0,-radius+eyeRadius,eyeRadius,10) elseif (shapeType == "polygon") then local points = {shape:getPoints()} love.graphics.polygon("fill",points) love.graphics.setColor(0,0,0,255) love.graphics.polygon("line",points) elseif (shapeType == "edge") then love.graphics.setColor(0,0,0,255) love.graphics.line(shape:getPoints()) elseif (shapeType == "chain") then love.graphics.setColor(0,0,0,255) love.graphics.line(shape:getPoints()) end end local function drawBody(body) local bx,by = body:getPosition() local bodyAngle = body:getAngle() love.graphics.push() love.graphics.translate(bx,by) love.graphics.rotate(bodyAngle) rng:setSeed(seed) local fixtures = body:getFixtureList() for i=1,#fixtures do drawFixture(fixtures[i]) end love.graphics.pop() end local drawnBodies = {} local function debugWorldDraw_scissor_callback(fixture) drawnBodies[fixture:getBody()] = true return true --search continues until false end local function debugWorldDraw(world,topLeft_x,topLeft_y,width,height) world:queryBoundingBox(topLeft_x,topLeft_y,topLeft_x+width,topLeft_y+height,debugWorldDraw_scissor_callback) love.graphics.setLineWidth(1) for body in pairs(drawnBodies) do drawnBodies[body] = nil drawBody(body) end love.graphics.setColor(0,255,0,255) love.graphics.setLineWidth(3) love.graphics.setPointSize(3) local joints = world:getJointList() for i=1,#joints do local x1,y1,x2,y2 = joints[i]:getAnchors() if (x1 and x2) then love.graphics.line(x1,y1,x2,y2) else if (x1) then love.graphics.point(x1,y1) end if (x2) then love.graphics.point(x2,y2) end end end love.graphics.setColor(255,0,0,255) love.graphics.setPointSize(3) local contacts = world:getContactList() for i=1,#contacts do local x1,y1,x2,y2 = contacts[i]:getPositions() if (x1) then love.graphics.point(x1,y1) end if (x2) then love.graphics.point(x2,y2) end end end return debugWorldDraw
mit
FFXIOrgins/FFXIOrgins
scripts/globals/spells/mages_ballad_iii.lua
4
1187
----------------------------------------- -- Spell: Mage's Ballad III -- Gradually restores target's MP. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function OnMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 3; local iBoost = caster:getMod(MOD_BALLAD_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_BALLAD,power,0,duration,caster:getID(), 0, 3)) then spell:setMsg(75); end return EFFECT_BALLAD; end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/effects/prowess_killer.lua
34
2312
----------------------------------- -- -- EFFECT_PROWESS : "Killer" effects bonus -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VERMIN_KILLER, effect:getPower()); target:addMod(MOD_BIRD_KILLER, effect:getPower()); target:addMod(MOD_AMORPH_KILLER, effect:getPower()); target:addMod(MOD_LIZARD_KILLER, effect:getPower()); target:addMod(MOD_AQUAN_KILLER, effect:getPower()); target:addMod(MOD_PLANTOID_KILLER, effect:getPower()); target:addMod(MOD_BEAST_KILLER, effect:getPower()); target:addMod(MOD_UNDEAD_KILLER, effect:getPower()); target:addMod(MOD_ARCANA_KILLER, effect:getPower()); target:addMod(MOD_DRAGON_KILLER, effect:getPower()); target:addMod(MOD_DEMON_KILLER, effect:getPower()); target:addMod(MOD_EMPTY_KILLER, effect:getPower()); -- target:addMod(MOD_HUMANOID_KILLER, effect:getPower()); target:addMod(MOD_LUMORIAN_KILLER, effect:getPower()); target:addMod(MOD_LUMINION_KILLER, effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VERMIN_KILLER, effect:getPower()); target:delMod(MOD_BIRD_KILLER, effect:getPower()); target:delMod(MOD_AMORPH_KILLER, effect:getPower()); target:delMod(MOD_LIZARD_KILLER, effect:getPower()); target:delMod(MOD_AQUAN_KILLER, effect:getPower()); target:delMod(MOD_PLANTOID_KILLER, effect:getPower()); target:delMod(MOD_BEAST_KILLER, effect:getPower()); target:delMod(MOD_UNDEAD_KILLER, effect:getPower()); target:delMod(MOD_ARCANA_KILLER, effect:getPower()); target:delMod(MOD_DRAGON_KILLER, effect:getPower()); target:delMod(MOD_DEMON_KILLER, effect:getPower()); target:delMod(MOD_EMPTY_KILLER, effect:getPower()); -- target:delMod(MOD_HUMANOID_KILLER, effect:getPower()); target:delMod(MOD_LUMORIAN_KILLER, effect:getPower()); target:delMod(MOD_LUMINION_KILLER, effect:getPower()); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/garlic_cracker_+1.lua
35
1345
----------------------------------------- -- ID: 4280 -- Item: garlic_cracker_+1 -- Food Effect: 5Min, All Races ----------------------------------------- -- Magic Regen While Healing 8 -- Undead Killer 5 -- Blind 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,300,4280); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 8); target:addMod(MOD_UNDEAD_KILLER, 5); target:addMod(MOD_BLINDRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 8); target:delMod(MOD_UNDEAD_KILLER, 5); target:delMod(MOD_BLINDRES, 5); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/abilities/maguss_roll.lua
6
1407
----------------------------------- -- Ability: Magus's Roll ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- OnUseAbility ----------------------------------- function OnAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else return 0,0; end end; function OnUseAbilityRoll(caster, target, ability, total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {5, 20, 6, 8, 9, 3, 10, 13, 14, 15, 25} local effectpower = effectpowers[total] if (total < 12 and caster:hasPartyJob(JOB_BLU) ) then effectpower = effectpower + 8; end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_MAGUSS_ROLL, effectpower, 0, duration, target:getID(), total, MOD_MDEF) == false) then ability:setMsg(423); end end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/pipin_hot_popoto.lua
35
1291
----------------------------------------- -- ID: 4282 -- Item: pipin_hot_popoto -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 25 -- Vitality 3 -- HP recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4282); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_VIT, 3); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_VIT, 3); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
joshimoo/Algorithm-Implementations
Depth_Limited_Search/Lua/Yonaba/dls.lua
26
3110
-- Generic Depth-Limited search algorithm implementation -- See : http://en.wikipedia.org/wiki/Depth-limited_search -- Notes : this is a generic implementation of Depth-Limited search algorithm. -- It is devised to be used on any type of graph (point-graph, tile-graph, -- or whatever. It expects to be initialized with a handler, which acts as -- an interface between the search algorithm and the search space. -- The DLS class expects a handler to be initialized. Roughly said, the handler -- is an interface between your search space and the generic search algorithm. -- This ensures flexibility, so that the generic algorithm can be adapted to -- search on any kind of space. -- The passed-in handler should implement those functions. -- handler.getNode(...) -> returns a Node (instance of node.lua) -- handler.getNeighbors(n) -> returns an array of all nodes that can be reached -- via node n (also called successors of node n) -- The actual implementation uses recursion to look up for the path. -- Between consecutive path requests, the user must call the :resetForNextSearch() -- method to clear all nodes data created during a previous search. -- The generic Node class provided (see node.lua) should also be implemented -- through the handler. Basically, it should describe how nodes are labelled -- and tested for equality for a custom search space. -- The following functions should be implemented: -- function Node:initialize(...) -> creates a Node with custom attributes -- function Node:isEqualTo(n) -> returns if self is equal to node n -- function Node:toString() -> returns a unique string representation of -- the node, for debug purposes -- See custom handlers for reference (*_hander.lua). -- Dependencies local class = require 'utils.class' -- Builds and returns the path to the goal node local function backtrace(node) local path = {} repeat table.insert(path, 1, node) node = node.parent until not node return path end -- Initializes Depth-Limited search with a custom handler local DLS = class() function DLS:initialize(handler) self.handler = handler end -- Clears all nodes for a next search -- Must be called in-between consecutive searches function DLS:resetForNextSearch() local nodes = self.handler.getAllNodes() for _, node in ipairs(nodes) do node.visited, node.parent = nil, nil end end -- Returns the path between start and goal locations -- start : a Node representing the start location -- goal : a Node representing the target location -- depth : the maximum depth of search -- returns : an array of nodes function DLS:findPath(start, goal, depth) if start == goal then return backtrace(start) end if depth == 0 then return end start.visited = true local neighbors = self.handler.getNeighbors(start) for _, neighbor in ipairs(neighbors) do if not neighbor.visited then neighbor.parent = start local foundGoal = self:findPath(neighbor, goal, depth - 1) if foundGoal then return foundGoal end end end end return DLS
mit
Capster/Metro
lua/metro/ui/listview.lua
1
15311
local PANEL = {} AccessorFunc( PANEL, "m_bDirty", "Dirty", FORCE_BOOL ) AccessorFunc( PANEL, "m_bSortable", "Sortable", FORCE_BOOL ) AccessorFunc( PANEL, "m_iHeaderHeight", "HeaderHeight" ) AccessorFunc( PANEL, "m_iDataHeight", "DataHeight" ) AccessorFunc( PANEL, "m_bMultiSelect", "MultiSelect" ) AccessorFunc( PANEL, "m_bHideHeaders", "HideHeaders" ) --[[--------------------------------------------------------- Name: Init -----------------------------------------------------------]] function PANEL:Init() self:SetSortable( true ) self:SetMouseInputEnabled( true ) self:SetMultiSelect( true ) self:SetHideHeaders( false ) self:SetDrawBackground( true ) self:SetHeaderHeight( 26 ) self:SetDataHeight( 22 ) self.Columns = {} self.Lines = {} self.Sorted = {} self:SetDirty( true ) self.pnlCanvas = Metro.Create( "Panel", self ) self.VBar = Metro.Create( "MetroVScrollBar", self ) self.VBar:SetZPos( 20 ) end function PANEL:Paint(w, h) draw.RoundedBox(0, 0, 0, w, h, Metro.Colors.LVBackground) end --[[--------------------------------------------------------- Name: DisableScrollbar -----------------------------------------------------------]] function PANEL:DisableScrollbar() if ( IsValid( self.VBar ) ) then self.VBar:Remove() end self.VBar = nil end --[[--------------------------------------------------------- Name: GetLines -----------------------------------------------------------]] function PANEL:GetLines() return self.Lines end --[[--------------------------------------------------------- Name: GetInnerTall -----------------------------------------------------------]] function PANEL:GetInnerTall() return self:GetCanvas():GetTall() end --[[--------------------------------------------------------- Name: GetCanvas -----------------------------------------------------------]] function PANEL:GetCanvas() return self.pnlCanvas end --[[--------------------------------------------------------- Name: AddColumn -----------------------------------------------------------]] function PANEL:AddColumn( strName, strMaterial, iPosition ) local pColumn = nil if ( self.m_bSortable ) then pColumn = Metro.Create( "MetroListViewColumn", self ) else pColumn = Metro.Create( "MetroListViewColumnPlain", self ) end pColumn:SetName( strName ) pColumn:SetMaterial( strMaterial ) pColumn:SetZPos( 10 ) if ( iPosition ) then -- Todo, insert in specific position else local ID = table.insert( self.Columns, pColumn ) pColumn:SetColumnID( ID ) end self:InvalidateLayout() return pColumn end --[[--------------------------------------------------------- Name: RemoveLine -----------------------------------------------------------]] function PANEL:RemoveLine( LineID ) local Line = self:GetLine( LineID ) local SelectedID = self:GetSortedID( LineID ) self.Lines[ LineID ] = nil table.remove( self.Sorted, SelectedID ) self:SetDirty( true ) self:InvalidateLayout() Line:Remove() end --[[--------------------------------------------------------- Name: ColumnWidth -----------------------------------------------------------]] function PANEL:ColumnWidth( i ) local ctrl = self.Columns[ i ] if (!ctrl) then return 0 end return ctrl:GetWide() end --[[--------------------------------------------------------- Name: FixColumnsLayout -----------------------------------------------------------]] function PANEL:FixColumnsLayout() local NumColumns = #self.Columns if ( NumColumns == 0 ) then return end local AllWidth = 0 for k, Column in pairs( self.Columns ) do AllWidth = AllWidth + Column:GetWide() end local ChangeRequired = self.pnlCanvas:GetWide() - AllWidth local ChangePerColumn = math.floor( ChangeRequired / NumColumns ) local Remainder = ChangeRequired - (ChangePerColumn * NumColumns) for k, Column in pairs( self.Columns ) do local TargetWidth = Column:GetWide() + ChangePerColumn Remainder = Remainder + ( TargetWidth - Column:SetWidth( TargetWidth ) ) end -- If there's a remainder, try to palm it off on the other panels, equally while ( Remainder != 0 ) do local PerPanel = math.floor( Remainder / NumColumns ) for k, Column in pairs( self.Columns ) do Remainder = math.Approach( Remainder, 0, PerPanel ) local TargetWidth = Column:GetWide() + PerPanel Remainder = Remainder + (TargetWidth - Column:SetWidth( TargetWidth )) if ( Remainder == 0 ) then break end end Remainder = math.Approach( Remainder, 0, 1 ) end -- Set the positions of the resized columns local x = 0 for k, Column in pairs( self.Columns ) do Column.x = x x = x + Column:GetWide() Column:SetTall( self:GetHeaderHeight() ) Column:SetVisible( !self:GetHideHeaders() ) end end --[[--------------------------------------------------------- Name: Paint -----------------------------------------------------------]] function PANEL:PerformLayout() -- Do Scrollbar local Wide = self:GetWide() local YPos = 0 if ( IsValid( self.VBar ) ) then self.VBar:SetPos( self:GetWide() - 16, 0 ) self.VBar:SetSize( 16, self:GetTall() ) self.VBar:SetUp( self.VBar:GetTall() - self:GetHeaderHeight(), self.pnlCanvas:GetTall() ) YPos = self.VBar:GetOffset() if ( self.VBar.Enabled ) then Wide = Wide - 16 end end if ( self.m_bHideHeaders ) then self.pnlCanvas:SetPos( 0, YPos ) else self.pnlCanvas:SetPos( 0, YPos + self:GetHeaderHeight() ) end self.pnlCanvas:SetSize( Wide, self.pnlCanvas:GetTall() ) self:FixColumnsLayout() -- -- If the data is dirty, re-layout -- if ( self:GetDirty( true ) ) then self:SetDirty( false ) local y = self:DataLayout() self.pnlCanvas:SetTall( y ) -- Layout again, since stuff has changed.. self:InvalidateLayout( true ) end end --[[--------------------------------------------------------- Name: OnScrollbarAppear -----------------------------------------------------------]] function PANEL:OnScrollbarAppear() self:SetDirty( true ) self:InvalidateLayout() end --[[--------------------------------------------------------- Name: OnRequestResize -----------------------------------------------------------]] function PANEL:OnRequestResize( SizingColumn, iSize ) -- Find the column to the right of this one local Passed = false local RightColumn = nil for k, Column in ipairs( self.Columns ) do if ( Passed ) then RightColumn = Column break end if ( SizingColumn == Column ) then Passed = true end end -- Alter the size of the column on the right too, slightly if ( RightColumn ) then local SizeChange = SizingColumn:GetWide() - iSize RightColumn:SetWide( RightColumn:GetWide() + SizeChange ) end SizingColumn:SetWide( iSize ) self:SetDirty( true ) -- Invalidating will munge all the columns about and make it right self:InvalidateLayout() end --[[--------------------------------------------------------- Name: DataLayout -----------------------------------------------------------]] function PANEL:DataLayout() local y = 0 local h = self.m_iDataHeight for k, Line in ipairs( self.Sorted ) do Line:SetPos( 1, y ) Line:SetSize( self:GetWide()-2, h ) Line:DataLayout( self ) Line:SetAltLine( k % 2 == 1 ) y = y + Line:GetTall() end return y end --[[--------------------------------------------------------- Name: AddLine - returns the line number. -----------------------------------------------------------]] function PANEL:AddLine( ... ) self:SetDirty( true ) self:InvalidateLayout() local Line = Metro.Create( "MetroListViewLine", self.pnlCanvas ) local ID = table.insert( self.Lines, Line ) Line:SetListView( self ) Line:SetID( ID ) -- This assures that there will be an entry for every column for k, v in pairs( self.Columns ) do Line:SetColumnText( k, "" ) end for k, v in pairs( {...} ) do Line:SetColumnText( k, v ) end -- Make appear at the bottom of the sorted list local SortID = table.insert( self.Sorted, Line ) if ( SortID % 2 == 1 ) then Line:SetAltLine( true ) end return Line end --[[--------------------------------------------------------- Name: OnMouseWheeled -----------------------------------------------------------]] function PANEL:OnMouseWheeled( dlta ) if ( !IsValid( self.VBar ) ) then return end return self.VBar:OnMouseWheeled( dlta ) end --[[--------------------------------------------------------- Name: OnMouseWheeled -----------------------------------------------------------]] function PANEL:ClearSelection( dlta ) for k, Line in pairs( self.Lines ) do Line:SetSelected( false ) end end --[[--------------------------------------------------------- Name: GetSelectedLine -----------------------------------------------------------]] function PANEL:GetSelectedLine() for k, Line in pairs( self.Lines ) do if ( Line:IsSelected() ) then return k end end end --[[--------------------------------------------------------- Name: GetLine -----------------------------------------------------------]] function PANEL:GetLine( id ) return self.Lines[ id ] end --[[--------------------------------------------------------- Name: GetSortedID -----------------------------------------------------------]] function PANEL:GetSortedID( line ) for k, v in pairs( self.Sorted ) do if ( v:GetID() == line ) then return k end end end --[[--------------------------------------------------------- Name: OnClickLine -----------------------------------------------------------]] function PANEL:OnClickLine( Line, bClear ) local bMultiSelect = self.m_bMultiSelect if ( !bMultiSelect && !bClear ) then return end -- -- Control, multi select -- if ( bMultiSelect && input.IsKeyDown( KEY_LCONTROL ) ) then bClear = false end -- -- Shift block select -- if ( bMultiSelect && input.IsKeyDown( KEY_LSHIFT ) ) then local Selected = self:GetSortedID( self:GetSelectedLine() ) if ( Selected ) then if ( bClear ) then self:ClearSelection() end local LineID = self:GetSortedID( Line:GetID() ) local First = math.min( Selected, LineID ) local Last = math.max( Selected, LineID ) for id = First, Last do local line = self.Sorted[ id ] line:SetSelected( true ) end return end end -- -- Check for double click -- if ( Line:IsSelected() && Line.m_fClickTime && (!bMultiSelect || bClear) ) then local fTimeDistance = SysTime() - Line.m_fClickTime if ( fTimeDistance < 0.3 ) then self:DoDoubleClick( Line:GetID(), Line ) return end end -- -- If it's a new mouse click, or this isn't -- multiselect we clear the selection -- if ( !bMultiSelect || bClear ) then self:ClearSelection() end if ( Line:IsSelected() ) then return end Line:SetSelected( true ) Line.m_fClickTime = SysTime() self:OnRowSelected( Line:GetID(), Line ) end function PANEL:SortByColumns( c1, d1, c2, d2, c3, d3, c4, d4 ) table.Copy( self.Sorted, self.Lines ) table.sort( self.Sorted, function( a, b ) if (!IsValid( a )) then return true end if (!IsValid( b )) then return false end if ( c1 && a:GetColumnText( c1 ) != b:GetColumnText( c1 ) ) then if ( d1 ) then a, b = b, a end return a:GetColumnText( c1 ) < b:GetColumnText( c1 ) end if ( c2 && a:GetColumnText( c2 ) != b:GetColumnText( c2 ) ) then if ( d2 ) then a, b = b, a end return a:GetColumnText( c2 ) < b:GetColumnText( c2 ) end if ( c3 && a:GetColumnText( c3 ) != b:GetColumnText( c3 ) ) then if ( d3 ) then a, b = b, a end return a:GetColumnText( c3 ) < b:GetColumnText( c3 ) end if ( c4 && a:GetColumnText( c4 ) != b:GetColumnText( c4 ) ) then if ( d4 ) then a, b = b, a end return a:GetColumnText( c4 ) < b:GetColumnText( c4 ) end return true end ) self:SetDirty( true ) self:InvalidateLayout() end --[[--------------------------------------------------------- Name: SortByColumn -----------------------------------------------------------]] function PANEL:SortByColumn( ColumnID, Desc ) table.Copy( self.Sorted, self.Lines ) table.sort( self.Sorted, function( a, b ) if ( Desc ) then a, b = b, a end return a:GetColumnText( ColumnID ) < b:GetColumnText( ColumnID ) end ) self:SetDirty( true ) self:InvalidateLayout() end --[[--------------------------------------------------------- Name: SelectFirstItem Selects the first item based on sort.. -----------------------------------------------------------]] function PANEL:SelectItem( Item ) if ( !Item ) then return end Item:SetSelected( true ) self:OnRowSelected( Item:GetID(), Item ) end --[[--------------------------------------------------------- Name: SelectFirstItem Selects the first item based on sort.. -----------------------------------------------------------]] function PANEL:SelectFirstItem() self:ClearSelection() self:SelectItem( self.Sorted[ 1 ] ) end --[[--------------------------------------------------------- Name: DoDoubleClick -----------------------------------------------------------]] function PANEL:DoDoubleClick( LineID, Line ) -- For Override end --[[--------------------------------------------------------- Name: OnRowSelected -----------------------------------------------------------]] function PANEL:OnRowSelected( LineID, Line ) -- For Override end --[[--------------------------------------------------------- Name: OnRowRightClick -----------------------------------------------------------]] function PANEL:OnRowRightClick( LineID, Line ) -- For Override end --[[--------------------------------------------------------- Name: Clear -----------------------------------------------------------]] function PANEL:Clear() for k, v in pairs( self.Lines ) do v:Remove() end self.Lines = {} self.Sorted = {} self:SetDirty( true ) end function PANEL:ClearColumns() for k,v in pairs(self.Columns) do v:Remove() end self.Columns = {} end --[[--------------------------------------------------------- Name: GetSelected -----------------------------------------------------------]] function PANEL:GetSelected() local ret = {} for k, v in pairs( self.Lines ) do if ( v:IsLineSelected() ) then table.insert( ret, v ) end end return ret end function PANEL:SizeToContents( ) self:SetHeight( self.pnlCanvas:GetTall() + self:GetHeaderHeight() ) end function PANEL:SetFolder(folder) local target = "GAME" local files, folders = file.Find(folder.."/*", target) self:Clear() self:ClearColumns() self:AddColumn("Name") self:AddColumn("Date") self:AddColumn("Size") for k,v in pairs(files) do local size = string.NiceSize(file.Size(folder.."/"..v, target)) local date = os.date("%d.%m.%Y", file.Time(folder.."/"..v, target)) local type = Metro.FileTypes:GetTypeFromExtension(Metro.FileTypes:GetExtensionFromName(v)) self:AddLine(v, date, size):SetIcon(type.Icon) end end Metro.Register( "MetroListView", PANEL, "DPanel" )
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Konschtat_Highlands/npcs/qm1.lua
34
1376
----------------------------------- -- Area: Konschtat Highlands -- NPC: qm1 (???) -- Continues Quests: Past Perfect -- @pos -201 16 80 108 ----------------------------------- package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Konschtat_Highlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local PastPerfect = player:getQuestStatus(BASTOK,PAST_PERFECT); if (PastPerfect == QUEST_ACCEPTED) then player:addKeyItem(0x6d); player:messageSpecial(KEYITEM_OBTAINED,0x6d); -- Tattered Mission Orders else player:messageSpecial(FIND_NOTHING); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/items/colored_egg.lua
35
1274
----------------------------------------- -- ID: 4487 -- Item: colored_egg -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Magic 20 -- Attack 3 ----------------------------------------- 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,4487); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_ATT, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_ATT, 3); end;
gpl-3.0
msburgess3200/PERP
gamemodes/perp/gamemode/items/furniture_bathtub.lua
1
1263
local ITEM = {}; ITEM.ID = 6; ITEM.Reference = "furniture_bathtub"; ITEM.Name = "Bathtub"; ITEM.Description = "A large bathtub. Looks like it could hold a lot of water.\n\nLeft click to spawn as prop."; ITEM.Weight = 10; ITEM.Cost = 1000; ITEM.MaxStack = 100; ITEM.InventoryModel = "models/props_interiors/BathTub01a.mdl"; ITEM.ModelCamPos = Vector(0, -94, 10); ITEM.ModelLookAt = Vector(0, 0, 0); ITEM.ModelFOV = 70; ITEM.WorldModel = "models/props_interiors/BathTub01a.mdl"; ITEM.RestrictedSelling = false; // Used for drugs and the like. So we can't sell it. ITEM.EquipZone = nil; ITEM.PredictUseDrop = false; // If this isn't true, the server will tell the client when something happens to us. if SERVER then function ITEM.OnUse ( Player ) local prop = Player:SpawnProp(ITEM); if (!prop || !IsValid(prop)) then return false; end prop:GetTable().WaterSource = true; return true; end function ITEM.OnDrop ( Player ) return true; end function ITEM.Equip ( Player ) end function ITEM.Holster ( Player ) end else function ITEM.OnUse ( slotID ) return true; end function ITEM.OnDrop ( ) return true; end end GM:RegisterItem(ITEM);
mit
PioneerMakeTeam/Cretaceous
wicker/init/kernel_components/extra_utilities.lua
5
1981
--[[ Copyright (C) 2013 simplex This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ]]-- return function() local GetEnvironmentLayer = assert( GetEnvironmentLayer ) local GetOuterEnvironment = assert( GetOuterEnvironment ) local AddLazyVariableTo = assert( AddLazyVariableTo ) local tostring = assert( _G.tostring ) --[[ -- Propagates the error point to the outer environment. --]] function OuterError(str, ...) local out_env, out_ind = GetEnvironmentLayer(1, true) return error( (str and tostring(str) or "ERROR"):format(...), out_ind ) end local OuterError = OuterError --[[ -- Propagates the assertion point to the outer environment. --]] function OuterAssert(cond, str, ...) if not cond then return OuterError(str or "assertion failed!", ...) end end local OuterAssert = OuterAssert --[[ -- Adds a lazy variable to the current environment. --]] function AddLazyVariable(k, fn) return AddLazyVariableTo( GetOuterEnvironment(), k, fn ) end local AddLazyVariable = AddLazyVariable public_pairs = (function() local next = assert( _G.next ) local type = assert( _G.type ) local sbyte = assert( _G.string.byte ) local us = sbyte("_", 1) local function f(s, var) repeat var = next(s, var) until type(var) ~= "string" or sbyte(var, 1) ~= us return var end return function(t) return f, t end end)() local public_pairs = public_pairs end
mit
msburgess3200/PERP
gamemodes/perp/entities/weapons/weapon_perp_paramedic_defib/shared.lua
1
3110
if SERVER then AddCSLuaFile("shared.lua") end if CLIENT then SWEP.PrintName = "Defibrillator" SWEP.Slot = 2 SWEP.SlotPos = 1 SWEP.DrawAmmo = false SWEP.DrawCrosshair = false end SWEP.Author = "RedMist" SWEP.Instructions = "Left Click: Attempt to shock victim back to life. Right Click: Charge defibrillator." SWEP.Contact = "" SWEP.Purpose = "" SWEP.ViewModelFOV = 62 SWEP.ViewModelFlip = false SWEP.AnimPrefix = "rpg" SWEP.Spawnable = false SWEP.AdminSpawnable = true SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = 0 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "" SWEP.ViewModel = "models/weapons/v_defilibrator.mdl"; SWEP.WorldModel = "models/perp2/w_fists.mdl"; if CLIENT then function SWEP:GetViewModelPosition ( Pos, Ang ) //Ang:RotateAroundAxis(Ang:Forward(), 90); //Pos = Pos + Ang:Forward() * 3; Pos = Pos + Ang:Up() * 6; return Pos, Ang; end end function SWEP:Initialize() //if SERVER then self:SetWeaponHoldType("normal") //end self.ChargeAmmount = 0; self.NextDecharge = CurTime() + 5; self.SmoothCharge = CurTime() + 5; self.LastNoChargeError = CurTime(); end function SWEP:CanPrimaryAttack ( ) return true; end function SWEP:PrimaryAttack() self.Weapon:SetNextPrimaryFire(CurTime() + 1) self.Weapon:SetNextSecondaryFire(CurTime() + 1) if self.ChargeAmmount < 75 then if SERVER and self.LastNoChargeError + 1 < CurTime() then self.LastNoChargeError = CurTime(); self.Owner:Notify('Not enough charge!'); end return false; end local EyeTrace = self.Owner:GetEyeTrace(); local Distance = self.Owner:EyePos():Distance(EyeTrace.HitPos); if Distance > 75 then return false; end if CLIENT then LastCPRUpdate = LastCPRUpdate or 0; if LastCPRUpdate + .5 < CurTime() then LastCPRUpdate = CurTime(); for k, v in pairs(player.GetAll()) do if !v:Alive() then for _, ent in pairs(ents.FindInSphere(EyeTrace.HitPos, 5)) do if ent == v:GetRagdollEntity() then self.Weapon:EmitSound("perp2/revive.wav"); self.Weapon:SendWeaponAnim(ACT_VM_PRIMARYATTACK); self.ChargeAmmount = self.ChargeAmmount - 75 RunConsoleCommand('perp_m_h', v:UniqueID()); return; end end end end end end end function SWEP:Think ( ) /*if CurTime() < self.NextDecharge then if self.ChargeAmmount != 0 then self.ChargeAmmount = self.ChargeAmmount - 1; end self.NextDecharge = CurTime() + 5; end*/ end function SWEP:SecondaryAttack() if (GAMEMODE.LastChargeUp && GAMEMODE.LastChargeUp + .75 > CurTime()) then return; end self.Weapon:SetNextSecondaryFire(CurTime() + .75) self.Weapon:SetNextPrimaryFire(CurTime() + .75) self.Weapon:SendWeaponAnim(ACT_VM_SECONDARYATTACK); //self.Weapon:EmitSound("ambient/energy/spark5.wav"); GAMEMODE.LastChargeUp = CurTime(); self.ChargeAmmount = math.Clamp(self.ChargeAmmount + 25, 0, 100); end function SWEP:GetChargeAmmount ( ) return self.ChargeAmmount; end
mit
facebook/fbnn
fbnn/SparseKmax.lua
1
5121
-- Copyright 2004-present Facebook. All Rights Reserved. local sparse = require 'sparse' --[[ This module performs a sparse embedding with the following process: 1. Perform a dense embedding 2. Apply a linear transformation (to high dimensional space) 3. Make the output k-sparse The parameters of the dense embedding and the linear transformation are learned. Since the fprop may be slow, we keep a candidate set for each word which consists of the most likely indices to be turned on after the k-max operation. We record the number of activations for each member of this set, and periodically resize it to keep only the most active indices. Thus the initial training with large candidate sets will be slow, but will get faster and faster as we restrict their sizes. ]] local SparseKmax, parent = torch.class('nn.SparseKmax','nn.Module') --[[ Parameters: * `vocabSize` - number of entries in the dense lookup table * `nDenseDim` - number of dimensions for initial dense embedding * `nSparseDim` - number of dimensions for final sparse embedding * `k` - number of nonzeros in sparse space * `nCandidates` - initial size of the candidate set ]] function SparseKmax:__init(vocabSize,nDenseDim,nSparseDim,k,nCandidates) self.nDenseDim = nDenseDim self.nSparseDim = nSparseDim self.K = k self.nCandidates = nCandidates self.weights = torch.FloatTensor(nSparseDim,nDenseDim) self.counts = torch.FloatTensor(vocabSize,nCandidates) self.candidates = torch.ShortTensor(vocabSize,nCandidates) self.denseEmbedding = nn.WeightedLookupTable(vocabSize,nDenseDim) for i = 1,vocabSize do self.candidates[i]:copy(torch.range(1,nCandidates)) end -- Intermediate gradients wrt outputs of dense embeddings. self.gradEmbeddings = torch.FloatTensor(1,nDenseDim) -- Intermediate gradients wrt inputs to k-max layer. self.gradInputKmax = torch.FloatTensor(1,self.K,2) -- This stores activations before k-max operation. self.activations = torch.FloatTensor(nCandidates,2) self.output = torch.FloatTensor(1,self.K,2) self:reset() end function SparseKmax:reset(stdv) self.denseEmbedding:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weights:size(2)) end self.counts:zero() self.weights:uniform(-stdv,stdv) end function SparseKmax:updateOutput(input) local nInputs = input:size(1) -- Compute outputs of the dense embedding. self.dense = self.denseEmbedding:forward(input) self.output:resize(nInputs,self.K,2) -- Loop over the dense embeddings of the input words. for i = 1,input:size(1) do local candidates = self.candidates[input[i][1]] -- Copy the indices of candidates into the output. self.activations[{{},1}]:copy(candidates) self.activations[{{},2}]:zero() -- Compute the activations for each element of the candidate set. sparse.SaddMtimesDoverlap(self.weights,self.dense[i],self.activations) -- Pick top k and copy the scores/indices into the output. -- We sort the indices since this will likely be needed later. local topk_val,topk_indx = torch.topk(self.activations[{{},2}],self.K) local sorted_indices,sorting_indx = torch.sort(candidates:index(1,topk_indx:long())) self.output[{i,{},1}]:copy(sorted_indices) self.output[{i,{},2}]:copy(topk_val:index(1,sorting_indx)) -- Increment counts. for j = 1,self.K do self.counts[input[i][1]][topk_indx[j]] = self.counts[input[i][1]][topk_indx[j]] + 1 end end return self.output end -- Update the candidate set based on the counts of activations. -- `nCandidates` is the size of the new candidate sets. function SparseKmax:updateCandidateSets(nCandidates) self.nCandidates = nCandidates local nEntities = self.candidates:size(1) local newCandidates = torch.FloatTensor(nEntities,nCandidates) -- For each entity, find indices of top activations and keep them. for i = 1,nEntities do local _,topk = torch.topk(self.counts[i],nCandidates) newCandidates[i]:copy(self.candidates[i]:index(1,topk:long())) end self.candidates = newCandidates self.counts:zero() self.activations = torch.FloatTensor(nCandidates,2) end -- Note, we assume `gradOutput` is sparse since the output is sparse as well. function SparseKmax:accUpdateGradParameters(input, gradOutput, lr) lr = lr or 1 local nInputs = input:size(1) self.gradEmbeddings:resize(nInputs,self.nDenseDim) self.gradEmbeddings:zero() self.gradInputKmax:resize(nInputs,self.K,2) for i = 1,nInputs do -- Compute gradients wrt kmax input. self.gradInputKmax[{i,{},1}]:copy(self.output[i][{{},1}]) self.gradInputKmax[{i,{},2}]:zero() sparse.SaddSoverlap(self.gradInputKmax[i],gradOutput[i]) -- Compute gradients wrt dense embedding output. sparse.addMtimesS(self.weights:t(),self.gradInputKmax[i],self.gradEmbeddings[i]) end -- Update the weights. for i = 1,nInputs do sparse.addDouterS(self.denseEmbedding.output[i], self.gradInputKmax[i], self.weights:t(),-lr) end -- Update the dense embedding weights. self.denseEmbedding:accUpdateGradParameters(input,self.gradEmbeddings,lr) end
bsd-3-clause
jonathanelscpt/sip-normalization-scripts
sip-normalization-scripts/libra-from-metadata.lua
1
1567
--[[ Author : Jonathan Els Version : 1.0 Description: Workaround for defect in Libra Recorder CTI Matching ignoring recording headers (.e.g. x-nearendaddr and x-farendaddr), which contain the exact DNs required for matching purposes. From/RURI may (correctly) contain mis-matches in the event of calling party normalization as part of standard E.164 dial plans. Normalize From header by replacing URI host portion with what is sent in metadata for "x-nearendaddr" tag. Matches the phone's actual extension and facilitates Libra call recording that currently looks at URI host portion only. Notes: Addresses recording issues of mismatched host portion in forwarded, transferred and other mid-call re-INVITE type scenarios. Addresses recording issues with E.164 numbers being sent to libra for PSTN calls instead of internal extension. Exceptions: None Future development: None --]] M = {} trace.enable() function M.outbound_ANY(msg) -- Get "From" header local from = msg:getHeader("From") -- Fetch x-nearendaddr and modify uri host portion of From header local nearendaddr = string.match(from, "x-nearendaddr=(%d+);") local newFrom = string.gsub(from, "<sip:.*@", "<sip:" .. nearendaddr .. "@") -- Update From Header with nearendaddr as URI host portion msg:modifyHeader("From", newFrom) end return M
mit
FFXIOrgins/FFXIOrgins
scripts/globals/weaponskills/circle_blade.lua
6
1227
----------------------------------- -- Circle Blade -- Sword weapon skill -- Skill Level: 150 -- Delivers an area of effect attack. Attack radius varies with TP. -- Aligned with the Aqua Gorget & Thunder Gorget. -- Aligned with the Aqua Belt & Thunder Belt. -- Element: None -- Modifiers: STR:35% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function OnUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Gael-de-Sailly/minetest-minetestforfun-server
mods/nether/nether/guide.lua
3
15924
local cube = minetest.inventorycube -- the content of the guide local guide_infos = { { description = "Mushrooms", {"text", "Nether mushrooms can be found on the nether's ground and\n".. "on netherrack soil, it can be dug by hand."}, {"image", {1, 1, "riesenpilz_nether_shroom_side.png"}}, {"y", 0.2}, {"text", "If you drop it without holding the fast key, you can split it into its stem and head:"}, {"image", {1, 1, "nether_shroom_top.png", 1}}, {"image", {1, 1, "nether_shroom_stem.png"}}, {"y", 0.1}, {"text", "You can get more mushrooms by using a netherrack soil:\n".. "1. search a dark place and, if necessary, place netherrack with air about it\n".. "2. right click with cooked blood onto the netherrack to make it soiled\n".. "3. right click onto the netherrack soil with a nether mushroom head to add some spores\n".. "4. dig the mushroom which grew after some time to make place for another one"}, {"image", {1, 1, "riesenpilz_nether_shroom_side.png", 6, 0.12}}, {"y", 1}, {"image", {1, 1, "nether_netherrack.png^nether_netherrack_soil.png", 1.8}}, {"image", {1, 1, "nether_hotbed.png", 1.3, -0.4}}, {"image", {1, 1, "nether_netherrack.png^nether_netherrack_soil.png", 3.6}}, {"image", {1, 1, "nether_shroom_top.png", 3.1, -0.5}}, {"image", {1, 1, "nether_netherrack.png^nether_netherrack_soil.png", 6}}, {"image", {1, 1, "nether_netherrack.png"}}, }, { description = "Tools", {"text", "You can craft 5 kinds of tools in the nether,\n".. "which (except the mushroom pick) require sticks to be crafted:"}, {"image", {1, 1, "nether_pick_mushroom.png"}}, {"y", 0.1}, {"text", "strength : 1\n".. "The mushroom pick needs mushroom stems and heads to be crafted."}, {"image", {1, 1, "nether_pick_wood.png"}}, {"y", 0.1}, {"text", "strength : 2\n".. "The nether wood pick can be crafted with cooked nether blood wood."}, {"image", {1, 1, "nether_axe_netherrack.png", 1.5}}, {"image", {1, 1, "nether_shovel_netherrack.png", 3}}, {"image", {1, 1, "nether_sword_netherrack.png", 4.5}}, {"image", {1, 1, "nether_pick_netherrack.png"}}, {"y", 0.1}, {"text", "strength : 3\n".. "The red netherrack tools can be crafted with usual netherrack."}, {"image", {1, 1, "nether_axe_netherrack_blue.png", 1.5}}, {"image", {1, 1, "nether_shovel_netherrack_blue.png", 3}}, {"image", {1, 1, "nether_sword_netherrack_blue.png", 4.5}}, {"image", {1, 1, "nether_pick_netherrack_blue.png"}}, {"y", 0.1}, {"text", "strength : 3\n".. "The blue netherrack tools can be crafted with blue netherrack."}, {"image", {1, 1, "nether_axe_white.png", 1.5}}, {"image", {1, 1, "nether_shovel_white.png", 3}}, {"image", {1, 1, "nether_sword_white.png", 4.5}}, {"image", {1, 1, "nether_pick_white.png"}}, {"y", 0.1}, {"text", "strength : 3\n".. "The siwtonic tools can be crafted with the siwtonic ore."}, }, { description = "Blood structures", {"text", "You can find blood structures on the ground and\n".. "dig their nodes even with the bare hand."}, {"y", 0.5}, {"text", "One contains 4 kinds of blocks :"}, {"image", {1, 1, cube("nether_blood.png"), 1}}, {"image", {1, 1, cube("nether_blood_top.png", "nether_blood.png^nether_blood_side.png", "nether_blood.png^nether_blood_side.png"), 2}}, {"image", {1, 1, "nether_fruit.png", 3}}, {"image", {1, 1, cube("nether_blood_stem_top.png", "nether_blood_stem.png", "nether_blood_stem.png")}}, {"y", 0.1}, {"text", "Blood stem, blood, blood head and nether fruit"}, {"y", 0.1}, {"text", "You can craft 4 blood wood with the stem :"}, {"image", {1, 1, cube("nether_wood.png")}}, {"y", 0.1}, {"text", "The 4 blood nodes can be cooked and, except\n".. "blood wood, their blood can be extracted."}, }, { description = "Fruits", {"text", "You can find the nether fruits on blood structures\n".. "and dig them even with the bare hand."}, {"image", {1, 1, "nether_fruit.png"}}, {"text", "Eating it will make you lose life but\n".. "it might feed you and give you blood :"}, {"image", {1, 1, "nether_blood_extracted.png"}}, {"y", 0.2}, {"text", "If you eat it at the right place inside a portal,\n".. "you will teleport instead of getting blood."}, {"y", 0.2}, {"text", "If you drop it without holding the fast key,\n".. "you can split it into its fruit and leaf:"}, {"image", {1, 1, "nether_fruit_leaf.png", 1}}, {"image", {1, 1, "nether_fruit_no_leaf.png"}}, {"y", 0.2}, {"text", "Craft a fruit leave block out of 9 fruit leaves\n".. "The fruit can be used to craft a nether pearl."}, {"image", {1, 1, cube("nether_fruit_leaves.png")}}, {"y", 0.2}, {"text", "A fruit leaves block"}, }, { description = "Cooking", {"text", "To get a furnace you need to dig at least 8 netherrack bricks.\n".. "They can be found at pyramid like constructions and require at least\n".. "a strength 1 nether pick to be dug.\n".. "To craft the furnace, use the netherrack bricks like cobble:"}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 0.5}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 1}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png")}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 1}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png")}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 0.5}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 1}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png")}}, {"y", 0.2}, {"text", "To begin cooking stuff, you can use a mushroom or fruit.\n".. "After that it's recommended to use cooked blood nodes."}, {"y", 0.1}, {"text", "Some nether items can be cooked:"}, {"image", {1, 1, cube("nether_blood_stem_top_cooked.png", "nether_blood_stem_cooked.png", "nether_blood_stem_cooked.png"), 0.35}}, {"image", {1, 1, cube("nether_blood_cooked.png"), 1.6}}, {"image", {1, 1, cube("nether_blood_top_cooked.png", "nether_blood_cooked.png^nether_blood_side_cooked.png", "nether_blood_cooked.png^nether_blood_side_cooked.png"), 2.9}}, {"image", {1, 1, cube("nether_wood_cooked.png"), 4.3}}, {"y", 1.2}, {"text", "Some cooked blood stem, cooked blood,\n".. "cooked blood head and cooked blood wood,"}, {"image", {1, 1, "nether_hotbed.png", 0.3}}, {"image", {1, 1, "nether_pearl.png", 2}}, {"y", 1.2}, {"text", "Some cooked extracted blood and a nether pearl"}, }, { description = "Extractors", {"text", "Here you can find out information about the nether extractor."}, {"y", 0.2}, {"text", "Here you can see its craft recipe:"}, {"image", {0.5, 0.5, cube("nether_blood_top_cooked.png", "nether_blood_cooked.png^nether_blood_side_cooked.png", "nether_blood_cooked.png^nether_blood_side_cooked.png"), 0.5}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 1}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png")}}, {"image", {0.5, 0.5, cube("nether_blood_extractor.png"), 2.5}}, {"image", {0.5, 0.5, "nether_shroom_stem.png", 0.5}}, {"image", {0.5, 0.5, cube("nether_blood_cooked.png"), 1}}, {"image", {0.5, 0.5, cube("nether_blood_cooked.png")}}, {"image", {0.5, 0.5, cube("nether_blood_stem_top_cooked.png", "nether_blood_stem_cooked.png", "nether_blood_stem_cooked.png"), 0.5}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png"), 1}}, {"image", {0.5, 0.5, cube("nether_netherrack_brick.png")}}, {"y", 0.2}, {"text", "Extract blood from the blood nodes you get from the blood structures.\n".. "You can also get blood with a nether fruit."}, {"y", 0.2}, {"text", "So you can use it:\n".. "1. place it somewhere\n".. "2. place blood blocks next to it (4 or less)\n".. "3. right click with extracted blood onto it to power it\n".. "4. take the new extracted blood and dig the extracted nodes"}, {"y", 0.2}, {"text", "Example (view from the top):"}, {"y", 0.88}, {"image", {1, 1, "nether_blood_stem_top.png", 0.82, -0.88}}, {"image", {1, 1, "nether_blood.png", 1.63}}, {"image", {1, 1, "nether_blood_extractor.png", 0.82}}, {"image", {1, 1, "nether_blood_stem_top_empty.png", 3.82, -0.88}}, {"image", {1, 1, "nether_blood_empty.png", 4.63}}, {"image", {1, 1, "nether_blood_empty.png", 3.001}}, {"image", {1, 1, "nether_blood_extractor.png", 3.82}}, {"image", {1, 1, "nether_blood.png"}}, {"image", {1, 1, "nether_blood.png", 0.82, -0.12}}, {"image", {1, 1, "nether_blood_empty.png", 3.82, -0.12}}, {"y", 1.2}, {"text", "The empty blood stem can be crafted into empty nether wood,\n".. "which can be crafted into nether sticks."}, }, { description = "Ores", {"text", "You can find 5 types of ores:"}, {"image", {1, 1, cube("nether_netherrack_black.png"), 4}}, {"image", {1, 1, cube("nether_netherrack.png")}}, {"y", 0.2}, {"text", "The red netherrack is generated like stone.\n".. "The black netherrack is generated like gravel.\n".. "Both require at least a strength 2 nether pick to be dug."}, {"image", {1, 1, cube("nether_white.png"), 4}}, {"image", {1, 1, cube("nether_netherrack_blue.png")}}, {"y", 0.2}, {"text", "The blue netherrack is generated like diamond ore.\n".. "The siwtonic ore is generated like mese blocks.\n".. "Both require at least a strength 3 nether pick to be dug."}, {"image", {1, 1, cube("nether_netherrack_tiled.png"), 4}}, {"image", {1, 1, cube("glow_stone.png")}}, {"y", 0.2}, {"text", "Glow stone can be used for lighting.\n".. "Tiled netherrack is generated like coal ore.\n".. "Glow stone requires at least a strength 1 pick to be dug.\n".. "Dig tiled netherrack with at least a level 2 pickaxe."}, }, { description = "Vines", {"text", "Feed nether vines with blood.\n".. "Dig them with anything."}, {"image", {1, 1, "nether_vine.png"}}, {"y", 0.2}, {"text", "Grow nether child by placing\n".. "placing it to a dark place onto a\n".. "blood structure head node."}, {"image", {1, 1, "nether_sapling.png"}}, {"y", -0.10}, {"image", {1, 1, "nether_blood.png^nether_blood_side.png"}}, }, { description = "Pearls", {"text", "The nether pearl can be used to teleport by throwing it.\n".. "Here is how to get one :"}, {"y", 0.2}, {"text", "First of all craft 2 mushroom heads and 1 nether fruit\n".. "without leaf together :"}, {"image", {1, 1, "nether_shroom_top.png"}}, {"image", {1, 1, "nether_fim.png", 3}}, {"image", {1, 1, "nether_fruit_no_leaf.png"}}, {"image", {1, 1, "nether_shroom_top.png"}}, {"y", 0.2}, {"text", "Put the result into the furnace\n".. "to cook it into a nether pearl :"}, {"image", {1, 1, "nether_pearl.png"}}, }, { description = "Bricks", {"text", "Craft bricks out of red,\n".. "black and blue netherrack."}, {"image", {1, 1, cube("nether_netherrack_brick_black.png"), 1}}, {"image", {1, 1, cube("nether_netherrack_brick_blue.png"), 2}}, {"image", {1, 1, cube("nether_netherrack_brick.png")}}, {"y", 0.4}, {"text", "Dig them with at least a level 1 pickaxe."}, {"y", 0.2}, }, { description = "Portals", {"text", "Here you can find out how to built the nether portal."}, {"y", 0.3}, {"text", "A nether portal requires following nodes:"}, {"y", 0.05}, {"text", "21 empty nether wooden planks\n".. "12 blue netherrack bricks\n".. "12 black netherrack\n".. "8 red netherrack\n".. "8 cooked nether wood\n".. "4 nether fruits\n".. "2 siwtonic blocks"}, {"y", 0.2}, {"text", "It should look approximately like this one:"}, {"image", {5.625, 6, "nether_teleporter.png", 0, -1.5}}, {"y", 5.5}, {"text", "Activate it by standing in the middle,\n".. "on the siwtonic block and eating a nether fruit.\n".. "Take enough stuff with you to build a portal when you'll come back."}, }, { description = "Forests", {"text", "The nether forest is generated in caves,\n".. "above the usual nether."}, {"y", 0.2}, {"text", "There you can find some plants:"}, {"image", {1, 1, "nether_grass_middle.png", 1}}, {"image", {1, 1, "nether_grass_big.png", 2}}, {"image", {1, 1, "nether_grass_small.png"}}, {"y", 0.2}, {"text", "Use the nether forest grass to get paper.\n".. "Craft paper out of the dried grass."}, {"image", {1, 1, cube("nether_tree_top.png", "nether_tree.png", "nether_tree.png")}}, {"y", 0.2}, {"text", "Nether trunks can be found at nether trees.\n".. "Craft nether wood out of nether trunk."}, {"image", {1, 1, "nether_glowflower.png"}}, {"y", 0.2}, {"text", "Use it for lighting and decoration."}, }, } -- the size of guide pages local guide_size = {x=40, y=10, cx=0.2, cy=0.2} -- informations about settings and ... local formspec_offset = {x=0.25, y=0.50} local font_size if minetest.is_singleplayer() then font_size = tonumber(minetest.setting_get("font_size")) or 13 else font_size = 13 end guide_size.fx = math.floor((40*(guide_size.cx+formspec_offset.x))*font_size) guide_size.fy = font_size/40 -- the default guide formspecs local guide_forms = { contents = "size[3.6,"..(#guide_infos)-2 ..";]label["..guide_size.cx+0.7 ..","..guide_size.cy+0.2 ..";Contents:]", } -- change the infos to formspecs for n,data in ipairs(guide_infos) do local form = "" local y = 0 local x = guide_size.cx for _,i in ipairs(data) do local typ, content = unpack(i) if typ == "y" then y = y+content elseif typ == "x" then x = math.max(x, content) elseif typ == "text" then local tab = minetest.splittext(content, guide_size.fx) local l = guide_size.cx for _,str in ipairs(tab) do form = form.."label["..guide_size.cx ..","..guide_size.cy+y..";"..str.."]" y = y+guide_size.fy l = math.max(l, #str) end x = math.max(x, l/font_size) elseif typ == "image" then local w, h, texture_name, px, py = unpack(content) if not px then form = form.."image["..guide_size.cx..","..guide_size.cy+y+h*0.3 ..";"..w..","..h..";"..texture_name.."]" y = y+h else px = guide_size.cx+px py = py or 0 form = form.."image["..px..",".. guide_size.cy+y+h*0.3+py ..";"..w..","..h..";"..texture_name.."]" x = math.max(x, px+w) end end end form = "size["..x*1.8 ..","..y+1 ..";]"..form.."button["..x/2-0.5 ..","..y ..";1,2;quit;Back]" guide_forms[n] = {data.description, form} end local desc_tab = {} for n,i in ipairs(guide_forms) do desc_tab[i[1]] = n end -- creates contents formspec local y = 0 for y,i in ipairs(guide_forms) do local desc, form = unpack(i) local s = #desc*1.3/font_size+1.5 guide_forms.contents = guide_forms.contents.."button["..guide_size.cx*12/s-0.5 ..","..guide_size.cy+y/1.3 ..";"..s..",1;name;"..desc.."]" end -- shows the contents of the formspec local function show_guide(pname) minetest.show_formspec(pname, "nether_guide_contents", guide_forms["contents"]) end minetest.register_on_player_receive_fields(function(player, formname, fields) if formname == "nether_guide_contents" then local fname = fields.name local pname = player:get_player_name() if fname and pname then minetest.show_formspec(pname, "nether_guide", guide_forms[desc_tab[fname]][2]) end elseif formname == "nether_guide" then local fname = fields.quit local pname = player:get_player_name() if fname and pname then minetest.show_formspec(pname, "nether_guide_contents", guide_forms["contents"]) end end end) minetest.register_chatcommand("nether_help", { params = "", description = "Shows a nether guide", func = function(name) local player = minetest.get_player_by_name(name) if not player then minetest.chat_send_player(name, "Something went wrong.") return false end --[[ if player:getpos().y > nether.start then minetest.chat_send_player(name, "Usually you don't neet this guide here. You can view it in the nether.") return false end --]] minetest.chat_send_player(name, "Showing guide...") show_guide(name) return true end })
unlicense
sjznxd/lc-20130127
applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> 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 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
apache-2.0
fartoverflow/naev
dat/missions/neutral/cargo.lua
8
4208
--[[ -- These are regular cargo delivery missions. Pay is low, but so is difficulty. -- Most of these missions require BULK ships. Not for small ships! --]] include "dat/scripts/cargo_common.lua" include "dat/scripts/numstring.lua" lang = naev.lang() if lang == "es" then else -- default english misn_desc = "%s in the %s system needs a delivery of %d tons of %s." misn_reward = "%s credits" cargosize = {} cargosize[0] = "Small" -- Note: indexed from 0, to match mission tiers. cargosize[1] = "Medium" cargosize[2] = "Sizeable" cargosize[3] = "Large" cargosize[4] = "Bulk" title_p1 = {} title_p1[1] = " cargo delivery to %s in the %s system" title_p1[2] = " freight delivery to %s in the %s system" title_p1[3] = " transport to %s in the %s system" title_p1[4] = " delivery to %s in the %s system" -- Note: please leave the trailing space on the line below! Needed to make the newline show up. title_p2 = [[ Cargo: %s (%d tons) Jumps: %d Travel distance: %d]] full = {} full[1] = "No room in ship" full[2] = "You don't have enough cargo space to accept this mission. You need %d tons of free space (you need %d more)." --=Landing=-- cargo_land_title = "Delivery success!" cargo_land_p1 = {} cargo_land_p1[1] = "The crates of " cargo_land_p1[2] = "The drums of " cargo_land_p1[3] = "The containers of " cargo_land_p2 = {} cargo_land_p2[1] = " are carried out of your ship by a sullen group of workers. The job takes inordinately long to complete, and the leader pays you without speaking a word." cargo_land_p2[2] = " are rushed out of your vessel by a team shortly after you land. Before you can even collect your thoughts, one of them presses a credit chip in your hand and departs." cargo_land_p2[3] = " are unloaded by an exhausted-looking bunch of dockworkers. Still, they make fairly good time, delivering your pay upon completion of the job." cargo_land_p2[4] = " are unloaded by a team of robotic drones supervised by a human overseer, who hands you your pay when they finish." accept_title = "Mission Accepted" osd_title = "Cargo mission" osd_msg = "Fly to %s in the %s system." end -- Create the mission function create() -- Note: this mission does not make any system claims. -- Calculate the route, distance, jumps and cargo to take destplanet, destsys, numjumps, traveldist, cargo, tier = cargo_calculateRoute() if destplanet == nil then misn.finish(false) end -- Choose amount of cargo and mission reward. This depends on the mission tier. -- Note: Pay is independent from amount by design! Not all deals are equally attractive! finished_mod = 2.0 -- Modifier that should tend towards 1.0 as naev is finished as a game amount = rnd.rnd(5 + 25 * tier, 20 + 60 * tier) jumpreward = 200 distreward = 0.09 reward = 1.5^tier * (numjumps * jumpreward + traveldist * distreward) * finished_mod * (1. + 0.05*rnd.twosigma()) misn.setTitle(buildCargoMissionDescription( nil, amount, cargo, destplanet, destsys )) misn.markerAdd(destsys, "computer") misn.setDesc(cargosize[tier] .. title_p1[rnd.rnd(1, #title_p1)]:format(destplanet:name(), destsys:name()) .. title_p2:format(cargo, amount, numjumps, traveldist)) misn.setReward(misn_reward:format(numstring(reward))) end -- Mission is accepted function accept() if player.pilot():cargoFree() < amount then tk.msg(full[1], full[2]:format(amount, amount - player.pilot():cargoFree())) misn.finish() end misn.accept() misn.cargoAdd(cargo, amount) -- TODO: change to jettisonable cargo once custom commodities are in. For piracy purposes. misn.osdCreate(osd_title, {osd_msg:format(destplanet:name(), destsys:name())}) hook.land("land") end -- Land hook function land() if planet.cur() == destplanet then -- Semi-random message. tk.msg(cargo_land_title, cargo_land_p1[rnd.rnd(1, #cargo_land_p1)] .. cargo .. cargo_land_p2[rnd.rnd(1, #cargo_land_p2)]) player.pay(reward) misn.finish(true) end end function abort () misn.finish(false) end
gpl-3.0
velukh/MplusLedger
Libs/AceAddon-3.0/AceAddon-3.0.lua
17
26462
--- **AceAddon-3.0** provides a template for creating addon objects. -- It'll provide you with a set of callback functions that allow you to simplify the loading -- process of your addon.\\ -- Callbacks provided are:\\ -- * **OnInitialize**, which is called directly after the addon is fully loaded. -- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present. -- * **OnDisable**, which is only called when your addon is manually being disabled. -- @usage -- -- A small (but complete) addon, that doesn't do anything, -- -- but shows usage of the callbacks. -- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- function MyAddon:OnInitialize() -- -- do init tasks here, like loading the Saved Variables, -- -- or setting up slash commands. -- end -- -- function MyAddon:OnEnable() -- -- Do more initialization here, that really enables the use of your addon. -- -- Register Events, Hook functions, Create Frames, Get information from -- -- the game that wasn't available in OnInitialize -- end -- -- function MyAddon:OnDisable() -- -- Unhook, Unregister Events, Hide frames that you created. -- -- You would probably only use an OnDisable if you want to -- -- build a "standby" mode, or be able to toggle modules on/off. -- end -- @class file -- @name AceAddon-3.0.lua -- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $ local MAJOR, MINOR = "AceAddon-3.0", 12 local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR) if not AceAddon then return end -- No Upgrade needed. AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame AceAddon.addons = AceAddon.addons or {} -- addons in general AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon. AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon -- Lua APIs local tinsert, tconcat, tremove = table.insert, table.concat, table.remove local fmt, tostring = string.format, tostring local select, pairs, next, type, unpack = select, pairs, next, type, unpack local loadstring, assert, error = loadstring, assert, error local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget -- Global vars/functions that we don't upvalue since they might get hooked, or upgraded -- List them here for Mikk's FindGlobals script -- GLOBALS: LibStub, IsLoggedIn, geterrorhandler --[[ xpcall safecall implementation ]] local xpcall = xpcall local function errorhandler(err) return geterrorhandler()(err) end local function CreateDispatcher(argCount) local code = [[ local xpcall, eh = ... local method, ARGS local function call() return method(ARGS) end local function dispatch(func, ...) method = func if not method then return end ARGS = ... return xpcall(call, eh) end return dispatch ]] local ARGS = {} for i = 1, argCount do ARGS[i] = "arg"..i end code = code:gsub("ARGS", tconcat(ARGS, ", ")) return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler) end local Dispatchers = setmetatable({}, {__index=function(self, argCount) local dispatcher = CreateDispatcher(argCount) rawset(self, argCount, dispatcher) return dispatcher end}) Dispatchers[0] = function(func) return xpcall(func, errorhandler) end local function safecall(func, ...) -- we check to see if the func is passed is actually a function here and don't error when it isn't -- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not -- present execution should continue without hinderance if type(func) == "function" then return Dispatchers[select('#', ...)](func, ...) end end -- local functions that will be implemented further down local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype -- used in the addon metatable local function addontostring( self ) return self.name end -- Check if the addon is queued for initialization local function queuedForInitialization(addon) for i = 1, #AceAddon.initializequeue do if AceAddon.initializequeue[i] == addon then return true end end return false end --- Create a new AceAddon-3.0 addon. -- Any libraries you specified will be embeded, and the addon will be scheduled for -- its OnInitialize and OnEnable callbacks. -- The final addon object, with all libraries embeded, will be returned. -- @paramsig [object ,]name[, lib, ...] -- @param object Table to use as a base for the addon (optional) -- @param name Name of the addon object to create -- @param lib List of libraries to embed into the addon -- @usage -- -- Create a simple addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0") -- -- -- Create a Addon object based on the table of a frame -- local MyFrame = CreateFrame("Frame") -- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0") function AceAddon:NewAddon(objectorname, ...) local object,name local i=1 if type(objectorname)=="table" then object=objectorname name=... i=2 else name=objectorname end if type(name)~="string" then error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end if self.addons[name] then error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2) end object = object or {} object.name = name local addonmeta = {} local oldmeta = getmetatable(object) if oldmeta then for k, v in pairs(oldmeta) do addonmeta[k] = v end end addonmeta.__tostring = addontostring setmetatable( object, addonmeta ) self.addons[name] = object object.modules = {} object.orderedModules = {} object.defaultModuleLibraries = {} Embed( object ) -- embed NewModule, GetModule methods self:EmbedLibraries(object, select(i,...)) -- add to queue of addons to be initialized upon ADDON_LOADED tinsert(self.initializequeue, object) return object end --- Get the addon object by its name from the internal AceAddon registry. -- Throws an error if the addon object cannot be found (except if silent is set). -- @param name unique name of the addon object -- @param silent if true, the addon is optional, silently return nil if its not found -- @usage -- -- Get the Addon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") function AceAddon:GetAddon(name, silent) if not silent and not self.addons[name] then error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2) end return self.addons[name] end -- - Embed a list of libraries into the specified addon. -- This function will try to embed all of the listed libraries into the addon -- and error if a single one fails. -- -- **Note:** This function is for internal use by :NewAddon/:NewModule -- @paramsig addon, [lib, ...] -- @param addon addon object to embed the libs in -- @param lib List of libraries to embed into the addon function AceAddon:EmbedLibraries(addon, ...) for i=1,select("#", ... ) do local libname = select(i, ...) self:EmbedLibrary(addon, libname, false, 4) end end -- - Embed a library into the addon object. -- This function will check if the specified library is registered with LibStub -- and if it has a :Embed function to call. It'll error if any of those conditions -- fails. -- -- **Note:** This function is for internal use by :EmbedLibraries -- @paramsig addon, libname[, silent[, offset]] -- @param addon addon object to embed the library in -- @param libname name of the library to embed -- @param silent marks an embed to fail silently if the library doesn't exist (optional) -- @param offset will push the error messages back to said offset, defaults to 2 (optional) function AceAddon:EmbedLibrary(addon, libname, silent, offset) local lib = LibStub:GetLibrary(libname, true) if not lib and not silent then error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2) elseif lib and type(lib.Embed) == "function" then lib:Embed(addon) tinsert(self.embeds[addon], libname) return true elseif lib then error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2) end end --- Return the specified module from an addon object. -- Throws an error if the addon object cannot be found (except if silent is set) -- @name //addon//:GetModule -- @paramsig name[, silent] -- @param name unique name of the module -- @param silent if true, the module is optional, silently return nil if its not found (optional) -- @usage -- -- Get the Addon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- -- Get the Module -- MyModule = MyAddon:GetModule("MyModule") function GetModule(self, name, silent) if not self.modules[name] and not silent then error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2) end return self.modules[name] end local function IsModuleTrue(self) return true end --- Create a new module for the addon. -- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\ -- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as -- an addon object. -- @name //addon//:NewModule -- @paramsig name[, prototype|lib[, lib, ...]] -- @param name unique name of the module -- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional) -- @param lib List of libraries to embed into the addon -- @usage -- -- Create a module with some embeded libraries -- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0") -- -- -- Create a module with a prototype -- local prototype = { OnEnable = function(self) print("OnEnable called!") end } -- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0") function NewModule(self, name, prototype, ...) if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end -- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well. -- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is. local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name)) module.IsModule = IsModuleTrue module:SetEnabledState(self.defaultModuleState) module.moduleName = name if type(prototype) == "string" then AceAddon:EmbedLibraries(module, prototype, ...) else AceAddon:EmbedLibraries(module, ...) end AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries)) if not prototype or type(prototype) == "string" then prototype = self.defaultModulePrototype or nil end if type(prototype) == "table" then local mt = getmetatable(module) mt.__index = prototype setmetatable(module, mt) -- More of a Base class type feel. end safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy. self.modules[name] = module tinsert(self.orderedModules, module) return module end --- Returns the real name of the addon or module, without any prefix. -- @name //addon//:GetName -- @paramsig -- @usage -- print(MyAddon:GetName()) -- -- prints "MyAddon" function GetName(self) return self.moduleName or self.name end --- Enables the Addon, if possible, return true or false depending on success. -- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback -- and enabling all modules of the addon (unless explicitly disabled).\\ -- :Enable() also sets the internal `enableState` variable to true -- @name //addon//:Enable -- @paramsig -- @usage -- -- Enable MyModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() function Enable(self) self:SetEnabledState(true) -- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still -- it'll be enabled after the init process if not queuedForInitialization(self) then return AceAddon:EnableAddon(self) end end --- Disables the Addon, if possible, return true or false depending on success. -- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback -- and disabling all modules of the addon.\\ -- :Disable() also sets the internal `enableState` variable to false -- @name //addon//:Disable -- @paramsig -- @usage -- -- Disable MyAddon -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:Disable() function Disable(self) self:SetEnabledState(false) return AceAddon:DisableAddon(self) end --- Enables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object. -- @name //addon//:EnableModule -- @paramsig name -- @usage -- -- Enable MyModule using :GetModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Enable() -- -- -- Enable MyModule using the short-hand -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:EnableModule("MyModule") function EnableModule(self, name) local module = self:GetModule( name ) return module:Enable() end --- Disables the Module, if possible, return true or false depending on success. -- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object. -- @name //addon//:DisableModule -- @paramsig name -- @usage -- -- Disable MyModule using :GetModule -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyModule = MyAddon:GetModule("MyModule") -- MyModule:Disable() -- -- -- Disable MyModule using the short-hand -- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon") -- MyAddon:DisableModule("MyModule") function DisableModule(self, name) local module = self:GetModule( name ) return module:Disable() end --- Set the default libraries to be mixed into all modules created by this object. -- Note that you can only change the default module libraries before any module is created. -- @name //addon//:SetDefaultModuleLibraries -- @paramsig lib[, lib, ...] -- @param lib List of libraries to embed into the addon -- @usage -- -- Create the addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- Configure default libraries for modules (all modules need AceEvent-3.0) -- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0") -- -- Create a module -- MyModule = MyAddon:NewModule("MyModule") function SetDefaultModuleLibraries(self, ...) if next(self.modules) then error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2) end self.defaultModuleLibraries = {...} end --- Set the default state in which new modules are being created. -- Note that you can only change the default state before any module is created. -- @name //addon//:SetDefaultModuleState -- @paramsig state -- @param state Default state for new modules, true for enabled, false for disabled -- @usage -- -- Create the addon object -- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon") -- -- Set the default state to "disabled" -- MyAddon:SetDefaultModuleState(false) -- -- Create a module and explicilty enable it -- MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() function SetDefaultModuleState(self, state) if next(self.modules) then error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2) end self.defaultModuleState = state end --- Set the default prototype to use for new modules on creation. -- Note that you can only change the default prototype before any module is created. -- @name //addon//:SetDefaultModulePrototype -- @paramsig prototype -- @param prototype Default prototype for the new modules (table) -- @usage -- -- Define a prototype -- local prototype = { OnEnable = function(self) print("OnEnable called!") end } -- -- Set the default prototype -- MyAddon:SetDefaultModulePrototype(prototype) -- -- Create a module and explicitly Enable it -- MyModule = MyAddon:NewModule("MyModule") -- MyModule:Enable() -- -- should print "OnEnable called!" now -- @see NewModule function SetDefaultModulePrototype(self, prototype) if next(self.modules) then error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2) end if type(prototype) ~= "table" then error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2) end self.defaultModulePrototype = prototype end --- Set the state of an addon or module -- This should only be called before any enabling actually happend, e.g. in/before OnInitialize. -- @name //addon//:SetEnabledState -- @paramsig state -- @param state the state of an addon or module (enabled=true, disabled=false) function SetEnabledState(self, state) self.enabledState = state end --- Return an iterator of all modules associated to the addon. -- @name //addon//:IterateModules -- @paramsig -- @usage -- -- Enable all modules -- for name, module in MyAddon:IterateModules() do -- module:Enable() -- end local function IterateModules(self) return pairs(self.modules) end -- Returns an iterator of all embeds in the addon -- @name //addon//:IterateEmbeds -- @paramsig local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end --- Query the enabledState of an addon. -- @name //addon//:IsEnabled -- @paramsig -- @usage -- if MyAddon:IsEnabled() then -- MyAddon:Disable() -- end local function IsEnabled(self) return self.enabledState end local mixins = { NewModule = NewModule, GetModule = GetModule, Enable = Enable, Disable = Disable, EnableModule = EnableModule, DisableModule = DisableModule, IsEnabled = IsEnabled, SetDefaultModuleLibraries = SetDefaultModuleLibraries, SetDefaultModuleState = SetDefaultModuleState, SetDefaultModulePrototype = SetDefaultModulePrototype, SetEnabledState = SetEnabledState, IterateModules = IterateModules, IterateEmbeds = IterateEmbeds, GetName = GetName, } local function IsModule(self) return false end local pmixins = { defaultModuleState = true, enabledState = true, IsModule = IsModule, } -- Embed( target ) -- target (object) - target object to embed aceaddon in -- -- this is a local function specifically since it's meant to be only called internally function Embed(target, skipPMixins) for k, v in pairs(mixins) do target[k] = v end if not skipPMixins then for k, v in pairs(pmixins) do target[k] = target[k] or v end end end -- - Initialize the addon after creation. -- This function is only used internally during the ADDON_LOADED event -- It will call the **OnInitialize** function on the addon object (if present), -- and the **OnEmbedInitialize** function on all embeded libraries. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- @param addon addon object to intialize function AceAddon:InitializeAddon(addon) safecall(addon.OnInitialize, addon) local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedInitialize, lib, addon) end end -- we don't call InitializeAddon on modules specifically, this is handled -- from the event handler and only done _once_ end -- - Enable the addon after creation. -- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED, -- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons. -- It will call the **OnEnable** function on the addon object (if present), -- and the **OnEmbedEnable** function on all embeded libraries.\\ -- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- Use :Enable on the addon itself instead. -- @param addon addon object to enable function AceAddon:EnableAddon(addon) if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end if self.statuses[addon.name] or not addon.enabledState then return false end -- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable. self.statuses[addon.name] = true safecall(addon.OnEnable, addon) -- make sure we're still enabled before continueing if self.statuses[addon.name] then local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedEnable, lib, addon) end end -- enable possible modules. local modules = addon.orderedModules for i = 1, #modules do self:EnableAddon(modules[i]) end end return self.statuses[addon.name] -- return true if we're disabled end -- - Disable the addon -- Note: This function is only used internally. -- It will call the **OnDisable** function on the addon object (if present), -- and the **OnEmbedDisable** function on all embeded libraries.\\ -- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled. -- -- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing. -- Use :Disable on the addon itself instead. -- @param addon addon object to enable function AceAddon:DisableAddon(addon) if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end if not self.statuses[addon.name] then return false end -- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable. self.statuses[addon.name] = false safecall( addon.OnDisable, addon ) -- make sure we're still disabling... if not self.statuses[addon.name] then local embeds = self.embeds[addon] for i = 1, #embeds do local lib = LibStub:GetLibrary(embeds[i], true) if lib then safecall(lib.OnEmbedDisable, lib, addon) end end -- disable possible modules. local modules = addon.orderedModules for i = 1, #modules do self:DisableAddon(modules[i]) end end return not self.statuses[addon.name] -- return true if we're disabled end --- Get an iterator over all registered addons. -- @usage -- -- Print a list of all installed AceAddon's -- for name, addon in AceAddon:IterateAddons() do -- print("Addon: " .. name) -- end function AceAddon:IterateAddons() return pairs(self.addons) end --- Get an iterator over the internal status registry. -- @usage -- -- Print a list of all enabled addons -- for name, status in AceAddon:IterateAddonStatus() do -- if status then -- print("EnabledAddon: " .. name) -- end -- end function AceAddon:IterateAddonStatus() return pairs(self.statuses) end -- Following Iterators are deprecated, and their addon specific versions should be used -- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon) function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end -- Event Handling local function onEvent(this, event, arg1) -- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then -- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration while(#AceAddon.initializequeue > 0) do local addon = tremove(AceAddon.initializequeue, 1) -- this might be an issue with recursion - TODO: validate if event == "ADDON_LOADED" then addon.baseName = arg1 end AceAddon:InitializeAddon(addon) tinsert(AceAddon.enablequeue, addon) end if IsLoggedIn() then while(#AceAddon.enablequeue > 0) do local addon = tremove(AceAddon.enablequeue, 1) AceAddon:EnableAddon(addon) end end end end AceAddon.frame:RegisterEvent("ADDON_LOADED") AceAddon.frame:RegisterEvent("PLAYER_LOGIN") AceAddon.frame:SetScript("OnEvent", onEvent) -- upgrade embeded for name, addon in pairs(AceAddon.addons) do Embed(addon, true) end -- 2010-10-27 nevcairiel - add new "orderedModules" table if oldminor and oldminor < 10 then for name, addon in pairs(AceAddon.addons) do addon.orderedModules = {} for module_name, module in pairs(addon.modules) do tinsert(addon.orderedModules, module) end end end
mit
zaeem998/vtbot
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/abilities/pets/aero_ii.lua
6
1159
--------------------------------------------------- -- Aero 2 --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); require("/scripts/globals/magic"); --------------------------------------------------- function OnAbilityCheck(player, target, ability) return 0,0; end; function OnPetAbility(target, pet, skill) local spell = getSpell(155); --calculate raw damage local dmg = calculateMagicDamage(113,1,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); --get resist multiplier (1x if no resist) local resist = applyPlayerResistance(pet,-1,target,pet:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL, ELE_WIND); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = mobAddBonuses(pet,spell,target,dmg, 4); --add on TP bonuses local tp = pet:getTP(); if tp < 100 then tp = 100; end dmg = dmg * tp / 100; --add in final adjustments dmg = finalMagicAdjustments(pet,target,spell,dmg); return dmg; end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/globals/abilities/pets/healing_breath_i.lua
6
1272
--------------------------------------------------- -- Healing Breath I --------------------------------------------------- require("/scripts/globals/settings"); require("/scripts/globals/status"); require("/scripts/globals/monstertpmoves"); --------------------------------------------------- function OnAbilityCheck(player, target, ability) return 0,0; end; function OnPetAbility(target, pet, skill, master) -- TODO: Correct base value (45/256). See Healing Breath III for details. ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 0; if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then deep = 1+((master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25); pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST); end local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath local base = math.floor((45/256)*(1+(pet:getTP()/1024))*(pet:getHP())+42); if(target:getHP()+base > target:getMaxHP()) then base = target:getMaxHP() - target:getHP(); --cap it end skill:setMsg(MSG_SELF_HEAL); target:addHP(base); return base; end
gpl-3.0
gadLinux/thrift
test/lua/test_basic_server.lua
30
3451
-- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- http://www.apache.org/licenses/LICENSE-2.0 -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. require('ThriftTest_ThriftTest') require('TSocket') require('TBufferedTransport') require('TFramedTransport') require('THttpTransport') require('TCompactProtocol') require('TJsonProtocol') require('TBinaryProtocol') require('TServer') require('liblualongnumber') -------------------------------------------------------------------------------- -- Handler TestHandler = ThriftTestIface:new{} -- Stops the server function TestHandler:testVoid() end function TestHandler:testString(str) return str end function TestHandler:testBool(bool) return bool end function TestHandler:testByte(byte) return byte end function TestHandler:testI32(i32) return i32 end function TestHandler:testI64(i64) return i64 end function TestHandler:testDouble(d) return d end function TestHandler:testBinary(by) return by end function TestHandler:testStruct(thing) return thing end -------------------------------------------------------------------------------- -- Test local server function teardown() if server then server:close() end end function parseArgs(rawArgs) local opt = { protocol='binary', transport='buffered', port='9090', } for i, str in pairs(rawArgs) do if i > 0 then k, v = string.match(str, '--(%w+)=(%w+)') assert(opt[k] ~= nil, 'Unknown argument') opt[k] = v end end return opt end function testBasicServer(rawArgs) local opt = parseArgs(rawArgs) -- Handler & Processor local handler = TestHandler:new{} assert(handler, 'Failed to create handler') local processor = ThriftTestProcessor:new{ handler = handler } assert(processor, 'Failed to create processor') -- Server Socket local socket = TServerSocket:new{ port = opt.port } assert(socket, 'Failed to create server socket') -- Transport & Factory local transports = { buffered = TBufferedTransportFactory, framed = TFramedTransportFactory, http = THttpTransportFactory, } assert(transports[opt.transport], 'Failed to create framed transport factory') local trans_factory = transports[opt.transport]:new{} local protocols = { binary = TBinaryProtocolFactory, compact = TCompactProtocolFactory, json = TJSONProtocolFactory, } local prot_factory = protocols[opt.protocol]:new{} assert(prot_factory, 'Failed to create binary protocol factory') -- Simple Server server = TSimpleServer:new{ processor = processor, serverTransport = socket, transportFactory = trans_factory, protocolFactory = prot_factory } assert(server, 'Failed to create server') -- Serve server:serve() server = nil end testBasicServer(arg) teardown()
apache-2.0
subzrk/BadRotations
Libs/LibSpellRange-1.0/libs/LibStub/tests/test.lua
86
2013
debugstack = debug.traceback strmatch = string.match loadfile("../LibStub.lua")() local lib, oldMinor = LibStub:NewLibrary("Pants", 1) -- make a new thingy assert(lib) -- should return the library table assert(not oldMinor) -- should not return the old minor, since it didn't exist -- the following is to create data and then be able to check if the same data exists after the fact function lib:MyMethod() end local MyMethod = lib.MyMethod lib.MyTable = {} local MyTable = lib.MyTable local newLib, newOldMinor = LibStub:NewLibrary("Pants", 1) -- try to register a library with the same version, should silently fail assert(not newLib) -- should not return since out of date local newLib, newOldMinor = LibStub:NewLibrary("Pants", 0) -- try to register a library with a previous, should silently fail assert(not newLib) -- should not return since out of date local newLib, newOldMinor = LibStub:NewLibrary("Pants", 2) -- register a new version assert(newLib) -- library table assert(rawequal(newLib, lib)) -- should be the same reference as the previous assert(newOldMinor == 1) -- should return the minor version of the previous version assert(rawequal(lib.MyMethod, MyMethod)) -- verify that values were saved assert(rawequal(lib.MyTable, MyTable)) -- verify that values were saved local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 3 Blah") -- register a new version with a string minor version (instead of a number) assert(newLib) -- library table assert(newOldMinor == 2) -- previous version was 2 local newLib, newOldMinor = LibStub:NewLibrary("Pants", "Blah 4 and please ignore 15 Blah") -- register a new version with a string minor version (instead of a number) assert(newLib) assert(newOldMinor == 3) -- previous version was 3 (even though it gave a string) local newLib, newOldMinor = LibStub:NewLibrary("Pants", 5) -- register a new library, using a normal number instead of a string assert(newLib) assert(newOldMinor == 4) -- previous version was 4 (even though it gave a string)
gpl-3.0
soroushwilson/wilson1
plugins/help_fa.lua
1
3808
do function run(msg, matches) if msg.to.type == 'chat' and is_momod(msg) then return 'Tele soroush Command List'.. [[ 💙 ليست دستورات به زبان فارسي ❤️ 🔴 اخراج [کد،ايدي،ريپلی] 🔹شخص مورد نظر از گروه اخراج ميشود. 🔴 بن ‌[ايدي،کد،ريپلی] 🔹شخص مورد نظر از گروه محروم ميشود 🔴 حذف بن [کد،ايدي،ریپلی] 🔹شخص مورد نظر از محرومیت خارج ميشود 🔴 لیست بن 🔹ليست افرادي که از گروه محروم شده اند ➖➖➖➖➖➖➖ 🔴 قفل [نام|تگ|فحش|تبلیغات|ایموجی| 🔸ربات|عربی|اعضا|جوین|رسانه| 🔸چت|انگلیسی|حساسیت|فروارد| 🔸فیلم|گیف|صدا|عکس ها|مخاطب|پوکر] 🔹قفل کردن موارد مورد نظر ☜مثال: قفل نام 🔴 باز کردن [نام|فحش|تبلیغات|ایموجی| 🔸ربات|عربی|اعضا|عکس|جوین|رسانه| 🔸چت|تگ|انگلیسی|حساسیت|فروارد| 🔸فیلم|گیف|صدا|عکس ها|مخاطب|پوکر] 🔹باز کردن موارد قفل شده ☜مثال: باز کردن نام ➖➖➖➖➖➖➖ 🔴حساسیت 2-30 🔹تعیین مقدار حساسیت اسپم ☜مثال: حساسیت 5 ➖➖➖➖➖➖➖ 🔴 لیست فیلتر 🔹ليست کلمه هاي فيلتر شده 🔴 فيلتر + کلمه 🔹فيلتر کردن کلمه 🔴 فيلتر - کلمه 🔹ازاد کردن از فیلتر 🔴حذف لیست فیلتر 🔹پاک کردن تمام کلمات از لیست فیلتر ➖➖➖➖➖➖➖ 🔴 صاحب؟ 🔹نمايش آيدي مدير گروه 🔴 ليست مديران 🔹مشاهده ليست مدیران 🔴 افزودن مدير 🔹اضافه کردن مدير 🔴 حذف مدیر 🔹حذف کردن از مديریت ➖➖➖➖➖➖➖ 🔴 تغییر عکس 🔹عوض و قفل کردن عکس گروه 🔴تغییر نام (نام مورد نظر) 🔹تعويض نام گروه ➖➖➖➖➖➖➖ 🔴 توضيحات 🔹مشاهده توضيحات گروه 🔴 قوانين 🔹مشاهده قوانين گروه 🔴 ثبت توضیحات (متن) 🔹ثبت توضیحات جدید براي گروه 🔴ثبت قوانین (متن) 🔹ثبت قوانین جدید براي گروه ➖➖➖➖➖➖➖ 🔴 لينک جديد 🔹ساخت لينک جدید برای گروه 🔴 لينک 🔹دریافت لينک گروه 🔴 لينک خصوصي 🔹ارسال لينک در چت خصوصي ➖➖➖➖➖➖➖ 🔴 ايدی 🔹ايدي خود در گروه حتی با (ریپلی|یوزر) ➖➖➖➖➖➖➖ ⇦راهنمای فان مشاهده لیست دستورات سرگرمی به زبان فارسی ⇨!help برای مشاهده لیست دستورات به زبان انگلیسی ⇨!help در پیوی ربات این دستور را زده و از پیوی گروه را مدیریت کنید ➖➖➖➖➖➖➖ 1_برای ارسال نظر از دستور (ارسال نظر [متن]) استفاده کنيد مثال: ارسال نظر تست 2_برای عضويت در گروه پشتيبانی کلمه (ساپورت) را در پیوی ربات ارسال کنيد 3_برای دریافت لینک گروه پشتیبانی از دستور (لینک ساپورت) استفاده کنید 4_برای ادد شدن ربات سخنگو ما از دستور !kosgo استفاده کنید👌😂 ➖➖➖➖➖➖➖ Final Version Tele_soroush Sudo Users : 👤 soroush ]] end end return { description = "Robot About", usage = "help: View Robot About", patterns = { "^راهنما$" }, run = run } end
gpl-2.0
hacker44-h44/1104
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
sjznxd/luci-0.11-aa
modules/admin-full/luasrc/model/cbi/admin_network/ifaces.lua
5
13985
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008-2011 Jo-Philipp Wich <xm@subsignal.org> 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 $Id: ifaces.lua 9067 2012-08-17 08:24:24Z jow $ ]]-- local fs = require "nixio.fs" local ut = require "luci.util" local pt = require "luci.tools.proto" local nw = require "luci.model.network" local fw = require "luci.model.firewall" arg[1] = arg[1] or "" local has_dnsmasq = fs.access("/etc/config/dhcp") local has_firewall = fs.access("/etc/config/firewall") m = Map("network", translate("Interfaces") .. " - " .. arg[1]:upper(), translate("On this page you can configure the network interfaces. You can bridge several interfaces by ticking the \"bridge interfaces\" field and enter the names of several network interfaces separated by spaces. You can also use <abbr title=\"Virtual Local Area Network\">VLAN</abbr> notation <samp>INTERFACE.VLANNR</samp> (<abbr title=\"for example\">e.g.</abbr>: <samp>eth0.1</samp>).")) m:chain("wireless") if has_firewall then m:chain("firewall") end nw.init(m.uci) fw.init(m.uci) local net = nw:get_network(arg[1]) local function backup_ifnames(is_bridge) if not net:is_floating() and not m:get(net:name(), "_orig_ifname") then local ifcs = net:get_interfaces() or { net:get_interface() } if ifcs then local _, ifn local ifns = { } for _, ifn in ipairs(ifcs) do ifns[#ifns+1] = ifn:name() end if #ifns > 0 then m:set(net:name(), "_orig_ifname", table.concat(ifns, " ")) m:set(net:name(), "_orig_bridge", tostring(net:is_bridge())) end end end end -- redirect to overview page if network does not exist anymore (e.g. after a revert) if not net then luci.http.redirect(luci.dispatcher.build_url("admin/network/network")) return end -- protocol switch was requested, rebuild interface config and reload page if m:formvalue("cbid.network.%s._switch" % net:name()) then -- get new protocol local ptype = m:formvalue("cbid.network.%s.proto" % net:name()) or "-" local proto = nw:get_protocol(ptype, net:name()) if proto then -- backup default backup_ifnames() -- if current proto is not floating and target proto is not floating, -- then attempt to retain the ifnames --error(net:proto() .. " > " .. proto:proto()) if not net:is_floating() and not proto:is_floating() then -- if old proto is a bridge and new proto not, then clip the -- interface list to the first ifname only if net:is_bridge() and proto:is_virtual() then local _, ifn local first = true for _, ifn in ipairs(net:get_interfaces() or { net:get_interface() }) do if first then first = false else net:del_interface(ifn) end end m:del(net:name(), "type") end -- if the current proto is floating, the target proto not floating, -- then attempt to restore ifnames from backup elseif net:is_floating() and not proto:is_floating() then -- if we have backup data, then re-add all orphaned interfaces -- from it and restore the bridge choice local br = (m:get(net:name(), "_orig_bridge") == "true") local ifn local ifns = { } for ifn in ut.imatch(m:get(net:name(), "_orig_ifname")) do ifn = nw:get_interface(ifn) if ifn and not ifn:get_network() then proto:add_interface(ifn) if not br then break end end end if br then m:set(net:name(), "type", "bridge") end -- in all other cases clear the ifnames else local _, ifc for _, ifc in ipairs(net:get_interfaces() or { net:get_interface() }) do net:del_interface(ifc) end m:del(net:name(), "type") end -- clear options local k, v for k, v in pairs(m:get(net:name())) do if k:sub(1,1) ~= "." and k ~= "type" and k ~= "ifname" and k ~= "_orig_ifname" and k ~= "_orig_bridge" then m:del(net:name(), k) end end -- set proto m:set(net:name(), "proto", proto:proto()) m.uci:save("network") m.uci:save("wireless") -- reload page luci.http.redirect(luci.dispatcher.build_url("admin/network/network", arg[1])) return end end -- dhcp setup was requested, create section and reload page if m:formvalue("cbid.dhcp._enable._enable") then m.uci:section("dhcp", "dhcp", nil, { interface = arg[1], start = "100", limit = "150", leasetime = "12h" }) m.uci:save("dhcp") luci.http.redirect(luci.dispatcher.build_url("admin/network/network", arg[1])) return end local ifc = net:get_interface() s = m:section(NamedSection, arg[1], "interface", translate("Common Configuration")) s.addremove = false s:tab("general", translate("General Setup")) s:tab("advanced", translate("Advanced Settings")) s:tab("physical", translate("Physical Settings")) if has_firewall then s:tab("firewall", translate("Firewall Settings")) end st = s:taboption("general", DummyValue, "__status", translate("Status")) local function set_status() -- if current network is empty, print a warning if not net:is_floating() and net:is_empty() then st.template = "cbi/dvalue" st.network = nil st.value = translate("There is no device assigned yet, please attach a network device in the \"Physical Settings\" tab") else st.template = "admin_network/iface_status" st.network = arg[1] st.value = nil end end m.on_init = set_status m.on_after_save = set_status p = s:taboption("general", ListValue, "proto", translate("Protocol")) p.default = net:proto() if not net:is_installed() then p_install = s:taboption("general", Button, "_install") p_install.title = translate("Protocol support is not installed") p_install.inputtitle = translate("Install package %q" % net:opkg_package()) p_install.inputstyle = "apply" p_install:depends("proto", net:proto()) function p_install.write() return luci.http.redirect( luci.dispatcher.build_url("admin/system/packages") .. "?submit=1&install=%s" % net:opkg_package() ) end end p_switch = s:taboption("general", Button, "_switch") p_switch.title = translate("Really switch protocol?") p_switch.inputtitle = translate("Switch protocol") p_switch.inputstyle = "apply" local _, pr for _, pr in ipairs(nw:get_protocols()) do p:value(pr:proto(), pr:get_i18n()) if pr:proto() ~= net:proto() then p_switch:depends("proto", pr:proto()) end end auto = s:taboption("advanced", Flag, "auto", translate("Bring up on boot")) auto.default = (net:proto() == "none") and auto.disabled or auto.enabled if not net:is_virtual() then br = s:taboption("physical", Flag, "type", translate("Bridge interfaces"), translate("creates a bridge over specified interface(s)")) br.enabled = "bridge" br.rmempty = true br:depends("proto", "static") br:depends("proto", "dhcp") br:depends("proto", "none") stp = s:taboption("physical", Flag, "stp", translate("Enable <abbr title=\"Spanning Tree Protocol\">STP</abbr>"), translate("Enables the Spanning Tree Protocol on this bridge")) stp:depends("type", "bridge") stp.rmempty = true end if not net:is_floating() then ifname_single = s:taboption("physical", Value, "ifname_single", translate("Interface")) ifname_single.template = "cbi/network_ifacelist" ifname_single.widget = "radio" ifname_single.nobridges = true ifname_single.rmempty = false ifname_single.network = arg[1] ifname_single:depends("type", "") function ifname_single.cfgvalue(self, s) -- let the template figure out the related ifaces through the network model return nil end function ifname_single.write(self, s, val) local i local new_ifs = { } local old_ifs = { } for _, i in ipairs(net:get_interfaces() or { net:get_interface() }) do old_ifs[#old_ifs+1] = i:name() end for i in ut.imatch(val) do new_ifs[#new_ifs+1] = i -- if this is not a bridge, only assign first interface if self.option == "ifname_single" then break end end table.sort(old_ifs) table.sort(new_ifs) for i = 1, math.max(#old_ifs, #new_ifs) do if old_ifs[i] ~= new_ifs[i] then backup_ifnames() for i = 1, #old_ifs do net:del_interface(old_ifs[i]) end for i = 1, #new_ifs do net:add_interface(new_ifs[i]) end break end end end end if not net:is_virtual() then ifname_multi = s:taboption("physical", Value, "ifname_multi", translate("Interface")) ifname_multi.template = "cbi/network_ifacelist" ifname_multi.nobridges = true ifname_multi.rmempty = false ifname_multi.network = arg[1] ifname_multi.widget = "checkbox" ifname_multi:depends("type", "bridge") ifname_multi.cfgvalue = ifname_single.cfgvalue ifname_multi.write = ifname_single.write end if has_firewall then fwzone = s:taboption("firewall", Value, "_fwzone", translate("Create / Assign firewall-zone"), translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it.")) fwzone.template = "cbi/firewall_zonelist" fwzone.network = arg[1] fwzone.rmempty = false function fwzone.cfgvalue(self, section) self.iface = section local z = fw:get_zone_by_network(section) return z and z:name() end function fwzone.write(self, section, value) local zone = fw:get_zone(value) if not zone and value == '-' then value = m:formvalue(self:cbid(section) .. ".newzone") if value and #value > 0 then zone = fw:add_zone(value) else fw:del_network(section) end end if zone then fw:del_network(section) zone:add_network(section) end end end function p.write() end function p.remove() end function p.validate(self, value, section) if value == net:proto() then if not net:is_floating() and net:is_empty() then local ifn = ((br and (br:formvalue(section) == "bridge")) and ifname_multi:formvalue(section) or ifname_single:formvalue(section)) for ifn in ut.imatch(ifn) do return value end return nil, translate("The selected protocol needs a device assigned") end end return value end local form, ferr = loadfile( ut.libpath() .. "/model/cbi/admin_network/proto_%s.lua" % net:proto() ) if not form then s:taboption("general", DummyValue, "_error", translate("Missing protocol extension for proto %q" % net:proto()) ).value = ferr else setfenv(form, getfenv(1))(m, s, net) end local _, field for _, field in ipairs(s.children) do if field ~= st and field ~= p and field ~= p_install and field ~= p_switch then if next(field.deps) then local _, dep for _, dep in ipairs(field.deps) do dep.deps.proto = net:proto() end else field:depends("proto", net:proto()) end end end -- -- Display DNS settings if dnsmasq is available -- if has_dnsmasq and net:proto() == "static" then m2 = Map("dhcp", "", "") local has_section = false m2.uci:foreach("dhcp", "dhcp", function(s) if s.interface == arg[1] then has_section = true return false end end) if not has_section then s = m2:section(TypedSection, "dhcp", translate("DHCP Server")) s.anonymous = true s.cfgsections = function() return { "_enable" } end x = s:option(Button, "_enable") x.title = translate("No DHCP Server configured for this interface") x.inputtitle = translate("Setup DHCP Server") x.inputstyle = "apply" else s = m2:section(TypedSection, "dhcp", translate("DHCP Server")) s.addremove = false s.anonymous = true s:tab("general", translate("General Setup")) s:tab("advanced", translate("Advanced Settings")) function s.filter(self, section) return m2.uci:get("dhcp", section, "interface") == arg[1] end local ignore = s:taboption("general", Flag, "ignore", translate("Ignore interface"), translate("Disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " .. "this interface.")) local start = s:taboption("general", Value, "start", translate("Start"), translate("Lowest leased address as offset from the network address.")) start.optional = true start.datatype = "or(uinteger,ip4addr)" start.default = "100" local limit = s:taboption("general", Value, "limit", translate("Limit"), translate("Maximum number of leased addresses.")) limit.optional = true limit.datatype = "uinteger" limit.default = "150" local ltime = s:taboption("general", Value, "leasetime", translate("Leasetime"), translate("Expiry time of leased addresses, minimum is 2 Minutes (<code>2m</code>).")) ltime.rmempty = true ltime.default = "12h" local dd = s:taboption("advanced", Flag, "dynamicdhcp", translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"), translate("Dynamically allocate DHCP addresses for clients. If disabled, only " .. "clients having static leases will be served.")) dd.default = dd.enabled s:taboption("advanced", Flag, "force", translate("Force"), translate("Force DHCP on this network even if another server is detected.")) -- XXX: is this actually useful? --s:taboption("advanced", Value, "name", translate("Name"), -- translate("Define a name for this network.")) mask = s:taboption("advanced", Value, "netmask", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"), translate("Override the netmask sent to clients. Normally it is calculated " .. "from the subnet that is served.")) mask.optional = true mask.datatype = "ip4addr" s:taboption("advanced", DynamicList, "dhcp_option", translate("DHCP-Options"), translate("Define additional DHCP options, for example \"<code>6,192.168.2.1," .. "192.168.2.2</code>\" which advertises different DNS servers to clients.")) for i, n in ipairs(s.children) do if n ~= ignore then n:depends("ignore", "") end end end end return m, m2
apache-2.0
vietlq/luasocket
etc/forward.lua
61
2077
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if table.getn(arg) < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
mit
VideahGams/NumberFucker3DS
game/main.lua
1
7243
local board = {} local size_w = 3 local size_h = 3 local n local min, max = 1, 9 local gameover = false local biggest_x, biggest_y local bigfont = love.graphics.newFont("Junction-bold.ttf", 54) local smallfont = love.graphics.newFont("Junction-bold.ttf", 32) local anim_from_x, anim_from_y local anim_to_x, anim_to_y local anim_from, anim_to local anim_dt = 0 local anim_time = 0.35 local anim_after math.randomseed(os.time()) -- tweening functions local function inBack(a, b, t) if not s then s = 1.70158 end return (b - a) * t * t * ((s + 1) * t - s) + a end local function lerp(a, b, t) return (1 - t) * a + t * b end local function lerp2(a, b, t) return a + (b - a) * t end local function cerp(a, b, t) local f = (1 - math.cos(t * math.pi)) * 0.5 return a * (1 - f) + b * f end local function getTileColor(n) local a = 60 return 255, 255, 255, a end local function generate() n = math.random(min, max) biggest_x, biggest_y = nil, nil gameover = false for i = 1, size_h do board[i] = {} for j = 1, size_w do board[i][j] = 0 end end end local function getField(x, y) x = x - 50 y = y + 20 x = math.floor((x - 4) / (64 + 4)) + 1 y = math.floor((y - 4 - 40) / (64 + 4)) + 1 print(x) return x, y end local update local function launchAnim(x1, y1, x2, y2, from, to) anim_from_x, anim_from_y = x2, y2 anim_to_x, anim_to_y = x1, y1 anim_from, anim_to = from, to anim_dt = 0 end local function merge(x1, y1, x2, y2) launchAnim(x1, y1, x2, y2, board[y2][x2], board[y1][x1]) board[y1][x1] = board[y1][x1] + board[y2][x2] board[y2][x2] = 0 anim_after = function() update(x1, y1) end end function update(x, y) if not biggest_x and not biggest_y then biggest_x, biggest_y = 1, 1 end -- finds biggest for y, row in ipairs(board) do for x, field in ipairs(row) do if field > board[biggest_y][biggest_x] then biggest_x, biggest_y = x, y end end end -- find the biggest block around local maxval, maxx, maxy = math.huge local minval, minx, miny = 0 for _, v in ipairs({{x - 1, y}, {x + 1, y}, {x, y - 1}, {x, y + 1}}) do local i, j = unpack(v) if board[j] and board[j][i] and board[j][i] ~= 0 then if board[j][i] < maxval and (board[j][i] % board[y][x]) == 0 then maxval, maxx, maxy = board[j][i], i, j end end end if maxval ~= math.huge then merge(maxx, maxy, x, y) end -- check if the board is all filled local occupied = 0 for y, row in ipairs(board) do for x, field in ipairs(row) do if field ~= 0 then occupied = occupied + 1 end end end if occupied == size_w * size_h then gameover = true end end local function place(x, y) if anim_from_x and anim_dt < anim_time then return end -- disable when the animation is running so can't bug combos if not board[y] or not board[y][x] then return end if not (board[y] and board[y][x] and board[y][x] ~= 0) then board[y][x] = n else return end n = math.random(min, max) update(x, y) end function love.load() io.stdout:setvbuf("no") generate() end function love.draw() love.graphics.setScreen('top') local w, h = love.graphics.getWidth(), love.graphics.getHeight() love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", 0, 0, w, h) love.graphics.setColor(255, 255, 255, 60) love.graphics.rectangle("fill", 0, 0, w, h) local font = bigfont local text = gameover and ("SCORE: " .. board[biggest_y][biggest_x]) or tostring(n) love.graphics.setFont(font) love.graphics.setColor(255, 255, 255, 255) love.graphics.print(text, (w - font:getWidth(text)) / 2, (h / 2) - (font:getHeight() / 2)) love.graphics.setScreen('bottom') love.graphics.push() love.graphics.translate(50, -20) for y, row in ipairs(board) do for x, field in ipairs(row) do if anim_from_x == x and anim_from_y == y and anim_dt < anim_time then field = 0 end if field == 0 then love.graphics.setColor(255, 255, 255, 30) else love.graphics.setColor(getTileColor(field)) end if x == biggest_x and y == biggest_y then love.graphics.setColor(255, 255, 255, 255) end local rx, ry = 4 + (x - 1) * (64 + 4), 4 + (y - 1) * (64 + 4) + 40 love.graphics.rectangle("fill", rx, ry, 64, 64) if x == biggest_x and y == biggest_y then love.graphics.setColor(0, 0, 0) else love.graphics.setColor(255, 255, 255, 255) end if field ~= 0 then local font = smallfont local text = tostring(field) love.graphics.setFont(smallfont) love.graphics.print(text, rx + (64 - font:getWidth(text)) / 2, ry + (64 - font:getHeight()) / 2) end end end -- anim around the biggest if biggest_x then local rx, ry = 4 + (biggest_x - 1) * (64 + 4), 4 + (biggest_y - 1) * (64 + 4) + 40 love.graphics.setColor(255, 255, 255, 15) --love.graphics.circle("fill", rx + 64 / 2, ry + 64 / 2, 48 + math.cos(love.timer.getTime() * 2) * 8) end -- animations if anim_from_x and anim_dt < anim_time then -- draw the TO field local x, y = anim_to_x, anim_to_y local rx, ry = 4 + (x - 1) * (64 + 4), 4 + (y - 1) * (64 + 4) + 40 -- under the transparent tile love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", rx, ry, 64, 64) love.graphics.setColor(getTileColor(anim_to)) if x == biggest_x and y == biggest_y then love.graphics.setColor(255, 255, 255) end love.graphics.rectangle("fill", rx, ry, 64, 64) if x == biggest_x and y == biggest_y then love.graphics.setColor(0, 0, 0) else love.graphics.setColor(255, 255, 255) end local font = smallfont local text = tostring(anim_to) love.graphics.setFont(smallfont) love.graphics.print(text, rx + (64 - font:getWidth(text)) / 2, ry + (64 - font:getHeight()) / 2) -- draw the flying tile local x = inBack(anim_from_x, anim_to_x, anim_dt / anim_time) local y = inBack(anim_from_y, anim_to_y, anim_dt / anim_time) local rx, ry = 4 + (x - 1) * (64 + 4), 4 + (y - 1) * (64 + 4) + 40 love.graphics.setColor(0, 0, 0) love.graphics.rectangle("fill", rx, ry, 64, 64) love.graphics.setColor(getTileColor(anim_from)) if anim_to_x == biggest_x and anim_to_y == biggest_y then love.graphics.setColor(255, 255, 255) end love.graphics.rectangle("fill", rx, ry, 64, 64) if anim_to_x == biggest_x and anim_to_y == biggest_y then love.graphics.setColor(0, 0, 0) else love.graphics.setColor(255, 255, 255) end local font = smallfont local text = tostring(anim_from) love.graphics.setFont(smallfont) love.graphics.print(text, rx + (64 - font:getWidth(text)) / 2, ry + (64 - font:getHeight()) / 2) end love.graphics.pop() end function love.update(dt) if love.keyboard.isDown('start') then love.event.quit() end anim_dt = anim_dt + dt if anim_dt - dt < anim_time and anim_dt > anim_time and anim_after then anim_after() end end function love.mousepressed(x, y, button) if gameover then generate() return end local x, y = getField(x, y) place(x, y) end
mit
TW1STaL1CKY/pac3
lua/pac3/core/client/parts/gesture.lua
2
2749
local PART = {} PART.ClassName = "gesture" PART.NonPhysical = true PART.ThinkTime = 0 PART.Group = 'entity' PART.Icon = 'icon16/thumb_up.png' pac.StartStorableVars() pac.GetSet(PART, "Loop", false) pac.GetSet(PART, "GestureName", "", {editor_panel = "sequence"}) pac.GetSet(PART, "SlotName", "attackreload", {enums = function(part) return part.ValidGestureSlots end}) pac.GetSet(PART, "SlotWeight", 1) pac.EndStorableVars() PART.random_gestlist = {} PART.ValidGestureSlots = { attackreload = GESTURE_SLOT_ATTACK_AND_RELOAD, grenade = GESTURE_SLOT_GRENADE, jump = GESTURE_SLOT_JUMP, swim = GESTURE_SLOT_SWIM, flinch = GESTURE_SLOT_FLINCH, vcd = GESTURE_SLOT_VCD, custom = GESTURE_SLOT_CUSTOM } function PART:GetOwner() return self.BaseClass.GetOwner(self) -- until gesture functions for non-players end function PART:GetSequenceList() local ent = self:GetOwner() if ent:IsValid() then return ent:GetSequenceList() end return {"none"} end function PART:GetSlotID() return self.ValidGestureSlots[self.SlotName] or GESTURE_SLOT_CUSTOM end function PART:SetLoop(bool) self.Loop = bool if not self:IsHidden() then self:OnShow() end end function PART:SetGestureName(name) self.GestureName = name local list = name:Split(";") for k,v in next,list do if v:Trim() == "" then list[k] = nil end end self.random_gestlist = list if not self:IsHidden() then self:OnShow() end end function PART:SetSlotName(name) local ent = self:GetOwner() if ent:IsValid() and ent:IsPlayer() then -- to stop gestures getting stuck for _, v in next,self.ValidGestureSlots do ent:AnimResetGestureSlot(v) end end self.SlotName = name if not self:IsHidden() then self:OnShow() end end function PART:SetSlotWeight(num) local ent = self:GetOwner() if ent:IsValid() and ent:IsPlayer() then ent:AnimSetGestureWeight(self:GetSlotID(), num) end self.SlotWeight = num end function PART:OnShow() local ent = self:GetOwner() if ent:IsValid() and ent:IsPlayer() then -- function is for players only :( local gesture = self.random_gestlist and table.Random(self.random_gestlist) or self.GestureName local slot = self:GetSlotID() ent:AnimResetGestureSlot(slot) local act = ent:GetSequenceActivity(ent:LookupSequence(gesture)) if act ~= 1 then ent:AnimRestartGesture(slot, act, not self.Loop) end ent:AnimSetGestureWeight(slot, self.SlotWeight or 1) end end function PART:OnHide() local ent = self:GetOwner() if ent:IsValid() and ent:IsPlayer() and self.Loop then ent:AnimResetGestureSlot(self:GetSlotID()) end end PART.OnRemove = PART.OnHide pac.RegisterPart(PART)
gpl-3.0
adamsumm/SMBRNN
Torch/model/RNN.lua
6
1135
local RNN = {} function RNN.rnn(input_size, rnn_size, n, dropout) -- there are n+1 inputs (hiddens on each layer and x) local inputs = {} table.insert(inputs, nn.Identity()()) -- x for L = 1,n do table.insert(inputs, nn.Identity()()) -- prev_h[L] end local x, input_size_L local outputs = {} for L = 1,n do local prev_h = inputs[L+1] if L == 1 then x = OneHot(input_size)(inputs[1]) input_size_L = input_size else x = outputs[(L-1)] if dropout > 0 then x = nn.Dropout(dropout)(x) end -- apply dropout, if any input_size_L = rnn_size end -- RNN tick local i2h = nn.Linear(input_size_L, rnn_size)(x) local h2h = nn.Linear(rnn_size, rnn_size)(prev_h) local next_h = nn.Tanh()(nn.CAddTable(){i2h, h2h}) table.insert(outputs, next_h) end -- set up the decoder local top_h = outputs[#outputs] if dropout > 0 then top_h = nn.Dropout(dropout)(top_h) end local proj = nn.Linear(rnn_size, input_size)(top_h) local logsoft = nn.LogSoftMax()(proj) table.insert(outputs, logsoft) return nn.gModule(inputs, outputs) end return RNN
mit
peval/Atlas
lib/load-multi.lua
39
13282
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --- --[[ (Not so) simple example of a run-time module loader for MySQL Proxy Usage: 1. load this module in the Proxy. 2. From a client, run the command PLOAD name_of_script and you can use the features implemented in the new script immediately. 3. Successive calls to PLOAD will load a new one. 4. Previous scripts will still be active, and the loader will use all of them in sequence to see if one handles the request 5. CAVEAT. If your script has a read_query function that *always* returns a non null value (e.g. a logging feature) then other modules, although loaded, are not used. If you have any such modules, you must load them at the end of the sequence. 6. to remove a module, use UNLOAD module_name IMPORTANT NOTICE: the proxy will try to load the file in the directory where the proxy (NOT THE CLIENT) was started. To use modules not in such directory, you need to specify an absolute path. --]] local VERSION = '0.1.3' local DEBUG = os.getenv('DEBUG') or 0 DEBUG = DEBUG + 0 --- -- print_debug() -- conditionally print a message -- function proxy.global.print_debug (msg) if DEBUG > 0 then print(msg) end end --- -- Handlers for MySQL Proxy hooks -- Initially, they are void. -- If the loaded module has implemented any -- functions, they are associated with these handlers -- if proxy.global.loaded_handlers == nil then proxy.global.loaded_handlers = { rq = {}, rqr = {}, dc = {}, cs = {}, rh = {}, ra = {}, rar = {}, } end --- -- list of functions loaded from user modules -- if proxy.global.handled_function == nil then proxy.global.handled_functions = { rq = 'read_query', rqr = 'read_query_result', cs = 'connect_server', rh = 'read_handshake', ra = 'read_auth', rar = 'read_auth_result', dc = 'disconnect_client', } end if proxy.global.handler_status == nil then proxy.global.handler_status = {} end local funcs_to_create = { cs = 0, ra = 1, rar = 1, rh = 1, dc = 0, } --- -- creates the hooks for Proxy handled functions -- for id, has_param in pairs(funcs_to_create) do local parameter = has_param == 1 and 'myarg' or '' local fstr = string.format( [[ function %s(%s) if #proxy.global.loaded_handlers['%s'] then for i, h in pairs(proxy.global.loaded_handlers['%s']) do if h then proxy.global.print_debug ( 'handling "%s" using ' .. h.name) local result = h.handler(%s) if result then return result end end end end -- return end ]], proxy.global.handled_functions[id], parameter, id, id, proxy.global.handled_functions[id], parameter ) proxy.global.print_debug ('creating function ' .. proxy.global.handled_functions[id]) assert(loadstring(fstr))() end --- -- an error string to describe the error occurring -- local load_multi_error_str = '' --- -- set_error() -- -- sets the error string -- -- @param msg the message to be assigned to the error string -- function set_error(msg) load_multi_error_str = msg proxy.global.print_debug (msg) return nil end --- -- file_exists() -- -- checks if a file exists -- -- @param fname the file name -- function file_exists(fname) local fh=io.open( fname, 'r') if fh then fh:close() return true else return false end end local module_counter = 0 --- -- get_module() -- -- This function scans an existing lua file, and turns it into -- a closure exporting two function handlers, one for -- read_query() and one for read_query_result(). -- If the input script does not contain the above functions, -- get_module fails. -- -- @param module_name the name of the existing script -- function get_module(module_name) -- -- assumes success -- load_multi_error_str = '' -- -- the module is copied to a temporary file -- on a given directory -- module_counter = module_counter + 1 local new_module = 'tmpmodule' .. module_counter local tmp_dir = '/tmp/' local new_filename = tmp_dir .. new_module .. '.lua' local source_script = module_name if not source_script:match('.lua$') then source_script = source_script .. '.lua' end -- -- if the new module does not exist -- an error is returned -- if not file_exists(source_script) then set_error('file not found ' .. source_script) return end -- -- if the module directory is not on the search path, -- we need to add it -- if not package.path:match(tmp_dir) then package.path = tmp_dir .. '?.lua;' .. package.path end -- -- Make sure that the module is not loaded. -- If we don't remove it from the list of loaded modules, -- subsequent load attempts will silently fail -- package.loaded[new_module] = nil local ofh = io.open(new_filename, 'w') -- -- Writing to the new package, starting with the -- header and the wrapper function -- ofh:write( string.format( "module('%s', package.seeall)\n" .. "function make_funcs()\n" , new_module) ) local found_funcs = {} -- -- Copying contents from the original script -- to the new module, and checking for the existence -- of the handler functions -- for line in io.lines(source_script) do ofh:write(line .. "\n") for i,v in pairs(proxy.global.handled_functions) do if line:match('^%s*function%s+' ..v .. '%s*%(') then found_funcs[i] = v break end end end -- -- closing the wrapper on the new module -- local return_value = '' for i,v in pairs(found_funcs) do return_value = return_value .. i .. ' = ' .. v .. ', ' end ofh:write( 'return { ' .. return_value .. '}\n' .. 'end\n' ) ofh:close() -- -- Final check. If the handlers were not found, the load fails -- -- if (found_one == false ) then set_error('script ' .. source_script .. ' does not contain a proxy handled function') return end -- -- All set. The new module is loaded -- with a new function that will return the handlers -- local result = require(new_module) os.remove(new_filename) return result end --- -- simple_dataset() -- -- returns a dataset made of a header and a message -- -- @param header the column name -- @param message the contents of the column function proxy.global.simple_dataset (header, message) proxy.response.type = proxy.MYSQLD_PACKET_OK proxy.response.resultset = { fields = {{type = proxy.MYSQL_TYPE_STRING, name = header}}, rows = { { message} } } return proxy.PROXY_SEND_RESULT end --- -- make_regexp_from_command() -- -- creates a regular expression for fast scanning of the command -- -- @param cmd the command to be converted to regexp -- function proxy.global.make_regexp_from_command(cmd, options) local regexp= '^%s*'; for ch in cmd:gmatch('(.)') do regexp = regexp .. '[' .. ch:upper() .. ch:lower() .. ']' end if options and options.capture then regexp = regexp .. '%s+(%S+)' end return regexp end -- -- The default command for loading a new module is PLOAD -- You may change it through an environment variable -- local proxy_load_command = os.getenv('PLOAD') or 'pload' local proxy_unload_command = os.getenv('PUNLOAD') or 'punload' local proxy_help_command = os.getenv('PLOAD_HELP') or 'pload_help' local currently_using = 0 local pload_regexp = proxy.global.make_regexp_from_command(proxy_load_command, {capture = 1}) local punload_regexp = proxy.global.make_regexp_from_command(proxy_unload_command,{ capture = 1} ) local pload_help_regexp = proxy.global.make_regexp_from_command(proxy_help_command,{ capture = nil} ) local pload_help_dataset = { {proxy_load_command .. ' module_name', 'loads a given module'}, {proxy_unload_command .. 'module_name', 'unloads and existing module'}, {proxy_help_command, 'shows this help'}, } --- -- removes a module from the loaded list -- function remove_module (module_name) local found_module = false local to_delete = { loaded = {}, status = {} } for i,lmodule in pairs(proxy.global.handler_status) do if i == module_name then found_module = true local counter = 0 for j,h in pairs(lmodule) do -- proxy.global.print_debug('removing '.. module_name .. ' (' .. i ..') ' .. h.id .. ' -> ' .. h.ndx ) to_delete['loaded'][h.id] = h.ndx counter = counter + 1 to_delete['status'][i] = counter end end end for i,v in pairs (to_delete['loaded']) do table.remove(proxy.global.loaded_handlers[i], v) end for i,v in pairs (to_delete['status']) do table.remove(proxy.global.handler_status[i], v) end if found_module == false then return proxy.global.simple_dataset(module_name, 'NOT FOUND') end return proxy.global.simple_dataset(module_name, 'unloaded') end --- -- creates a dataset from a list of header names -- and a list of rows -- @param header a list of field names -- @param dataset a list of row contents function proxy.global.make_dataset (header, dataset) proxy.response.type = proxy.MYSQLD_PACKET_OK proxy.response.resultset = { fields = {}, rows = {} } for i,v in pairs (header) do table.insert(proxy.response.resultset.fields, {type = proxy.MYSQL_TYPE_STRING, name = v}) end for i,v in pairs (dataset) do table.insert(proxy.response.resultset.rows, v ) end return proxy.PROXY_SEND_RESULT end -- -- This function is called at each query. -- The request for loading a new script is handled here -- function read_query (packet) currently_using = 0 if packet:byte() ~= proxy.COM_QUERY then return end local query = packet:sub(2) -- Checks if a PLOAD command was issued. -- A regular expresion check is faster than -- doing a full tokenization. (Especially on large queries) -- if (query:match(pload_help_regexp)) then return proxy.global.make_dataset({'command','description'}, pload_help_dataset) end local unload_module = query:match(punload_regexp) if (unload_module) then return remove_module(unload_module) end local new_module = query:match(pload_regexp) if (new_module) then --[[ If a request for loading is received, then we attempt to load the new module using the get_module() function --]] local new_tablespace = get_module(new_module) if (new_tablespace) then local handlers = new_tablespace.make_funcs() -- -- The new module must have at least handlers for read_query() -- or disconnect_client. read_query_result() is optional. -- The loading function returns nil if no handlers were found -- proxy.global.print_debug('') proxy.global.handler_status[new_module] = {} for i,v in pairs( proxy.global.handled_functions) do local handler_str = type(handlers[i]) proxy.global.print_debug (i .. ' ' .. handler_str ) if handlers[i] then table.insert(proxy.global.loaded_handlers[i] , { name = new_module, handler = handlers[i]} ) table.insert(proxy.global.handler_status[new_module], { func = proxy.global.handled_functions[i], id=i, ndx = #proxy.global.loaded_handlers[i] }) end end if handlers['rqr'] and not handlers['rq'] then table.insert(proxy.global.loaded_handlers['rq'] , nil ) end if handlers['rq'] and not handlers['rqr'] then table.insert(proxy.global.loaded_handlers['rqr'] , nil ) end -- -- Returns a confirmation that a new module was loaded -- return proxy.global.simple_dataset('info', 'module "' .. new_module .. '" loaded' ) else -- -- The load was not successful. -- Inform the user -- return proxy.global.simple_dataset('ERROR', 'load of "' .. new_module .. '" failed (' .. load_multi_error_str .. ')' ) end end -- -- If a handler was installed from a new module, it is called -- now. -- if #proxy.global.loaded_handlers['rq'] then for i,rqh in pairs(proxy.global.loaded_handlers['rq']) do proxy.global.print_debug ( 'handling "read_query" using ' .. i .. ' -> ' .. rqh.name) local result = rqh.handler(packet) if (result) then currently_using = i return result end end end end -- -- this function is called every time a result set is -- returned after an injected query -- function read_query_result(inj) -- -- If the dynamically loaded module had an handler for read_query_result() -- it is called now -- local rqrh = proxy.global.loaded_handlers['rqr'][currently_using] if rqrh then proxy.global.print_debug ( 'handling "read_query_result" using ' .. currently_using .. ' -> ' .. rqrh.name) local result = rqrh.handler(inj) if result then return result end end end
gpl-2.0
teahouse/FWServer
skynet/3rd/lpeg/re.lua
160
6286
-- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $ -- imported functions and modules local tonumber, type, print, error = tonumber, type, print, error local setmetatable = setmetatable local m = require"lpeg" -- 'm' will be used to parse expressions, and 'mm' will be used to -- create expressions; that is, 're' runs on 'm', creating patterns -- on 'mm' local mm = m -- pattern's metatable local mt = getmetatable(mm.P(0)) -- No more global accesses after this point local version = _VERSION if version == "Lua 5.2" then _ENV = nil end local any = m.P(1) -- Pre-defined names local Predef = { nl = m.P"\n" } local mem local fmem local gmem local function updatelocale () mm.locale(Predef) Predef.a = Predef.alpha Predef.c = Predef.cntrl Predef.d = Predef.digit Predef.g = Predef.graph Predef.l = Predef.lower Predef.p = Predef.punct Predef.s = Predef.space Predef.u = Predef.upper Predef.w = Predef.alnum Predef.x = Predef.xdigit Predef.A = any - Predef.a Predef.C = any - Predef.c Predef.D = any - Predef.d Predef.G = any - Predef.g Predef.L = any - Predef.l Predef.P = any - Predef.p Predef.S = any - Predef.s Predef.U = any - Predef.u Predef.W = any - Predef.w Predef.X = any - Predef.x mem = {} -- restart memoization fmem = {} gmem = {} local mt = {__mode = "v"} setmetatable(mem, mt) setmetatable(fmem, mt) setmetatable(gmem, mt) end updatelocale() local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end) local function getdef (id, defs) local c = defs and defs[id] if not c then error("undefined name: " .. id) end return c end local function patt_error (s, i) local msg = (#s < i + 20) and s:sub(i) or s:sub(i,i+20) .. "..." msg = ("pattern error near '%s'"):format(msg) error(msg, 2) end local function mult (p, n) local np = mm.P(true) while n >= 1 do if n%2 >= 1 then np = np * p end p = p * p n = n/2 end return np end local function equalcap (s, i, c) if type(c) ~= "string" then return nil end local e = #c + i if s:sub(i, e - 1) == c then return e else return nil end end local S = (Predef.space + "--" * (any - Predef.nl)^0)^0 local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0 local arrow = S * "<-" local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1 name = m.C(name) -- a defined name only have meaning in a given environment local Def = name * m.Carg(1) local num = m.C(m.R"09"^1) * S / tonumber local String = "'" * m.C((any - "'")^0) * "'" + '"' * m.C((any - '"')^0) * '"' local defined = "%" * Def / function (c,Defs) local cat = Defs and Defs[c] or Predef[c] if not cat then error ("name '" .. c .. "' undefined") end return cat end local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R local item = defined + Range + m.C(any) local Class = "[" * (m.C(m.P"^"^-1)) -- optional complement symbol * m.Cf(item * (item - "]")^0, mt.__add) / function (c, p) return c == "^" and any - p or p end * "]" local function adddef (t, k, exp) if t[k] then error("'"..k.."' already defined as a rule") else t[k] = exp end return t end local function firstdef (n, r) return adddef({n}, n, r) end local function NT (n, b) if not b then error("rule '"..n.."' used outside a grammar") else return mm.V(n) end end local exp = m.P{ "Exp", Exp = S * ( m.V"Grammar" + m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) ); Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul) * (#seq_follow + patt_error); Prefix = "&" * S * m.V"Prefix" / mt.__len + "!" * S * m.V"Prefix" / mt.__unm + m.V"Suffix"; Suffix = m.Cf(m.V"Primary" * S * ( ( m.P"+" * m.Cc(1, mt.__pow) + m.P"*" * m.Cc(0, mt.__pow) + m.P"?" * m.Cc(-1, mt.__pow) + "^" * ( m.Cg(num * m.Cc(mult)) + m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow)) ) + "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div)) + m.P"{}" * m.Cc(nil, m.Ct) + m.Cg(Def / getdef * m.Cc(mt.__div)) ) + "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt)) ) * S )^0, function (a,b,f) return f(a,b) end ); Primary = "(" * m.V"Exp" * ")" + String / mm.P + Class + defined + "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" / function (n, p) return mm.Cg(p, n) end + "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end + m.P"{}" / mm.Cp + "{~" * m.V"Exp" * "~}" / mm.Cs + "{|" * m.V"Exp" * "|}" / mm.Ct + "{" * m.V"Exp" * "}" / mm.C + m.P"." * m.Cc(any) + (name * -arrow + "<" * name * ">") * m.Cb("G") / NT; Definition = name * arrow * m.V"Exp"; Grammar = m.Cg(m.Cc(true), "G") * m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0, adddef) / mm.P } local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error) local function compile (p, defs) if mm.type(p) == "pattern" then return p end -- already compiled local cp = pattern:match(p, 1, defs) if not cp then error("incorrect pattern", 3) end return cp end local function match (s, p, i) local cp = mem[p] if not cp then cp = compile(p) mem[p] = cp end return cp:match(s, i or 1) end local function find (s, p, i) local cp = fmem[p] if not cp then cp = compile(p) / 0 cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) } fmem[p] = cp end local i, e = cp:match(s, i or 1) if i then return i, e - 1 else return i end end local function gsub (s, p, rep) local g = gmem[p] or {} -- ensure gmem[p] is not collected while here gmem[p] = g local cp = g[rep] if not cp then cp = compile(p) cp = mm.Cs((cp / rep + 1)^0) g[rep] = cp end return cp:match(s) end -- exported names local re = { compile = compile, match = match, find = find, gsub = gsub, updatelocale = updatelocale, } if version == "Lua 5.1" then _G.re = re end return re
mit
zhouxiaoxiaoxujian/skynet
3rd/lpeg/re.lua
160
6286
-- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $ -- imported functions and modules local tonumber, type, print, error = tonumber, type, print, error local setmetatable = setmetatable local m = require"lpeg" -- 'm' will be used to parse expressions, and 'mm' will be used to -- create expressions; that is, 're' runs on 'm', creating patterns -- on 'mm' local mm = m -- pattern's metatable local mt = getmetatable(mm.P(0)) -- No more global accesses after this point local version = _VERSION if version == "Lua 5.2" then _ENV = nil end local any = m.P(1) -- Pre-defined names local Predef = { nl = m.P"\n" } local mem local fmem local gmem local function updatelocale () mm.locale(Predef) Predef.a = Predef.alpha Predef.c = Predef.cntrl Predef.d = Predef.digit Predef.g = Predef.graph Predef.l = Predef.lower Predef.p = Predef.punct Predef.s = Predef.space Predef.u = Predef.upper Predef.w = Predef.alnum Predef.x = Predef.xdigit Predef.A = any - Predef.a Predef.C = any - Predef.c Predef.D = any - Predef.d Predef.G = any - Predef.g Predef.L = any - Predef.l Predef.P = any - Predef.p Predef.S = any - Predef.s Predef.U = any - Predef.u Predef.W = any - Predef.w Predef.X = any - Predef.x mem = {} -- restart memoization fmem = {} gmem = {} local mt = {__mode = "v"} setmetatable(mem, mt) setmetatable(fmem, mt) setmetatable(gmem, mt) end updatelocale() local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end) local function getdef (id, defs) local c = defs and defs[id] if not c then error("undefined name: " .. id) end return c end local function patt_error (s, i) local msg = (#s < i + 20) and s:sub(i) or s:sub(i,i+20) .. "..." msg = ("pattern error near '%s'"):format(msg) error(msg, 2) end local function mult (p, n) local np = mm.P(true) while n >= 1 do if n%2 >= 1 then np = np * p end p = p * p n = n/2 end return np end local function equalcap (s, i, c) if type(c) ~= "string" then return nil end local e = #c + i if s:sub(i, e - 1) == c then return e else return nil end end local S = (Predef.space + "--" * (any - Predef.nl)^0)^0 local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0 local arrow = S * "<-" local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1 name = m.C(name) -- a defined name only have meaning in a given environment local Def = name * m.Carg(1) local num = m.C(m.R"09"^1) * S / tonumber local String = "'" * m.C((any - "'")^0) * "'" + '"' * m.C((any - '"')^0) * '"' local defined = "%" * Def / function (c,Defs) local cat = Defs and Defs[c] or Predef[c] if not cat then error ("name '" .. c .. "' undefined") end return cat end local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R local item = defined + Range + m.C(any) local Class = "[" * (m.C(m.P"^"^-1)) -- optional complement symbol * m.Cf(item * (item - "]")^0, mt.__add) / function (c, p) return c == "^" and any - p or p end * "]" local function adddef (t, k, exp) if t[k] then error("'"..k.."' already defined as a rule") else t[k] = exp end return t end local function firstdef (n, r) return adddef({n}, n, r) end local function NT (n, b) if not b then error("rule '"..n.."' used outside a grammar") else return mm.V(n) end end local exp = m.P{ "Exp", Exp = S * ( m.V"Grammar" + m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) ); Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul) * (#seq_follow + patt_error); Prefix = "&" * S * m.V"Prefix" / mt.__len + "!" * S * m.V"Prefix" / mt.__unm + m.V"Suffix"; Suffix = m.Cf(m.V"Primary" * S * ( ( m.P"+" * m.Cc(1, mt.__pow) + m.P"*" * m.Cc(0, mt.__pow) + m.P"?" * m.Cc(-1, mt.__pow) + "^" * ( m.Cg(num * m.Cc(mult)) + m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow)) ) + "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div)) + m.P"{}" * m.Cc(nil, m.Ct) + m.Cg(Def / getdef * m.Cc(mt.__div)) ) + "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt)) ) * S )^0, function (a,b,f) return f(a,b) end ); Primary = "(" * m.V"Exp" * ")" + String / mm.P + Class + defined + "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" / function (n, p) return mm.Cg(p, n) end + "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end + m.P"{}" / mm.Cp + "{~" * m.V"Exp" * "~}" / mm.Cs + "{|" * m.V"Exp" * "|}" / mm.Ct + "{" * m.V"Exp" * "}" / mm.C + m.P"." * m.Cc(any) + (name * -arrow + "<" * name * ">") * m.Cb("G") / NT; Definition = name * arrow * m.V"Exp"; Grammar = m.Cg(m.Cc(true), "G") * m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0, adddef) / mm.P } local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error) local function compile (p, defs) if mm.type(p) == "pattern" then return p end -- already compiled local cp = pattern:match(p, 1, defs) if not cp then error("incorrect pattern", 3) end return cp end local function match (s, p, i) local cp = mem[p] if not cp then cp = compile(p) mem[p] = cp end return cp:match(s, i or 1) end local function find (s, p, i) local cp = fmem[p] if not cp then cp = compile(p) / 0 cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) } fmem[p] = cp end local i, e = cp:match(s, i or 1) if i then return i, e - 1 else return i end end local function gsub (s, p, rep) local g = gmem[p] or {} -- ensure gmem[p] is not collected while here gmem[p] = g local cp = g[rep] if not cp then cp = compile(p) cp = mm.Cs((cp / rep + 1)^0) g[rep] = cp end return cp:match(s) end -- exported names local re = { compile = compile, match = match, find = find, gsub = gsub, updatelocale = updatelocale, } if version == "Lua 5.1" then _G.re = re end return re
mit
MOSAVI17/Gbot
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
MAXtgBOT/Telemax-TG
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
mahdmahdia/DBDB
libs/JSON.lua
3765
34843
-- -*- 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 --
gpl-2.0
dddaaaddd/super_me
libs/JSON.lua
3765
34843
-- -*- 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 --
gpl-2.0
mahdikord/mahdibaryaji
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
punisherbot/test
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
kastnerkyle/MemNN
MemN2N-lang-model/main.lua
18
5587
-- Copyright (c) 2015-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the BSD-style license found in the -- LICENSE file in the root directory of this source tree. An additional grant -- of patent rights can be found in the PATENTS file in the same directory. require('xlua') require('paths') local tds = require('tds') paths.dofile('data.lua') paths.dofile('model.lua') local function train(words) local N = math.ceil(words:size(1) / g_params.batchsize) local cost = 0 local y = torch.ones(1) local input = torch.CudaTensor(g_params.batchsize, g_params.edim) local target = torch.CudaTensor(g_params.batchsize) local context = torch.CudaTensor(g_params.batchsize, g_params.memsize) local time = torch.CudaTensor(g_params.batchsize, g_params.memsize) input:fill(g_params.init_hid) for t = 1, g_params.memsize do time:select(2, t):fill(t) end for n = 1, N do if g_params.show then xlua.progress(n, N) end for b = 1, g_params.batchsize do local m = math.random(g_params.memsize + 1, words:size(1)-1) target[b] = words[m+1] context[b]:copy( words:narrow(1, m - g_params.memsize + 1, g_params.memsize)) end local x = {input, target, context, time} local out = g_model:forward(x) cost = cost + out[1] g_paramdx:zero() g_model:backward(x, y) local gn = g_paramdx:norm() if gn > g_params.maxgradnorm then g_paramdx:mul(g_params.maxgradnorm / gn) end g_paramx:add(g_paramdx:mul(-g_params.dt)) end return cost/N/g_params.batchsize end local function test(words) local N = math.ceil(words:size(1) / g_params.batchsize) local cost = 0 local input = torch.CudaTensor(g_params.batchsize, g_params.edim) local target = torch.CudaTensor(g_params.batchsize) local context = torch.CudaTensor(g_params.batchsize, g_params.memsize) local time = torch.CudaTensor(g_params.batchsize, g_params.memsize) input:fill(g_params.init_hid) for t = 1, g_params.memsize do time:select(2, t):fill(t) end local m = g_params.memsize + 1 for n = 1, N do if g_params.show then xlua.progress(n, N) end for b = 1, g_params.batchsize do target[b] = words[m+1] context[b]:copy( words:narrow(1, m - g_params.memsize + 1, g_params.memsize)) m = m + 1 if m > words:size(1)-1 then m = g_params.memsize + 1 end end local x = {input, target, context, time} local out = g_model:forward(x) cost = cost + out[1] end return cost/N/g_params.batchsize end local function run(epochs) for i = 1, epochs do local c, ct c = train(g_words_train) ct = test(g_words_valid) -- Logging local m = #g_log_cost+1 g_log_cost[m] = {m, c, ct} g_log_perp[m] = {m, math.exp(c), math.exp(ct)} local stat = {perplexity = math.exp(c) , epoch = m, valid_perplexity = math.exp(ct), LR = g_params.dt} if g_params.test then local ctt = test(g_words_test) table.insert(g_log_cost[m], ctt) table.insert(g_log_perp[m], math.exp(ctt)) stat['test_perplexity'] = math.exp(ctt) end print(stat) -- Learning rate annealing if m > 1 and g_log_cost[m][3] > g_log_cost[m-1][3] * 0.9999 then g_params.dt = g_params.dt / 1.5 if g_params.dt < 1e-5 then break end end end end local function save(path) local d = {} d.params = g_params d.paramx = g_paramx:float() d.log_cost = g_log_cost d.log_perp = g_log_perp torch.save(path, d) end -------------------------------------------------------------------- -------------------------------------------------------------------- -- model params: local cmd = torch.CmdLine() cmd:option('--gpu', 1, 'GPU id to use') cmd:option('--edim', 150, 'internal state dimension') cmd:option('--lindim', 75, 'linear part of the state') cmd:option('--init_std', 0.05, 'weight initialization std') cmd:option('--init_hid', 0.1, 'initial internal state value') cmd:option('--sdt', 0.01, 'initial learning rate') cmd:option('--maxgradnorm', 50, 'maximum gradient norm') cmd:option('--memsize', 100, 'memory size') cmd:option('--nhop', 6, 'number of hops') cmd:option('--batchsize', 128) cmd:option('--show', false, 'print progress') cmd:option('--load', '', 'model file to load') cmd:option('--save', '', 'path to save model') cmd:option('--epochs', 100) cmd:option('--test', false, 'enable testing') g_params = cmd:parse(arg or {}) print(g_params) cutorch.setDevice(g_params.gpu) g_vocab = tds.hash() g_ivocab = tds.hash() g_ivocab[#g_vocab+1] = '<eos>' g_vocab['<eos>'] = #g_vocab+1 g_words_train = g_read_words('data/ptb.train.txt', g_vocab, g_ivocab) g_words_valid = g_read_words('data/ptb.valid.txt', g_vocab, g_ivocab) g_words_test = g_read_words('data/ptb.test.txt', g_vocab, g_ivocab) g_params.nwords = #g_vocab print('vocabulary size ' .. #g_vocab) g_model = g_build_model(g_params) g_paramx, g_paramdx = g_model:getParameters() g_paramx:normal(0, g_params.init_std) if g_params.load ~= '' then local f = torch.load(g_params.load) g_paramx:copy(f.paramx) end g_log_cost = {} g_log_perp = {} g_params.dt = g_params.sdt print('starting to run....') run(g_params.epochs) if g_params.save ~= '' then save(g_params.save) end
bsd-3-clause
routek/qMp
packages/qmp-system/files/usr/lib/lua/luci/controller/qmp.lua
1
3527
--[[ Copyright (C) 2011 Fundacio Privada per a la Xarxa Oberta, Lliure i Neutral guifi.net This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. The full GNU General Public License is included in this distribution in the file called "COPYING". --]] module("luci.controller.qmp", package.seeall) function index() local nixio = require "nixio" -- Making qmp as default local root = node() root.target = alias("qmp") root.index = true -- Main window with auth enabled overview = entry({"qmp"}, template("admin_status/index"), "qMp", 1) overview.dependent = false overview.sysauth = "root" overview.sysauth_authenticator = "htmlauth" -- Rest of entries entry({"qmp","status"}, template("admin_status/index"), "Status", 2).dependent=false entry({"qmp","configuration"}, cbi("qmp/easy_setup"), "Device configuration", 4).dependent=false entry({"qmp","configuration","easy_setup"}, cbi("qmp/easy_setup"), "qMp easy setup", 1).dependent=false entry({"qmp","configuration","basic"}, cbi("qmp/basic"), "Basic settings", 2).dependent=false entry({"qmp","configuration","network"}, cbi("qmp/network"), "Network settings", 3).dependent=false entry({"qmp","configuration","network","advanced"}, cbi("qmp/network_adv"), "Advanced network settings", 1).dependent=false entry({"qmp","configuration","wifi"}, cbi("qmp/wireless"), "Wireless settings", 4).dependent=false entry({"qmp","configuration","services"}, cbi("qmp/services"), "qMp services", 5).dependent=false entry({"qmp","configuration","gateways"}, cbi("qmp/gateways"), "qMp gateways", 6).dependent=false entry({"qmp","tools"}, call("action_tools"), "Tools", 5).dependent=false entry({"qmp","tools","tools"}, call("action_tools"), "Network testing", 1).dependent=false if nixio.fs.stat("/usr/lib/lua/luci/model/cbi/qmp/mdns.lua","type") ~= nil then entry({"qmp","tools","mDNS"}, cbi("qmp/mdns"), "DNS mesh", 1).dependent=false end -- entry({"qmp","tools","splash"}, call("action_splash"), "Splash", 2).dependent=false -- entry({"qmp","tools","map"}, call("action_map"), "Map", 3).dependent=false entry({"qmp","about"}, call("action_status"), "About", 9).dependent=false end function action_status() package.path = package.path .. ";/etc/qmp/?.lua" local qmp = require "qmpinfo" local ipv4 = qmp.get_ipv4() local hostname = qmp.get_hostname() local uname = qmp.get_uname() local version = qmp.get_version() luci.template.render("qmp/overview",{ipv4=ipv4,hostname=hostname,uname=uname,version=version}) end function action_tools() package.path = package.path .. ";/etc/qmp/?.lua" local qmp = require "qmpinfo" local nodes = qmp.nodes() local key = qmp.get_key() luci.template.render("qmp/tools",{nodes=nodes,key=key}) end function action_splash() luci.template.render("qmp/splash") end function action_map() luci.template.render("qmp/b6m") end
gpl-2.0
sjznxd/luci-0.11-aa
libs/sgi-luci/luasrc/ttpd/handler/luci.lua
53
1923
--[[ HTTP server implementation for LuCI - luci handler (c) 2008 Steven Barth <steven@midlink.org> 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 $Id$ ]]-- local dsp = require "luci.dispatcher" local util = require "luci.util" local http = require "luci.http" local ltn12 = require "luci.ltn12" local mod = require "luci.ttpd.module" local table = require "table" local coroutine = require "coroutine" module "luci.ttpd.handler.luci" Luci = util.class(mod.Handler) Response = mod.Response function Luci.__init__(self, limit) mod.Handler.__init__(self) end function Luci.handle_head(self, ...) return (self:handle_get(...)) end function Luci.handle_post(self, ...) return self:handle_get(...) end function Luci.handle_get(self, request, sourcein, sinkerr) local r = http.Request( request.env, sourcein, sinkerr ) local res, id, data1, data2 = true, 0, nil, nil local headers = {} local status = 200 local active = true local x = coroutine.create(dsp.httpdispatch) while not id or id < 3 do res, id, data1, data2 = coroutine.resume(x, r) if not res then status = 500 headers["Content-Type"] = "text/plain" local err = {id} return Response( status, headers ), function() return table.remove(err) end end if id == 1 then status = data1 elseif id == 2 then headers[data1] = data2 end end local function iter() local res, id, data = coroutine.resume(x) if not res then return nil, id elseif not id or not active then return true elseif id == 5 then active = false while (coroutine.resume(x)) do end return nil elseif id == 4 then return data end if coroutine.status(x) == "dead" then return nil end end return Response(status, headers), iter end
apache-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/West_Sarutabaruta/npcs/Naguipeillont_RK.lua
8
2962
----------------------------------- -- Area: West Sarutabaruta -- NPC: Naguipeillont, R.K. -- Type: Outpost Conquest Guards -- @pos -11.322 -13.459 317.696 115 ----------------------------------- package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/West_Sarutabaruta/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = SARUTABARUTA; local 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 local 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 local 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 local 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
dcelasun/thrift
lib/lua/TTransport.lua
115
2800
-- -- Licensed to the Apache Software Foundation (ASF) under one -- or more contributor license agreements. See the NOTICE file -- distributed with this work for additional information -- regarding copyright ownership. The ASF licenses this file -- to you under the Apache License, Version 2.0 (the -- "License"); you may not use this file except in compliance -- with the License. You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, -- software distributed under the License is distributed on an -- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY -- KIND, either express or implied. See the License for the -- specific language governing permissions and limitations -- under the License. -- require 'Thrift' TTransportException = TException:new { UNKNOWN = 0, NOT_OPEN = 1, ALREADY_OPEN = 2, TIMED_OUT = 3, END_OF_FILE = 4, INVALID_FRAME_SIZE = 5, INVALID_TRANSFORM = 6, INVALID_CLIENT_TYPE = 7, errorCode = 0, __type = 'TTransportException' } function TTransportException:__errorCodeToString() if self.errorCode == self.NOT_OPEN then return 'Transport not open' elseif self.errorCode == self.ALREADY_OPEN then return 'Transport already open' elseif self.errorCode == self.TIMED_OUT then return 'Transport timed out' elseif self.errorCode == self.END_OF_FILE then return 'End of file' elseif self.errorCode == self.INVALID_FRAME_SIZE then return 'Invalid frame size' elseif self.errorCode == self.INVALID_TRANSFORM then return 'Invalid transform' elseif self.errorCode == self.INVALID_CLIENT_TYPE then return 'Invalid client type' else return 'Default (unknown)' end end TTransportBase = __TObject:new{ __type = 'TTransportBase' } function TTransportBase:isOpen() end function TTransportBase:open() end function TTransportBase:close() end function TTransportBase:read(len) end function TTransportBase:readAll(len) local buf, have, chunk = '', 0 while have < len do chunk = self:read(len - have) have = have + string.len(chunk) buf = buf .. chunk if string.len(chunk) == 0 then terror(TTransportException:new{ errorCode = TTransportException.END_OF_FILE }) end end return buf end function TTransportBase:write(buf) end function TTransportBase:flush() end TServerTransportBase = __TObject:new{ __type = 'TServerTransportBase' } function TServerTransportBase:listen() end function TServerTransportBase:accept() end function TServerTransportBase:close() end TTransportFactoryBase = __TObject:new{ __type = 'TTransportFactoryBase' } function TTransportFactoryBase:getTransport(trans) return trans end
apache-2.0
msburgess3200/PERP
gamemodes/perp/gamemode/vehicles/Old Cars/swat_van.lua
1
2506
/////////////////////////////// // © 2009-2010 Pulsar Effect // // All rights reserved // /////////////////////////////// // This material may not be // // reproduced, displayed, // // modified or distributed // // without the express prior // // written permission of the // // the copyright holder. // /////////////////////////////// VEHICLE = {}; VEHICLE.ID = 'x'; VEHICLE.Name = "SWAT Van"; VEHICLE.Make = "Ford"; VEHICLE.Model = "Crown Royal"; VEHICLE.Script = "swatvan"; VEHICLE.Cost = 0; VEHICLE.PaintJobCost = 0; VEHICLE.DF = false; VEHICLE.CustomBodyGroup = nil; VEHICLE.PaintJobs = { {model = 'models/perp2.5/swat_van.mdl', skin = '0', name = '', color = Color(0, 0, 0, 255)}, }; VEHICLE.PassengerSeats = { {Vector(23.57, -35, 45), Angle(0, 0, 0)}, {Vector(35, 85, 50), Angle(0, 90, 0)}, {Vector(-35, 85, 50), Angle(0, -90, 0)}, }; VEHICLE.ExitPoints = { Vector(108.4158, 53.3863, 2.2271), Vector(-108.4158, 53.3863, 2.2271), Vector(-62.5363, -185.0254, 2.8965), Vector(62.5363, -185.0254, 2.8965), }; VEHICLE.DefaultIceFriction = 1.5; VEHICLE.PlayerReposition_Pos = nil; VEHICLE.PlayerReposition_Ang = nil; VEHICLE.ViewAdjustments_FirstPerson = nil; VEHICLE.ViewAdjustments_ThirdPerson = nil; VEHICLE.RequiredClass = TEAM_SWAT; VEHICLE.PaintText = ""; VEHICLE.HornNoise = "PERP2.5/firetruck_horn.mp3"; VEHICLE.HeadlightPositions = { {Vector(37.0823, 134.9541, 45.3427), Angle(20, 0, 0)}; {Vector(-37.0823, 134.9541, 45.3427), Angle(20, 0, 0)}; }; VEHICLE.TaillightPositions = { {Vector(-37.7724, -128.7918, 91.6226), Angle(20, -180, 0)}; {Vector(-37.3994, -134.2080, 57.0039), Angle(20, -180, 0)}; {Vector(-36.9836, -135.1196, 51.0537), Angle(20, -180, 0)}; {Vector(37.7724, -128.7918, 91.6226), Angle(20, -180, 0)}; {Vector(37.3994, -134.2080, 57.0039), Angle(20, -180, 0)}; {Vector(36.9836, -135.1196, 51.0537), Angle(20, -180, 0)}; }; VEHICLE.UnderglowPositions = { }; VEHICLE.RevvingSound = nil; VEHICLE.SpinoutSound = nil; VEHICLE.SirenNoise = Sound("PERP2.5/siren_long.mp3"); VEHICLE.SirenNoise_Alt = nil; VEHICLE.SirenColors = { {Color(255, 0, 0, 255), Vector(15.9293, 68.5494, 106.8396)}, {Color(255, 0, 0, 255), Vector(-15.9293, 68.5494, 106.8396)}, }; GM:RegisterVehicle(VEHICLE);
mit
Mogara/QSanguosha
extension-doc/16-RoleJudgement.lua
15
15976
--[[ 在前面五个文档中,您已经学习了在开启身份预知的情况下,让 AI 按照您的要求去工作的所有基本知识了。 为了真正熟悉 AI 的编写,接下来您需要做的只是不断地模仿和练习。 下面你可以根据自己的情况作出选择: + 如果您对身份判断不感兴趣,或者认为您添加的技能和卡牌对身份判断影响很小。 您可以直接跳到 17-Example.lua,并且仅仅阅读其中与身份判断无关的部分。 + 如果您希望进一步了解身份判断部分的 AI,欢迎继续阅读本文档。 本文档将集中介绍 smart-ai.lua 中第二部分“身份、动机、仇恨值”的内容。 首先需要树立一个概念,在一局游戏中,所有的 AI 共享同一套身份判断有关的数据。 而并不是像一些人想象的那样,每个 AI 有自己的身份判断数据。 另外,下面介绍的内容均以 8 人身份局为例。 对于某些很特殊的情况(例如国战),此处不作介绍。 ++ 与 AI 身份判断有关的表 (注意,它们都是 sgs 而不是 SmartAI 的元素,这就印证了上面的说法) 下面这些表的元素名称,如果没有特别说明,都是 ServerPlayer 对象的对象名,即形如 "sgsX" 的字符串。 * sgs.ai_loyalty:表,包含忠诚度 % 元素:数值,为元素名称所对应的玩家的忠诚度,取值范围为 [-160, 160]。 数值越大越忠诚,初始值为 0,主公的忠诚度永远为 160。 ? sgs.ai_anti_lord:表 % 元素:数值,为元素名称对应的玩家的明确攻击主公的次数,取值范围为非负数。 初始值为 nil ! sgs.ai_renegade_suspect:表,包含内奸的可疑程度 % 元素:数值,为元素名称对应的玩家的内奸可疑程度,取值范围为非负数。 数值越大越像内奸,初始值为 nil ? sgs.ai_explicit:表,包含玩家目前表现出的身份 % 元素:字符串,为以下四个值之一: %% loyalist:忠臣(sgs.ai_loyalty 达到 160) %% loyalish:跳忠,但没有到可以判为忠臣的程度(sgs.ai_loyalty 达到 80,但没达到 160) %% rebel:反贼(sgs.ai_loyalty 达到 -160) %% rebelish:跳反,但没有到可以判为反贼的程度(sgs.ai_loyalty 小于 -80,但没达到 -160) 初始值为 nil,主公的取值永远为 "loyalist"。 在目前版本的 AI 中,对忠臣与跳忠,反贼与跳反之间的区别并不明晰。 (表现为很多时候对待忠臣与对待跳忠玩家的策略是完全相同的,反贼也是) 这有待以后逐步完善。 还有一些其它的表,因为还不完善,在此不作介绍。 ++ AI 如何运用与身份判断有关的表里面的数据 将上面几个表整合起来得到敌友关系的是如下的重要函数: * SmartAI:objectiveLevel(player):获得对玩家 player 的动机水平。 % player:ServerPlayer* % 返回值:数值,表示自身对 player 的动机水平。 动机水平为负,表示 player 是自己的友方。 动机水平介乎 0 到 3 之间(含 0 与 3),表示 player 是自己的敌方,但是不会对 player 使用【杀】。 动机水平大于 3,表示 player 是自己的敌方,且会对 player 使用【杀】。 总的来说,动机水平越负,表示友善程度越高。 目前的 AI 中,动机水平取值范围为 [-3, 6]。 此函数是 AI 中被调用最为频繁的函数之一。 想进一步了解 SmartAI.objectiveLevel 是怎么具体运用上面几个表里面的数据而最终得到动机水平的, 可以参见 smart-ai.lua 中的相关源码,此处不作介绍。 在 12-SmartAI.lua 中介绍的一系列与敌友关系有关的函数,都是基于 SmartAI.objectiveLevel 的。 当然,如果开启了身份预知,那么这些与敌友关系有关的函数将直接调用源代码中 AI 部分的相应代码。 在此顺带介绍一下与身份预知关系最密切的一个函数。 ! sgs.isRolePredictable():是否按照身份预知下的策略去运行 AI % 返回值:布尔值,含义同上。 注意 “是否按照身份预知下的策略去运行 AI” 与 “是否在服务器窗口中勾选了身份预知” 是两个不同的概念。 更多细节请参看 sgs.isRolePredictable() 的源代码。 此外,还需要知道下面这一重要函数: * SmartAI:updatePlayers(inclusive):更新与敌友关系有关的列表。 % inclusive:布尔值,此处不作介绍。 % 返回值:nil。 % 相关表格:sgs.ai_global_flags 此函数有以下几个作用: + 将 sgs.ai_global_flags 指明的所有元素重置为 nil(详见下面的说明) + 生成表 self.friends, self.friends_noself, self.enemies。 此函数也是 AI 中被调用最为频繁的函数之一。 如果你有任何技能的 AI 代码觉得在开始之前更新一下这几个列表会比较好,可以直接在技能代码中调用]] self:updatePlayers() --[[ * sgs.ai_global_flags:表,包括表 sgs 中所有需要重置为 nil 的元素名称。 % 元素名称:无,用 table.insert 把元素加入本表 % 元素:字符串,要重置的元素名称。 用下面一个例子来说明,设原来]] sgs.ai_global_flags == {"abc", "def-ghi", "@foo"} sgs.abc == 3 sgs["def-ghi"] == true sgs["@foo"] == function(a, b) return a + b/2 + 3 end -- 则在执行 SmartAI.updatePlayers 之后 sgs.ai_global_flags == {"abc", "def-ghi", "@foo"} sgs.abc == nil sgs["def-ghi"] == nil sgs["@foo"] == nil --[[ ++ AI 如何设置与身份判断有关的表里面的数据 前面两个部分的代码都是需要了解的,但是在实际编写的过程中并不需要直接用到。 与各个扩展最为紧密的使得 AI 的身份判断部分能够正确工作的代码,都落在这一部分。 在 AI 中,我们通过调用下面两个函数来更新与身份判断有关的表里面的数据。 ? sgs.refreshLoyalty(player, intention):更新玩家 player 的忠诚度 % player:ServerPlayer*,要更新忠诚度的玩家 % intention:数值,需要更新的忠诚度。 % 返回值:nil 这一函数的作用是更新表 sgs.ai_loyalty 的值, 使得 sgs.ai_loyalty 表中元素名称为 player 的对象名的元素增加 intention。 并相应更新 sgs.ai_renegade_suspect 和 sgs.ai_explicit。 % 例子:]] sgs.refreshLoyalty("sgs5", 80) -- 对象名为 sgs5 的玩家的忠诚度加上 80 sgs.refreshLoyalty("sgs7", -100) --[[ 对象名为 sgs7 的玩家的忠诚度减去 100 这一函数实际上较少直接使用,仅用于少数与主公技有关的身份判断情形。 下面这一函数更经常使用,用起来也更为方便: * sgs.updateIntention(from, to, intention, card):根据仇恨值更新忠诚度 % from:ServerPlayer*,行为来源 % to:ServerPlayer*,行为对象 % intention:数值,行为的仇恨值 % card:Card*,与行为有关的卡牌(可以是实体卡或者虚拟卡),如果行为不涉及卡牌,则为 nil。 所谓仇恨值,是指 from 对 to 执行这一行为表明 from 对 to 有多大的敌意。 对于目前的 AI,仇恨值与忠诚度的关系如下: 如果 to 是主公,则 from 的忠诚度减去仇恨值的两倍。 如果 to 跳忠或可被判为忠臣,则 from 的忠诚度减去仇恨值。 如果 to 跳反或可被判为反贼,则 from 的忠诚度增加仇恨值。 % 返回值:nil % 例子:]] sgs.updateIntention(huatuo, sunquan, -80) --[[华佗对孙权执行了一个友善的行为,仇恨值为 -80 为了简化诸如多目标锦囊的 sgs.updateIntention 的调用流程,另设了一个辅助函数:]] function sgs.updateIntentions(from, tos, intention, card) -- % from, intention, card, 返回值:含义同 sgs.updateIntention -- % tos:表,包含所有行为对象 for _, to in ipairs(tos) do -- 遍历 tos 中的玩家 if from:objectName() ~= to:objectName() then -- 如果行为来源与行为对象不是同一个人 sgs.updateIntention(from, to, intention,card) end end end --[[ 介绍完这些重要的工具函数之后,可以开始讲述 AI 如何从具体的游戏过程中设置与身份判断有关的表的数据了。 这一部分内容略为难以理解,但却是未来 AI 身份判断进一步完善的突破口。 如果没有兴趣了解更多细节,可以直接跳到本文档后面关于 sgs.ai_card_intention 的描述。 不阅读这一部分对于实际 AI 的编写影响很小。 ---------------------选读部分开始--------------------- 在这一部分,AI 的角色变了,AI 不再是决策者,而成为了游戏的观察者和记录者。 这部分 AI 的主要任务,就是处理游戏中发生的各种事件,得出这些事件背后意味着的敌友关系。 而很容易理解,对于一局游戏来说,只要有一个记录者就够了。 ! sgs.recorder:一个特殊的 SmartAI 对象,它是游戏的记录者 ! SmartAI:filterEvent(event, player, data):记录发生的事件。 % event:TriggerEvent 类型,表示事件的种类,详情请参见神主的讲座帖和 src/server/structs.h。 % player:ServerPlayer*,事件发生的对象 % data:QVariant*,与事件有关的数据 % 返回值:nil % 相关的表:很多,详见下述。 这一函数当 self 不是 sgs.recorder 的时候将不会执行任何与身份判断有关的处理。 当 self 是 sgs.recorder 的时候,会根据事件不同作出不同的处理。 这一函数会在以下事件发生时调用 SmartAI.updatePlayer: sgs.CardUsed, sgs.CardEffect, sgs.Death, sgs.PhaseChange, sgs.GameStart 接下来要介绍一个在编写扩展的时候从来不需要用到,但是对 AI 却很重要的事件:sgs.ChoiceMade。 这个事件表示 player 作出了某种选择。 这个事件之所以如此重要,是因为它具有超前性,例如,“作出使用某张牌的选择” 明显比 sgs.CardUsed 时间要超前得多。 后者发生在卡牌使用的结算完成之后。 这个事件在解决循环激将的问题上起到了关键作用。下面会具体说明。 接下来介绍与 sgs.ChoiceMade 有关的表: * sgs.ai_choicemade_filter:表,包含与 sgs.ChoiceMade 有关的身份判断的 AI 代码。 % 元素名称与元素:目前版本的 AI 中共 5 个。 %% cardUsed:表,包含“决定使用某张卡牌”相关的事件响应函数 %%% 元素名称:无,用 table.insert 把元素加入本表 %%% 元素:函数,原型为 function(player, carduse) %%%% player,返回值:与 SmartAI.filterEvent 含义相同 %%%% carduse:CardUseStruct*,卡牌使用结构体,用于描述作出的决策。 不难理解,大部分与 AI 出牌有关的身份判断代码应该放在这一部分。 但是,目前由于历史原因,大部分使用卡牌的身份判断还是交给了 sgs.CardUsed 事件去处理, 即在卡牌结算结束后处理。 %% cardResponsed:表,包含“决定打出某张卡牌或不打出任何卡牌”相关的事件响应函数 %%% 元素名称:Room::askForCard 当中的 prompt %%% 元素:函数,原型为 function(player, promptlist) %%%% player,返回值:与 SmartAI.filterEvent 含义相同 %%%% promptlist:表 %%%%% promptlist[2]:Room::askForCard 或者 Room::askForUseCard 当中的 pattern %%%%% promptlist[#promptlist]:字符串,若为 "_nil_",表示决定不打出卡牌,否则表示打出了卡牌。 %% skillInvoke:表,包含“决定发动或不发动某项技能”相关的事件响应函数 %%% 元素名称:技能名 %%% 元素,原型为 function(player, promptlist) %%%% player,返回值:与 SmartAI.filterEvent 含义相同 %%%% promptlist:表 %%%% promptlist[3]:字符串,若为 "yes",表示选择发动此技能,否则选择不发动。 %% skillChoice:表,包含“决定选择某一项”相关的事件响应函数 %%% 元素名称:技能名 %%% 元素,原型为 function(player, promptlist) %%%% player,返回值:与 SmartAI.filterEvent 含义相同 %%%% promptlist:表 %%%% promptlist[3]:字符串,为所作的选择。 %% Nullification:表,包括“决定使用无懈可击”相关的事件响应函数 这个表目前很少用到,不作介绍。 % 例子:standard-ai.lua 第 472 至 497,531 至 536 行关于激将的代码。]] -- sgs.jijiangsource 用于记录激将的来源 table.insert(sgs.ai_global_flags, "jijiangsource") -- 每当执行 SmartAI.updatePlayers 时,清除激将的来源 local jijiang_filter = function(player, carduse) if carduse.card:inherits("JijiangCard") then -- 如果有人使用了激将技能卡 sgs.jijiangsource = player -- 记录激将来源 else -- 如果有人使用了其它卡(注意是使用不是打出) sgs.jijiangsource = nil -- 清除激将来源 end end table.insert(sgs.ai_choicemade_filter.cardUsed, jijiang_filter) -- 把上面的函数注册到 sgs.ai_choicemade_filter 里面 sgs.ai_skill_invoke.jijiang = function(self, data) local cards = self.player:getHandcards() for _, card in sgs.qlist(cards) do if card:inherits("Slash") then return false end end if sgs.jijiangsource then return false else return true end -- 如果已经有人在激将,则不发动激将 end sgs.ai_choicemade_filter.skillInvoke.jijiang = function(player, promptlist) if promptlist[#promptlist] == "yes" then-- 如果有人在要求打出【杀】询问是否发动激将时,选择了发动激将 sgs.jijiangsource = player -- 记录下激将的来源 end end -- 中间数行代码略去 sgs.ai_choicemade_filter.cardResponsed["@jijiang-slash"] = function(player, promptlist) if promptlist[#promptlist] ~= "_nil_" then -- 如果有人响应了激将 sgs.updateIntention(player, sgs.jijiangsource, -40) -- 响应激将者对激将来源的仇恨值为 -40 sgs.jijiangsource = nil -- 当有人响应时,激将的结算结束,故清除激将来源 end end --[[ 这个例子完整地展示了 sgs.ai_choicemade_filter 的应用。 如果您能够读懂这部分的代码,并且理解这部分的代码是如何防止循环激将的。您对 AI 的了解已经很不错了。 当然,读不懂也没关系,因为像激将这样的技能毕竟还是少数。 SmartAI.filterEvent 除了会处理 sgs.ChoiceMade,以及如前所述在一系列事件发生时调用 SmartAI.updatePlayers 之外, 还会处理下面的事件:sgs.CardEffect, sgs.Damaged, sgs.CardUsed, sgs.CardLost, sgs.StartJudge。 很遗憾,在目前版本的 AI 中,大部分的事件都没有提供可供扩展使用的接口。唯一提供了接口的是 sgs.CardUsed。 与这个事件相应的表是下面这个: ---------------------选读部分结束--------------------- * sgs.ai_card_intention:表,包括与卡牌使用相关的仇恨值 % 元素名称:卡牌的类名 % 元素:数值或函数 %% 函数:原型为 (card, from, tos, source) %%% card:Card*,所使用的卡牌 %%% from:ServerPlayer*,卡牌的使用者 %%% tos:表,包括卡牌的所有使用对象 %%% source:ServerPlayer*,在卡牌使用时处于出牌阶段的玩家 在这个函数中,需要手动调用 sgs.updateIntention 来指明仇恨值。 %% 数值:表明卡牌使用者对卡牌使用对象的仇恨值。 实际上会自动调用函数 sgs.updateIntentions 对于绝大部分的卡牌,用数值已经可以满足要求。 % 例子 1:standard-ai.lua 第 1105 行关于青囊的代码。]] sgs.ai_card_intention.QingnangCard = -100 -- 青囊的使用者对使用对象的仇恨值为 -100 -- 例子 2:maneuvering-ai.lua 第 180 至 188 行关于铁索连环的代码。 sgs.ai_card_intention.IronChain=function(card,from,tos,source) for _, to in ipairs(tos) do -- tos 是一个表 if to:isChained() then -- 若使用对象处于连环状态 -- 注意这里指的是铁索连环使用完之后的状态 sgs.updateIntention(from, to, 80) -- 使用者对使用对象的仇恨值为 80 else sgs.updateIntention(from, to, -80) end end end
gpl-3.0
FFXIOrgins/FFXIOrgins
scripts/zones/Norg/npcs/Mamaulabion.lua
19
7883
----------------------------------- -- Area: Norg -- NPC: Mamaulabion -- Starts and finishes Quest: Mama Mia -- @zone 252 -- @pos -57 -9 68 (88) --CSIDs for Mamaulabion --0x005D / 93 = Standard --0x00BF / 191 = start quest --0x00C0 / 192 = quest accepted --0x00C1 / 193 = given an item --0x00C2 / 194 = given an item you already gave --0x00C3 / 195 = all 7 items given --0x00C4 / 196 = after 7 items, but need more time until reward is given --0x00C5 / 197 = reward --0x00C6 / 198 = after quest is complete --0x00F3 / 243 = get new ring if you dropped yours --I did alot of copy/pasting, so you may notice a reduncency on comments XD --But it can make it easier to follow aswell. --"Mamaulabion will inform you of the items delivered thus far, as of the May 2011 update." --i have no clue where this event is, so i have no idea how to add this (if this gets scripted, please remove this comment) --"Upon completion of this quest, the above items no longer appear in the rewards list for defeating the Prime Avatars." --will require changing other avatar quests and making a variable for it all. (if this gets scripted, please remove this comment) ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(OUTLANDS,MAMA_MIA) == QUEST_ACCEPTED) then local tradesMamaMia = player:getVar("tradesMamaMia") if(trade:hasItemQty(1202,1) and trade:getItemCount() == 1) then -- Trade Bubbly water wasSet = player:getMaskBit(tradesMamaMia,0) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",0,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif(trade:hasItemQty(1203,1) and trade:getItemCount() == 1) then -- Trade Egil's torch wasSet = player:getMaskBit(tradesMamaMia,1) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",1,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif(trade:hasItemQty(1204,1) and trade:getItemCount() == 1) then -- Trade Eye of mept wasSet = player:getMaskBit(tradesMamaMia,2) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",2,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif(trade:hasItemQty(1205,1) and trade:getItemCount() == 1) then -- Trade Desert Light wasSet = player:getMaskBit(tradesMamaMia,3) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",3,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif(trade:hasItemQty(1206,1) and trade:getItemCount() == 1) then -- Trade Elder Branch wasSet = player:getMaskBit(tradesMamaMia,4) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",4,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif(trade:hasItemQty(1207,1) and trade:getItemCount() == 1) then -- Trade Rust 'B' Gone wasSet = player:getMaskBit(tradesMamaMia,5) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",5,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end elseif(trade:hasItemQty(1208,1) and trade:getItemCount() == 1) then -- Trade Ancients' Key wasSet = player:getMaskBit(tradesMamaMia,6) tradesMamaMia = player:setMaskBit(tradesMamaMia,"tradesMamaMia",6,true) if(player:isMaskFull(tradesMamaMia,7) == true) then player:startEvent(0x00C3); -- Traded all seven items elseif(wasSet) then player:startEvent(0x00C2); -- Traded an item you already gave else player:startEvent(0x00C1); -- Traded an item end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local MamaMia = player:getQuestStatus(OUTLANDS,MAMA_MIA); local moonlitPath = player:getQuestStatus(WINDURST,THE_MOONLIT_PATH); local EvokersRing = player:hasItem(14625); local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day local questday = player:getVar("MamaMia_date") if(MamaMia == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 4 and moonlitPath == QUEST_COMPLETED) then player:startEvent(0x00BF); -- Start Quest "Mama Mia" elseif(MamaMia == QUEST_ACCEPTED) then local tradesMamaMia = player:getVar("tradesMamaMia") local maskFull = player:isMaskFull(tradesMamaMia,7) if(maskFull) then if(realday == questday) then player:startEvent(0x00C4); --need to wait longer for reward elseif(questday ~= 0) then player:startEvent(0x00C5); --Reward end else player:startEvent(0x00C0); -- During Quest "Mama Mia" end elseif(MamaMia == QUEST_COMPLETED and EvokersRing) then player:startEvent(0x00C6); -- New standard dialog after "Mama Mia" is complete elseif(MamaMia == QUEST_COMPLETED and EvokersRing == false) then player:startEvent(0x00F3); -- Quest completed, but dropped ring else player:startEvent(0x005D); -- 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 == 0x00BF) then player:addQuest(OUTLANDS,MAMA_MIA); elseif(csid == 0x00C1) then player:tradeComplete(); elseif(csid == 0x00C3) then player:tradeComplete(); player:setVar("MamaMia_date", os.date("%j")); -- %M for next minute, %j for next day elseif(csid == 0x00C5) then if(player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14625); -- Evokers Ring else player:addItem(14625); -- Evokers Ring player:messageSpecial(ITEM_OBTAINED,14625); -- Evokers Ring player:addFame(OUTLANDS,NORG_FAME*30); --idk how much fame the quest adds, just left at 30 which the levi quest gave. player:completeQuest(OUTLANDS,MAMA_MIA); player:setVar("tradesMamaMia",0) end elseif (csid == 0x00F3) then if(option == 1) then player:delQuest(OUTLANDS,MAMA_MIA); player:addQuest(OUTLANDS,MAMA_MIA); end end end;
gpl-3.0
Crigges/WurstScript
Wurstpack/wehack.lua
1
24809
-- This file is executed once on we start up. The state perseveres -- through callbacks -- -- wehack.runprocess: Wait for exit code, report errors (grimext) -- wehack.runprocess2: Wait for exit code, don't report errors (jasshelper) -- wehack.execprocess: Don't wait for exit code (War3) -- grimregpath = "Software\\Grimoire\\" --warcraftdir = grim.getregpair(grimregpath,"War3InstallPath") --if warcraftdir == 0 then -- wehack.messagebox("Error, could not find warcraft install path in wehack.lua") --end isstartup = true grimdir = grim.getcwd() dofile("wehacklib.lua") dofile("findpath.lua") if path==0 or path=="" then path = "." end mapvalid = true cmdargs = "" -- used to execute external tools on save confregpath = "HKEY_CURRENT_USER\\Software\\Grimoire\\" haveext = grim.exists("grimext\\grimex.dll") if haveext then utils = wehack.addmenu("Extensions") end whmenu = wehack.addmenu("Grimoire") wh_window = TogMenuEntry:New(whmenu,"Start War3 with -window",nil,true) wh_opengl = TogMenuEntry:New(whmenu,"Start War3 with -opengl",nil,false) if not grim.isnewcompiler(path.."\\war3.exe") then wh_grimoire = TogMenuEntry:New(whmenu,"Start War3 with Grimoire",nil,true) wh_enablewar3err = TogMenuEntry:New(whmenu,"Enable war3err",nil,true) wh_enablejapi = TogMenuEntry:New(whmenu,"Enable japi",nil,false) --wh_machine = TogMenuEntry:New(whmenu,"Enable warmachine",nil,false) end wehack.addmenuseparator(whmenu) wh_tesh = TogMenuEntry:New(whmenu,"Enable TESH",nil,true) if grim.isdotnetinstalled() then wh_colorizer = TogMenuEntry:New(whmenu,"Enable Colorizer",nil,true) end wh_nolimits = TogMenuEntry:New(whmenu,"Enable no limits", function(self) grim.nolimits(self.checked) end,false) wh_oehack = TogMenuEntry:New(whmenu,"Enable object editor hack", function(self) grim.objecteditorhack(self.checked) end,true) wh_syndisable = TogMenuEntry:New(whmenu,"Disable WE syntax checker", function(self) grim.syndisable(self.checked) end,true) wh_descpopup = TogMenuEntry:New(whmenu,"Disable default description nag", function(self) grim.descpopup(self.checked) end,true) wh_autodisable = TogMenuEntry:New(whmenu,"Don't let WE disable triggers", function(self) grim.autodisable(self.checked) end,true) wh_alwaysenable = TogMenuEntry:New(whmenu,"Always allow trigger enable", function(self) grim.alwaysenable(self.checked) end,true) wh_disablesound = TogMenuEntry:New(whmenu,"Mute editor sounds",nil,true) wh_firstsavenag = TogMenuEntry:New(whmenu,"Disable first save warning",nil,true) wehack.addmenuseparator(whmenu) usetestmapconf = (grim.getregpair(confregpath,"Use custom test map settings") == "on") function testmapconfig() usetestmapconf = wehack.testmapconfig(path,usetestmapconf) if usetestmapconf then grim.setregstring(confregpath,"Use custom test map settings","on") else grim.setregstring(confregpath,"Use custom test map settings","off") end end wh_configtest = MenuEntry:New(whmenu,"Customize test map settings",testmapconfig); function attachdebugger() wehack.execprocess("w3jdebug\\pyw3jdebug.exe") end havedebugger = grim.exists("w3jdebug\\pyw3jdebug.exe") if havedebugger then wh_debug = MenuEntry:New(whmenu,"Attach debugger",attachdebugger) end function aboutpopup() wehack.showaboutdialog("Grimoire 1.5") end wh_about = MenuEntry:New(whmenu,"About Grimoire ...",aboutpopup) function wurst_compilationserver_start() wehack.execprocess("wurstscript\\wurstscript.exe --startServer") end function wurst_compilationserver_stop() wehack.execprocess("wurstscript\\wurstscript_b.exe -stopServer") end -- ##WurstScript## havewurst = grim.exists("wurstscript\\wurstscript.exe") if havewurst then wurstmenu = wehack.addmenu("WurstScript") function wurst_command() if wurst_b_enable.checked then return "wurstscript\\wurstscript_b.exe" else return "wurstscript\\wurstscript.exe" end end wurst_enable = TogMenuEntry:New(wurstmenu,"Enable WurstScript",nil,true) wurst_b_enable = TogMenuEntry:New(wurstmenu,"Use Wurst compilation server",nil,false) -- TODO -- MenuEntry:New(wurstmenu,"Start Wurst compilation server ",wurst_compilationserver_start) MenuEntry:New(wurstmenu,"Stop Wurst compilation server ",wurst_compilationserver_stop) wehack.addmenuseparator(wurstmenu) -- optimizer options wurst_optenable = TogMenuEntry:New(wurstmenu,"Enable Froptimizer",nil,false) wurst_localoptenable = TogMenuEntry:New(wurstmenu,"Enable (experimental) local optimizations",nil,false) wurst_inliner = TogMenuEntry:New(wurstmenu, "Enable Inliner",nil,false) wehack.addmenuseparator(wurstmenu) -- debug options wurst_stacktraces = TogMenuEntry:New(wurstmenu, "Enable stack-traces",nil,false) wurst_uncheckedDispatch = TogMenuEntry:New(wurstmenu, "Enable unchecked dispatch",nil,false) wurst_nodebug = TogMenuEntry:New(wurstmenu, "Disable debug messages",nil,false) wurst_debug = TogMenuEntry:New(wurstmenu,"Debug Mode",nil,false) wehack.addmenuseparator(wurstmenu) -- compiletime options wurst_compiletimefunctions = TogMenuEntry:New(wurstmenu, "Run compiletime functions",nil,false) wurst_injectObjects = TogMenuEntry:New(wurstmenu, "Inject compiletime objects",nil,false) wehack.addmenuseparator(wurstmenu) -- other tools wurst_useJmpq2 = TogMenuEntry:New(wurstmenu, "Use JMpq-v2 (deprecated)",nil,false) function wurst_runfileexporter() curmap = wehack.findmappath() if curmap ~= "" then wehack.execprocess(wurst_command() .. " --extractImports \"" .. curmap .. "\"") else wehack.messagebox("No map loaded. Try saving the map first.","Wurst",false) end end MenuEntry:New(wurstmenu,"Extract all imported files",wurst_runfileexporter) wehack.addmenuseparator(wurstmenu) function wurstshowerr() wehack.execprocess(wurst_command() .. " --showerrors") end function wurstabout() wehack.execprocess(wurst_command() .. " --about") end -- TODO wurstshowerrm = MenuEntry:New(wurstmenu,"Show previous errors",wurstshowerr) wurstaboutm = MenuEntry:New(wurstmenu,"About WurstScript ...",wurstabout) end -- ##EndWurstScript## -- ## Jasshelper ## --Here I'll add the custom menu to jasshelper. moyack jh_path = "vexorian" havejh = grim.exists("vexorianjasshelper\\jasshelper.exe") if havejh then jhmenu = wehack.addmenu("JassHelper") jh_enable = TogMenuEntry:New(jhmenu,"Enable JassHelper",nil,true) wehack.addmenuseparator(jhmenu) jh_debug = TogMenuEntry:New(jhmenu,"Debug Mode",nil,false) jh_disable = TogMenuEntry:New(jhmenu,"Disable vJass syntax",nil,false) jh_disableopt = TogMenuEntry:New(jhmenu,"Disable script optimization",nil,false) wehack.addmenuseparator(jhmenu) function jhshowerr() wehack.execprocess(jh_path.."jasshelper\\jasshelper.exe --showerrors") end function jhabout() wehack.execprocess(jh_path.."jasshelper\\jasshelper.exe --about") end jhshowerrm = MenuEntry:New(jhmenu,"Show previous errors",jhshowerr) jhaboutm = MenuEntry:New(jhmenu,"About JassHelper ...",jhabout) function jhshowhelp() jhsetpath() wehack.execprocess("starter.bat ./"..jh_path.."jasshelper\\jasshelpermanual.html") end jhhelp = MenuEntry:New(jhmenu, "JassHelper Documentation...", jhshowhelp) end -- # end jasshelper # -- # begin sharpcraft # haveSharpCraft = grim.exists("SharpCraft\\SharpCraft.exe") if haveSharpCraft then sharpCraftMenu = wehack.addmenu("SharpCraft") sharpCraftEnable = TogMenuEntry:New(sharpCraftMenu,"Run with ShapCraft",nil,true) end -- # end sharpcraft # function initshellext() local first, last = string.find(grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit.Scenario\\shell\\open\\command\\", ""),"NewGen",1) if first then wehack.checkmenuentry(shellext.menu,shellext.id,1) else local second, third = string.find(grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit.Scenario\\shell\\open\\command\\", ""),".bat",1) if second then wehack.checkmenuentry(shellext.menu,shellext.id,1) else wehack.checkmenuentry(shellext.menu,shellext.id,0) end end end function fixopencommand(disable,warpath,grimpath,filetype) --local curval = grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","") --if curval ~= 0 then -- if disable then -- grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","",string.gsub(curval, "%%L", "%%1")) -- else -- grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","",string.gsub(curval, "%%1", "%%L")) -- end --end local wepath = "\""..grimpath.."\\NewGen WE.exe\"" if not grim.exists(grimpath.."\\NewGen WE.exe") then wepath = "\""..grimpath.."\\we.bat\"" end if disable then grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","","\""..warpath.."\\World Editor.exe\" -loadfile \"%L\"") else grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\open\\command\\","",wepath.." -loadfile \"%L\"") end end function registerextension(disable,warpath,grimpath,filetype,istft) if disable then grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\command\\"); grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\"); grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\command\\"); grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\"); grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\opengl\\command\\"); grim.deleteregkey("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\opengl\\"); else --if istft then -- gamepath = "\""..warpath.."\\Frozen Throne.exe\"" --else -- gamepath = "\""..warpath.."\\Warcraft III.exe\"" --end --grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\","","Play Fullscreen") --grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\command\\","",gamepath.." -loadfile \"%L\"") --grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\","","Play Windowed") --grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\command\\","",gamepath.." -window -loadfile \"%L\"") local gamepath = "\""..grimpath.."\\NewGen Warcraft.exe\"" if not grim.exists(grimpath.."\\NewGen Warcraft.exe") then gamepath = "\""..grimpath.."\\startwar3.bat\"" end grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\","","Play Fullscreen") grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\fullscreen\\command\\","",gamepath.." -loadfile \"%L\"") grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\","","Play Windowed") grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\windowed\\command\\","",gamepath.." -window -loadfile \"%L\"") grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\opengl\\","","Play With OpenGL") grim.setregstring("HKEY_CLASSES_ROOT\\WorldEdit."..filetype.."\\shell\\opengl\\command\\","",gamepath.." -window -opengl -loadfile \"%L\"") end end function toggleshellext() local istft = (grim.getregpair("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "InstallPathX") ~= 0) local first, last = string.find(grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit.Scenario\\shell\\open\\command\\", ""),"NewGen",1) local found = false if first then found = true else local second, third = string.find(grim.getregpair("HKEY_CLASSES_ROOT\\WorldEdit.Scenario\\shell\\open\\command\\", ""),".bat",1) if second then found = true end end if path ~= 0 and grimdir ~= 0 then fixopencommand(found,path,grimdir,"Scenario") registerextension(found,path,grimdir,"Scenario",istft) fixopencommand(found,path,grimdir,"ScenarioEx") registerextension(found,path,grimdir,"ScenarioEx",istft) fixopencommand(found,path,grimdir,"Campaign") registerextension(found,path,grimdir,"Campaign",istft) fixopencommand(found,path,grimdir,"AIData") if found then wehack.checkmenuentry(shellext.menu,shellext.id,0) else wehack.checkmenuentry(shellext.menu,shellext.id,1) end end end function initlocalfiles() if grim.getregpair("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files") == 0 then wehack.checkmenuentry(localfiles.menu,localfiles.id,0) else wehack.checkmenuentry(localfiles.menu,localfiles.id,1) end end function togglelocalfiles() if grim.getregpair("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files") == 0 then grim.setregdword("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files", 1) wehack.checkmenuentry(localfiles.menu,localfiles.id,1) else grim.setregdword("HKEY_CURRENT_USER\\Software\\Blizzard Entertainment\\Warcraft III\\", "Allow Local Files", 0) wehack.checkmenuentry(localfiles.menu,localfiles.id,0) end end function runobjectmerger(mode) curmap = wehack.findmappath() if curmap ~= "" then source = wehack.openfiledialog("Unit files (*.w3u)|*.w3u|Item files (*.w3t)|*w3t|Doodad files (*.w3d)|*.w3d|Destructable files (*.w3b)|*.w3b|Ability files (*.w3a)|*.w3a|Buff files (*.w3h)|*.w3h|Upgrade files (*.w3q)|*.w3q|", "w3a", "Select files to import ...", true) grim.log("got in lua: " .. source) if source ~= "" then list = strsplit("|", source); -- cmdargs = "ObjectMerger \""..curmap.."\" "..wehack.getlookupfolders().." "..mode..fileargsjoin(list) cmdargs = "grimext\\ObjectMerger.exe \""..curmap.."\" "..wehack.getlookupfolders().." "..mode..fileargsjoin(list) grim.log("assembled cmdline: " .. cmdargs) -- wehack.messagebox(cmdargs,"Grimoire",false) wehack.savemap() grim.log("called saved map") end else showfirstsavewarning() end end function runconstantmerger() curmap = wehack.findmappath() if curmap ~= "" then source = wehack.openfiledialog("Text files (*.txt)|*.txt|", "txt", "Select files to import ...", true) if source ~= "" then list = strsplit("|", source); -- cmdargs = "ConstantMerger \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list) cmdargs = "grimext\\ConstantMerger.exe \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list) -- wehack.messagebox(cmdargs,"Grimoire",false) wehack.savemap() end else showfirstsavewarning() end end function runtriggermerger() curmap = wehack.findmappath() if curmap ~= "" then source = wehack.openfiledialog("GUI Trigger files (*.wtg)|*.wtg|Custom Text Trigger files (*.wct)|*wct|", "wtg", "Select trigger data to import ...", true) if source ~= "" then list = strsplit("|", source); -- cmdargs = "TriggerMerger \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list) cmdargs = "grimext\\TriggerMerger.exe \""..curmap.."\" "..wehack.getlookupfolders()..fileargsjoin(list) -- wehack.messagebox(cmdargs,"Grimoire",false) wehack.savemap() end else showfirstsavewarning() end end function runfileimporterfiles() curmap = wehack.findmappath() if curmap ~= "" then source = wehack.openfiledialog("All files (*.*)|*.*|", "*", "Select files to import ...", true) if source ~= "" then list = strsplit("|", source); inmpqpath = wehack.inputbox("Specify the target path ...","FileImporter","Units\\") -- cmdargs = "FileImporter \""..curmap.."\" "..wehack.getlookupfolders()..argsjoin(inmpqpath,list) cmdargs = "grimext\\FileImporter.exe \""..curmap.."\" "..wehack.getlookupfolders()..argsjoin(inmpqpath,list) -- wehack.messagebox(cmdargs,"Grimoire",false) wehack.savemap() end else showfirstsavewarning() end end function runfileimporterdir() curmap = wehack.findmappath() if curmap ~= "" then source = wehack.browseforfolder("Select the source directory ...") if source ~= "" then -- cmdargs = "FileImporter \""..curmap.."\" "..wehack.getlookupfolders().." \""..source.."\"" cmdargs = "grimext\\FileImporter.exe \""..curmap.."\" "..wehack.getlookupfolders().." \""..source.."\"" -- wehack.messagebox(cmdargs,"Grimoire",false) wehack.savemap() end else showfirstsavewarning() end end function runfileexporter() curmap = wehack.findmappath() if curmap ~= "" then target = wehack.browseforfolder("Select the target directory ...") if target ~= "" then -- wehack.rungrimextool("FileExporter", curmap, removequotes(wehack.getlookupfolders()), target) wehack.runprocess("grimext\\FileExporter.exe \""..curmap.."\" "..wehack.getlookupfolders().." \""..target.."\"") end else showfirstsavewarning() end end function runtilesetter() curmap = wehack.findmappath() if curmap ~= "" then map = wehack.openarchive(curmap,15) oldtiles = wehack.getcurrenttiles() wehack.closearchive(map) if oldtiles ~= "" then newtiles = wehack.tilesetconfig(string.sub(oldtiles,1,1), string.sub(oldtiles,2)) if newtiles ~= "" then tileset = string.sub(newtiles,1,1) tiles = string.sub(newtiles,2) if tileset ~= "" and tiles ~= "" then -- cmdargs = "TileSetter \""..curmap.."\" "..wehack.getlookupfolders().." "..tileset.." "..tiles cmdargs = "grimext\\TileSetter.exe \""..curmap.."\" "..wehack.getlookupfolders().." "..tileset.." "..tiles wehack.savemap() end end -- tileset = wehack.inputbox("Specify the tileset ...","TileSetter",string.sub(oldtiles,1,1)) -- if tileset ~= "" then -- tiles = wehack.inputbox("Specify the tile list ...","TileSetter",string.sub(oldtiles,2)) -- if tiles ~= "" then -- cmdargs = "grimext\\TileSetter.exe \""..curmap.."\" "..wehack.getlookupfolders().." "..tileset.." "..tiles -- wehack.savemap() -- end -- end end else showfirstsavewarning() end end function showfirstsavewarning() if wh_firstsavenag.checked then return else local msg = "Could not find path to map, please try saving again" if wurst_b_enable.checked then msg = msg .. "\nMake sure that the compilation server is running or try disabling the server!" end wehack.messagebox(msg,"Grimoire",false) end end function testmap(cmdline) --if havewurst and wurst_enable.checked and not mapvalid then -- return --end --wehack.messagebox(cmdline) --mappath = strsplit(" ",cmdline)[2] --compilemap_path(mappath) if haveSharpCraft and sharpCraftEnable.checked then -- remove default .exe local pos = string.find(cmdline, ".exe") cmdline = string.sub(cmdline, 4 + pos) -- replace with SharpCraft exe cmdline = "SharpCraft\\SharpCraft.exe -game " .. cmdline end if wh_opengl.checked then cmdline = cmdline .. " -opengl" end if wh_window.checked then cmdline = cmdline .. " -window" end wehack.execprocess(cmdline) end function compilemap_path(mappath,tries) if mappath == "" then showfirstsavewarning() return end map = wehack.openarchive(mappath,15) wehack.extractfile("wurstscript\\common.j","scripts\\common.j") wehack.extractfile("wurstscript\\Blizzard.j","scripts\\Blizzard.j") wehack.extractfile(jh_path.."jasshelper\\common.j","scripts\\common.j") wehack.extractfile(jh_path.."jasshelper\\Blizzard.j","scripts\\Blizzard.j") wehack.extractfile("war3map.j","war3map.j") wehack.closearchive(map) if cmdargs ~= "" then local cmdtable = argsplit(cmdargs) -- local len = table.getn(cmdtable) -- for i = 1, len do -- cmdtable[i] = removequotes(cmdtable[i]) -- end -- wehack.rungrimextool(cmdtable) grim.log("running tool on save: "..cmdargs) wehack.runprocess(cmdargs) cmdargs = "" end if havejh and jh_enable.checked then cmdline = jh_path .. "jasshelper\\jasshelper.exe" if jh_debug.checked then cmdline = cmdline .. " --debug" end if jh_disable.checked then cmdline = cmdline .. " --nopreprocessor" end if jh_disableopt.checked then cmdline = cmdline .. " --nooptimize" end cmdline = cmdline .. " "..jh_path.."jasshelper\\common.j "..jh_path.."jasshelper\\blizzard.j \"" .. mappath .."\"" toolresult = 0 toolresult = wehack.runprocess(cmdline) if toolresult == 0 then mapvalid = true else mapvalid = false end end if havewurst and wurst_enable.checked then cmdline = wurst_command() cmdline = cmdline .. " -gui" if wurst_debug.checked then --cmdline = cmdline .. " --debug" end --if wurst_disable.checked then --cmdline = cmdline .. " --nopreprocessor" --end if wurst_optenable.checked then cmdline = cmdline .. " -opt" end if wurst_localoptenable.checked then cmdline = cmdline .. " -localOptimizations" end if wurst_inliner.checked then cmdline = cmdline .. " -inline" end if wurst_stacktraces.checked then cmdline = cmdline .. " -stacktraces" end if wurst_uncheckedDispatch.checked then cmdline = cmdline .. " -uncheckedDispatch" end if wurst_nodebug.checked then cmdline = cmdline .. " -nodebug" end if wurst_compiletimefunctions.checked then cmdline = cmdline .. " -runcompiletimefunctions" end if wurst_injectObjects.checked then cmdline = cmdline .. " -injectobjects" end if wurst_useJmpq2.checked then cmdline = cmdline .. " --jmpq2" end -- cmdline = cmdline .. " -lib ./wurstscript/lib/" cmdline = cmdline .. " wurstscript\\common.j wurstscript\\Blizzard.j \"" .. mappath .."\"" toolresult = 0 -- if wurst_fast ~= nil and wurst_fast.checked then -- toolresult = wehack.runjasshelper(wurst_debug.checked, wurst_disable.checked, "jasshelper\\common.j", "jasshelper\\blizzard.j", mappath, "") -- else toolresult = wehack.runprocess2(cmdline) -- end if toolresult == 0 then mapvalid = true else mapvalid = false if wurst_b_enable.checked then if tries == 0 then -- try starting compilation server wurst_compilationserver_start() -- try again compilemap_path(mappath,tries+1) else wehack.messagebox("Could not run Wurst with compilation server.","Wurst",false) end else wehack.messagebox("Could not run Wurst.","Wurst",false) end end end end function compilemap() mappath = wehack.findmappath() compilemap_path(mappath,0) end if haveext then localfiles = MenuEntry:New(utils,"Enable Local Files",togglelocalfiles) shellext = MenuEntry:New(utils,"Register Shell Extensions",toggleshellext) initlocalfiles() initshellext() wehack.addmenuseparator(utils) end if haveext and grim.exists("grimext\\tilesetter.exe") then tilesetter = MenuEntry:New(utils,"Edit Tileset",runtilesetter) end if haveext and grim.exists("grimext\\fileexporter.exe") then fileexporter = MenuEntry:New(utils,"Export Files",runfileexporter) end if haveext and grim.exists("grimext\\fileimporter.exe") then fileimporterdir = MenuEntry:New(utils,"Import Directory",runfileimporterdir) fileimporterfiles = MenuEntry:New(utils,"Import Files",runfileimporterfiles) end if haveext and grim.exists("grimext\\objectmerger.exe") then objectmerger = MenuEntry:New(utils,"Merge Object Editor Data",function(self) runobjectmerger("m") end) objectreplacer = MenuEntry:New(utils,"Replace Object Editor Data",function(self) runobjectmerger("r") end) objectimporter = MenuEntry:New(utils,"Import Object Editor Data",function(self) runobjectmerger("i") end) end if haveext and grim.exists("grimext\\constantmerger.exe") then constantmerger = MenuEntry:New(utils,"Merge Constants Data",runconstantmerger) end if haveext and grim.exists("grimext\\triggermerger.exe") then triggermerger = MenuEntry:New(utils,"Merge Trigger Data",runtriggermerger) end function extabout() grim.openlink("http://www.wc3campaigns.net") end if haveext then wehack.addmenuseparator(utils) aboutextensions = MenuEntry:New(utils,"About Grimex ...",extabout) end isstartup = false
apache-2.0
m2mselect/owrt
feeds/luci/libs/luci-lib-px5g/lua/px5g/util.lua
170
1148
--[[ * px5g - Embedded x509 key and certificate generator based on PolarSSL * * Copyright (C) 2009 Steven Barth <steven@midlink.org> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License, version 2.1 as published by the Free Software Foundation. ]]-- local nixio = require "nixio" local table = require "table" module "px5g.util" local preamble = { key = "-----BEGIN RSA PRIVATE KEY-----", cert = "-----BEGIN CERTIFICATE-----", request = "-----BEGIN CERTIFICATE REQUEST-----" } local postamble = { key = "-----END RSA PRIVATE KEY-----", cert = "-----END CERTIFICATE-----", request = "-----END CERTIFICATE REQUEST-----" } function der2pem(data, type) local b64 = nixio.bin.b64encode(data) local outdata = {preamble[type]} for i = 1, #b64, 64 do outdata[#outdata + 1] = b64:sub(i, i + 63) end outdata[#outdata + 1] = postamble[type] outdata[#outdata + 1] = "" return table.concat(outdata, "\n") end function pem2der(data) local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""}) return nixio.bin.b64decode(b64) end
gpl-2.0
FFXIOrgins/FFXIOrgins
scripts/zones/Aht_Urhgan_Whitegate/npcs/Gigirk.lua
34
1031
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Gigirk -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0298); 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
april-org/april-ann
packages/basics/matrix/lua_src/generic_serialization.lua
2
6704
local function archive_wrapper(s) if class.is_a(s, aprilio.package) then assert(s:number_of_files() == 1, "Expected only 1 file in the package") return s:open(1) else return s end end matrix.__generic__ = matrix.__generic__ or {} matrix.__generic__.__make_generic_to_lua_string__ = function(matrix_class, defmode) local name = matrix_class.meta_instance.id class.extend(matrix_class, "to_lua_string", function(self, format) return string.format("%s.fromString[[%s]]", name, self:toString(format or defmode)) end) end -- GENERIC FROM FILENAME matrix.__generic__.__make_generic_fromFilename__ = function(matrix_class) matrix_class.fromFilename = function(filename) local f = april_assert(io.open(filename), "Unable to open %s", filename) local ret = table.pack(matrix_class.read(archive_wrapper( f ))) f:close() return table.unpack(ret) end end -- GENERIC FROM TAB FILENAME matrix.__generic__.__make_generic_fromTabFilename__ = function(matrix_class) matrix_class.fromTabFilename = function(filename) local f = april_assert(io.open(filename), "Unable to open %s", filename) local ret = table.pack(matrix_class.read(archive_wrapper( f ), { [matrix.options.tab] = true })) f:close() return table.unpack(ret) end end matrix.__generic__.__make_generic_fromCSVFilename__ = function(matrix_class) matrix_class.fromCSVFilename = function(filename,args) local args = get_table_fields({ [matrix.options.delim] = { mandatory=true, type_match="string", default="," }, [matrix.options.default] = { mandatory=false }, header = { type_match="boolean" }, [matrix.options.map] = { mandatory=false, type_match="table", }, }, args) local header = args.header args.header = nil args[matrix.options.empty] = true args[matrix.options.tab] = true local f = april_assert(io.open(filename), "Unable to open %s", filename) local f = archive_wrapper( f ) if header then header = string.tokenize(f:read("*l"), args[matrix.options.delim]) end local ret = table.pack(matrix_class.read(f, args)) f:close() if header then table.insert(ret, header) end return table.unpack(ret) end end -- GENERIC FROM STRING matrix.__generic__.__make_generic_fromString__ = function(matrix_class) matrix_class.fromString = function(str) return matrix_class.read(aprilio.stream.input_lua_string(str)) end end -- GENERIC TO FILENAME matrix.__generic__.__make_generic_toFilename__ = function(matrix_class, defmode) class.extend(matrix_class, "toFilename", function(self,filename,mode) local mode = mode or defmode local f = april_assert(io.open(filename,"w"), "Unable to open %s", filename) local ret = table.pack(self:write(f, { [matrix.options.ascii] = (mode=="ascii") })) f:close() return table.unpack(ret) end) end -- GENERIC TO TAB FILENAME matrix.__generic__.__make_generic_toTabFilename__ = function(matrix_class) class.extend(matrix_class, "toTabFilename", function(self,filename,mode) local f = april_assert(io.open(filename,"w"), "Unable to open %s", filename) local ret = table.pack(self:write(f, { [matrix.options.ascii] = (mode=="ascii"), [matrix.options.tab] = true })) f:close() return table.unpack(ret) end) end matrix.__generic__.__make_generic_toCSVFilename__ = function(matrix_class) class.extend(matrix_class, "toCSVFilename", function(self,filename,args) local args = get_table_fields({ [matrix.options.delim] = { mandatory=true, type_match="string", default="," }, header = { type_match="table" }, }, args) local delim = args[matrix.options.delim] assert(#delim == 1, "delim should be a 1 character string") local header = args.header args.header = nil local f = april_assert(io.open(filename,"w"), "Unable to open %s", filename) if header then f:write(table.concat(header, delim)) f:write("\n") end local ret = table.pack(self:write(f, { [matrix.options.ascii] = true, [matrix.options.delim] = delim, [matrix.options.tab] = true })) f:close() return table.unpack(ret) end) end -- GENERIC TO STRING matrix.__generic__.__make_generic_toString__ = function(matrix_class, defmode) class.extend(matrix_class, "toString", function(self,mode) local mode = mode or defmode return self:write({ [matrix.options.ascii] = (mode=="ascii") }) end) end function matrix.__generic__.__make_all_serialization_methods__(matrix_class, defmode) local defmode = defmode or "binary" matrix.__generic__.__make_generic_fromFilename__(matrix_class) matrix.__generic__.__make_generic_fromTabFilename__(matrix_class) matrix.__generic__.__make_generic_fromString__(matrix_class) matrix.__generic__.__make_generic_fromCSVFilename__(matrix_class) matrix.__generic__.__make_generic_toFilename__(matrix_class, defmode) matrix.__generic__.__make_generic_toTabFilename__(matrix_class) matrix.__generic__.__make_generic_toString__(matrix_class, defmode) matrix.__generic__.__make_generic_to_lua_string__(matrix_class, defmode) matrix.__generic__.__make_generic_toCSVFilename__(matrix_class) class.extend_metamethod(matrix_class, "ipylua_toseries", function(self) local self = self:squeeze() assert(self:num_dim() == 1, "Needs a rank one matrix") return self end ) end
gpl-3.0
Kosmos82/kosmosdarkstar
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
Kosmos82/kosmosdarkstar
scripts/zones/Leafallia/Zone.lua
30
1242
----------------------------------- -- -- Zone: Leafallia -- ----------------------------------- package.loaded["scripts/zones/Leafallia/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Leafallia/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-1,0,0,151); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Castle_Oztroja/npcs/qm2.lua
13
1407
----------------------------------- -- Area: Castle Oztroja -- NPC: qm2 (???) -- Used In Quest: Whence Blows the Wind -- @pos -100 -63 58 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Castle_Oztroja/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(JEUNO,WHENCE_BLOWS_THE_WIND) == QUEST_ACCEPTED and player:hasKeyItem(YAGUDO_CREST) == false) then player:addKeyItem(YAGUDO_CREST); player:messageSpecial(KEYITEM_OBTAINED, YAGUDO_CREST); 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
Kosmos82/kosmosdarkstar
scripts/globals/spells/bluemagic/body_slam.lua
35
1710
----------------------------------------- -- Spell: Body Slam -- Delivers an area attack. Damage varies with TP -- Spell cost: 74 MP -- Monster Type: Dragon -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: VIT+1, MP+5 -- Level: 62 -- Casting Time: 1 seconds -- Recast Time: 27.75 seconds -- Skillchain Element(s): Lightning (can open Liquefaction or Detonation; can close Impaction or Fusion) -- Combos: Max HP Boost ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_BLUNT; params.scattr = SC_IMPACTION; params.numhits = 1; params.multiplier = 1.5; params.tp150 = 1.5; params.tp300 = 1.5; params.azuretp = 1.5; params.duppercap = 75; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.4; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Open_sea_route_to_Mhaura/Zone.lua
13
1464
----------------------------------- -- -- Zone: Open_sea_route_to_Mhaura (47) -- ----------------------------------- package.loaded["scripts/zones/Open_sea_route_to_Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Open_sea_route_to_Mhaura/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then local position = math.random(-2,2) + 0.150; player:setPos(position,-2.100,3.250,64); end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x0404); player:messageSpecial(DOCKING_IN_MHAURA); 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 == 0x0404) then player:setPos(0,0,0,0,249); end end;
gpl-3.0
squeek502/luvit
tests/test-http-post-1mb.lua
11
2276
--[[ Copyright 2015 The Luvit Authors. All Rights Reserved. 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 http = require('http') local string = require('string') local HOST = "127.0.0.1" local PORT = process.env.PORT or 10085 local server = nil local client = nil local a = string.rep('a', 1024) local data = string.rep(a, 1024) local MB = data:len() require('tap')(function(test) test('http-post-1mb', function(expect) server = http.createServer(function(request, response) p('server:onConnection') local buffer = {} assert(request.method == "POST") assert(request.url == "/foo") assert(request.headers.bar == "cats") request:on('data', function(chunk) table.insert(buffer, chunk) end) request:on('end', expect(function() p('server:onEnd') assert(table.concat(buffer) == data) response:write(data) response:finish() end)) end) server:listen(PORT, HOST, function() local headers = { {'bar', 'cats'}, {'Content-Length', MB}, {'Transfer-Encoding', 'chunked'} } local body = {} local req = http.request({ host = HOST, port = PORT, method = 'POST', path = "/foo", headers = headers }, function(response) assert(response.statusCode == 200) assert(response.httpVersion == '1.1') response:on('data', function(data) body[#body+1] = data p('chunk received',data:len()) end) response:on('end', expect(function(data) data = table.concat(body) assert(data:len() == MB) p('Response ended') server:close() end)) end) req:write(data) req:done() end) end) end)
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Lower_Jeuno/npcs/_l02.lua
13
1556
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- @zone 245 -- @pos -89.022 -0 -123.317 ----------------------------------- 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") == 9) then player:setVar("cService",10); end elseif (hour >= 18 and hour < 21) then if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (player:getVar("cService") == 22) then player:setVar("cService",23); 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
Kosmos82/kosmosdarkstar
scripts/globals/items/serving_of_mille_feuille.lua
18
1471
----------------------------------------- -- ID: 5559 -- Item: Serving of Mille Feuille -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +8 -- MP +15 -- Intelligence +1 -- HP Recoverd while healing 1 -- MP Recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5559); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_MP, 15); target:addMod(MOD_INT, 1); target:addMod(MOD_HPHEAL, 1); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_MP, 15); target:delMod(MOD_INT, 1); target:delMod(MOD_HPHEAL, 1); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
tizzybec/30log
specs/instances.lua
3
4271
require 'luacov' local class = require '30log' context('Instantiation', function() local Window, window before(function() Window = class('Window', {size = 100}) function Window:setSize(size) self.size = size end window = Window:new() end) test('instances are created via new()',function() assert_true(class.isInstance(window)) assert_true(class.isInstance(window, Window)) end) test('or via a class call, as a function',function() local window = Window() assert_true(class.isInstance(window)) assert_true(class.isInstance(window, Window)) end) test('instances can access their class attributes',function() assert_equal(window.size,100) end) test('they also access their class methods',function() window:setSize(50) assert_equal(window.size, 50) end) test('instances cannot instantiate new instances', function() local function should_err() local win_new = window:new() end local function should_err2() local win_new = window() end assert_error(should_err) assert_error(should_err2) end) end) context('init() method, when provided',function() local Window, window before(function() Window = class {size = 100} function Window:init(size) Window.setSize(self,size) end function Window:setSize(size) self.size = size end end) test('is used as an initialization function when instantiating with new(...)',function() window = Window:new(75) assert_equal(window.size,75) end) test('is used as an initialization function when instantiating via a class call',function() window = Window(90) assert_equal(window.size,90) end) end) context('init can also be a table',function() local Window, window before(function() Window = class() Window.init = {size = 200} end) test('its keys will be copied into the new instance',function() window = Window:new() assert_equal(window.size, 200) end) end) context('tostring(instance) returns a string representing an instance', function() local instance_named_class, instance_unnamed_class before(function() instance_named_class = class('class')() instance_unnamed_class = class()() end) test('it works for instances from named classes', function() assert_type(tostring(instance_named_class),'string') end) test('and also for instances from unnamed classes', function() assert_type(tostring(instance_unnamed_class),'string') end) end) context('attributes',function() local aclass, instance before(function() aclass = class('aclass', {attr = 'attr', value = 0}) instance = aclass() end) test('instances have access to their class attributes', function() assert_equal(instance.attr, 'attr') assert_equal(instance.value, 0) end) test('but they can override their class attributes', function() instance.attr, instance.value = 'instance_attr', 1 assert_equal(instance.attr, 'instance_attr') assert_equal(instance.value, 1) end) test('without affecting the class attributes', function() assert_equal(aclass.attr, 'attr') assert_equal(aclass.value, 0) end) end) context('methods',function() local aclass, instance before(function() aclass = class() function aclass:say(something) return something end instance = aclass() end) test('instances have access to their class methods', function() assert_equal(instance:say('hi!'), 'hi!') end) test('instances cannot call new(), as it raises an error', function() assert_error(function() return instance:new() end) assert_error(function() return instance() end) end) test('instances cannot call extends(), as it raises an error', function() assert_error(function() return instance:extends() end) end) test('instances cannot call include(), as it raises an error', function() assert_error(function() return instance:include({}) end) end) test('instances cannot call has(), as it raises an error', function() assert_error(function() return instance:has({}) end) end) test('instances cannot call classOf(), as it raises an error', function() assert_error(function() return instance:classOf(aclass) end) end) test('instances cannot call subclassOf(), as it raises an error', function() assert_error(function() return instance:subclassOf(aclass) end) end) end)
mit
vinzenz/premake
src/_premake_main.lua
7
3768
-- -- _premake_main.lua -- Script-side entry point for the main program logic. -- Copyright (c) 2002-2009 Jason Perkins and the Premake project -- local scriptfile = "premake4.lua" local shorthelp = "Type 'premake4 --help' for help" local versionhelp = "premake4 (Premake Build Script Generator) %s" -- -- Inject a new target platform into each solution; called if the --platform -- argument was specified on the command line. -- local function injectplatform(platform) if not platform then return true end platform = premake.checkvalue(platform, premake.fields.platforms.allowed) for sln in premake.solution.each() do local platforms = sln.platforms or { } -- an empty table is equivalent to a native build if #platforms == 0 then table.insert(platforms, "Native") end -- the solution must provide a native build in order to support this feature if not table.contains(platforms, "Native") then return false, sln.name .. " does not target native platform\nNative platform settings are required for the --platform feature." end -- add it to the end of the list, if it isn't in there already if not table.contains(platforms, platform) then table.insert(platforms, platform) end sln.platforms = platforms end return true end -- -- Script-side program entry point. -- function _premake_main(scriptpath) -- if running off the disk (in debug mode), load everything -- listed in _manifest.lua; the list divisions make sure -- everything gets initialized in the proper order. if (scriptpath) then local scripts = dofile(scriptpath .. "/_manifest.lua") for _,v in ipairs(scripts) do dofile(scriptpath .. "/" .. v) end end -- Set up the environment for the chosen action early, so side-effects -- can be picked up by the scripts. premake.action.set(_ACTION) -- Seed the random number generator so actions don't have to do it themselves math.randomseed(os.time()) -- If there is a project script available, run it to get the -- project information, available options and actions, etc. local fname = _OPTIONS["file"] or scriptfile if (os.isfile(fname)) then dofile(fname) end -- Process special options if (_OPTIONS["version"]) then printf(versionhelp, _PREMAKE_VERSION) return 1 end if (_OPTIONS["help"]) then premake.showhelp() return 1 end -- If no action was specified, show a short help message if (not _ACTION) then print(shorthelp) return 1 end -- If there wasn't a project script I've got to bail now if (not os.isfile(fname)) then error("No Premake script ("..scriptfile..") found!", 2) end -- Validate the command-line arguments. This has to happen after the -- script has run to allow for project-specific options action = premake.action.current() if (not action) then error("Error: no such action '" .. _ACTION .. "'", 0) end ok, err = premake.option.validate(_OPTIONS) if (not ok) then error("Error: " .. err, 0) end -- Sanity check the current project setup ok, err = premake.checktools() if (not ok) then error("Error: " .. err, 0) end -- If a platform was specified on the command line, inject it now ok, err = injectplatform(_OPTIONS["platform"]) if (not ok) then error("Error: " .. err, 0) end -- work-in-progress: build the configurations print("Building configurations...") premake.buildconfigs() ok, err = premake.checkprojects() if (not ok) then error("Error: " .. err, 0) end -- Hand over control to the action printf("Running action '%s'...", action.trigger) premake.action.call(action.trigger) print("Done.") return 0 end
gpl-2.0
yasinghorbani/seed
plugins/tr.lua
14
1877
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
angel2d/angel2d
Code/Angel/Scripting/EngineScripts/sugar.lua
7
3727
------------------------------------------------------------------------------ -- Copyright (C) 2008-2014, Shane Liesegang -- All rights reserved. -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions are met: -- -- * Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- * Redistributions in binary form must reproduce the above copyright -- notice, this list of conditions and the following disclaimer in the -- documentation and/or other materials provided with the distribution. -- * Neither the name of the copyright holder nor the names of any -- contributors may be used to endorse or promote products derived from -- this software without specific prior written permission. -- -- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -- AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -- IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -- ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE -- LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -- CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -- SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -- INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -- CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -- ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE -- POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------ require "util" -- Singleton shortcuts theWorld = World_GetInstance() theTagList = TagCollection_GetInstance() theSwitchboard = Switchboard_GetInstance() theCamera = Camera_GetInstance() theSound = SoundDevice_GetInstance() theTuning = Tuning_GetInstance() thePrefs = Preferences_GetInstance() if (ANGEL_MOBILE == false) then theControllerManager = ControllerManager_GetInstance() sysLog = CompoundLog_GetSystemLog() end -- Input accessors if (ANGEL_MOBILE == false) then theController = theControllerManager:GetController() controllerOne = theController controllerTwo = theControllerManager:GetController(1) end -- Convenience functions function reset() theWorld:ResetWorld() end function tune(varName, newVal) if (type(newVal) == "table") then theTuning:SetVector(varName, newVal) elseif (type(newVal) == "number") then theTuning:SetFloat(varName, newVal) else theTuning:SetString(varName, tostring(newVal)) end theTuning:AddToRuntimeTuningList(varName) end -- COLOR_MAP and paint form a convenience function for setting a color and tag -- at the same time. More importantly, it's a good goldspike to ensure that -- the scripting <-> engine glue is functioning. (Note that it passes a -- a table instead of a Color object, stress testing the input typemaps.) COLOR_MAP = { white = {1.0, 1.0, 1.0}, black = {0.0, 0.0, 0.0}, red = {1.0, 0.0, 0.0}, green = {0.0, 1.0, 0.0}, blue = {0.0, 0.0, 1.0}, yellow = {1.0, 1.0, 0.0}, magenta = {1.0, 0.0, 1.0}, cyan = {0.0, 1.0, 1.0}, purple = {0.5, 0.0, 1.0}, orange = {1.0, 0.5, 0.0}, } function paint(a, colorName) colTable = COLOR_MAP[colorName] if (colTable == nil) then print("No color " .. colorName .. " defined.") return end for name, val in pairs(COLOR_MAP) do a:Untag(name) end a:SetColor(colTable) a:Tag(colorName) end addClassMethod("Actor", "Paint", paint)
bsd-3-clause
vizewang/skynet
service/launcher.lua
51
3199
local skynet = require "skynet" local core = require "skynet.core" require "skynet.manager" -- import manager apis local string = string local services = {} local command = {} local instance = {} -- for confirm (function command.LAUNCH / command.ERROR / command.LAUNCHOK) local function handle_to_address(handle) return tonumber("0x" .. string.sub(handle , 2)) end local NORET = {} function command.LIST() local list = {} for k,v in pairs(services) do list[skynet.address(k)] = v end return list end function command.STAT() local list = {} for k,v in pairs(services) do local stat = skynet.call(k,"debug","STAT") list[skynet.address(k)] = stat end return list end function command.KILL(_, handle) handle = handle_to_address(handle) skynet.kill(handle) local ret = { [skynet.address(handle)] = tostring(services[handle]) } services[handle] = nil return ret end function command.MEM() local list = {} for k,v in pairs(services) do local kb, bytes = skynet.call(k,"debug","MEM") list[skynet.address(k)] = string.format("%.2f Kb (%s)",kb,v) end return list end function command.GC() for k,v in pairs(services) do skynet.send(k,"debug","GC") end return command.MEM() end function command.REMOVE(_, handle, kill) services[handle] = nil local response = instance[handle] if response then -- instance is dead response(not kill) -- return nil to caller of newservice, when kill == false instance[handle] = nil end -- don't return (skynet.ret) because the handle may exit return NORET end local function launch_service(service, ...) local param = table.concat({...}, " ") local inst = skynet.launch(service, param) local response = skynet.response() if inst then services[inst] = service .. " " .. param instance[inst] = response else response(false) return end return inst end function command.LAUNCH(_, service, ...) launch_service(service, ...) return NORET end function command.LOGLAUNCH(_, service, ...) local inst = launch_service(service, ...) if inst then core.command("LOGON", skynet.address(inst)) end return NORET end function command.ERROR(address) -- see serivce-src/service_lua.c -- init failed local response = instance[address] if response then response(false) instance[address] = nil end services[address] = nil return NORET end function command.LAUNCHOK(address) -- init notice local response = instance[address] if response then response(true, address) instance[address] = nil end return NORET end -- for historical reasons, launcher support text command (for C service) skynet.register_protocol { name = "text", id = skynet.PTYPE_TEXT, unpack = skynet.tostring, dispatch = function(session, address , cmd) if cmd == "" then command.LAUNCHOK(address) elseif cmd == "ERROR" then command.ERROR(address) else error ("Invalid text command " .. cmd) end end, } skynet.dispatch("lua", function(session, address, cmd , ...) cmd = string.upper(cmd) local f = command[cmd] if f then local ret = f(address, ...) if ret ~= NORET then skynet.ret(skynet.pack(ret)) end else skynet.ret(skynet.pack {"Unknown command"} ) end end) skynet.start(function() end)
mit
hawkthorne/hawkthorne-client-lua
src/verticalparticles.lua
3
1546
---------------------------------------------------------------------- -- verticalparticles.lua -- Manages the particles for the starry select menu background. -- Created by tjvezina ---------------------------------------------------------------------- Particle = {} Particle.__index = Particle local window = require 'window' function Particle:new() new = {} setmetatable(new, Particle) local winWidth = window.width new.size = math.random(3) new.pos = { x = math.random(winWidth), y = math.random(window.height) } local ratio = 1.0 - math.cos(math.abs(new.pos.x - winWidth/2) * 2 / winWidth) * 0.6 new.speed = 300 * (ratio + math.random()/4) return new end -- Loop each particle repeatedly over the screen function Particle:update(dt) self.pos.y = self.pos.y - (dt * self.speed) if self.pos.y < 0 then self.pos.y = window.height end end function Particle:draw() love.graphics.setPoint(self.size, "rough") love.graphics.point(self.pos.x, self.pos.y) end VerticalParticles = {} local particleCount = 100 local particles = {} -- Generate the requested number of particles function VerticalParticles.init() for i = 1,particleCount do table.insert(particles, Particle:new()) end end function VerticalParticles.update(dt) for _,particle in ipairs(particles) do particle:update(dt) end end function VerticalParticles.draw() love.graphics.setColor( 255, 255, 255, 255 ) for _,particle in ipairs(particles) do particle:draw() end end return VerticalParticles
mit
tinymins/MY
MY_Toolbox/src/MY_FooterTip.lua
1
11296
-------------------------------------------------------- -- This file is part of the JX3 Mingyi Plugin. -- @link : https://jx3.derzh.com/ -- @desc : ºÃÓÑ¡¢°ï»á³ÉÔ±½ÅÏÂÐÕÃûÏÔʾ -- @author : ÜøÒÁ @Ë«ÃÎÕò @×··çõæÓ° -- @modifier : Emil Zhai (root@derzh.com) -- @copyright: Copyright (c) 2013 EMZ Kingsoft Co., Ltd. -------------------------------------------------------- ------------------------------------------------------------------------------------------------------- -- these global functions are accessed all the time by the event handler -- so caching them is worth the effort ------------------------------------------------------------------------------------------------------- local ipairs, pairs, next, pcall, select = ipairs, pairs, next, pcall, select local string, math, table = string, math, table -- lib apis caching local X = MY local UI, GLOBAL, CONSTANT, wstring, lodash = X.UI, X.GLOBAL, X.CONSTANT, X.wstring, X.lodash ------------------------------------------------------------------------------------------------------- local PLUGIN_NAME = 'MY_Toolbox' local PLUGIN_ROOT = X.PACKET_INFO.ROOT .. PLUGIN_NAME local MODULE_NAME = 'MY_Toolbox' local _L = X.LoadLangPack(PLUGIN_ROOT .. '/lang/') -------------------------------------------------------------------------- if not X.AssertVersion(MODULE_NAME, _L[MODULE_NAME], '^9.0.0') then return end -------------------------------------------------------------------------- local O = X.CreateUserSettingsModule('MY_FooterTip', _L['General'], { bFriend = { ePathType = X.PATH_TYPE.ROLE, szLabel = _L['MY_Toolbox'], xSchema = X.Schema.Boolean, xDefaultValue = false, }, bFriendNav = { ePathType = X.PATH_TYPE.ROLE, szLabel = _L['MY_Toolbox'], xSchema = X.Schema.Boolean, xDefaultValue = false, }, bFriendDungeonHide = { ePathType = X.PATH_TYPE.ROLE, szLabel = _L['MY_Toolbox'], xSchema = X.Schema.Boolean, xDefaultValue = true, }, bTongMember = { ePathType = X.PATH_TYPE.ROLE, szLabel = _L['MY_Toolbox'], xSchema = X.Schema.Boolean, xDefaultValue = false, }, bTongMemberNav = { ePathType = X.PATH_TYPE.ROLE, szLabel = _L['MY_Toolbox'], xSchema = X.Schema.Boolean, xDefaultValue = false, }, bTongMemberDungeonHide = { ePathType = X.PATH_TYPE.ROLE, szLabel = _L['MY_Toolbox'], xSchema = X.Schema.Boolean, xDefaultValue = true, }, }) local D = {} function D.Apply() -- ºÃÓѸßÁÁ if Navigator_Remove then Navigator_Remove('MY_FRIEND_TIP') end if D.bReady and O.bFriend and not X.IsInShieldedMap() and (not O.bFriendDungeonHide or not X.IsInDungeon()) then local hShaList = UI.GetShadowHandle('MY_FriendHeadTip') if not hShaList.freeShadows then hShaList.freeShadows = {} end hShaList:Show() local function OnPlayerEnter(dwID) local tar = GetPlayer(dwID) local me = GetClientPlayer() if not tar or not me or X.IsIsolated(tar) ~= X.IsIsolated(me) then return end local p = X.GetFriend(dwID) if p then if O.bFriendNav and Navigator_SetID then Navigator_SetID('MY_FRIEND_TIP.' .. dwID, TARGET.PLAYER, dwID, p.name) else local sha = hShaList:Lookup(tostring(dwID)) if not sha then hShaList:AppendItemFromString('<shadow>name="' .. dwID .. '"</shadow>') sha = hShaList:Lookup(tostring(dwID)) end local r, g, b, a = 255,255,255,255 local szTip = '>> ' .. p.name .. ' <<' sha:ClearTriangleFanPoint() sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:AppendCharacterID(dwID, false, r, g, b, a, 0, 40, szTip, 0, 1) sha:Show() end end end local function OnPlayerLeave(dwID) if O.bFriendNav and Navigator_Remove then Navigator_Remove('MY_FRIEND_TIP.' .. dwID) else local sha = hShaList:Lookup(tostring(dwID)) if sha then sha:Hide() table.insert(hShaList.freeShadows, sha) end end end local function RescanNearby() for _, p in ipairs(X.GetNearPlayer()) do OnPlayerEnter(p.dwID) end end RescanNearby() X.RegisterEvent('ON_ISOLATED', 'MY_FRIEND_TIP', function(event) -- dwCharacterID, nIsolated local me = GetClientPlayer() if arg0 == UI_GetClientPlayerID() then for _, p in ipairs(X.GetNearPlayer()) do if X.IsIsolated(p) == X.IsIsolated(me) then OnPlayerEnter(p.dwID) else OnPlayerLeave(p.dwID) end end else local tar = GetPlayer(arg0) if tar then if X.IsIsolated(tar) == X.IsIsolated(me) then OnPlayerEnter(arg0) else OnPlayerLeave(arg0) end end end end) X.RegisterEvent('PLAYER_ENTER_SCENE', 'MY_FRIEND_TIP', function(event) OnPlayerEnter(arg0) end) X.RegisterEvent('PLAYER_LEAVE_SCENE', 'MY_FRIEND_TIP', function(event) OnPlayerLeave(arg0) end) X.RegisterEvent('DELETE_FELLOWSHIP', 'MY_FRIEND_TIP', function(event) RescanNearby() end) X.RegisterEvent('PLAYER_FELLOWSHIP_UPDATE', 'MY_FRIEND_TIP', function(event) RescanNearby() end) X.RegisterEvent('PLAYER_FELLOWSHIP_CHANGE', 'MY_FRIEND_TIP', function(event) RescanNearby() end) else X.RegisterEvent('ON_ISOLATED', 'MY_FRIEND_TIP', false) X.RegisterEvent('PLAYER_ENTER_SCENE', 'MY_FRIEND_TIP', false) X.RegisterEvent('PLAYER_LEAVE_SCENE', 'MY_FRIEND_TIP', false) X.RegisterEvent('DELETE_FELLOWSHIP', 'MY_FRIEND_TIP', false) X.RegisterEvent('PLAYER_FELLOWSHIP_UPDATE', 'MY_FRIEND_TIP', false) X.RegisterEvent('PLAYER_FELLOWSHIP_CHANGE', 'MY_FRIEND_TIP', false) UI.GetShadowHandle('MY_FriendHeadTip'):Hide() end -- °ï»á³ÉÔ±¸ßÁÁ if Navigator_Remove then Navigator_Remove('MY_GUILDMEMBER_TIP') end if D.bReady and O.bTongMember and not X.IsInShieldedMap() and (not O.bTongMemberDungeonHide or not X.IsInDungeon()) then local hShaList = UI.GetShadowHandle('MY_TongMemberHeadTip') if not hShaList.freeShadows then hShaList.freeShadows = {} end hShaList:Show() local function OnPlayerEnter(dwID, nRetryCount) nRetryCount = nRetryCount or 0 if nRetryCount > 5 then return end local tar = GetPlayer(dwID) local me = GetClientPlayer() if not tar or not me or me.dwTongID == 0 or me.dwID == tar.dwID or tar.dwTongID ~= me.dwTongID or X.IsIsolated(tar) ~= X.IsIsolated(me) then return end if tar.szName == '' then X.DelayCall(500, function() OnPlayerEnter(dwID, nRetryCount + 1) end) return end if O.bTongMemberNav and Navigator_SetID then Navigator_SetID('MY_GUILDMEMBER_TIP.' .. dwID, TARGET.PLAYER, dwID, tar.szName) else local sha = hShaList:Lookup(tostring(dwID)) if not sha then hShaList:AppendItemFromString('<shadow>name="' .. dwID .. '"</shadow>') sha = hShaList:Lookup(tostring(dwID)) end local r, g, b, a = 255,255,255,255 local szTip = '> ' .. tar.szName .. ' <' sha:ClearTriangleFanPoint() sha:SetTriangleFan(GEOMETRY_TYPE.TEXT) sha:AppendCharacterID(dwID, false, r, g, b, a, 0, 40, szTip, 0, 1) sha:Show() end end local function OnPlayerLeave(dwID) if O.bTongMemberNav and Navigator_Remove then Navigator_Remove('MY_GUILDMEMBER_TIP.' .. dwID) else local sha = hShaList:IsValid() and hShaList:Lookup(tostring(dwID)) if sha then sha:Hide() table.insert(hShaList.freeShadows, sha) end end end for _, p in ipairs(X.GetNearPlayer()) do OnPlayerEnter(p.dwID) end X.RegisterEvent('ON_ISOLATED', 'MY_GUILDMEMBER_TIP', function(event) -- dwCharacterID, nIsolated local me = GetClientPlayer() if arg0 == UI_GetClientPlayerID() then for _, p in ipairs(X.GetNearPlayer()) do if X.IsIsolated(p) == X.IsIsolated(me) then OnPlayerEnter(p.dwID) else OnPlayerLeave(p.dwID) end end else local tar = GetPlayer(arg0) if tar then if X.IsIsolated(tar) == X.IsIsolated(me) then OnPlayerEnter(arg0) else OnPlayerLeave(arg0) end end end end) X.RegisterEvent('PLAYER_ENTER_SCENE', 'MY_GUILDMEMBER_TIP', function(event) OnPlayerEnter(arg0) end) X.RegisterEvent('PLAYER_LEAVE_SCENE', 'MY_GUILDMEMBER_TIP', function(event) OnPlayerLeave(arg0) end) else X.RegisterEvent('ON_ISOLATED', 'MY_GUILDMEMBER_TIP', false) X.RegisterEvent('PLAYER_ENTER_SCENE', 'MY_GUILDMEMBER_TIP', false) X.RegisterEvent('PLAYER_LEAVE_SCENE', 'MY_GUILDMEMBER_TIP', false) UI.GetShadowHandle('MY_TongMemberHeadTip'):Hide() end end X.RegisterUserSettingsUpdate('@@INIT@@', 'MY_FooterTip', function() D.bReady = true D.Apply() end) X.RegisterEvent('LOADING_ENDING', 'MY_FooterTip', D.Apply) function D.OnPanelActivePartial(ui, nPaddingX, nPaddingY, nW, nH, nX, nY, nLH) -- ºÃÓѸßÁÁ nX = nPaddingX nX = nX + ui:Append('WndCheckBox', { x = nX, y = nY, w = 'auto', text = _L['Friend headtop tips'], checked = MY_FooterTip.bFriend, oncheck = function(bCheck) MY_FooterTip.bFriend = not MY_FooterTip.bFriend end, }):Width() + 5 nX = nX + ui:Append('WndCheckBox', { x = nX, y = nY, w = 'auto', text = _L['Friend headtop hide in dungeon'], checked = MY_FooterTip.bFriendDungeonHide, oncheck = function(bCheck) MY_FooterTip.bFriendDungeonHide = not MY_FooterTip.bFriendDungeonHide end, autoenable = function() return MY_FooterTip.bFriend end, }):Width() + 5 nX = nX + ui:Append('WndCheckBox', { x = nX, y = nY, w = 'auto', text = _L['Friend headtop tips nav'], checked = MY_FooterTip.bFriendNav, oncheck = function(bCheck) MY_FooterTip.bFriendNav = not MY_FooterTip.bFriendNav end, autoenable = function() return MY_FooterTip.bFriend end, }):Width() + 5 nY = nY + nLH -- °ï»á¸ßÁÁ nX = nPaddingX nX = nX + ui:Append('WndCheckBox', { x = nX, y = nY, w = 'auto', text = _L['Tong member headtop tips'], checked = MY_FooterTip.bTongMember, oncheck = function(bCheck) MY_FooterTip.bTongMember = not MY_FooterTip.bTongMember end, }):Width() + 5 nX = nX + ui:Append('WndCheckBox', { x = nX, y = nY, w = 'auto', text = _L['Tong member headtop hide in dungeon'], checked = MY_FooterTip.bTongMemberDungeonHide, oncheck = function(bCheck) MY_FooterTip.bTongMemberDungeonHide = not MY_FooterTip.bTongMemberDungeonHide end, autoenable = function() return MY_FooterTip.bTongMember end, }):Width() + 5 nX = nX + ui:Append('WndCheckBox', { x = nX, y = nY, w = 'auto', text = _L['Tong member headtop tips nav'], checked = MY_FooterTip.bTongMemberNav, oncheck = function(bCheck) MY_FooterTip.bTongMemberNav = not MY_FooterTip.bTongMemberNav end, autoenable = function() return MY_FooterTip.bTongMember end, }):Width() + 5 nY = nY + nLH return nX, nY end -- Global exports do local settings = { name = 'MY_FooterTip', exports = { { fields = { 'OnPanelActivePartial', }, root = D, }, { fields = { 'bFriend', 'bFriendNav', 'bFriendDungeonHide', 'bTongMember', 'bTongMemberNav', 'bTongMemberDungeonHide', }, root = O, }, }, imports = { { fields = { 'bFriend', 'bFriendNav', 'bFriendDungeonHide', 'bTongMember', 'bTongMemberNav', 'bTongMemberDungeonHide', }, triggers = { bFriend = D.Apply, bFriendNav = D.Apply, bFriendDungeonHide = D.Apply, bTongMember = D.Apply, bTongMemberNav = D.Apply, bTongMemberDungeonHide = D.Apply, }, root = O, }, }, } MY_FooterTip = X.CreateModule(settings) end
bsd-3-clause
Kosmos82/kosmosdarkstar
scripts/zones/Northern_San_dOria/npcs/Eperdur.lua
12
5419
----------------------------------- -- Area: Northern San d'Oria -- NPC: Eperdur -- Starts and Finishes Quest: Altana's Sorrow (finish), Acting in Good Faith (finish), Healing the Land, -- @pos 129 -6 96 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) AltanaSorrow = player:getQuestStatus(BASTOK,ALTANA_S_SORROW); ActingInGoodFaith = player:getQuestStatus(WINDURST,ACTING_IN_GOOD_FAITH); HealingTheLand = player:getQuestStatus(SANDORIA,HEALING_THE_LAND); SorceryOfTheNorth = player:getQuestStatus(SANDORIA,SORCERY_OF_THE_NORTH); if (AltanaSorrow == QUEST_ACCEPTED and player:hasKeyItem(LETTER_FROM_VIRNAGE)) then player:startEvent(0x02a7); -- Finish quest "Altana's Sorrow" elseif (ActingInGoodFaith == QUEST_ACCEPTED and player:hasKeyItem(GANTINEUXS_LETTER)) then player:startEvent(0x02a8); -- Finish quest "Acting in Good Faith" elseif (HealingTheLand == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 4 and player:getMainLvl() >= 10) then player:startEvent(0x02a9); -- Start quest "Healing the Land" elseif (HealingTheLand == QUEST_ACCEPTED and player:hasKeyItem(SEAL_OF_BANISHING)) then player:startEvent(0x02aa); -- During quest "Healing the Land" elseif (HealingTheLand == QUEST_ACCEPTED and player:hasKeyItem(SEAL_OF_BANISHING) == false) then player:startEvent(0x02ab); -- Finish quest "Healing the Land" elseif (HealingTheLand == QUEST_COMPLETED and SorceryOfTheNorth == QUEST_AVAILABLE and player:needToZone()) then player:startEvent(0x02ac); -- New standard dialog after "Healing the Land" elseif (HealingTheLand == QUEST_COMPLETED and SorceryOfTheNorth == QUEST_AVAILABLE and player:needToZone() == false) then player:startEvent(0x02ad); -- Start quest "Sorcery of the North" elseif (SorceryOfTheNorth == QUEST_ACCEPTED and player:hasKeyItem(FEIYIN_MAGIC_TOME) == false) then player:startEvent(0x02ae); -- During quest "Sorcery of the North" elseif (SorceryOfTheNorth == QUEST_ACCEPTED and player:hasKeyItem(FEIYIN_MAGIC_TOME)) then player:startEvent(0x02af); -- Finish quest "Sorcery of the North" else player:startEvent(0x02a6); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x02a7) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4731); else player:addTitle(PILGRIM_TO_DEM); player:delKeyItem(LETTER_FROM_VIRNAGE); player:addItem(4731); player:messageSpecial(ITEM_OBTAINED,4731); -- Scroll of Teleport-Dem player:addFame(BASTOK,30); player:completeQuest(BASTOK,ALTANA_S_SORROW); end elseif (csid == 0x02a8) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4732); else player:addTitle(PILGRIM_TO_MEA); player:delKeyItem(GANTINEUXS_LETTER); player:addItem(4732); player:messageSpecial(ITEM_OBTAINED,4732); -- Scroll of Teleport-Mea player:addFame(WINDURST,30); player:completeQuest(WINDURST,ACTING_IN_GOOD_FAITH); end elseif (csid == 0x02a9 and option == 0) then player:addQuest(SANDORIA,HEALING_THE_LAND); player:addKeyItem(SEAL_OF_BANISHING); player:messageSpecial(KEYITEM_OBTAINED,SEAL_OF_BANISHING); elseif (csid == 0x02ab) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4730); else player:addTitle(PILGRIM_TO_HOLLA); player:addItem(4730); player:messageSpecial(ITEM_OBTAINED,4730); -- Scroll of Teleport-Holla player:needToZone(true); player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,HEALING_THE_LAND); end elseif (csid == 0x02ad and option == 0) then player:addQuest(SANDORIA,SORCERY_OF_THE_NORTH); elseif (csid == 0x02af) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4747); else player:delKeyItem(FEIYIN_MAGIC_TOME); player:addItem(4747); player:messageSpecial(ITEM_OBTAINED,4747); -- Scroll of Teleport-Vahzl player:addFame(SANDORIA,30); player:completeQuest(SANDORIA,SORCERY_OF_THE_NORTH); end end end;
gpl-3.0
King098/LuaFramework-ToLua-FairyGUI
Assets/LuaFramework/ToLua/Lua/jit/v.lua
5
5769
---------------------------------------------------------------------------- -- Verbose mode of the LuaJIT compiler. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module shows verbose information about the progress of the -- JIT compiler. It prints one line for each generated trace. This module -- is useful to see which code has been compiled or where the compiler -- punts and falls back to the interpreter. -- -- Example usage: -- -- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end" -- luajit -jv=myapp.out myapp.lua -- -- Default output is to stderr. To redirect the output to a file, pass a -- filename as an argument (use '-' for stdout) or set the environment -- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the -- module is started. -- -- The output from the first example should look like this: -- -- [TRACE 1 (command line):1 loop] -- [TRACE 2 (1/3) (command line):1 -> 1] -- -- The first number in each line is the internal trace number. Next are -- the file name ('(command line)') and the line number (':1') where the -- trace has started. Side traces also show the parent trace number and -- the exit number where they are attached to in parentheses ('(1/3)'). -- An arrow at the end shows where the trace links to ('-> 1'), unless -- it loops to itself. -- -- In this case the inner loop gets hot and is traced first, generating -- a root trace. Then the last exit from the 1st trace gets hot, too, -- and triggers generation of the 2nd trace. The side trace follows the -- path along the outer loop and *around* the inner loop, back to its -- start, and then links to the 1st trace. Yes, this may seem unusual, -- if you know how traditional compilers work. Trace compilers are full -- of surprises like this -- have fun! :-) -- -- Aborted traces are shown like this: -- -- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50] -- -- Don't worry -- trace aborts are quite common, even in programs which -- can be fully compiled. The compiler may retry several times until it -- finds a suitable trace. -- -- Of course this doesn't work with features that are not-yet-implemented -- (NYI error messages). The VM simply falls back to the interpreter. This -- may not matter at all if the particular trace is not very high up in -- the CPU usage profile. Oh, and the interpreter is quite fast, too. -- -- Also check out the -jdump module, which prints all the gory details. -- ------------------------------------------------------------------------------ -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local jutil = require("jit.util") local vmdef = require("jit.vmdef") local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo local type, format = type, string.format local stdout, stderr = io.stdout, io.stderr -- Active flag and output file handle. local active, out ------------------------------------------------------------------------------ local startloc, startex local function fmtfunc(func, pc) local fi = funcinfo(func, pc) if fi.loc then return fi.loc elseif fi.ffid then return vmdef.ffnames[fi.ffid] elseif fi.addr then return format("C:%x", fi.addr) else return "(?)" end end -- Format trace error message. local function fmterr(err, info) if type(err) == "number" then if type(info) == "function" then info = fmtfunc(info) end err = format(vmdef.traceerr[err], info) end return err end -- Dump trace states. local function dump_trace(what, tr, func, pc, otr, oex) if what == "start" then startloc = fmtfunc(func, pc) startex = otr and "("..otr.."/"..(oex == -1 and "stitch" or oex)..") " or "" else if what == "abort" then local loc = fmtfunc(func, pc) if loc ~= startloc then print(format("[TRACE --- %s%s -- %s at %s]\n", startex, startloc, fmterr(otr, oex), loc)) else print(format("[TRACE --- %s%s -- %s]\n", startex, startloc, fmterr(otr, oex))) end elseif what == "stop" then local info = traceinfo(tr) local link, ltype = info.link, info.linktype if ltype == "interpreter" then print(format("[TRACE %3s %s%s -- fallback to interpreter]\n", tr, startex, startloc)) elseif ltype == "stitch" then print(format("[TRACE %3s %s%s %s %s]\n", tr, startex, startloc, ltype, fmtfunc(func, pc))) elseif link == tr or link == 0 then print(format("[TRACE %3s %s%s %s]\n", tr, startex, startloc, ltype)) elseif ltype == "root" then print(format("[TRACE %3s %s%s -> %d]\n", tr, startex, startloc, link)) else print(format("[TRACE %3s %s%s -> %d %s]\n", tr, startex, startloc, link, ltype)) end else print(format("[TRACE %s]\n", what)) end out:flush() end end ------------------------------------------------------------------------------ -- Detach dump handlers. local function dumpoff() if active then active = false jit.attach(dump_trace) if out and out ~= stdout and out ~= stderr then out:close() end out = nil end end -- Open the output file and attach dump handlers. local function dumpon(outfile) if active then dumpoff() end if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stderr end jit.attach(dump_trace, "trace") active = true end -- Public module functions. return { on = dumpon, off = dumpoff, start = dumpon -- For -j command line option. }
mit
BooM-amour/superbomb
plugins/ingroup.lua
371
44212
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local leave_ban = "no" if data[tostring(msg.to.id)]['settings']['leave_ban'] then leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] end local 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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators 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 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] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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_namemod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" 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 local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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_membermod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function set_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'yes' then return 'Group is already public' else data[tostring(target)]['settings']['public'] = 'yes' save_data(_config.moderation.data, data) end return 'Group is now: public' end local function unset_public_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['public'] if group_member_lock == 'no' then return 'Group is not public' else data[tostring(target)]['settings']['public'] = 'no' save_data(_config.moderation.data, data) return 'Group is now: not public' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators 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 set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators 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 local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = '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 = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(user_id, chat_id) local user_info local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(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 matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end end if matches[1] == 'unlock' then local target = msg.to.id if matches[2] == 'name' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link:\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] local user_info = redis:hgetall('user:'..group_owner) if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") if user_info.username then return "Group onwer is @"..user_info.username.." ["..group_owner.."]" else return "Group owner is ["..group_owner..']' end end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then return "Wrong number,range is [5-20]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == '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 if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
harveyhu2012/luci
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdhna.lua
78
1844
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2011 Manuel Munz <freifunk at somakoma dot de> 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 $Id$ ]]-- local uci = require "luci.model.uci".cursor() local ipv = uci:get_first("olsrd", "olsrd", "IpVersion", "4") mh = Map("olsrd", translate("OLSR - HNA-Announcements"), translate("Hosts in a OLSR routed network can announce connecitivity " .. "to external networks using HNA messages.")) if ipv == "6and4" or ipv == "4" then hna4 = mh:section(TypedSection, "Hna4", translate("Hna4"), translate("Both values must use the dotted decimal notation.")) hna4.addremove = true hna4.anonymous = true hna4.template = "cbi/tblsection" net4 = hna4:option(Value, "netaddr", translate("Network address")) net4.datatype = "ip4addr" net4.placeholder = "10.11.12.13" net4.default = "10.11.12.13" msk4 = hna4:option(Value, "netmask", translate("Netmask")) msk4.datatype = "ip4addr" msk4.placeholder = "255.255.255.255" msk4.default = "255.255.255.255" end if ipv == "6and4" or ipv == "6" then hna6 = mh:section(TypedSection, "Hna6", translate("Hna6"), translate("IPv6 network must be given in full notation, " .. "prefix must be in CIDR notation.")) hna6.addremove = true hna6.anonymous = true hna6.template = "cbi/tblsection" net6 = hna6:option(Value, "netaddr", translate("Network address")) net6.datatype = "ip6addr" net6.placeholder = "fec0:2200:106:0:0:0:0:0" net6.default = "fec0:2200:106:0:0:0:0:0" msk6 = hna6:option(Value, "prefix", translate("Prefix")) msk6.datatype = "range(0,128)" msk6.placeholder = "128" msk6.default = "128" end return mh
apache-2.0
maysam0111/ss
plugins/invite.lua
2
1317
do local function callbackres(extra, success, result) local user = 'user#id'..result.peer_id local chat = 'chat#id'..extra.chatid local channel = 'channel#id'..extra.chatid if is_banned(result.id, extra.chatid) then send_large_msg(chat, 'User is banned.') send_large_msg(channel, 'User is banned.') elseif is_gbanned(result.id) then send_large_msg(chat, 'User is globaly banned.') send_large_msg(channel, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) channel_invite(channel, user, ok_cb, false) end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_momod(msg) then return end if not is_admin1(msg) then -- For admins only ! return 'Only admins can invite.' end if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin1(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' or msg.to.type ~= 'channel' then local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") resolve_username(username, callbackres, cbres_extra) end end return { patterns = { "^[#!/]invite (.*)$" }, run = run } end
gpl-2.0
Kosmos82/kosmosdarkstar
scripts/globals/mobskills/PL_Heavy_Stomp.lua
33
1168
--------------------------------------------- -- Heavy Stomp -- -- Description: Deals heavy damage to targets within an area of effect. Additional effect: Paralysis -- Type: Physical -- Utsusemi/Blink absorb: 2-3 shadows -- Range: Unknown radial -- Notes: Paralysis effect has a very long duration. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) local mobSkin = mob:getModelId(); if (mobSkin == 421) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = math.random(2,3); local accmod = 1; local dmgmod = .7; 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); local typeEffect = EFFECT_PARALYSIS; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 15, 0, 360); target:delHP(dmg); return dmg; end;
gpl-3.0
hawkthorne/hawkthorne-client-lua
src/nodes/material.lua
1
1656
----------------------------------------------- -- material.lua -- Represents a material when it is in the world -- Created by HazardousPeach ----------------------------------------------- local controls = require 'controls' local Item = require 'items/item' local Material = {} Material.__index = Material Material.isMaterial = true --- -- Creates a new material object -- @return the material object created function Material.new(node, collider) local material = {} setmetatable(material, Material) material.name = node.name material.image = love.graphics.newImage('images/materials/'..node.name..'.png') material.image_q = love.graphics.newQuad( 0, 0, 24, 24, material.image:getWidth(),material.image:getHeight() ) --TODO: reimplement use of foreground property --material.foreground = node.properties.foreground material.position = {x = node.x, y = node.y} material.width = node.width material.height = node.height material.touchedPlayer = nil material.exists = true return material end --- -- Draws the material to the screen -- @return nil function Material:draw() if not self.exists then return end love.graphics.drawq(self.image, self.image_q, self.position.x, self.position.y) end --- -- Called when the material begins colliding with another node -- @return nil function Material:collide(node, dt, mtv_x, mtv_y) end --- -- Called when the material finishes colliding with another node -- @return nil function Material:collide_end(node, dt) end --- -- Updates the material and allows the player to pick it up. function Material:update() end return Material
mit
Kosmos82/kosmosdarkstar
scripts/zones/Spire_of_Dem/npcs/_0j1.lua
39
1330
----------------------------------- -- Area: Spire_of_Dem -- NPC: web of regret ----------------------------------- package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/zones/Spire_of_Dem/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
firebaugh/Digitowls
Lib/Platform/Nao/Body/dcm.lua
4
1300
module(..., package.seeall); require("shm"); require("carray"); sensorShm = shm.open('dcmSensor'); actuatorShm = shm.open('dcmActuator'); sensor = {}; actuator = {}; function get_sensor_shm(shmkey, index) if (index) then return sensor[shmkey][index]; else local t = {}; for i = 1,#sensor[shmkey] do t[i] = sensor[shmkey][i]; end return t; end end function set_actuator_shm(shmkey, val, index) index = index or 1; if (type(val) == "number") then actuator[shmkey][index] = val; elseif (type(val) == "table") then for i = 1,#val do actuator[shmkey][index+i-1] = val[i]; end end end function init() for k,v in sensorShm.next, sensorShm do sensor[k] = carray.cast(sensorShm:pointer(k)); getfenv()["get_sensor_"..k] = function(index) return get_sensor_shm(k, index); end end for k,v in actuatorShm.next, actuatorShm do actuator[k] = carray.cast(actuatorShm:pointer(k)); getfenv()["set_actuator_"..k] = function(val, index) return set_actuator_shm(k, val, index); end end nJoint = #actuator.position; -- Initialize actuator commands and positions for i = 1,nJoint do actuator.command[i] = sensor.position[i]; actuator.position[i] = sensor.position[i]; end end
gpl-3.0
justincormack/snabbswitch
lib/ljsyscall/syscall/netbsd/syscalls.lua
24
4076
-- BSD specific syscalls local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" return function(S, hh, c, C, types) local ffi = require "ffi" local errno = ffi.errno local t, pt, s = types.t, types.pt, types.s local ret64, retnum, retfd, retbool, retptr, retiter = hh.ret64, hh.retnum, hh.retfd, hh.retbool, hh.retptr, hh.retiter local h = require "syscall.helpers" local istype, mktype, getfd = h.istype, h.mktype, h.getfd local octal = h.octal function S.paccept(sockfd, addr, addrlen, set, flags) if set then set = mktype(t.sigset, set) end local saddr = pt.sockaddr(addr) return retfd(C.paccept(getfd(sockfd), saddr, addrlen, set, c.SOCK[flags])) end local mntstruct = { ffs = t.ufs_args, --nfs = t.nfs_args, --mfs = t.mfs_args, tmpfs = t.tmpfs_args, sysvbfs = t.ufs_args, ptyfs = t.ptyfs_args, procfs = t.procfs_args, } function S.mount(fstype, dir, flags, data, datalen) local str if type(data) == "string" then -- common case, for ufs etc str = data data = {fspec = pt.char(str)} end if data then local tp = mntstruct[fstype] if tp then data = mktype(tp, data) end else datalen = 0 end local ret = C.mount(fstype, dir, c.MNT[flags], data, datalen or #data) return retbool(ret) end function S.reboot(how, bootstr) return retbool(C.reboot(c.RB[how], bootstr)) end function S.fsync_range(fd, how, start, length) return retbool(C.fsync_range(getfd(fd), c.FSYNC[how], start, length)) end function S.getvfsstat(flags, buf, size) -- note order of args as usually leave buf empty flags = c.VFSMNT[flags or "WAIT"] -- default not zero if not buf then local n, err = C.getvfsstat(nil, 0, flags) if not n then return nil, t.error(err or errno()) end --buf = t.statvfss(n) -- TODO define size = s.statvfs * n end size = size or #buf local n, err = C.getvfsstat(buf, size, flags) if not n then return nil, err end return buf -- TODO need type with number end -- TODO when we define this for osx can go in common code (curently defined in libc.lua) function S.getcwd(buf, size) size = size or c.PATH_MAX buf = buf or t.buffer(size) local ret, err = C.getcwd(buf, size) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buf) end function S.kqueue1(flags) return retfd(C.kqueue1(c.O[flags])) end -- TODO this is the same as ppoll other than if timeout is modified, which Linux syscall but not libc does; could merge function S.pollts(fds, timeout, set) if timeout then timeout = mktype(t.timespec, timeout) end if set then set = mktype(t.sigset, set) end return retnum(C.pollts(fds.pfd, #fds, timeout, set)) end function S.ktrace(tracefile, ops, trpoints, pid) return retbool(C.ktrace(tracefile, c.KTROP[ops], c.KTRFAC(trpoints, "V2"), pid)) end function S.fktrace(fd, ops, trpoints, pid) return retbool(C.fktrace(getfd(fd), c.KTROP[ops], c.KTRFAC(trpoints, "V2"), pid)) end function S.utrace(label, addr, len) return retbool(C.utrace(label, addr, len)) -- TODO allow string to be passed as addr? end -- pty functions function S.grantpt(fd) return S.ioctl(fd, "TIOCGRANTPT") end function S.unlockpt(fd) return 0 end function S.ptsname(fd) local pm, err = S.ioctl(fd, "TIOCPTSNAME") if not pm then return nil, err end return ffi.string(pm.sn) end -- TODO we need to fix sigaction in NetBSD, syscall seems to have changed to sigaction_tramp function S.pause() return S.select({}) end -- select on nothing forever -- ksem functions. Not very well documented! You shoudl probably use pthreads in most cases function S.ksem_init(value, semid) semid = semid or t.intptr1() local ok, err = C._ksem_init(value, semid) if not ok then return nil, t.error(err or errno()) end return semid[0] end function S.ksem_destroy(semid) return retbool(C._ksem_destroy(semid)) end return S end
apache-2.0
Igalia/snabb
lib/ljsyscall/syscall/netbsd/syscalls.lua
24
4076
-- BSD specific syscalls local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" return function(S, hh, c, C, types) local ffi = require "ffi" local errno = ffi.errno local t, pt, s = types.t, types.pt, types.s local ret64, retnum, retfd, retbool, retptr, retiter = hh.ret64, hh.retnum, hh.retfd, hh.retbool, hh.retptr, hh.retiter local h = require "syscall.helpers" local istype, mktype, getfd = h.istype, h.mktype, h.getfd local octal = h.octal function S.paccept(sockfd, addr, addrlen, set, flags) if set then set = mktype(t.sigset, set) end local saddr = pt.sockaddr(addr) return retfd(C.paccept(getfd(sockfd), saddr, addrlen, set, c.SOCK[flags])) end local mntstruct = { ffs = t.ufs_args, --nfs = t.nfs_args, --mfs = t.mfs_args, tmpfs = t.tmpfs_args, sysvbfs = t.ufs_args, ptyfs = t.ptyfs_args, procfs = t.procfs_args, } function S.mount(fstype, dir, flags, data, datalen) local str if type(data) == "string" then -- common case, for ufs etc str = data data = {fspec = pt.char(str)} end if data then local tp = mntstruct[fstype] if tp then data = mktype(tp, data) end else datalen = 0 end local ret = C.mount(fstype, dir, c.MNT[flags], data, datalen or #data) return retbool(ret) end function S.reboot(how, bootstr) return retbool(C.reboot(c.RB[how], bootstr)) end function S.fsync_range(fd, how, start, length) return retbool(C.fsync_range(getfd(fd), c.FSYNC[how], start, length)) end function S.getvfsstat(flags, buf, size) -- note order of args as usually leave buf empty flags = c.VFSMNT[flags or "WAIT"] -- default not zero if not buf then local n, err = C.getvfsstat(nil, 0, flags) if not n then return nil, t.error(err or errno()) end --buf = t.statvfss(n) -- TODO define size = s.statvfs * n end size = size or #buf local n, err = C.getvfsstat(buf, size, flags) if not n then return nil, err end return buf -- TODO need type with number end -- TODO when we define this for osx can go in common code (curently defined in libc.lua) function S.getcwd(buf, size) size = size or c.PATH_MAX buf = buf or t.buffer(size) local ret, err = C.getcwd(buf, size) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buf) end function S.kqueue1(flags) return retfd(C.kqueue1(c.O[flags])) end -- TODO this is the same as ppoll other than if timeout is modified, which Linux syscall but not libc does; could merge function S.pollts(fds, timeout, set) if timeout then timeout = mktype(t.timespec, timeout) end if set then set = mktype(t.sigset, set) end return retnum(C.pollts(fds.pfd, #fds, timeout, set)) end function S.ktrace(tracefile, ops, trpoints, pid) return retbool(C.ktrace(tracefile, c.KTROP[ops], c.KTRFAC(trpoints, "V2"), pid)) end function S.fktrace(fd, ops, trpoints, pid) return retbool(C.fktrace(getfd(fd), c.KTROP[ops], c.KTRFAC(trpoints, "V2"), pid)) end function S.utrace(label, addr, len) return retbool(C.utrace(label, addr, len)) -- TODO allow string to be passed as addr? end -- pty functions function S.grantpt(fd) return S.ioctl(fd, "TIOCGRANTPT") end function S.unlockpt(fd) return 0 end function S.ptsname(fd) local pm, err = S.ioctl(fd, "TIOCPTSNAME") if not pm then return nil, err end return ffi.string(pm.sn) end -- TODO we need to fix sigaction in NetBSD, syscall seems to have changed to sigaction_tramp function S.pause() return S.select({}) end -- select on nothing forever -- ksem functions. Not very well documented! You shoudl probably use pthreads in most cases function S.ksem_init(value, semid) semid = semid or t.intptr1() local ok, err = C._ksem_init(value, semid) if not ok then return nil, t.error(err or errno()) end return semid[0] end function S.ksem_destroy(semid) return retbool(C._ksem_destroy(semid)) end return S end
apache-2.0
aStonedPenguin/fprp
entities/weapons/stunstick/shared.lua
1
6191
AddCSLuaFile(); if CLIENT then SWEP.PrintName = "Stun Stick" SWEP.Slot = 0 SWEP.SlotPos = 5 SWEP.DrawAmmo = false SWEP.DrawCrosshair = false end SWEP.Base = "weapon_cs_base2" SWEP.Author = "fprp Developers" SWEP.Instructions = "Left click to discipline\nRight click to kill\nReload to threaten" SWEP.Contact = "" SWEP.Purpose = "" SWEP.IconLetter = "" SWEP.ViewModelFOV = 62 SWEP.ViewModelFlip = false SWEP.AnimPrefix = "stunstick" SWEP.Spawnable = true SWEP.AdminOnly = true SWEP.Category = "fprp (Utility)" SWEP.NextStrike = 0 SWEP.ViewModel = Model("models/weapons/v_stunbaton.mdl"); SWEP.WorldModel = Model("models/weapons/w_stunbaton.mdl"); SWEP.Sound = Sound("weapons/stunstick/stunstick_swing1.wav"); SWEP.Primary.ClipSize = -1 SWEP.Primary.DefaultClip = 0 SWEP.Primary.Automatic = false SWEP.Primary.Ammo = "" SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = 0 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "" function SWEP:Initialize() self:SetHoldType("normal"); self.Hit = { Sound("weapons/stunstick/stunstick_impact1.wav"), Sound("weapons/stunstick/stunstick_impact2.wav"); } self.FleshHit = { Sound("weapons/stunstick/stunstick_fleshhit1.wav"), Sound("weapons/stunstick/stunstick_fleshhit2.wav"); } end function SWEP:Deploy() if SERVER then self:SetColor(Color(0,0,255,255)); self:SetMaterial("models/shiny"); local vm = self.Owner:GetViewModel(); if not IsValid(vm) then return end vm:ResetSequence(vm:LookupSequence("idle01")); end return true end function SWEP:PreDrawViewModel() if SERVER or not IsValid(self.Owner) or not IsValid(self.Owner:GetViewModel()) then return end self.Owner:GetViewModel():SetColor(Color(0,0,255,255)); self.Owner:GetViewModel():SetMaterial("models/shiny"); end function SWEP:Holster() if SERVER then self:SetColor(Color(255,255,255,255)); self:SetMaterial(""); timer.Stop(self:GetClass() .. "_idle" .. self:EntIndex()); elseif CLIENT and IsValid(self.Owner) and IsValid(self.Owner:GetViewModel()) then self.Owner:GetViewModel():SetColor(Color(255,255,255,255)); self.Owner:GetViewModel():SetMaterial(""); end return true end function SWEP:OnRemove() if SERVER then self:SetColor(Color(255,255,255,255)); self:SetMaterial(""); timer.Stop(self:GetClass() .. "_idle" .. self:EntIndex()); elseif CLIENT and IsValid(self.Owner) and IsValid(self.Owner:GetViewModel()) then self.Owner:GetViewModel():SetColor(Color(255,255,255,255)); self.Owner:GetViewModel():SetMaterial(""); end end function SWEP:DoFlash(ply) if not IsValid(ply) or not ply:IsPlayer() then return end ply:ScreenFade(SCREENFADE.IN, color_white, 1.2, 0); end local entMeta = FindMetaTable("Entity"); function SWEP:DoAttack(dmg) if CurTime() < self.NextStrike then return end self:SetHoldType("melee"); timer.Simple(0.3, function() if self:IsValid() then self:SetHoldType("normal") end end) self.NextStrike = CurTime() + 0.51 -- Actual delay is set later. if CLIENT then return end timer.Stop(self:GetClass() .. "_idle" .. self:EntIndex()); local vm = self.Owner:GetViewModel(); if IsValid(vm) then vm:ResetSequence(vm:LookupSequence("idle01")); timer.Simple(0, function() if not IsValid(self) or not IsValid(self.Owner) or not IsValid(self.Owner:GetActiveWeapon()) or self.Owner:GetActiveWeapon() ~= self then return end self.Owner:SetAnimation(PLAYER_ATTACK1); if IsValid(self.Weapon) then self.Weapon:EmitSound(self.Sound); end local vm = self.Owner:GetViewModel(); if not IsValid(vm) then return end vm:ResetSequence(vm:LookupSequence("attackch")); vm:SetPlaybackRate(1 + 1/3); local duration = vm:SequenceDuration() / vm:GetPlaybackRate(); timer.Create(self:GetClass() .. "_idle" .. self:EntIndex(), duration, 1, function() if not IsValid(self) or not IsValid(self.Owner) then return end local vm = self.Owner:GetViewModel(); if not IsValid(vm) then return end vm:ResetSequence(vm:LookupSequence("idle01")); end); self.NextStrike = CurTime() + duration end); end self.Owner:LagCompensation(true); local trace = util.QuickTrace(self.Owner:EyePos(), self.Owner:GetAimVector() * 90, {self.Owner}); self.Owner:LagCompensation(false); if IsValid(trace.Entity) and trace.Entity.onStunStickUsed then trace.Entity:onStunStickUsed(self.Owner); return elseif IsValid(trace.Entity) and trace.Entity:GetClass() == "func_breakable_surf" then trace.Entity:Fire("Shatter"); self.Owner:EmitSound(self.Hit[math.random(1,#self.Hit)]); return end local ent = self.Owner:getEyeSightHitEntity(100, 15, fn.FAnd{fp{fn.Neq, self.Owner}, fc{IsValid, entMeta.GetPhysicsObject}}); if not IsValid(ent) then return end if not ent:isDoor() then ent:SetVelocity((ent:GetPos() - self.Owner:GetPos()) * 7); end if dmg > 0 then ent:TakeDamage(dmg, self.Owner, self); end if ent:IsPlayer() or ent:IsNPC() or ent:IsVehicle() then self.DoFlash(self, ent); self.Owner:EmitSound(self.FleshHit[math.random(1,#self.FleshHit)]); else self.Owner:EmitSound(self.Hit[math.random(1,#self.Hit)]); if FPP and FPP.plyCanTouchEnt(self.Owner, ent, "EntityDamage") then if ent.SeizeReward and not ent.beenSeized and not ent.burningup and self.Owner:isCP() and ent.Getowning_ent and self.Owner ~= ent:Getowning_ent() then self.Owner:addshekel(ent.SeizeReward); fprp.notify(self.Owner, 1, 4, fprp.getPhrase("you_received_x", fprp.formatshekel(ent.SeizeReward), fprp.getPhrase("bonus_destroying_entity"))); ent.beenSeized = true end ent:TakeDamage(1000-dmg, self.Owner, self) -- for illegal entities end end end function SWEP:PrimaryAttack() self:DoAttack(0); end function SWEP:SecondaryAttack() self:DoAttack(10); end function SWEP:Reload() self:SetHoldType("melee"); timer.Destroy("rp_stunstick_threaten"); timer.Create("rp_stunstick_threaten", 1, 1, function() if not IsValid(self) then return end self:SetHoldType("normal"); end); if not SERVER then return end if self.LastReload and self.LastReload > CurTime() - 0.1 then self.LastReload = CurTime() return end self.LastReload = CurTime(); self.Owner:EmitSound("weapons/stunstick/spark"..math.random(1,3)..".wav"); end
mit
Kosmos82/kosmosdarkstar
scripts/zones/Beaucedine_Glacier/TextIDs.lua
13
1124
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6562; -- You cannot obtain the item. Come back after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6564; -- You cannot obtain the #. Try trading again after sorting your inventory. ITEM_OBTAINED = 6565; -- Obtained: <item>. GIL_OBTAINED = 6566; -- Obtained <number> gil. KEYITEM_OBTAINED = 6568; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6571; -- You obtain BEASTMEN_BANNER = 81; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7226; -- You can't fish here. -- Conquest CONQUEST = 7474; -- You've earned conquest points! -- Other dialog NOTHING_OUT_OF_ORDINARY = 6579; -- There is nothing out of the ordinary here. -- Dynamis dialogs YOU_CANNOT_ENTER_DYNAMIS = 7855; -- You cannot enter Dynamis PLAYERS_HAVE_NOT_REACHED_LEVEL = 7857; -- Players who have not reached levelare prohibited from entering Dynamis. UNUSUAL_ARRANGEMENT_OF_BRANCHES = 7867; -- There is an unusual arrangement of branches here. -- conquest Base CONQUEST_BASE = 0;
gpl-3.0
harveyhu2012/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua
80
2561
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> 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 $Id$ ]]-- local ast = require("luci.asterisk") -- -- SIP trunk info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Trunk Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Trunk %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "trunks") ) end return form -- -- SIP trunk config -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Trunk") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "peer", qualify = "yes", } back = peer:option(DummyValue, "_overview", "Back to trunk overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks") sipdomain = peer:option(Value, "host", "SIP Domain") sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy") outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port") register = peer:option(Flag, "register", "Register with peer") register.enabled = "yes" register.disabled = "no" regext = peer:option(Value, "registerextension", "Extension to register (optional)") regext:depends({register="1"}) didval = peer:option(ListValue, "_did", "Number of assigned DID numbers") didval:value("", "(none)") for i=1,24 do didval:value(i) end dialplan = peer:option(ListValue, "context", "Dialplan Context") dialplan:value(arg[1] .. "_inbound", "(default)") cbimap.uci:foreach("asterisk", "dialplan", function(s) dialplan:value(s['.name']) end) return cbimap end
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/QuBia_Arena/mobs/Trion.lua
8
1489
----------------------------------- -- Area: qubia arena -- MOB: Trion -- the heir to the light sando 9-2 ----------------------------------- package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil; ----------------------------------- require("scripts/zones/QuBia_Arena/TextIDs"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:addMod(MOD_REGAIN, 30); end ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobRoam Action ----------------------------------- function onMobRoam(mob) local wait = mob:getLocalVar("wait"); local ready = mob:getLocalVar("ready"); if (ready == 0 and wait > 40) then local baseID = 17621014 + (mob:getBattlefield():getBattlefieldNumber() - 1) * 2 mob:setLocalVar("ready", bit.band(baseID, 0xFFF)); mob:setLocalVar("wait", 0); elseif (ready > 0) then mob:addEnmity(GetMobByID(ready + bit.lshift(mob:getZoneID(), 12) + 0x1000000),0,1); -- Waste Teo's time with this empty conditional and missing indents, YAY! else mob:setLocalVar("wait", wait+3); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) mob:getBattlefield():lose(); end;
gpl-3.0
Cadene/torch7
torchcwrap.lua
54
15111
local wrap = require 'cwrap' local types = wrap.types types.Tensor = { helpname = function(arg) if arg.dim then return string.format("Tensor~%dD", arg.dim) else return "Tensor" end end, declare = function(arg) local txt = {} table.insert(txt, string.format("THTensor *arg%d = NULL;", arg.i)) if arg.returned then table.insert(txt, string.format("int arg%d_idx = 0;", arg.i)); end return table.concat(txt, '\n') end, check = function(arg, idx) if arg.dim then return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor)) && (arg%d->nDimension == %d)", arg.i, idx, arg.i, arg.dim) else return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor))", arg.i, idx) end end, read = function(arg, idx) if arg.returned then return string.format("arg%d_idx = %d;", arg.i, idx) end end, init = function(arg) if type(arg.default) == 'boolean' then return string.format('arg%d = THTensor_(new)();', arg.i) elseif type(arg.default) == 'number' then return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg()) else error('unknown default tensor type value') end end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.default and arg.returned then table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) table.insert(txt, string.format('else')) if type(arg.default) == 'boolean' then -- boolean: we did a new() table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i)) else -- otherwise: point on default tensor --> retain table.insert(txt, string.format('{')) table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i)) -- so we need a retain table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i)) table.insert(txt, string.format('}')) end elseif arg.default then -- we would have to deallocate the beast later if we did a new -- unlikely anyways, so i do not support it for now if type(arg.default) == 'boolean' then error('a tensor cannot be optional if not returned') end elseif arg.returned then table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i)) end return table.concat(txt, '\n') end } types.Generator = { helpname = function(arg) return "Generator" end, declare = function(arg) return string.format("THGenerator *arg%d = NULL;", arg.i) end, check = function(arg, idx) return string.format("(arg%d = luaT_toudata(L, %d, torch_Generator))", arg.i, idx) end, read = function(arg, idx) end, init = function(arg) local text = {} -- If no generator is supplied, pull the default out of the torch namespace. table.insert(text, 'lua_getglobal(L,"torch");') table.insert(text, string.format('arg%d = luaT_getfieldcheckudata(L, -1, "_gen", torch_Generator);', arg.i)) table.insert(text, 'lua_pop(L, 2);') return table.concat(text, '\n') end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) end, postcall = function(arg) end } types.IndexTensor = { helpname = function(arg) return "LongTensor" end, declare = function(arg) local txt = {} table.insert(txt, string.format("THLongTensor *arg%d = NULL;", arg.i)) if arg.returned then table.insert(txt, string.format("int arg%d_idx = 0;", arg.i)); end return table.concat(txt, '\n') end, check = function(arg, idx) return string.format('(arg%d = luaT_toudata(L, %d, "torch.LongTensor"))', arg.i, idx) end, read = function(arg, idx) local txt = {} if not arg.noreadadd then table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, -1);", arg.i, arg.i)); end if arg.returned then table.insert(txt, string.format("arg%d_idx = %d;", arg.i, idx)) end return table.concat(txt, '\n') end, init = function(arg) return string.format('arg%d = THLongTensor_new();', arg.i) end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.default and arg.returned then table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) table.insert(txt, string.format('else')) -- means we did a new() table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i)) elseif arg.default then error('a tensor cannot be optional if not returned') elseif arg.returned then table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned or arg.returned then table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, 1);", arg.i, arg.i)); end if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('THLongTensor_retain(arg%d);', arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i)) end return table.concat(txt, '\n') end } for _,typename in ipairs({"ByteTensor", "CharTensor", "ShortTensor", "IntTensor", "LongTensor", "FloatTensor", "DoubleTensor"}) do types[typename] = { helpname = function(arg) if arg.dim then return string.format('%s~%dD', typename, arg.dim) else return typename end end, declare = function(arg) local txt = {} table.insert(txt, string.format("TH%s *arg%d = NULL;", typename, arg.i)) if arg.returned then table.insert(txt, string.format("int arg%d_idx = 0;", arg.i)); end return table.concat(txt, '\n') end, check = function(arg, idx) if arg.dim then return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s")) && (arg%d->nDimension == %d)', arg.i, idx, typename, arg.i, arg.dim) else return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s"))', arg.i, idx, typename) end end, read = function(arg, idx) if arg.returned then return string.format("arg%d_idx = %d;", arg.i, idx) end end, init = function(arg) if type(arg.default) == 'boolean' then return string.format('arg%d = TH%s_new();', arg.i, typename) elseif type(arg.default) == 'number' then return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg()) else error('unknown default tensor type value') end end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.default and arg.returned then table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) table.insert(txt, string.format('else')) if type(arg.default) == 'boolean' then -- boolean: we did a new() table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename)) else -- otherwise: point on default tensor --> retain table.insert(txt, string.format('{')) table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i)) -- so we need a retain table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename)) table.insert(txt, string.format('}')) end elseif arg.default then -- we would have to deallocate the beast later if we did a new -- unlikely anyways, so i do not support it for now if type(arg.default) == 'boolean' then error('a tensor cannot be optional if not returned') end elseif arg.returned then table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename)) end return table.concat(txt, '\n') end } end types.LongArg = { vararg = true, helpname = function(arg) return "(LongStorage | dim1 [dim2...])" end, declare = function(arg) return string.format("THLongStorage *arg%d = NULL;", arg.i) end, init = function(arg) if arg.default then error('LongArg cannot have a default value') end end, check = function(arg, idx) return string.format("torch_islongargs(L, %d)", idx) end, read = function(arg, idx) return string.format("arg%d = torch_checklongargs(L, %d);", arg.i, idx) end, carg = function(arg, idx) return string.format('arg%d', arg.i) end, creturn = function(arg, idx) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.returned then table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('THLongStorage_retain(arg%d);', arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i)) end if not arg.returned and not arg.creturned then table.insert(txt, string.format('THLongStorage_free(arg%d);', arg.i)) end return table.concat(txt, '\n') end } types.charoption = { helpname = function(arg) if arg.values then return "(" .. table.concat(arg.values, '|') .. ")" end end, declare = function(arg) local txt = {} table.insert(txt, string.format("const char *arg%d = NULL;", arg.i)) if arg.default then table.insert(txt, string.format("char arg%d_default = '%s';", arg.i, arg.default)) end return table.concat(txt, '\n') end, init = function(arg) return string.format("arg%d = &arg%d_default;", arg.i, arg.i) end, check = function(arg, idx) local txt = {} local txtv = {} table.insert(txt, string.format('(arg%d = lua_tostring(L, %d)) && (', arg.i, idx)) for _,value in ipairs(arg.values) do table.insert(txtv, string.format("*arg%d == '%s'", arg.i, value)) end table.insert(txt, table.concat(txtv, ' || ')) table.insert(txt, ')') return table.concat(txt, '') end, read = function(arg, idx) end, carg = function(arg, idx) return string.format('arg%d', arg.i) end, creturn = function(arg, idx) end, precall = function(arg) end, postcall = function(arg) end }
bsd-3-clause
wingo/snabbswitch
lib/ljsyscall/syscall/syscalls.lua
13
33583
-- choose correct syscalls for OS, plus shared calls -- note that where functions are identical if present but may be missing they can also go here -- note that OS specific calls are loaded at the end so they may override generic calls here local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local ffi = require "ffi" local bit = require "syscall.bit" local h = require "syscall.helpers" local err64 = h.err64 local errpointer = h.errpointer local getfd, istype, mktype, reviter = h.getfd, h.istype, h.mktype, h.reviter local function init(C, c, types) -- this could be an arguments, fcntl syscall is a function of this local fcntl = require("syscall." .. abi.os .. ".fcntl").init(types) local errno = ffi.errno local t, pt, s = types.t, types.pt, types.s local S = {} local function getdev(dev) if type(dev) == "table" then return t.device(dev).dev end if ffi.istype(t.device, dev) then dev = dev.dev end return dev end -- return helpers. -- 64 bit return helpers. Only use for lseek in fact; we use tonumber but remove if you need files over 56 bits long -- TODO only luaffi needs the cast as wont compare to number; hopefully fixed in future with 5.3 or a later luaffi. local function ret64(ret, err) if ret == err64 then return nil, t.error(err or errno()) end return tonumber(ret) end local function retnum(ret, err) -- return Lua number where double precision ok, eg file ops etc ret = tonumber(ret) if ret == -1 then return nil, t.error(err or errno()) end return ret end local function retfd(ret, err) if ret == -1 then return nil, t.error(err or errno()) end return t.fd(ret) end -- used for no return value, return true for use of assert local function retbool(ret, err) if ret == -1 then return nil, t.error(err or errno()) end return true end -- used for pointer returns, -1 is failure local function retptr(ret, err) if ret == errpointer then return nil, t.error(err or errno()) end return ret end -- generic iterator; this counts down to 0 so need no closure local function retiter(ret, err, array) ret = tonumber(ret) if ret == -1 then return nil, t.error(err or errno()) end return reviter, array, ret end -- generic system calls function S.close(fd) return retbool(C.close(getfd(fd))) end function S.chdir(path) return retbool(C.chdir(path)) end function S.fchdir(fd) return retbool(C.fchdir(getfd(fd))) end function S.fchmod(fd, mode) return retbool(C.fchmod(getfd(fd), c.MODE[mode])) end function S.fchown(fd, owner, group) return retbool(C.fchown(getfd(fd), owner or -1, group or -1)) end function S.lchown(path, owner, group) return retbool(C.lchown(path, owner or -1, group or -1)) end function S.chroot(path) return retbool(C.chroot(path)) end function S.umask(mask) return C.umask(c.MODE[mask]) end function S.sync() C.sync() end function S.flock(fd, operation) return retbool(C.flock(getfd(fd), c.LOCK[operation])) end -- TODO read should have consistent return type but then will differ from other calls. function S.read(fd, buf, count) if buf then return retnum(C.read(getfd(fd), buf, count or #buf or 4096)) end -- user supplied a buffer, standard usage count = count or 4096 buf = t.buffer(count) local ret, err = tonumber(C.read(getfd(fd), buf, count)) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buf, ret) -- user gets a string back, can get length from #string end function S.readv(fd, iov) iov = mktype(t.iovecs, iov) return retnum(C.readv(getfd(fd), iov.iov, #iov)) end function S.write(fd, buf, count) return retnum(C.write(getfd(fd), buf, count or #buf)) end function S.writev(fd, iov) iov = mktype(t.iovecs, iov) return retnum(C.writev(getfd(fd), iov.iov, #iov)) end function S.pread(fd, buf, count, offset) return retnum(C.pread(getfd(fd), buf, count, offset)) end function S.pwrite(fd, buf, count, offset) return retnum(C.pwrite(getfd(fd), buf, count or #buf, offset)) end if C.preadv and C.pwritev then -- these are missing in eg OSX function S.preadv(fd, iov, offset) iov = mktype(t.iovecs, iov) return retnum(C.preadv(getfd(fd), iov.iov, #iov, offset)) end function S.pwritev(fd, iov, offset) iov = mktype(t.iovecs, iov) return retnum(C.pwritev(getfd(fd), iov.iov, #iov, offset)) end end function S.lseek(fd, offset, whence) return ret64(C.lseek(getfd(fd), offset or 0, c.SEEK[whence or c.SEEK.SET])) end if C.readlink then function S.readlink(path, buffer, size) size = size or c.PATH_MAX buffer = buffer or t.buffer(size) local ret, err = tonumber(C.readlink(path, buffer, size)) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buffer, ret) end else function S.readlink(path, buffer, size) size = size or c.PATH_MAX buffer = buffer or t.buffer(size) local ret, err = tonumber(C.readlinkat(c.AT_FDCWD.FDCWD, path, buffer, size)) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buffer, ret) end end function S.fsync(fd) return retbool(C.fsync(getfd(fd))) end if C.stat then function S.stat(path, buf) if not buf then buf = t.stat() end local ret = C.stat(path, buf) if ret == -1 then return nil, t.error() end return buf end else function S.stat(path, buf) if not buf then buf = t.stat() end local ret = C.fstatat(c.AT_FDCWD.FDCWD, path, buf, 0) if ret == -1 then return nil, t.error() end return buf end end if C.lstat then function S.lstat(path, buf) if not buf then buf = t.stat() end local ret, err = C.lstat(path, buf) if ret == -1 then return nil, t.error(err or errno()) end return buf end else function S.lstat(path, buf) if not buf then buf = t.stat() end local ret, err = C.fstatat(c.AT_FDCWD.FDCWD, path, buf, c.AT.SYMLINK_NOFOLLOW) if ret == -1 then return nil, t.error(err or errno()) end return buf end end function S.fstat(fd, buf) if not buf then buf = t.stat() end local ret, err = C.fstat(getfd(fd), buf) if ret == -1 then return nil, t.error(err or errno()) end return buf end function S.truncate(path, length) return retbool(C.truncate(path, length)) end function S.ftruncate(fd, length) return retbool(C.ftruncate(getfd(fd), length)) end -- recent Linux does not have open, rmdir, unlink etc any more as syscalls if C.open then function S.open(pathname, flags, mode) return retfd(C.open(pathname, c.O[flags], c.MODE[mode])) end else function S.open(pathname, flags, mode) return retfd(C.openat(c.AT_FDCWD.FDCWD, pathname, c.O[flags], c.MODE[mode])) end end if C.rmdir then function S.rmdir(path) return retbool(C.rmdir(path)) end else function S.rmdir(path) return retbool(C.unlinkat(c.AT_FDCWD.FDCWD, path, c.AT.REMOVEDIR)) end end if C.unlink then function S.unlink(pathname) return retbool(C.unlink(pathname)) end else function S.unlink(path) return retbool(C.unlinkat(c.AT_FDCWD.FDCWD, path, 0)) end end if C.chmod then function S.chmod(path, mode) return retbool(C.chmod(path, c.MODE[mode])) end else function S.chmod(path, mode) return retbool(C.fchmodat(c.AT_FDCWD.FDCWD, path, c.MODE[mode], 0)) end end if C.access then function S.access(pathname, mode) return retbool(C.access(pathname, c.OK[mode])) end else function S.access(pathname, mode) return retbool(C.faccessat(c.AT_FDCWD.FDCWD, pathname, c.OK[mode], 0)) end end if C.chown then function S.chown(path, owner, group) return retbool(C.chown(path, owner or -1, group or -1)) end else function S.chown(path, owner, group) return retbool(C.fchownat(c.AT_FDCWD.FDCWD, path, owner or -1, group or -1, 0)) end end if C.mkdir then function S.mkdir(path, mode) return retbool(C.mkdir(path, c.MODE[mode])) end else function S.mkdir(path, mode) return retbool(C.mkdirat(c.AT_FDCWD.FDCWD, path, c.MODE[mode])) end end if C.symlink then function S.symlink(oldpath, newpath) return retbool(C.symlink(oldpath, newpath)) end else function S.symlink(oldpath, newpath) return retbool(C.symlinkat(oldpath, c.AT_FDCWD.FDCWD, newpath)) end end if C.link then function S.link(oldpath, newpath) return retbool(C.link(oldpath, newpath)) end else function S.link(oldpath, newpath) return retbool(C.linkat(c.AT_FDCWD.FDCWD, oldpath, c.AT_FDCWD.FDCWD, newpath, 0)) end end if C.rename then function S.rename(oldpath, newpath) return retbool(C.rename(oldpath, newpath)) end else function S.rename(oldpath, newpath) return retbool(C.renameat(c.AT_FDCWD.FDCWD, oldpath, c.AT_FDCWD.FDCWD, newpath)) end end if C.mknod then function S.mknod(pathname, mode, dev) return retbool(C.mknod(pathname, c.S_I[mode], getdev(dev) or 0)) end else function S.mknod(pathname, mode, dev) return retbool(C.mknodat(c.AT_FDCWD.FDCWD, pathname, c.S_I[mode], getdev(dev) or 0)) end end local function sproto(domain, protocol) -- helper function to lookup protocol type depending on domain TODO table? protocol = protocol or 0 if domain == c.AF.NETLINK then return c.NETLINK[protocol] end return c.IPPROTO[protocol] end function S.socket(domain, stype, protocol) domain = c.AF[domain] return retfd(C.socket(domain, c.SOCK[stype], sproto(domain, protocol))) end function S.socketpair(domain, stype, protocol, sv2) domain = c.AF[domain] sv2 = sv2 or t.int2() local ret, err = C.socketpair(domain, c.SOCK[stype], sproto(domain, protocol), sv2) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, t.fd(sv2[0]), t.fd(sv2[1]) end function S.dup(oldfd) return retfd(C.dup(getfd(oldfd))) end if C.dup2 then function S.dup2(oldfd, newfd) return retfd(C.dup2(getfd(oldfd), getfd(newfd))) end end if C.dup3 then function S.dup3(oldfd, newfd, flags) return retfd(C.dup3(getfd(oldfd), getfd(newfd), flags or 0)) end end function S.sendto(fd, buf, count, flags, addr, addrlen) if not addr then addrlen = 0 end local saddr = pt.sockaddr(addr) return retnum(C.sendto(getfd(fd), buf, count or #buf, c.MSG[flags], saddr, addrlen or #addr)) end function S.recvfrom(fd, buf, count, flags, addr, addrlen) local saddr if addr == false then addr = nil addrlen = nil else if addr then addrlen = addrlen or #addr else addr = t.sockaddr_storage() addrlen = addrlen or s.sockaddr_storage end if type(addrlen) == "number" then addrlen = t.socklen1(addrlen) end saddr = pt.sockaddr(addr) end local ret, err = C.recvfrom(getfd(fd), buf, count or #buf, c.MSG[flags], saddr, addrlen) -- TODO addrlen 0 here??? ret = tonumber(ret) if ret == -1 then return nil, t.error(err or errno()) end if addr then return ret, nil, t.sa(addr, addrlen[0]) else return ret end end function S.sendmsg(fd, msg, flags) if not msg then -- send a single byte message, eg enough to send credentials local buf1 = t.buffer(1) local io = t.iovecs{{buf1, 1}} msg = t.msghdr{msg_iov = io.iov, msg_iovlen = #io} end return retnum(C.sendmsg(getfd(fd), msg, c.MSG[flags])) end function S.recvmsg(fd, msg, flags) return retnum(C.recvmsg(getfd(fd), msg, c.MSG[flags])) end -- TODO better handling of msgvec, create one structure/table if C.sendmmsg then function S.sendmmsg(fd, msgvec, flags) msgvec = mktype(t.mmsghdrs, msgvec) return retbool(C.sendmmsg(getfd(fd), msgvec.msg, msgvec.count, c.MSG[flags])) end end if C.recvmmsg then function S.recvmmsg(fd, msgvec, flags, timeout) if timeout then timeout = mktype(t.timespec, timeout) end msgvec = mktype(t.mmsghdrs, msgvec) return retbool(C.recvmmsg(getfd(fd), msgvec.msg, msgvec.count, c.MSG[flags], timeout)) end end -- TODO {get,set}sockopt may need better type handling see new unfinished sockopt file, plus not always c.SO[] function S.setsockopt(fd, level, optname, optval, optlen) -- allocate buffer for user, from Lua type if know how, int and bool so far if not optlen and type(optval) == 'boolean' then optval = h.booltoc(optval) end if not optlen and type(optval) == 'number' then optval = t.int1(optval) optlen = s.int end return retbool(C.setsockopt(getfd(fd), c.SOL[level], c.SO[optname], optval, optlen)) end function S.getsockopt(fd, level, optname, optval, optlen) if not optval then optval, optlen = t.int1(), s.int end optlen = optlen or #optval local len = t.socklen1(optlen) local ret, err = C.getsockopt(getfd(fd), c.SOL[level], c.SO[optname], optval, len) if ret == -1 then return nil, t.error(err or errno()) end if len[0] ~= optlen then error("incorrect optlen for getsockopt: set " .. optlen .. " got " .. len[0]) end return optval[0] -- TODO will not work if struct, eg see netfilter end function S.bind(sockfd, addr, addrlen) local saddr = pt.sockaddr(addr) return retbool(C.bind(getfd(sockfd), saddr, addrlen or #addr)) end function S.listen(sockfd, backlog) return retbool(C.listen(getfd(sockfd), backlog or c.SOMAXCONN)) end function S.connect(sockfd, addr, addrlen) local saddr = pt.sockaddr(addr) return retbool(C.connect(getfd(sockfd), saddr, addrlen or #addr)) end function S.accept(sockfd, addr, addrlen) local saddr = pt.sockaddr(addr) if addr then addrlen = addrlen or t.socklen1() end return retfd(C.accept(getfd(sockfd), saddr, addrlen)) end function S.getsockname(sockfd, addr, addrlen) addr = addr or t.sockaddr_storage() addrlen = addrlen or t.socklen1(#addr) local saddr = pt.sockaddr(addr) local ret, err = C.getsockname(getfd(sockfd), saddr, addrlen) if ret == -1 then return nil, t.error(err or errno()) end return t.sa(addr, addrlen[0]) end function S.getpeername(sockfd, addr, addrlen) addr = addr or t.sockaddr_storage() addrlen = addrlen or t.socklen1(#addr) local saddr = pt.sockaddr(addr) local ret, err = C.getpeername(getfd(sockfd), saddr, addrlen) if ret == -1 then return nil, t.error(err or errno()) end return t.sa(addr, addrlen[0]) end function S.shutdown(sockfd, how) return retbool(C.shutdown(getfd(sockfd), c.SHUT[how])) end if C.poll then function S.poll(fds, timeout) return retnum(C.poll(fds.pfd, #fds, timeout or -1)) end end -- TODO rework fdset interface, see issue #71 -- fdset handlers local function mkfdset(fds, nfds) -- should probably check fd is within range (1024), or just expand structure size local set = t.fdset() for i, v in ipairs(fds) do local fd = tonumber(getfd(v)) if fd + 1 > nfds then nfds = fd + 1 end local fdelt = bit.rshift(fd, 5) -- always 32 bits set.fds_bits[fdelt] = bit.bor(set.fds_bits[fdelt], bit.lshift(1, fd % 32)) -- always 32 bit words end return set, nfds end local function fdisset(fds, set) local f = {} for i, v in ipairs(fds) do local fd = tonumber(getfd(v)) local fdelt = bit.rshift(fd, 5) -- always 32 bits if bit.band(set.fds_bits[fdelt], bit.lshift(1, fd % 32)) ~= 0 then table.insert(f, v) end -- careful not to duplicate fd objects end return f end -- TODO convert to metatype. Problem is how to deal with nfds if C.select then function S.select(sel, timeout) -- note same structure as returned local r, w, e local nfds = 0 if timeout then timeout = mktype(t.timeval, timeout) end r, nfds = mkfdset(sel.readfds or {}, nfds or 0) w, nfds = mkfdset(sel.writefds or {}, nfds) e, nfds = mkfdset(sel.exceptfds or {}, nfds) local ret, err = C.select(nfds, r, w, e, timeout) if ret == -1 then return nil, t.error(err or errno()) end return {readfds = fdisset(sel.readfds or {}, r), writefds = fdisset(sel.writefds or {}, w), exceptfds = fdisset(sel.exceptfds or {}, e), count = tonumber(ret)} end else function S.select(sel, timeout) if timeout then timeout = mktype(t.timespec, timeout / 1000) end return S.pselect(sel, timeout) end end -- TODO note that in Linux syscall modifies timeout, which is non standard, like ppoll function S.pselect(sel, timeout, set) -- note same structure as returned local r, w, e local nfds = 0 if timeout then timeout = mktype(t.timespec, timeout) end if set then set = mktype(t.sigset, set) end r, nfds = mkfdset(sel.readfds or {}, nfds or 0) w, nfds = mkfdset(sel.writefds or {}, nfds) e, nfds = mkfdset(sel.exceptfds or {}, nfds) local ret, err = C.pselect(nfds, r, w, e, timeout, set) if ret == -1 then return nil, t.error(err or errno()) end return {readfds = fdisset(sel.readfds or {}, r), writefds = fdisset(sel.writefds or {}, w), exceptfds = fdisset(sel.exceptfds or {}, e), count = tonumber(ret)} end function S.getuid() return C.getuid() end function S.geteuid() return C.geteuid() end function S.getpid() return C.getpid() end function S.getppid() return C.getppid() end function S.getgid() return C.getgid() end function S.getegid() return C.getegid() end function S.setuid(uid) return retbool(C.setuid(uid)) end function S.setgid(gid) return retbool(C.setgid(gid)) end function S.seteuid(uid) return retbool(C.seteuid(uid)) end function S.setegid(gid) return retbool(C.setegid(gid)) end function S.getsid(pid) return retnum(C.getsid(pid or 0)) end function S.setsid() return retnum(C.setsid()) end function S.setpgid(pid, pgid) return retbool(C.setpgid(pid or 0, pgid or 0)) end function S.getpgid(pid) return retnum(C.getpgid(pid or 0)) end if C.getpgrp then function S.getpgrp() return retnum(C.getpgrp()) end else function S.getpgrp() return retnum(C.getpgid(0)) end end function S.getgroups() local size = C.getgroups(0, nil) -- note for BSD could use NGROUPS_MAX instead if size == -1 then return nil, t.error() end local groups = t.groups(size) local ret = C.getgroups(size, groups.list) if ret == -1 then return nil, t.error() end return groups end function S.setgroups(groups) if type(groups) == "table" then groups = t.groups(groups) end return retbool(C.setgroups(groups.count, groups.list)) end function S.sigprocmask(how, set, oldset) oldset = oldset or t.sigset() if not set then how = c.SIGPM.SETMASK end -- value does not matter if set nil, just returns old set local ret, err = C.sigprocmask(c.SIGPM[how], t.sigset(set), oldset) if ret == -1 then return nil, t.error(err or errno()) end return oldset end function S.sigpending() local set = t.sigset() local ret, err = C.sigpending(set) if ret == -1 then return nil, t.error(err or errno()) end return set end function S.sigsuspend(mask) return retbool(C.sigsuspend(t.sigset(mask))) end function S.kill(pid, sig) return retbool(C.kill(pid, c.SIG[sig])) end -- _exit is the real exit syscall, or whatever is suitable if overridden in c.lua; libc.lua may override function S.exit(status) C._exit(c.EXIT[status or 0]) end function S.fcntl(fd, cmd, arg) cmd = c.F[cmd] if fcntl.commands[cmd] then arg = fcntl.commands[cmd](arg) end local ret, err = C.fcntl(getfd(fd), cmd, pt.void(arg or 0)) if ret == -1 then return nil, t.error(err or errno()) end if fcntl.ret[cmd] then return fcntl.ret[cmd](ret, arg) end return true end -- TODO return metatype that has length and can gc? function S.mmap(addr, length, prot, flags, fd, offset) return retptr(C.mmap(addr, length, c.PROT[prot], c.MAP[flags], getfd(fd or -1), offset or 0)) end function S.munmap(addr, length) return retbool(C.munmap(addr, length)) end function S.msync(addr, length, flags) return retbool(C.msync(addr, length, c.MSYNC[flags])) end function S.mlock(addr, len) return retbool(C.mlock(addr, len)) end function S.munlock(addr, len) return retbool(C.munlock(addr, len)) end function S.munlockall() return retbool(C.munlockall()) end function S.madvise(addr, length, advice) return retbool(C.madvise(addr, length, c.MADV[advice])) end function S.ioctl(d, request, argp) local read, singleton = false, false local name = request if type(name) == "string" then request = c.IOCTL[name] end if type(request) == "table" then local write = request.write local tp = request.type read = request.read singleton = request.singleton request = request.number if type(argp) ~= "string" and type(argp) ~= "cdata" and type ~= "userdata" then if write then if not argp then error("no argument supplied for ioctl " .. name) end argp = mktype(tp, argp) end if read then argp = argp or tp() end end else -- some sane defaults if no info if type(request) == "table" then request = request.number end if type(argp) == "string" then argp = pt.char(argp) end if type(argp) == "number" then argp = t.int1(argp) end end local ret, err = C.ioctl(getfd(d), request, argp) if ret == -1 then return nil, t.error(err or errno()) end if read and singleton then return argp[0] end if read then return argp end return true -- will need override for few linux ones that return numbers end if C.pipe then function S.pipe(fd2) fd2 = fd2 or t.int2() local ret, err = C.pipe(fd2) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, t.fd(fd2[0]), t.fd(fd2[1]) end else function S.pipe(fd2) fd2 = fd2 or t.int2() local ret, err = C.pipe2(fd2, 0) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, t.fd(fd2[0]), t.fd(fd2[1]) end end if C.gettimeofday then function S.gettimeofday(tv) tv = tv or t.timeval() -- note it is faster to pass your own tv if you call a lot local ret, err = C.gettimeofday(tv, nil) if ret == -1 then return nil, t.error(err or errno()) end return tv end end if C.settimeofday then function S.settimeofday(tv) return retbool(C.settimeofday(tv, nil)) end end function S.getrusage(who, ru) ru = ru or t.rusage() local ret, err = C.getrusage(c.RUSAGE[who], ru) if ret == -1 then return nil, t.error(err or errno()) end return ru end if C.fork then function S.fork() return retnum(C.fork()) end else function S.fork() return retnum(C.clone(c.SIG.CHLD, 0)) end end function S.execve(filename, argv, envp) local cargv = t.string_array(#argv + 1, argv or {}) cargv[#argv] = nil -- LuaJIT does not zero rest of a VLA local cenvp = t.string_array(#envp + 1, envp or {}) cenvp[#envp] = nil return retbool(C.execve(filename, cargv, cenvp)) end -- man page says obsolete for Linux, but implemented and useful for compatibility function S.wait4(pid, options, ru, status) -- note order of arguments changed as rarely supply status (as waitpid) if ru == false then ru = nil else ru = ru or t.rusage() end -- false means no allocation status = status or t.int1() local ret, err = C.wait4(c.WAIT[pid], status, c.W[options], ru) if ret == -1 then return nil, t.error(err or errno()) end return ret, nil, t.waitstatus(status[0]), ru end if C.waitpid then function S.waitpid(pid, options, status) -- note order of arguments changed as rarely supply status status = status or t.int1() local ret, err = C.waitpid(c.WAIT[pid], status, c.W[options]) if ret == -1 then return nil, t.error(err or errno()) end return ret, nil, t.waitstatus(status[0]) end end if S.waitid then function S.waitid(idtype, id, options, infop) -- note order of args, as usually dont supply infop if not infop then infop = t.siginfo() end local ret, err = C.waitid(c.P[idtype], id or 0, infop, c.W[options]) if ret == -1 then return nil, t.error(err or errno()) end return infop end end function S.setpriority(which, who, prio) return retbool(C.setpriority(c.PRIO[which], who or 0, prio)) end -- Linux overrides getpriority as it offsets return values so that they are not negative function S.getpriority(which, who) errno(0) local ret, err = C.getpriority(c.PRIO[which], who or 0) if ret == -1 and (err or errno()) ~= 0 then return nil, t.error(err or errno()) end return ret end -- these may not always exist, but where they do they have the same interface if C.creat then function S.creat(pathname, mode) return retfd(C.creat(pathname, c.MODE[mode])) end end if C.pipe2 then function S.pipe2(flags, fd2) fd2 = fd2 or t.int2() local ret, err = C.pipe2(fd2, c.OPIPE[flags]) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, t.fd(fd2[0]), t.fd(fd2[1]) end end if C.mlockall then function S.mlockall(flags) return retbool(C.mlockall(c.MCL[flags])) end end if C.linkat then function S.linkat(olddirfd, oldpath, newdirfd, newpath, flags) return retbool(C.linkat(c.AT_FDCWD[olddirfd], oldpath, c.AT_FDCWD[newdirfd], newpath, c.AT[flags])) end end if C.symlinkat then function S.symlinkat(oldpath, newdirfd, newpath) return retbool(C.symlinkat(oldpath, c.AT_FDCWD[newdirfd], newpath)) end end if C.unlinkat then function S.unlinkat(dirfd, path, flags) return retbool(C.unlinkat(c.AT_FDCWD[dirfd], path, c.AT[flags])) end end if C.renameat then function S.renameat(olddirfd, oldpath, newdirfd, newpath) return retbool(C.renameat(c.AT_FDCWD[olddirfd], oldpath, c.AT_FDCWD[newdirfd], newpath)) end end if C.mkdirat then function S.mkdirat(fd, path, mode) return retbool(C.mkdirat(c.AT_FDCWD[fd], path, c.MODE[mode])) end end if C.fchownat then function S.fchownat(dirfd, path, owner, group, flags) return retbool(C.fchownat(c.AT_FDCWD[dirfd], path, owner or -1, group or -1, c.AT[flags])) end end if C.faccessat then function S.faccessat(dirfd, pathname, mode, flags) return retbool(C.faccessat(c.AT_FDCWD[dirfd], pathname, c.OK[mode], c.AT[flags])) end end if C.readlinkat then function S.readlinkat(dirfd, path, buffer, size) size = size or c.PATH_MAX buffer = buffer or t.buffer(size) local ret, err = C.readlinkat(c.AT_FDCWD[dirfd], path, buffer, size) ret = tonumber(ret) if ret == -1 then return nil, t.error(err or errno()) end return ffi.string(buffer, ret) end end if C.mknodat then function S.mknodat(fd, pathname, mode, dev) return retbool(C.mknodat(c.AT_FDCWD[fd], pathname, c.S_I[mode], getdev(dev) or 0)) end end if C.utimensat then function S.utimensat(dirfd, path, ts, flags) if ts then ts = t.timespec2(ts) end -- TODO use mktype? return retbool(C.utimensat(c.AT_FDCWD[dirfd], path, ts, c.AT[flags])) end end if C.fstatat then function S.fstatat(fd, path, buf, flags) if not buf then buf = t.stat() end local ret, err = C.fstatat(c.AT_FDCWD[fd], path, buf, c.AT[flags]) if ret == -1 then return nil, t.error(err or errno()) end return buf end end if C.fchmodat then function S.fchmodat(dirfd, pathname, mode, flags) return retbool(C.fchmodat(c.AT_FDCWD[dirfd], pathname, c.MODE[mode], c.AT[flags])) end end if C.openat then function S.openat(dirfd, pathname, flags, mode) return retfd(C.openat(c.AT_FDCWD[dirfd], pathname, c.O[flags], c.MODE[mode])) end end if C.fchroot then function S.fchroot(fd) return retbool(C.fchroot(getfd(fd))) end end if C.lchmod then function S.lchmod(path, mode) return retbool(C.lchmod(path, c.MODE[mode])) end end if C.fdatasync then function S.fdatasync(fd) return retbool(C.fdatasync(getfd(fd))) end end -- Linux does not have mkfifo syscalls, emulated if C.mkfifo then function S.mkfifo(pathname, mode) return retbool(C.mkfifo(pathname, c.S_I[mode])) end end if C.mkfifoat then function S.mkfifoat(dirfd, pathname, mode) return retbool(C.mkfifoat(c.AT_FDCWD[dirfd], pathname, c.S_I[mode])) end end if C.utimes then function S.utimes(filename, ts) if ts then ts = t.timeval2(ts) end return retbool(C.utimes(filename, ts)) end end if C.lutimes then function S.lutimes(filename, ts) if ts then ts = t.timeval2(ts) end return retbool(C.lutimes(filename, ts)) end end if C.futimes then function S.futimes(fd, ts) if ts then ts = t.timeval2(ts) end return retbool(C.futimes(getfd(fd), ts)) end end if C.getdents then function S.getdents(fd, buf, size) size = size or 4096 -- may have to be equal to at least block size of fs buf = buf or t.buffer(size) local ret, err = C.getdents(getfd(fd), buf, size) if ret == -1 then return nil, t.error(err or errno()) end return t.dirents(buf, ret) end end if C.futimens then function S.futimens(fd, ts) if ts then ts = t.timespec2(ts) end return retbool(C.futimens(getfd(fd), ts)) end end if C.accept4 then function S.accept4(sockfd, addr, addrlen, flags) local saddr = pt.sockaddr(addr) if addr then addrlen = addrlen or t.socklen1() end return retfd(C.accept4(getfd(sockfd), saddr, addrlen, c.SOCK[flags])) end end if C.sigaction then function S.sigaction(signum, handler, oldact) if type(handler) == "string" or type(handler) == "function" then handler = {handler = handler, mask = "", flags = 0} -- simple case like signal end if handler then handler = mktype(t.sigaction, handler) end return retbool(C.sigaction(c.SIG[signum], handler, oldact)) end end if C.getitimer then function S.getitimer(which, value) value = value or t.itimerval() local ret, err = C.getitimer(c.ITIMER[which], value) if ret == -1 then return nil, t.error(err or errno()) end return value end end if C.setitimer then function S.setitimer(which, it, oldtime) oldtime = oldtime or t.itimerval() local ret, err = C.setitimer(c.ITIMER[which], mktype(t.itimerval, it), oldtime) if ret == -1 then return nil, t.error(err or errno()) end return oldtime end end if C.clock_getres then function S.clock_getres(clk_id, ts) ts = ts or t.timespec() local ret, err = C.clock_getres(c.CLOCK[clk_id], ts) if ret == -1 then return nil, t.error(err or errno()) end return ts end end if C.clock_gettime then function S.clock_gettime(clk_id, ts) ts = ts or t.timespec() local ret, err = C.clock_gettime(c.CLOCK[clk_id], ts) if ret == -1 then return nil, t.error(err or errno()) end return ts end end if C.clock_settime then function S.clock_settime(clk_id, ts) ts = mktype(t.timespec, ts) return retbool(C.clock_settime(c.CLOCK[clk_id], ts)) end end if C.clock_nanosleep then function S.clock_nanosleep(clk_id, flags, req, rem) rem = rem or t.timespec() local ret, err = C.clock_nanosleep(c.CLOCK[clk_id], c.TIMER[flags or 0], mktype(t.timespec, req), rem) if ret == -1 then if (err or errno()) == c.E.INTR then return true, nil, rem else return nil, t.error(err or errno()) end end return true -- no time remaining end end if C.timer_create then function S.timer_create(clk_id, sigev, timerid) timerid = timerid or t.timer() if sigev then sigev = mktype(t.sigevent, sigev) end local ret, err = C.timer_create(c.CLOCK[clk_id], sigev, timerid:gettimerp()) if ret == -1 then return nil, t.error(err or errno()) end return timerid end function S.timer_delete(timerid) return retbool(C.timer_delete(timerid:gettimer())) end function S.timer_settime(timerid, flags, new_value, old_value) if old_value ~= false then old_value = old_value or t.itimerspec() else old_value = nil end new_value = mktype(t.itimerspec, new_value) local ret, err = C.timer_settime(timerid:gettimer(), c.TIMER[flags], new_value, old_value) if ret == -1 then return nil, t.error(err or errno()) end return true, nil, old_value end function S.timer_gettime(timerid, curr_value) curr_value = curr_value or t.itimerspec() local ret, err = C.timer_gettime(timerid:gettimer(), curr_value) if ret == -1 then return nil, t.error(err or errno()) end return curr_value end function S.timer_getoverrun(timerid) return retnum(C.timer_getoverrun(timerid:gettimer())) end end -- legacy in many OSs, implemented using recvfrom, sendto if C.send then function S.send(fd, buf, count, flags) return retnum(C.send(getfd(fd), buf, count, c.MSG[flags])) end end if C.recv then function S.recv(fd, buf, count, flags) return retnum(C.recv(getfd(fd), buf, count, c.MSG[flags], false)) end end -- TODO not sure about this interface, maybe return rem as extra parameter see #103 if C.nanosleep then function S.nanosleep(req, rem) rem = rem or t.timespec() local ret, err = C.nanosleep(mktype(t.timespec, req), rem) if ret == -1 then if (err or errno()) == c.E.INTR then return true, nil, rem else return nil, t.error(err or errno()) end end return true -- no time remaining end end -- getpagesize might be a syscall, or in libc, or may not exist if C.getpagesize then function S.getpagesize() return retnum(C.getpagesize()) end end if C.syncfs then function S.syncfs(fd) return retbool(C.syncfs(getfd(fd))) end end -- although the pty functions are not syscalls, we include here, like eg shm functions, as easier to provide as methods on fds -- Freebsd has a syscall, other OSs use /dev/ptmx if C.posix_openpt then function S.posix_openpt(flags) return retfd(C.posix_openpt(c.O[flags])) end else function S.posix_openpt(flags) return S.open("/dev/ptmx", flags) end end S.openpt = S.posix_openpt function S.isatty(fd) local tc, err = S.tcgetattr(fd) if tc then return true else return nil, err end end if c.IOCTL.TIOCGSID then -- OpenBSD only has in legacy ioctls function S.tcgetsid(fd) return S.ioctl(fd, "TIOCGSID") end end -- now call OS specific for non-generic calls local hh = { ret64 = ret64, retnum = retnum, retfd = retfd, retbool = retbool, retptr = retptr, retiter = retiter } if (abi.rump and abi.types == "netbsd") or (not abi.rump and abi.bsd) then S = require("syscall.bsd.syscalls")(S, hh, c, C, types) end S = require("syscall." .. abi.os .. ".syscalls")(S, hh, c, C, types) return S end return {init = init}
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Southern_San_dOria/npcs/Raminel.lua
13
4948
----------------------------------- -- Area: Southern San d'Oria -- NPC: Raminel -- Involved in Quests: Riding on the Clouds -- @zone 230 -- @pos -56 2 -21 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); require("scripts/globals/pathfind"); local path = { -138.436340, -2.000000, 16.227097, -137.395432, -2.000000, 15.831898, -136.317108, -2.000000, 15.728185, -134.824036, -2.000000, 15.816396, -108.897049, -2.000000, 16.508110, -107.823288, -2.000000, 16.354126, -106.804962, -2.000000, 15.973084, -105.844963, -2.000000, 15.462379, -104.922585, -2.000000, 14.885456, -104.020050, -2.000000, 14.277813, -103.138374, -2.000000, 13.640303, -101.501289, -2.000000, 12.422975, -77.636841, 2.000000, -5.771687, -59.468536, 2.000000, -19.632719, -58.541172, 2.000000, -20.197826, -57.519985, 2.000000, -20.570829, -56.474659, 2.000000, -20.872238, -55.417450, 2.000000, -21.129019, -54.351425, 2.000000, -21.365578, -53.286743, 2.000000, -21.589529, -23.770412, 2.000000, -27.508755, -13.354427, 1.700000, -29.593290, -14.421194, 1.700000, -29.379389, -- auction house -43.848141, 2.000000, -23.492155, -56.516224, 2.000000, -20.955723, -57.555450, 2.000000, -20.638817, -58.514832, 2.000000, -20.127840, -59.426712, 2.000000, -19.534536, -60.322998, 2.000000, -18.917839, -61.203823, 2.000000, -18.279247, -62.510002, 2.000000, -17.300892, -86.411278, 2.000000, 0.921999, -105.625214, -2.000000, 15.580724, -106.582047, -2.000000, 16.089426, -107.647263, -2.000000, 16.304668, -108.732132, -2.000000, 16.383970, -109.819397, -2.000000, 16.423687, -110.907364, -2.000000, 16.429226, -111.995232, -2.000000, 16.411282, -140.205811, -2.000000, 15.668728, -- package Lusiane -139.296539, -2.000000, 16.786556 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); onPath(npc); -- test fromStart local start = pathfind.fromStart(path, 2); local startFirst = pathfind.get(path, 3); if (start[1] ~= startFirst[1] or start[2] ~= startFirst[2] or start[3] ~= startFirst[3]) then printf("[Error] start path is not right %f %f %f actually = %f %f %f", startFirst[1], startFirst[2], startFirst[3], start[1], start[2], start[3]); end -- test fromEnd -- local endPt = pathfind.fromEnd(path, 2); -- local endFirst = pathfind.get(path, 37); -- if (endPt[1] ~= endFirst[1] or endPt[2] ~= endFirst[2] or endPt[3] ~= endFirst[3]) then -- printf("[Error] endPt path is not right %f %f %f actually = %f %f %f", endFirst[1], endFirst[2], endFirst[3], endPt[1], endPt[2], endPt[3]); -- end end; function onPath(npc) if (npc:atPoint(pathfind.get(path, 23))) then local arp = GetNPCByID(17719409); npc:lookAt(arp:getPos()); npc:wait(); elseif (npc:atPoint(pathfind.get(path, -1))) then local lus = GetNPCByID(17719350); -- give package to Lusiane lus:showText(npc, RAMINEL_DELIVERY); npc:showText(lus, LUSIANE_THANK); -- wait default duration 4 seconds -- then continue path npc:wait(); elseif (npc:atPoint(pathfind.last(path))) then local lus = GetNPCByID(17719350); -- when I walk away stop looking at me lus:clearTargID(); end -- go back and forth the set path pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 1) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_1",0); player:tradeComplete(); player:addKeyItem(SCOWLING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0266); 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,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
Nax/citizenhack
dat/Rog-fila.lua
2
1796
-- NetHack 3.7 Rogue.des $NHDT-Date: 1432512784 2015/05/25 00:13:04 $ $NHDT-Branch: master $:$NHDT-Revision: 1.11 $ -- Copyright (c) 1992 by Dean Luick -- NetHack may be freely redistributed. See license for details. -- -- des.room({ type = "ordinary", contents = function() des.stair("up") des.object() des.monster({ id = "leprechaun", peaceful=0 }) end }) des.room({ type = "ordinary", contents = function() des.object() des.object() des.monster({ id = "leprechaun", peaceful=0 }) des.monster({ id = "guardian naga", peaceful=0 }) end }) des.room({ type = "ordinary", contents = function() des.object() des.trap() des.trap() des.object() des.monster({ id = "water nymph", peaceful=0 }) end }) des.room({ type = "ordinary", contents = function() des.stair("down") des.object() des.trap() des.trap() des.monster({ class = "l", peaceful=0 }) des.monster({ id = "guardian naga", peaceful=0 }) end }) des.room({ type = "ordinary", contents = function() des.object() des.object() des.trap() des.trap() des.monster({ id = "leprechaun", peaceful=0 }) end }) des.room({ type = "ordinary", contents = function() des.object() des.trap() des.trap() des.monster({ id = "leprechaun", peaceful=0 }) des.monster({ id = "water nymph", peaceful=0 }) end }) des.random_corridors()
mit
mynameiscraziu/body
plugins/sss.lua
44
9652
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No @'..member..' in group' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then send_large_msg(receiver, 'User @'..member..' ('..member_id..') BANNED!') return ban_user(member_id, chat_id) elseif get_cmd == 'globalban' then send_large_msg(receiver, 'User @'..member..' ('..member_id..') GLOBALLY BANNED!!') return superban_user(member_id, chat_id) elseif get_cmd == 'wlist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'wlist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == '+' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' BANNED!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == '-' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' UNbanned' end else return 'Only work in group' end end if matches[1] == 'globalban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == '+' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' GLOBALLY BANNED!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == '-' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' GLOBALLY UNbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'Only work in group' end end if matches[1] == 'wlist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Group Members Manager System", usage = { user = "/kickme : leave group", moderator = { "/kick (@user) : kick user", "/kick (id) : kick user", "/ban + (@user) : kick user for ever", "/ban + (id) : kick user for ever", "/ban - (id) : unban user" }, admin = { "/globalban + (@user) : ban user from all groups", "/globalban + (id) : ban user from all groups", "/globalban - (id) : globally unban user" }, }, patterns = { "^[!/](wlist) (enable)$", "^[!/](wlist) (disable)$", "^[!/](wlist) (user) (.*)$", "^[!/](wlist) (chat)$", "^[!/](wlist) (delete) (user) (.*)$", "^[!/](wlist) (delete) (chat)$", "^[!/](ban) (+) (.*)$", "^[!/](ban) (-) (.*)$", "^[!/](globalban) (+) (.*)$", "^[!/](globalban) (-) (.*)$", "^[!/](kick) (.*)$", "^[!/](kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
Kosmos82/kosmosdarkstar
scripts/globals/spells/bluemagic/mind_blast.lua
26
1989
----------------------------------------- -- Spell: Mind Blast -- Deals lightning damage to an enemy. Additional effect: Paralysis -- Spell cost: 82 MP -- Monster Type: Demons -- Spell Type: Magical (Lightning) -- Blue Magic Points: 4 -- Stat Bonus: MP+5 MND+1 -- Level: 73 -- Casting Time: 3 seconds -- Recast Time: 30 seconds -- Magic Bursts on: Impaction, Fragmentation, and Light -- Combos: Clear Mind ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local multi = 7.08; local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = multi; params.tMultiplier = 1.5; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, MND_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then multi = multi + 0.50; end if (damage > 0 and resist > 0.3) then local typeEffect = EFFECT_PARALYSIS; target:addStatusEffect(typeEffect,52,0,getBlueEffectDuration(caster,resist,typeEffect)); -- No info for power on the internet, static to 12 for now. end return damage; end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/globals/spells/shellra_v.lua
26
1101
----------------------------------------- -- Spell: Shellra ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local meritBonus = caster:getMerit(MERIT_SHELLRA_V); local duration = 1800; local power = 62; if (meritBonus > 0) then -- certain mobs can cast this spell, so don't apply the -2 for having 0 merits. power = power + meritBonus - 2; end power = power * 100/256; -- doing it this way because otherwise the merit power would have to be 0.78125. --printf("Shellra V Power: %d", power); duration = calculateDurationForLvl(duration, 75, target:getMainLvl()); local typeEffect = EFFECT_SHELL; if (target:addStatusEffect(typeEffect, power, 0, duration)) then spell:setMsg(230); else spell:setMsg(75); -- no effect end return typeEffect; end;
gpl-3.0
harveyhu2012/luci
modules/admin-full/luasrc/model/cbi/admin_system/fstab/swap.lua
84
1922
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> 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 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Swap Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "swap" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "swap", translate("Swap Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this swap")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) return m
apache-2.0
april-org/april-ann
packages/ann/optimizer/test/test-digits-l1.lua
3
5360
mathcore.set_use_cuda_default(util.is_cuda_available()) -- local check = utest.check local T = utest.test -- T("L1TestDigits", function() -- un generador de valores aleatorios... y otros parametros bunch_size = tonumber(arg[1]) or 64 semilla = 1234 weights_random = random(semilla) description = "256 inputs 256 tanh 128 tanh 10 log_softmax" inf = -1 sup = 1 shuffle_random = random(5678) learning_rate = 0.08 momentum = 0.0 L1_norm = 0.001 max_epochs = 10 -- training and validation errors = { {2.2798486, 2.0456107}, {1.7129538, 1.2954185}, {0.9751059, 0.6590891}, {0.5633602, 0.4138165}, {0.3464335, 0.3450162}, {0.2428290, 0.2518864}, {0.1867137, 0.1979152}, {0.1466725, 0.1708217}, {0.1282059, 0.1904573}, {0.1170338, 0.1766910}, } epsilon = 0.05 -- 5% -------------------------------------------------------------- m1 = ImageIO.read(string.get_path(arg[0]) .. "../../ann/test/digits.png"):to_grayscale():invert_colors():matrix() train_input = dataset.matrix(m1, { patternSize = {16,16}, offset = {0,0}, numSteps = {80,10}, stepSize = {16,16}, orderStep = {1,0} }) val_input = dataset.matrix(m1, { patternSize = {16,16}, offset = {1280,0}, numSteps = {20,10}, stepSize = {16,16}, orderStep = {1,0} }) -- una matriz pequenya la podemos cargar directamente m2 = matrix(10,{1,0,0,0,0,0,0,0,0,0}) -- ojito con este dataset, fijaros que usa una matriz de dim 1 y talla -- 10 PERO avanza con valor -1 y la considera CIRCULAR en su unica -- dimension train_output = dataset.matrix(m2, { patternSize = {10}, offset = {0}, numSteps = {800}, stepSize = {-1}, circular = {true} }) val_output = dataset.matrix(m2, { patternSize = {10}, offset = {0}, numSteps = {200}, stepSize = {-1}, circular = {true} }) thenet = ann.mlp.all_all.generate(description) trainer = trainable.supervised_trainer(thenet, ann.loss.multi_class_cross_entropy(10), bunch_size) trainer:build() trainer:set_option("learning_rate", learning_rate) trainer:set_option("momentum", momentum) trainer:set_option("L1_norm", L1_norm) -- bias has weight_decay of ZERO trainer:set_layerwise_option("b.", "L1_norm", 0) trainer:randomize_weights{ random = weights_random, inf = inf, sup = sup, use_fanin = true, } -- datos para entrenar datosentrenar = { input_dataset = train_input, output_dataset = train_output, shuffle = shuffle_random, } datosvalidar = { input_dataset = val_input, output_dataset = val_output, } totalepocas = 0 errorval = trainer:validate_dataset(datosvalidar) -- print("# Initial validation error:", errorval) clock = util.stopwatch() clock:go() -- print("Epoch Training Validation") for epoch = 1,max_epochs do collectgarbage("collect") totalepocas = totalepocas+1 errortrain,vartrain = trainer:train_dataset(datosentrenar) errorval,varval = trainer:validate_dataset(datosvalidar) printf("%4d %.7f %.7f :: %.7f %.7f\n", totalepocas,errortrain,errorval,vartrain,varval) check.number_eq(errortrain, errors[epoch][1], epsilon, string.format("Training error %g is not equal enough to ".. "reference error %g", errortrain, errors[epoch][1])) check.number_eq(errorval, errors[epoch][2], epsilon, string.format("Validation error %g is not equal enough to ".. "reference error %g", errorval, errors[epoch][2])) end clock:stop() cpu,wall = clock:read() --printf("Wall total time: %.3f per epoch: %.3f\n", wall, wall/max_epochs) --printf("CPU total time: %.3f per epoch: %.3f\n", cpu, cpu/max_epochs) -- print("Test passed! OK!") for wname,w in trainer:iterate_weights("w.*") do local v = w:clone():abs():min() check.TRUE(v == 0 or v > L1_norm) check.gt(w:eq(0.0):convert_to("float"):sum(), 0) -- print(w:eq(0.0):convert_to("float"):sum()) end end)
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/globals/weaponskills/flash_nova.lua
9
1395
----------------------------------- -- Skill level: 290 -- Delivers light elemental damage. Additional effect: Flash. Chance of effect varies with TP. -- Generates a significant amount of Enmity. -- Does not stack with Sneak Attack -- Aligned with Aqua Gorget. -- Aligned with Aqua Belt. -- Properties: -- Element: Light -- Skillchain Properties:Induration Reverberation -- Modifiers: STR:30% MND:30% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0; params.ele = ELE_LIGHT; params.skill = SKILL_CLB; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.5; params.mnd_wsc = 0.5; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0