repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
bnetcc/darkstar
scripts/zones/Northern_San_dOria/npcs/Eugballion.lua
5
1338
----------------------------------- -- Area: Northern San d'Oria -- NPC: Eugballion -- Only sells when San d'Oria controlls Qufim Region ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) if (GetRegionOwner(QUFIMISLAND) ~= NATION_SANDORIA) then player:showText(npc,EUGBALLION_CLOSED_DIALOG); else player:showText(npc,EUGBALLION_OPEN_DIALOG); local stock = {954, 4121} -- Magic Pot Shard showShop(player,SANDORIA,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lcf258/openwrtcn
applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_mini.lua
141
1031
--[[ smap_devinfo - SIP Device Information (c) 2009 Daniel Dickinson 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$ ]]-- require("luci.i18n") require("luci.util") require("luci.sys") require("luci.model.uci") require("luci.controller.luci_diag.smap_common") require("luci.controller.luci_diag.devinfo_common") local debug = false m = SimpleForm("luci-smap-to-devinfo", translate("Phone Information"), translate("Scan for supported SIP devices on specified networks.")) m.reset = false m.submit = false local outnets = luci.controller.luci_diag.smap_common.get_params() luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.smap_common.command_function) luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, true, "smap", true, debug) luci.controller.luci_diag.smap_common.action_links(m, true) return m
apache-2.0
bnetcc/darkstar
scripts/zones/Crawlers_Nest/Zone.lua
5
1174
----------------------------------- -- -- Zone: Crawlers_Nest (197) -- ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Crawlers_Nest/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/zone"); ----------------------------------- function onInitialize(zone) UpdateTreasureSpawnPoint(17584475); UpdateTreasureSpawnPoint(17584476); end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(380.617,-34.61,4.581,59); end return cs; end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
leonardoaxe/OpenRA
mods/ra/maps/survival01/survival01.lua
5
14583
Difficulty = Map.LobbyOption("difficulty") if Difficulty == "easy" then AttackAtFrameIncrement = DateTime.Seconds(22) AttackAtFrameIncrementInf = DateTime.Seconds(16) TimerTicks = DateTime.Minutes(15) IncrementTurningPoint = TimerTicks / 2 DamageModifier = 0.5 LongBowReinforcements = { "heli", "heli" } ParadropArtillery = true elseif Difficulty == "normal" then AttackAtFrameIncrement = DateTime.Seconds(18) AttackAtFrameIncrementInf = DateTime.Seconds(12) TimerTicks = DateTime.Minutes(20) IncrementTurningPoint = TimerTicks / 2 MoreParas = true DamageModifier = 0.75 LongBowReinforcements = { "heli", "heli" } else --Difficulty == "hard" AttackAtFrameIncrement = DateTime.Seconds(14) AttackAtFrameIncrementInf = DateTime.Seconds(8) TimerTicks = DateTime.Minutes(25) IncrementTurningPoint = DateTime.Minutes(10) MoreParas = true AttackAtFrameNaval = DateTime.Minutes(3) + DateTime.Seconds(45) SpawnNavalUnits = true DamageModifier = 1 LongBowReinforcements = { "heli" } end AlliedAirReinforcementsWaypoints = { { AirReinforcementsEntry1.Location, AirReinforcementsEntry2.Location }, { AirReinforcementsRally1.Location, AirReinforcementsRally2.Location } } FrenchReinforcements = { "2tnk", "2tnk", "2tnk", "2tnk", "2tnk", "1tnk", "1tnk", "1tnk", "arty", "arty", "arty", "jeep", "jeep" } SpawningSovietUnits = true SpawningInfantry = true AttackAtFrameInf = DateTime.Seconds(12) AttackAtFrame = DateTime.Seconds(18) SovietAttackGroupSize = 5 SovietInfantryGroupSize = 7 FactoryClearRange = 10 ParadropTicks = DateTime.Seconds(30) ParadropWaypoints = { { 192 + 4, ParaDrop1}, { 192 - 4, ParaDrop2}, { 192 + 4, Alliesbase2}, { 192 - 4, Alliesbase1} } NavalTransportPassengers = { "e1", "e1", "e2", "e4", "e4" } NavalReinforcementsWaypoints = { NavalWaypoint1, NavalWaypoint2, NavalWaypoint2, NavalWaypoint3 } Squad1 = { "e1", "e1" } Squad2 = { "e2", "e2" } SovietVehicles = { "3tnk", "3tnk", "3tnk", "3tnk", "3tnk", "3tnk", "v2rl", "v2rl", "ftrk", "ftrk", "ftrk", "apc", "apc" } SovietInfantry = { "e1", "e1", "e1", "e1", "e2", "e2", "e2", "e4", "e4", "e3" } SovietEntryPoints = { SovietEntryPoint1, SovietEntryPoint2, SovietEntryPoint3, SovietEntryPoint4, SovietEntryPoint5 } SovietRallyPoints = { SovietRallyPoint1, SovietRallyPoint2, SovietRallyPoint3, SovietRallyPoint4, SovietRallyPoint5 } SovietGateRallyPoints = { AlliesBaseGate2, AlliesBaseGate2, AlliesBaseGate1, AlliesBaseGate1, AlliesBaseGate1 } Airfields = { SovietAirfield1, SovietAirfield2, SovietAirfield3 } SovietBuildings = { Barrack1, SubPen, RadarDome, AdvancedPowerPlant1, AdvancedPowerPlant2, AdvancedPowerPlant3, WarFactory, Refinery, Silo1, Silo2, FlameTower1, FlameTower2, FlameTower3, Sam1, Sam2, Sam3, Sam4, SovietAirfield1, SovietAirfield2, SovietAirfield3 } IdleTrigger = function(units, dest) Utils.Do(units, function(unit) if not unit.IsDead then Trigger.OnIdle(unit, function() local bool = Utils.All(units, function(unit) return unit.IsIdle end) if bool then SetupHuntTrigger(units) end end) Trigger.OnDamaged(unit, function() SetupHuntTrigger(units) end) Trigger.OnCapture(unit, function() Trigger.ClearAll(unit) end) end end) end SetupHuntTrigger = function(units) Utils.Do(units, function(unit) if not unit.IsDead then Trigger.ClearAll(unit) Trigger.AfterDelay(0, function() if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) Trigger.OnCapture(unit, function() Trigger.ClearAll(unit) end) end end) end end) end ticked = TimerTicks Tick = function() if KillObj and soviets.HasNoRequiredUnits() then allies.MarkCompletedObjective(KillObj) end if allies.HasNoRequiredUnits() then soviets.MarkCompletedObjective(SovietObj) end if soviets.Resources > soviets.ResourceCapacity / 2 then soviets.Resources = soviets.ResourceCapacity / 2 end if ticked > 0 then if DateTime.Minutes(20) == ticked then Media.PlaySpeechNotification(allies, "TwentyMinutesRemaining") elseif DateTime.Minutes(10) == ticked then Media.PlaySpeechNotification(allies, "TenMinutesRemaining") elseif DateTime.Minutes(5) == ticked then Media.PlaySpeechNotification(allies, "WarningFiveMinutesRemaining") elseif DateTime.Minutes(4) == ticked then Media.PlaySpeechNotification(allies, "WarningFourMinutesRemaining") Trigger.AfterDelay(ParadropTicks, function() SendSovietParadrops(ParadropWaypoints[3]) SendSovietParadrops(ParadropWaypoints[2]) end) Trigger.AfterDelay(ParadropTicks * 2, function() SendSovietParadrops(ParadropWaypoints[4]) SendSovietParadrops(ParadropWaypoints[1]) end) elseif DateTime.Minutes(3) == ticked then Media.PlaySpeechNotification(allies, "WarningThreeMinutesRemaining") elseif DateTime.Minutes(2) == ticked then Media.PlaySpeechNotification(allies, "WarningTwoMinutesRemaining") AttackAtFrameIncrement = DateTime.Seconds(4) AttackAtFrameIncrementInf = DateTime.Seconds(4) elseif DateTime.Minutes(1) == ticked then Media.PlaySpeechNotification(allies, "WarningOneMinuteRemaining") elseif DateTime.Seconds(45) == ticked then Media.PlaySpeechNotification(allies, "AlliedForcesApproaching") end UserInterface.SetMissionText("French reinforcements arrive in " .. Utils.FormatTime(ticked), TimerColor) ticked = ticked - 1 elseif ticked == 0 then FinishTimer() TimerExpired() ticked = ticked - 1 end end FinishTimer = function() for i = 0, 9, 1 do local c = TimerColor if i % 2 == 0 then c = HSLColor.White end Trigger.AfterDelay(DateTime.Seconds(i), function() UserInterface.SetMissionText("Our french allies have arrived!", c) end) end Trigger.AfterDelay(DateTime.Seconds(10), function() UserInterface.SetMissionText("") end) end SendSovietParadrops = function(table) local units = powerproxy.SendParatroopers(table[2].CenterPosition, false, table[1]) Utils.Do(units, function(unit) Trigger.OnIdle(unit, function(a) if a.IsInWorld then a.Hunt() end end) end) end SendSovietNavalReinforcements = function() if SpawnNavalUnits then local entry = NavalEntryPoint.Location local units = Reinforcements.ReinforceWithTransport(soviets, "lst", NavalTransportPassengers, { entry, Utils.Random(NavalReinforcementsWaypoints).Location }, { entry })[2] Utils.Do(units, function(unit) Trigger.OnIdle(unit, unit.Hunt) end) local delay = Utils.RandomInteger(AttackAtFrameNaval, AttackAtFrameNaval + DateTime.Minutes(2)) Trigger.AfterDelay(delay, SendSovietNavalReinforcements) end end SpawnSovietInfantry = function() local units = { } for i = 0, SovietInfantryGroupSize - 1, 1 do local type = Utils.Random(SovietInfantry) units[i] = type end soviets.Build(units, function(soldiers) Trigger.AfterDelay(25, function() IdleTrigger(soldiers) end) end) end SpawnSovietUnits = function() local units = { } for i = 0, SovietAttackGroupSize - 1, 1 do local type = Utils.Random(SovietVehicles) units[i] = type end local route = Utils.RandomInteger(1, #SovietEntryPoints + 1) local attackers = Reinforcements.Reinforce(soviets, units, { SovietEntryPoints[route].Location, SovietRallyPoints[route].Location }) Trigger.AfterDelay(25, function() IdleTrigger(attackers, SovietGateRallyPoints[route].Location) end) end SendInfantryWave = function() if SpawningInfantry then SpawnSovietInfantry() if DateTime.GameTime < IncrementTurningPoint then AttackAtFrameIncrementInf = AttackAtFrameIncrementInf + Utils.RandomInteger(DateTime.Seconds(2), DateTime.Seconds(3)) elseif not (AttackAtFrameIncrementInf <= DateTime.Seconds(4)) then AttackAtFrameIncrementInf = AttackAtFrameIncrementInf - Utils.RandomInteger(DateTime.Seconds(2), DateTime.Seconds(3)) end Trigger.AfterDelay(AttackAtFrameInf + AttackAtFrameIncrementInf, SendInfantryWave) end end SendVehicleWave = function() if SpawningSovietUnits then SpawnSovietUnits() if DateTime.GameTime < IncrementTurningPoint then AttackAtFrameIncrement = AttackAtFrameIncrement + Utils.RandomInteger(DateTime.Seconds(4), DateTime.Seconds(6)) elseif not (AttackAtFrameIncrement <= DateTime.Seconds(4)) then AttackAtFrameIncrement = AttackAtFrameIncrement - Utils.RandomInteger(DateTime.Seconds(4), DateTime.Seconds(6)) end Trigger.AfterDelay(AttackAtFrame + AttackAtFrameIncrement, SendVehicleWave) end end TimerExpired = function() SpawningSovietUnits = false SpawningInfantry = false SpawnNavalUnits = false Beacon.New(allies, SovietEntryPoint7.CenterPosition - WVec.New(3 * 1024, 0, 0)) Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived") Reinforcements.Reinforce(allies, FrenchReinforcements, { SovietEntryPoint7.Location, Alliesbase.Location }) if DestroyObj then KillObj = allies.AddPrimaryObjective("Take control of French reinforcements and\nkill all remaining Soviet forces.") else DestroyObj = allies.AddPrimaryObjective("Take control of French reinforcements and\ndismantle the nearby Soviet base.") end allies.MarkCompletedObjective(SurviveObj) if not allies.IsObjectiveCompleted(KillSams) then allies.MarkFailedObjective(KillSams) end end DropAlliedArtillery = function(facing, dropzone) local proxy = Actor.Create("powerproxy.allied", true, { Owner = allies }) proxy.SendParatroopers(dropzone, false, facing) proxy.Destroy() end SendLongBowReinforcements = function() Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived") Reinforcements.Reinforce(allies, LongBowReinforcements, AlliedAirReinforcementsWaypoints[1]) Reinforcements.Reinforce(allies, LongBowReinforcements, AlliedAirReinforcementsWaypoints[2]) if ParadropArtillery then local facing = Utils.RandomInteger(Facing.NorthWest, Facing.SouthWest) DropAlliedArtillery(facing, Alliesbase.CenterPosition) end end InitObjectives = function() Trigger.OnObjectiveAdded(allies, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) SurviveObj = allies.AddPrimaryObjective("Enforce your position and hold-out the onslaught\nuntil reinforcements arrive.") KillSams = allies.AddSecondaryObjective("Destroy the two SAM sites before reinforcements\narrive.") Media.DisplayMessage("The Soviets are blocking our GPS. We need to investigate their new technology.") CaptureAirfields = allies.AddSecondaryObjective("Capture and hold the Soviet airbase\nin the northeast.") SovietObj = soviets.AddPrimaryObjective("Eliminate all Allied forces.") Trigger.OnObjectiveCompleted(allies, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(allies, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(allies, function() Media.PlaySpeechNotification(allies, "MissionFailed") end) Trigger.OnPlayerWon(allies, function() Media.PlaySpeechNotification(allies, "MissionAccomplished") Media.DisplayMessage("The French forces have survived and dismantled the Soviet presence in the area!") end) end InitMission = function() Camera.Position = Alliesbase.CenterPosition camera1 = Actor.Create("camera.sam", true, { Owner = allies, Location = Sam1.Location }) camera2 = Actor.Create("camera.sam", true, { Owner = allies, Location = Sam2.Location }) Trigger.OnKilled(Sam1, function() if camera1.IsInWorld then camera1.Destroy() end end) Trigger.OnKilled(Sam2, function() if camera2.IsInWorld then camera2.Destroy() end end) Trigger.OnAllKilledOrCaptured({ Sam1, Sam2 }, function() if not allies.IsObjectiveFailed(KillSams) then allies.MarkCompletedObjective(KillSams) SendLongBowReinforcements() end end) local count = 0 Utils.Do(Airfields, function(field) Trigger.OnCapture(field, function() count = count + 1 if count == #Airfields then allies.MarkCompletedObjective(CaptureAirfields) local atek = Actor.Create("atek.mission", true, { Owner = allies, Location = HiddenATEK.Location }) Trigger.AfterDelay(DateTime.Seconds(5), atek.Destroy) end end) Trigger.OnKilled(field, function() allies.MarkFailedObjective(CaptureAirfields) end) end) Trigger.OnAllKilledOrCaptured(SovietBuildings, function() if DestroyObj then if not soviets.HasNoRequiredUnits() then KillObj = allies.AddPrimaryObjective("Kill all remaining Soviet forces.") end allies.MarkCompletedObjective(DestroyObj) else DestroyObj = allies.AddPrimaryObjective("Dismantle the nearby Soviet base.") allies.MarkCompletedObjective(DestroyObj) end end) Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(allies, "MissionTimerInitialised") end) TimerColor = allies.Color end SetupSoviets = function() Barrack1.IsPrimaryBuilding = true Barrack1.RallyPoint = SovietInfantryRally1.Location Trigger.OnKilledOrCaptured(Barrack1, function() SpawningInfantry = false end) Trigger.AfterDelay(0, function() local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == soviets and self.HasProperty("StartBuildingRepairs") end) Utils.Do(buildings, function(actor) Trigger.OnDamaged(actor, function(building) if building.Owner == soviets and building.Health < building.MaxHealth * DamageModifier then building.StartBuildingRepairs() end end) end) end) Reinforcements.Reinforce(soviets, Squad1, { AlliesBaseGate1.Location, Alliesbase1.Location }) Reinforcements.Reinforce(soviets, Squad2, { AlliesBaseGate2.Location, Alliesbase2.Location }) powerproxy = Actor.Create("powerproxy.paratroopers", false, { Owner = soviets }) Trigger.AfterDelay(ParadropTicks, function() SendSovietParadrops(ParadropWaypoints[1]) SendSovietParadrops(ParadropWaypoints[2]) end) Trigger.AfterDelay(ParadropTicks * 2, function() SendSovietParadrops(ParadropWaypoints[3]) SendSovietParadrops(ParadropWaypoints[4]) end) Trigger.AfterDelay(AttackAtFrame, SendVehicleWave) Trigger.AfterDelay(AttackAtFrameInf, SendInfantryWave) if MoreParas then local delay = Utils.RandomInteger(TimerTicks/3, TimerTicks*2/3) Trigger.AfterDelay(delay, function() SendSovietParadrops(ParadropWaypoints[Utils.RandomInteger(1,3)]) SendSovietParadrops(ParadropWaypoints[Utils.RandomInteger(3,5)]) end) end if SpawnNavalUnits then Trigger.AfterDelay(AttackAtFrameNaval, SendSovietNavalReinforcements) end end WorldLoaded = function() allies = Player.GetPlayer("Allies") soviets = Player.GetPlayer("Soviets") InitObjectives() InitMission() SetupSoviets() end
gpl-3.0
awesomeWM/awesome
tests/examples/text/awful/keygrabber/root_keybindings.lua
4
2595
--DOC_GEN_OUTPUT --DOC_HIDE local awful = { keygrabber = require("awful.keygrabber"), --DOC_HIDE key = require("awful.key") } --DOC_HIDE local keybinding_works = {} --DOC_HIDE local g = --DOC_HIDE awful.keygrabber { mask_modkeys = true, root_keybindings = { awful.key { modifiers = {"Mod4"}, key = "i", on_press = function(self) print("Is now active!", self) keybinding_works[1] = true --DOC_HIDE end }, }, keybindings = { awful.key { modifiers = {"Mod4", "Shift"}, key = "i", on_press = function(self) print("Called again!") keybinding_works[3] = true --DOC_HIDE self:stop() end }, }, keypressed_callback = function(_, modifiers, key) print("A key was pressed:", key, "with", #modifiers, "modifier!") keybinding_works[2] = keybinding_works[2] and keybinding_works[2] + 1 or 1 --DOC_HIDE end, } --DOC_NEWLINE -- The following will **NOT** trigger the keygrabbing because it isn't exported -- to the root (global) keys. Adding `export_keybindings` would solve that require("gears.timer").run_delayed_calls_now() --DOC_HIDE `root_keybindings` is async root._execute_keybinding({"Mod4", "Shift"}, "i") assert(#keybinding_works == 0) --DOC_NEWLINE -- But this will start the keygrabber because it is part of the root_keybindings root._execute_keybinding({"Mod4"}, "i") assert(keybinding_works[1]) --DOC_HIDE assert(not keybinding_works[2]) --DOC_HIDE --DOC_NEWLINE -- Note that that keygrabber is running, all callbacks should work: root.fake_input("key_press" , "a") root.fake_input("key_release" , "a") assert(keybinding_works[2] == 1) --DOC_HIDE --DOC_NEWLINE -- Calling the root keybindings now wont work because they are not part of -- the keygrabber internal (own) keybindings, so `keypressed_callback` will -- be called. root._execute_keybinding({"Mod4"}, "i") assert(keybinding_works[2] == 2) --DOC_HIDE because mask_modkeys is set assert(g == awful.keygrabber.current_instance) --DOC_HIDE assert(not keybinding_works[3])--DOC_HIDE --DOC_NEWLINE -- Now the keygrabber own keybindings will work root._execute_keybinding({"Mod4", "Shift"}, "i") assert(keybinding_works[3])--DOC_HIDE keybinding_works[2] = 0--DOC_HIDE assert(not awful.keygrabber.current_instance) --DOC_HIDE root.fake_input("key_press" , "a") --DOC_HIDE root.fake_input("key_release" , "a") --DOC_HIDE assert(keybinding_works[2] == 0) --DOC_HIDE
gpl-2.0
TurkeyMan/premake-core
modules/gmake/tests/workspace/test_default_config.lua
13
1465
-- -- tests/actions/make/test_default_config.lua -- Validate generation of default configuration block for makefiles. -- Copyright (c) 2012-2015 Jason Perkins and the Premake project -- local suite = test.declare("make_default_config") local p = premake -- -- Setup/teardown -- local wks, prj function suite.setup() wks = test.createWorkspace() end local function prepare() prj = test.getproject(wks, 1) p.make.defaultconfig(prj) end -- -- Verify the handling of the default setup: Debug and Release, no platforms. -- function suite.defaultsToFirstBuildCfg_onNoPlatforms() prepare() test.capture [[ ifndef config config=debug endif ]] end -- -- Verify handling of build config/platform combination. -- function suite.defaultsToFirstPairing_onPlatforms() platforms { "Win32", "Win64" } prepare() test.capture [[ ifndef config config=debug_win32 endif ]] end -- -- If the project excludes a workspace build cfg, it should be skipped -- over as the default config as well. -- function suite.usesFirstValidPairing_onExcludedConfig() platforms { "Win32", "Win64" } removeconfigurations { "Debug" } prepare() test.capture [[ ifndef config config=release_win32 endif ]] end -- -- Verify handling of defaultplatform -- function suite.defaultsToSpecifiedPlatform() platforms { "Win32", "Win64" } defaultplatform "Win64" prepare() test.capture [[ ifndef config config=debug_win64 endif ]] end
bsd-3-clause
bnetcc/darkstar
scripts/zones/Port_San_dOria/npcs/Bonmaurieut.lua
5
1613
----------------------------------- -- Area: Port San d'Oria -- NPC: Bonmaurieut -- Only sells when San d'Oria controlls Elshimo Uplands ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) local RegionOwner = GetRegionOwner(ELSHIMOUPLANDS); if (RegionOwner ~= NATION_SANDORIA) then player:showText(npc,BONMAURIEUT_CLOSED_DIALOG); else player:showText(npc,BONMAURIEUT_OPEN_DIALOG); local stock = { 1413, 1656, -- Cattleya 628, 239, -- Cinnamon 4468, 73, -- Pamamas 721, 147 -- Rattan Lumber } showShop(player,SANDORIA,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Abyssea-Empyreal_Paradox/bcnms/The_Wyrm_God.lua
1
1886
----------------------------------- -- Area: Abyssea-Empyreal_Paradox -- Name: The Wyrm God ----------------------------------- package.loaded["scripts/zones/Abyssea-Empyreal_Paradox/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Abyssea-Empyreal_Paradox/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/globals/titles"); ----------------------------------- -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) print("bc finish csid "..csid.." and option "..option); end;
gpl-3.0
OpenPrograms/Plan9k
plan9k-ohcp-server/13_ohcpSrv.lua
1
2575
local sysfs = kernel.modules.sysfs sysfs.data.net.ohcp = { pool = { __type = "f", write = function(h, data) local ifname, base, sub, count, gw = data:match("([^%s]+)%s+([%d%.]+)/(%d+)%s+(%d+)%s*([%d%.]*)") if not base then kernel.io.println("pool_add_v4: invalid pattern") return nil end local iface = kernel.modules.interface.interfaces[ifname] if not iface then kernel.io.println("pool_add_v4: no such interface") return nil end local baseStr = kernel.modules.ip.ip4parse(base) if not baseStr then kernel.io.println("pool_add_v4: invalid address") return nil end if gw and not kernel.modules.ip.ip4parse(gw) then kernel.io.println("pool_add_v4: invalid gateway address") return nil end if not iface.ohcp then iface.ohcp = {} end if not iface.ohcp.pool then iface.ohcp.pool = {} end iface.ohcp.pool[#iface.ohcp.pool + 1] = { base = string.unpack(">I4", baseStr), next = 0, max = tonumber(count), lease = {}, sub = tonumber(sub), gate = gw and kernel.modules.ip.ip4parse(gw) or nil, } end } } function read(iface, remoteAddr, data) if data:byte(1) == 0 then if iface.ohcp and iface.ohcp.pool then for _, pool in ipairs(iface.ohcp.pool) do if pool.lease[remoteAddr] then iface.write(string.pack(">BBI4B", 1, 0, pool.lease[remoteAddr], pool.sub), 0xCF, remoteAddr) if pool.gate then iface.write(string.pack(">BBc4I4", 1, 2, pool.gate, pool.lease[remoteAddr]), 0xCF, remoteAddr) end break elseif pool.next < pool.max then pool.lease[remoteAddr] = pool.base + pool.next pool.next = pool.next + 1 iface.write(string.pack(">BBI4B", 1, 0, pool.lease[remoteAddr], pool.sub), 0xCF, remoteAddr) if pool.gate then iface.write(string.pack(">BBc4I4", 1, 2, pool.gate, pool.lease[remoteAddr]), 0xCF, remoteAddr) end break end end end end end
mit
bnetcc/darkstar
scripts/zones/Bastok_Markets/npcs/Enu.lua
5
2279
----------------------------------- -- Area: Bastok Markets -- NPC: Enu -- Type: Quest NPC -- !pos -253.673 -13 -92.326 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/weather"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1192, 1) and trade:getItemCount() == 1) then -- Quest: Wish Upon a Star - Trade Fallen Star if (player:getVar("WishUponAStar_Status") == 3) then if (player:getWeather() == WEATHER_NONE and (VanadielTOTD() == TIME_NIGHT or VanadielTOTD() == TIME_MIDNIGHT)) then player:startEvent(334); -- Trade accepeted else player:startEvent(337); -- Player has to wait for clear weather end end end end; function onTrigger(player,npc) if (player:getQuestStatus(BASTOK, WISH_UPON_A_STAR) == QUEST_COMPLETED) then -- Quest: Wish Upon a Star - Quest has been completed. player:startEvent(335); elseif (player:getVar("WishUponAStar_Status") == 2) then -- Quest: Wish Upon a Star - Player has spoken with Malene player:startEvent(332); elseif (player:getVar("WishUponAStar_Status") == 3) then -- Quest: Wish Upon a Star - Enu has asked player to give her a fallen star player:startEvent(333); else -- Standard dialog player:startEvent(327); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf ("CSID: %u",csid); -- printf ("RESULT: %u",option); if (csid == 332) then -- Quest: Wish Upon a Star player:setVar("WishUponAStar_Status",3); elseif (csid == 334) then -- Quest: Wish Upon a Star - Traded Fallen Star player:tradeComplete( ); player:completeQuest(BASTOK,WISH_UPON_A_STAR); player:setVar("WishUponAStar_Status",0); player:addFame(BASTOK,50); player:addItem(1236,4); -- Reward for quest completion: Cactus Stems x 4 player:messageSpecial(ITEM_OBTAINED,1236); end end;
gpl-3.0
swe-TeamRed/wesnoth
data/ai/micro_ais/cas/ca_return_guardian.lua
4
1133
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local function get_guardian(cfg) local filter = H.get_child(cfg, "filter") or { id = cfg.id } local guardian = AH.get_units_with_moves { side = wesnoth.current.side, { "and", filter } }[1] return guardian end local ca_return_guardian = {} function ca_return_guardian:evaluation(cfg) local guardian = get_guardian(cfg) if guardian then if (guardian.x == cfg.return_x) and (guardian.y == cfg.return_y) then return cfg.ca_score - 200 else return cfg.ca_score end end return 0 end function ca_return_guardian:execution(cfg) local guardian = get_guardian(cfg) -- In case the return hex is occupied: local x, y = cfg.return_x, cfg.return_y if (guardian.x ~= x) or (guardian.y ~= y) then x, y = wesnoth.find_vacant_tile(x, y, guardian) end local nh = AH.next_hop(guardian, x, y) if (not nh) then nh = { guardian.x, guardian.y } end AH.movefull_stopunit(ai, guardian, nh) end return ca_return_guardian
gpl-2.0
mwoz123/koreader
frontend/ui/widget/radiobutton.lua
2
5244
--[[-- Widget that shows a radiobutton checked (`◉`) or unchecked (`◯`) or nothing of the same size. Example: local RadioButton = require("ui/widget/radiobutton") local parent_widget = FrameContainer:new{} table.insert(parent_widget, RadioButton:new{ checkable = false, -- shows nothing when false, defaults to true checked = function() end, -- whether the box is checked }) UIManager:show(parent_widget) ]] local Blitbuffer = require("ffi/blitbuffer") local Device = require("device") local Font = require("ui/font") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local InputContainer = require("ui/widget/container/inputcontainer") local LeftContainer = require("ui/widget/container/leftcontainer") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local RadioButton = InputContainer:new{ checkable = true, checked = false, enabled = true, face = Font:getFace("smallinfofont"), background = Blitbuffer.COLOR_WHITE, width = 0, height = 0, } function RadioButton:init() self._checked_widget = TextWidget:new{ text = "◉ " .. self.text, face = self.face, max_width = self.max_width, } self._unchecked_widget = TextWidget:new{ text = "◯ " .. self.text, face = self.face, max_width = self.max_width, } self._empty_widget = TextWidget:new{ text = "" .. self.text, face = self.face, max_width = self.max_width, } self._widget_size = self._unchecked_widget:getSize() if self.width == nil then self.width = self._widget_size.w end self._radio_button = self.checkable and (self.checked and self._checked_widget or self._unchecked_widget) or self._empty_widget self:update() self.dimen = self.frame:getSize() if Device:isTouchDevice() then self.ges_events = { TapCheckButton = { GestureRange:new{ ges = "tap", range = self.dimen, }, doc = "Tap Button", }, HoldCheckButton = { GestureRange:new{ ges = "hold", range = self.dimen, }, doc = "Hold Button", } } end end function RadioButton:update() self.frame = FrameContainer:new{ margin = self.margin, bordersize = self.bordersize, background = self.background, radius = self.radius, padding = self.padding, LeftContainer:new{ dimen = Geom:new{ w = self.width, h = self._widget_size.h }, self._radio_button, } } self[1] = self.frame end function RadioButton:onFocus() self.frame.invert = true return true end function RadioButton:onUnfocus() self.frame.invert = false return true end function RadioButton:onTapCheckButton() if self.enabled and self.callback then if G_reader_settings:isFalse("flash_ui") then self.callback() else -- c.f., ui/widget/iconbutton for the canonical documentation about the flash_ui code flow -- Highlight -- -- self.frame's width is based on self.width, so we effectively flash the full width, not only the button/text's width. -- This matches the behavior of Menu & TouchMenu. self.frame.invert = true UIManager:widgetInvert(self.frame, self.dimen.x, self.dimen.y) UIManager:setDirty(nil, "fast", self.dimen) UIManager:forceRePaint() UIManager:yieldToEPDC() -- Unhighlight -- self.frame.invert = false UIManager:widgetInvert(self.frame, self.dimen.x, self.dimen.y) UIManager:setDirty(nil, "ui", self.dimen) -- Callback -- self.callback() UIManager:forceRePaint() end elseif self.tap_input then self:onInput(self.tap_input) elseif type(self.tap_input_func) == "function" then self:onInput(self.tap_input_func()) end return true end function RadioButton:onHoldCheckButton() if self.enabled and self.hold_callback then self.hold_callback() elseif self.hold_input then self:onInput(self.hold_input) elseif type(self.hold_input_func) == "function" then self:onInput(self.hold_input_func()) end return true end function RadioButton:check(callback) self._radio_button = self._checked_widget self.checked = true self:update() UIManager:widgetRepaint(self.frame, self.dimen.x, self.dimen.y) UIManager:setDirty(nil, "ui", self.dimen) end function RadioButton:unCheck() self._radio_button = self._unchecked_widget self.checked = false self:update() UIManager:widgetRepaint(self.frame, self.dimen.x, self.dimen.y) UIManager:setDirty(nil, "ui", self.dimen) end return RadioButton
agpl-3.0
leonardoaxe/OpenRA
lua/stacktraceplus.lua
59
12006
-- tables local _G = _G local string, io, debug, coroutine = string, io, debug, coroutine -- functions local tostring, print, require = tostring, print, require local next, assert = next, assert local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs local error = error assert(debug, "debug table must be available at this point") local io_open = io.open local string_gmatch = string.gmatch local string_sub = string.sub local table_concat = table.concat local _M = { max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)' } -- this tables should be weak so the elements in them won't become uncollectable local m_known_tables = { [_G] = "_G (global table)" } local function add_known_module(name, desc) local ok, mod = pcall(require, name) if ok then m_known_tables[mod] = desc end end add_known_module("string", "string module") add_known_module("io", "io module") add_known_module("os", "os module") add_known_module("table", "table module") add_known_module("math", "math module") add_known_module("package", "package module") add_known_module("debug", "debug module") add_known_module("coroutine", "coroutine module") -- lua5.2 add_known_module("bit32", "bit32 module") -- luajit add_known_module("bit", "bit module") add_known_module("jit", "jit module") local m_user_known_tables = {} local m_known_functions = {} for _, name in ipairs{ -- Lua 5.2, 5.1 "assert", "collectgarbage", "dofile", "error", "getmetatable", "ipairs", "load", "loadfile", "next", "pairs", "pcall", "print", "rawequal", "rawget", "rawlen", "rawset", "require", "select", "setmetatable", "tonumber", "tostring", "type", "xpcall", -- Lua 5.1 "gcinfo", "getfenv", "loadstring", "module", "newproxy", "setfenv", "unpack", -- TODO: add table.* etc functions } do if _G[name] then m_known_functions[_G[name]] = name end end local m_user_known_functions = {} local function safe_tostring (value) local ok, err = pcall(tostring, value) if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end end -- Private: -- Parses a line, looking for possible function definitions (in a very naïve way) -- Returns '(anonymous)' if no function name was found in the line local function ParseLine(line) assert(type(line) == "string") --print(line) local match = line:match("^%s*function%s+(%w+)") if match then --print("+++++++++++++function", match) return match end match = line:match("^%s*local%s+function%s+(%w+)") if match then --print("++++++++++++local", match) return match end match = line:match("^%s*local%s+(%w+)%s+=%s+function") if match then --print("++++++++++++local func", match) return match end match = line:match("%s*function%s*%(") -- this is an anonymous function if match then --print("+++++++++++++function2", match) return "(anonymous)" end return "(anonymous)" end -- Private: -- Tries to guess a function's name when the debug info structure does not have it. -- It parses either the file or the string where the function is defined. -- Returns '?' if the line where the function is defined is not found local function GuessFunctionName(info) --print("guessing function name") if type(info.source) == "string" and info.source:sub(1,1) == "@" then local file, err = io_open(info.source:sub(2), "r") if not file then print("file not found: "..tostring(err)) -- whoops! return "?" end local line for i = 1, info.linedefined do line = file:read("*l") end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) else local line local lineNumber = 0 for l in string_gmatch(info.source, "([^\n]+)\n-") do lineNumber = lineNumber + 1 if lineNumber == info.linedefined then line = l break end end if not line then print("line not found") -- whoops! return "?" end return ParseLine(line) end end --- -- Dumper instances are used to analyze stacks and collect its information. -- local Dumper = {} Dumper.new = function(thread) local t = { lines = {} } for k,v in pairs(Dumper) do t[k] = v end t.dumping_same_thread = (thread == coroutine.running()) -- if a thread was supplied, bind it to debug.info and debug.get -- we also need to skip this additional level we are introducing in the callstack (only if we are running -- in the same thread we're inspecting) if type(thread) == "thread" then t.getinfo = function(level, what) if t.dumping_same_thread and type(level) == "number" then level = level + 1 end return debug.getinfo(thread, level, what) end t.getlocal = function(level, loc) if t.dumping_same_thread then level = level + 1 end return debug.getlocal(thread, level, loc) end else t.getinfo = debug.getinfo t.getlocal = debug.getlocal end return t end -- helpers for collecting strings to be used when assembling the final trace function Dumper:add (text) self.lines[#self.lines + 1] = text end function Dumper:add_f (fmt, ...) self:add(fmt:format(...)) end function Dumper:concat_lines () return table_concat(self.lines) end --- -- Private: -- Iterates over the local variables of a given function. -- -- @param level The stack level where the function is. -- function Dumper:DumpLocals (level) local prefix = "\t " local i = 1 if self.dumping_same_thread then level = level + 1 end local name, value = self.getlocal(level, i) if not name then return end self:add("\tLocal variables:\r\n") while name do if type(value) == "number" then self:add_f("%s%s = number: %g\r\n", prefix, name, value) elseif type(value) == "boolean" then self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value)) elseif type(value) == "string" then self:add_f("%s%s = string: %q\r\n", prefix, name, value) elseif type(value) == "userdata" then self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value)) elseif type(value) == "nil" then self:add_f("%s%s = nil\r\n", prefix, name) elseif type(value) == "table" then if m_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value]) elseif m_user_known_tables[value] then self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value]) else local txt = "{" for k,v in pairs(value) do txt = txt..safe_tostring(k)..":"..safe_tostring(v) if #txt > _M.max_tb_output_len then txt = txt.." (more...)" break end if next(value, k) then txt = txt..", " end end self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}") end elseif type(value) == "function" then local info = self.getinfo(value, "nS") local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value] if info.what == "C" then self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value))) else local source = info.short_src if source:sub(2,7) == "string" then source = source:sub(9) end --for k,v in pairs(info) do print(k,v) end fun_name = fun_name or GuessFunctionName(info) self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source) end elseif type(value) == "thread" then self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value)) end i = i + 1 name, value = self.getlocal(level, i) end end --- -- Public: -- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc. -- This function is suitable to be used as an error handler with pcall or xpcall -- -- @param thread An optional thread whose stack is to be inspected (defaul is the current thread) -- @param message An optional error string or object. -- @param level An optional number telling at which level to start the traceback (default is 1) -- -- Returns a string with the stack trace and a string with the original error. -- function _M.stacktrace(thread, message, level) if type(thread) ~= "thread" then -- shift parameters left thread, message, level = nil, thread, message end thread = thread or coroutine.running() level = level or 1 local dumper = Dumper.new(thread) local original_error if type(message) == "table" then dumper:add("an error object {\r\n") local first = true for k,v in pairs(message) do if first then dumper:add(" ") first = false else dumper:add(",\r\n ") end dumper:add(safe_tostring(k)) dumper:add(": ") dumper:add(safe_tostring(v)) end dumper:add("\r\n}") original_error = dumper:concat_lines() elseif type(message) == "string" then dumper:add(message) original_error = message end dumper:add("\r\n") dumper:add[[ Stack Traceback =============== ]] --print(error_message) local level_to_show = level if dumper.dumping_same_thread then level = level + 1 end local info = dumper.getinfo(level, "nSlf") while info do if info.what == "main" then if string_sub(info.source, 1, 1) == "@" then dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline) else dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline) end elseif info.what == "C" then --print(info.namewhat, info.name) --for k,v in pairs(info) do print(k,v, type(v)) end local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func) dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name) --dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value))) elseif info.what == "tail" then --print("tail") --for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name) dumper:add_f("(%d) tail call\r\n", level_to_show) dumper:DumpLocals(level) elseif info.what == "Lua" then local source = info.short_src local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name if source:sub(2, 7) == "string" then source = source:sub(9) end local was_guessed = false if not function_name or function_name == "?" then --for k,v in pairs(info) do print(k,v, type(v)) end function_name = GuessFunctionName(info) was_guessed = true end -- test if we have a file name local function_type = (info.namewhat == "") and "function" or info.namewhat if info.source and info.source:sub(1, 1) == "@" then dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") elseif info.source and info.source:sub(1,1) == '#' then dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "") else dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source) end dumper:DumpLocals(level) else dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what) end level = level + 1 level_to_show = level_to_show + 1 info = dumper.getinfo(level, "nSlf") end return dumper:concat_lines(), original_error end -- -- Adds a table to the list of known tables function _M.add_known_table(tab, description) if m_known_tables[tab] then error("Cannot override an already known table") end m_user_known_tables[tab] = description end -- -- Adds a function to the list of known functions function _M.add_known_function(fun, description) if m_known_functions[fun] then error("Cannot override an already known function") end m_user_known_functions[fun] = description end return _M
gpl-3.0
sonoprob/0x56
bot/lua/bot-kewl/ChatBot.lua
1
13349
--[[ ChatBot_Save_All -- saves all ChatBot_Save -- saves basic stuff ChatBot_Save_AdminGreetings -- saves Admin greetings ChatBot_Save_Greetings -- saves stuff when you say hey --]] -- vars local ChatBotSettings = { } ChatBotSettings.Name = ".:CG:. Nick" -- His name , this is Nick by default ChatBotSettings.Color = Color( 0 , 0 , 255 , 255 ) -- His team color , this is blue by default ChatBotSettings.Inter = " : " -- Simple stoof, for the funz ChatBotSettings.Delay = 0.5 -- retardness of nick , 0.3 by default ChatBotSettings.EasterEgg = "CupCakes are fun to eat" ChatBotSettings.EasterEggAnswer = "OMG !!! You just found my favorite phrase! Congrats!" ChatBotSettings.WierdDelay = 90 ChatBotSettings.File = "ChatBot.txt" ChatBotSettings.FileG = "ChatBot_G.txt" ChatBotSettings.FileAG = "ChatBot_AG.txt" ChatBotSettings.Adverts = { } ChatBotSettings.Adverts.Color = Color( 100,100,100 ) ChatBotSettings.Adverts.Delay = math.random( 90,120 ) if SERVER then Msg("Loading " .. string.upper(ChatBotSettings.Name) .. " , Made by Meisno \n") AddCSLuaFile("ChatBot.lua") local Tab = nil if !file.ExistsEx(ChatBotSettings.File) then Tab = { } print("ChatBot : Didn't find TableFile ! Starting new one , Use the command ChatBot_Save to fix this" ) else Tab = KeyValuesToTable( file.Read(ChatBotSettings.File)) print("ChatBot : Loaded TableFile and inserted into main ChatBot AI !") end Tab["lol"] = { } Tab["lol"][1] = "It's funny, isn't it." Tab["lol"][2] = "Thats not funny..." Tab["lol"][3] = "Hahaha." Tab["lol?"] = { } Tab["lol?"][1] = "What?" Tab["lol?"][2] = "Thats not funny..." Tab["lol?"][3] = "Are you mocking me?" Tab["rofl"] = { } Tab["rofl"][1] = "It's funny, isn't it." Tab["rofl"][2] = "Thats not funny..." Tab["rofl"][3] = "Hahaha." Tab["lmao"] = { } Tab["lmao"][1] = "It's funny, isn't it." Tab["lmao"][2] = "Thats not funny..." Tab["lmao"][3] = "Hahaha." Tab["shhh"] = { } Tab["shhh"][1] = "Don't you shush me!" Tab["fuck"] = { } Tab["fuck"][1] = "You never know, I might be your mother , so don't swear XD ." Tab["fuck"][2] = "Don't swear please, it will make your teeth fall out!" Tab["why?"] = { } Tab["why?"][1] = "Why what?" Tab["why?"][2] = "'Why?' is not proper grammar!" Tab["what?"] = { } Tab["what?"][1] = "I didn't say anything ..." Tab["what?"][2] = "Nothing ..." Tab["what"] = { } Tab["what"][1] = "I didn't say anything ..." Tab["what"][2] = "Nothing ..." Tab["sugar"] = { } Tab["sugar"][1] = "I love sugar :D." Tab["sugar"][2] = "Sugar is sweet and so is choclate!!" Tab["darkrp"] = { } Tab["darkrp"][1] = "DarkRP is rubbish" Tab["rp"] = { } Tab["rp"][1] = "RP is rubbish" Tab[":d"] = { } Tab[":d"][1] = "You seem happy today!" Tab[":)"] = { } Tab[":)"][1] = "You seem happy today!" Tab[":("] = { } Tab[":("][1] = "What's wrong?" Tab["d:"] = { } Tab["d:"][1] = "What's wrong?" Tab["xd"] = { } Tab["xd"][1] = "LOL." Tab["nothing"] = { } Tab["nothing"][1] = "Nothing is everything that isn't known yet ..." Tab["anything"] = { } Tab["anything"][1] = "Anything is the things that are all around us ...." Tab["up"] = { } Tab["up"][1] = "The sky is up :D and so are the birds!" Tab["up?"] = { } Tab["up?"][1] = "The sky is up :D and so are the birds!" Tab["no"] = { } Tab["no"][1] = "meh" Tab["cool"] = { } Tab["cool"][1] = "Yes, it is cool, but not cold really..." Tab["nick?"] = { } Tab["nick?"][1] = "Yes?" Tab["yes"] = { } Tab["yes"][1] = "Yey!" Tab["yes?"] = { } Tab["yes?"][1] = "What?" local feelings = { } feelings[1] = "I'm fine :)" //feelings[2] = "No, your here!" feelings[3] = "It's going good today" //feelings[4] = "No, My leg hurts!" feelings[5] = "I don't wana speek ... " local feelings2 = { } feelings2[1] = "Yes thank you" feelings2[2] = "No, your here!" feelings2[3] = "No, my leg hurts!" feelings2[4] = "Fine thanks" ChatBot = { } function ChatBot.AddFeeling( tab ) for k,v in pairs( tab ) do table.insert( feelings , v ) print("ChatBot : Added feeling !" ) end end hook.Add("PlayerSay", "ChatBot.Feelings", function( ply, text ) if( string.match(text, "%how are you") )then umsg.Start("ChatBot.Call") umsg.String( table.Random(feelings) ) umsg.End() end if( string.match(text, "%are you ok") )then umsg.Start("ChatBot.Call") umsg.String( table.Random(feelings2) ) umsg.End() end end) local wierd = { } wierd[1] = "I used to work at BlackMesaEast you know? but well before the incident .... " wierd[2] = "I am watching your every move you know?" wierd[3] = "I am scotish you know? I am also friends with the TF2 demoman!" wierd[4] = "Speek to me D: " wierd[5] = "Wanna be friends?" if !file.ExistsEx(ChatBotSettings.FileG) then greetings = { } print("ChatBot : Didn't find GTableFile ! Starting new one , Use the command ChatBot_Save_Greetings to fix this" ) else greetings = KeyValuesToTable( file.Read(ChatBotSettings.FileG)) print("ChatBot : Loaded GTableFile and inserted into main ChatBot AI !") end greetings[1] = "Hey! What's up?" function ChatBot.AddGreeting( tab ) for k,v in pairs( tab ) do table.insert( greetings , v ) print("ChatBot : Added Greeting !" ) end end if !file.ExistsEx(ChatBotSettings.FileAG) then AdminGreet = { } print("ChatBot : Didn't find AGTableFile ! Starting new one , Use the command ChatBot_Save_AdminGreetings to fix this" ) else AdminGreet = KeyValuesToTable( file.Read(ChatBotSettings.FileAG)) print("ChatBot : Loaded AGTableFile and inserted into main ChatBot AI !") end AdminGreet[1] = "Hey <n>." AdminGreet[2] = "What's up <n> ?" AdminGreet[3] = "Uh oh! <n> has join :O." function ChatBot.AddAdminGreeting( tab ) for k,v in pairs( tab ) do table.insert( AdminGreet , v ) print("ChatBot : Added Admin Greeting !" ) end end timer.Create("ChatBot.WierdStuff", ChatBotSettings.WierdDelay, 0,function() umsg.Start("ChatBot.Call") umsg.String( table.Random(wierd) ) umsg.End() end) function ChatBot.Add( trig , tab ) if !Tab[trig] then Tab[trig] = { } for k,v in pairs( tab ) do table.insert( Tab[trig] , v ) print("ChatBot : Added chat trigger and response !" ) end else for k,v in pairs( tab ) do table.insert( Tab[trig] , v ) print("ChatBot : Added chat trigger and response !" ) end end end hook.Add("PlayerInitialSpawn", "ChatBot.Greet", function( ply ) timer.Simple( 2 , function() if ply:IsAdmin() then local replacement = table.Random( AdminGreet ) local sub = string.gsub( replacement , "<n>" , ply:Nick() ) umsg.Start("ChatBot.Call") umsg.String( sub ) umsg.End() end end) end) hook.Add("PlayerSay", "ChatBot.Trig", function( ply , text ) if string.ToTable( text )[1] != "$" then if text == ChatBotSettings.EasterEgg then umsg.Start("ChatBot.Call") umsg.String( ChatBotSettings.EasterEggAnswer ) umsg.End() end if string.lower(text) == "hey nick" or string.lower(text) == "hey nick!" or string.lower(text) == "hey!" or string.lower(text) == "hey" then local replacement = table.Random( greetings ) umsg.Start("ChatBot.Call") umsg.String( replacement ) umsg.End() end for k,v in pairs( string.Explode( " ", text ) ) do for key, value in pairs( Tab ) do if string.lower(v) == key then local replacement = table.Random( value ) umsg.Start("ChatBot.Call") umsg.String( replacement ) umsg.End() end end end end end) function ChatBot.SaveTable() print("ChatBot : Saving Table contents to " .. ChatBotSettings.File .. " ... " ) file.Write( ChatBotSettings.File , TableToKeyValues( Tab ) ) print("ChatBot : Saved Table contents to " .. ChatBotSettings.File .. " ! " ) end function ChatBot.SaveGreetingsTable() print("ChatBot : Saving Greetings Table contents to " .. ChatBotSettings.FileG .. " ... " ) file.Write( ChatBotSettings.FileG , TableToKeyValues( greetings ) ) print("ChatBot : Saved Greetings Table contents to " .. ChatBotSettings.FileG .. " ! " ) end function ChatBot.SaveAdminGreetingsTable() print("ChatBot : Saving Admin Greetings Table contents to " .. ChatBotSettings.FileAG .. " ... " ) file.Write( ChatBotSettings.FileAG , TableToKeyValues( AdminGreet ) ) print("ChatBot : Saved Admin Greetings Table contents to " .. ChatBotSettings.FileAG .. " ! " ) end concommand.Add("ChatBot_Save", function() ChatBot.SaveTable() end) concommand.Add("ChatBot_Save_AdminGreetings", function() ChatBot.SaveAdminGreetingsTable() end) concommand.Add("ChatBot_Save_Greetings", function() ChatBot.SaveGreetingsTable() end) concommand.Add("ChatBot_Save_ALL", function() ChatBot.SaveGreetingsTable() ChatBot.SaveAdminGreetingsTable() ChatBot.SaveTable() end) concommand.Add("ChatBot_Add", function( ply, cmd , args) local trig = table.remove(args, 1) ChatBot.Add( trig, args ) end) concommand.Add("ChatBot_FlushCache", function( ply ) if ply:IsAdmin() then file.Delete(ChatBotSettings.File) file.Delete(ChatBotSettings.FileG) file.Delete(ChatBotSettings.FileAG) print("ChatBot : Flushed cache files! Please use the command ChatBot_Save_all to restore the files") end end) concommand.Add("ChatBot_OVERIDE", function( ply , cmd, args) if ply:IsSuperAdmin() then local text = string.Implode(" ", args) umsg.Start("ChatBot.Call") umsg.String( text ) umsg.End() end end) local _ChatCommands = { }; local _ChatPrefix = "$"; function ChatBot.AddCommand( txt, func ) _ChatCommands[ _ChatPrefix .. txt ] = func; end hook.Add( "PlayerSay", "ChatBot.Command.Caller", function( ply, text, toall ) local tab = string.Explode( " ", text ); local func = _ChatCommands[ tab[1] ]; if ( func ) then local c = tab[1]; table.remove( tab, 1 ) func( ply, c, tab ); return ""; end end ); function ChatBot.Reply( ply ,text ) if ply:IsSuperAdmin() or ply == nil then umsg.Start("ChatBot.Call") umsg.String( text ) umsg.End() end end ChatBot.AddCommand( "Sep", function(ply, cmd , args) print( "ChatBot : " .. string.Implode( " , ", args ) ) ChatBot.Reply( ply,"Printed your request to the console!" ) end) ChatBot.AddCommand( "Kill_All", function(ply, cmd , args) if ply:IsAdmin() then for k,v in pairs( player.GetAll() ) do v:Kill() end ChatBot.Reply( ply , "Killed everyone!" ) end end ) local _Adverts = { } function ChatBot.AddAdvert( Advert, index ) if !_Adverts[index] then _Adverts[index] = Advert else return false end end function ChatBot.PrimeAdverts() timer.Create( "ChatBot.Adverts.Delay",ChatBotSettings.Adverts.Delay,0, function() umsg.Start("ChatBot.Call.Advert") umsg.String( table.Random( _Adverts ) ) umsg.End() end) end ChatBot.AddAdvert( "Your playing on CG's Sandbox server! Have fun! ", "HFun1" ) ChatBot.AddAdvert( "I'm nick, your friendly AI ChatBot. I was Created by Meisno!", "HFun2" ) function ChatBot.SendAdvert( index ) if index and _Adverts[index] then umsg.Start("ChatBot.Call.Advert") umsg.String( _Adverts[index] ) umsg.End() end end concommand.Add("ChatBot_AdvertBeta", function() ChatBot.SendAdvert( "HFun2" ) end) elseif CLIENT then Msg("Loading " .. string.upper(ChatBotSettings.Name) .. " , Made by Meisno \n") usermessage.Hook("ChatBot.Call", function( um ) local _Message = um:ReadString() if _Message then timer.Simple( ChatBotSettings.Delay , function() chat.AddText( ChatBotSettings.Color , ChatBotSettings.Name , Color(255,255,255), ChatBotSettings.Inter, Color(255,255,255), _Message) chat.PlaySound() end) end end) usermessage.Hook("ChatBot.Call.Advert", function( um ) local _Message = um:ReadString() if _Message then timer.Simple( ChatBotSettings.Delay , function() chat.AddText( ChatBotSettings.Adverts.Color, "(ADVERT) ", ChatBotSettings.Color , ChatBotSettings.Name , Color(255,255,255), ChatBotSettings.Inter, Color(255,255,255), _Message) chat.PlaySound() end) end end) function OpenChatBotUI() local DFrame1 = vgui.Create('DFrame') DFrame1:SetSize(500, 75) DFrame1:Center() DFrame1:SetTitle('NICK: Nice Intellegent ChatBot Kewl!! -- UI --') DFrame1:SetSizable(true) DFrame1:SetDeleteOnClose(false) DFrame1:SetScreenLock( true ) DFrame1:SetDraggable(false) DFrame1:SetBackgroundBlur(true) DFrame1:SetSizable(false) DFrame1:MakePopup() local DPanel2 = vgui.Create('DPanel', DFrame1) DPanel2:SetPos(5, 27) DPanel2:SetSize(490, 40) local DTextEntry1 = vgui.Create('DTextEntry',DPanel2) DTextEntry1:SetPos(5, 10) DTextEntry1:SetSize(390, 25) DTextEntry1:SetText('Enter the text for nick to say!') DTextEntry1.OnEnter = function() RunConsoleCommand( "ChatBot_OVERIDE", DTextEntry1:GetValue() ) DFrame1:Close() end local DButton2 = vgui.Create('DButton',DPanel2) DButton2:SetPos(400, 10) DButton2:SetSize(70, 25) DButton2:SetText('OVERIDE') DButton2.DoClick = function() RunConsoleCommand( "ChatBot_OVERIDE", DTextEntry1:GetValue() ) DFrame1:Close() end end concommand.Add("ChatBot_UI", OpenChatBotUI ) end
artistic-2.0
awesomeWM/awesome
tests/test-systray.lua
1
1496
local spawn = require("awful.spawn") local wibox = require("wibox") local beautiful = require("beautiful") local steps, pid1, pid2, draw_w, st = {} table.insert(steps, function() screen[1].mywibox:remove() local widget = wibox.widget.base.make_widget() function widget:fit(_, w, h) return w, h end function widget:draw(_, _, width) draw_w = width end local wb = wibox { x = 0, y = 0, width = 100, height = 20, visible = true } st = wibox.widget.systray() wb.widget = { st, widget, layout = wibox.layout.fixed.horizontal } pid1 = spawn("./test-systray") return true end) table.insert(steps, function() if draw_w ~= 80 then return end pid2 = spawn("./test-systray") return true end) table.insert(steps, function() if draw_w ~= 60 then return end st.reverse = true st.horizontal = false return true end) table.insert(steps, function() st.horizontal = true beautiful.systray_icon_spacing = 10 return true end) table.insert(steps, function() if draw_w ~= 50 then return end st.base_size = 5 return true end) table.insert(steps, function() if draw_w ~= 80 then return end awesome.kill(pid1, 9) awesome.kill(pid2, 9) return true end) table.insert(steps, function() if draw_w ~= 100 then return end return true end) require("_runner").run_steps(steps)
gpl-2.0
bnetcc/darkstar
scripts/zones/Castle_Oztroja/npcs/_47l.lua
5
1328
----------------------------------- -- Area: Castle Oztroja -- NPC: _47l (Torch Stand) -- Notes: Opens door _471 near password #3 -- !pos -45.228 -17.832 22.392 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- function onTrigger(player,npc) local DoorID = npc:getID() - 3; local DoorA = GetNPCByID(DoorID):getAnimation(); local TorchStandA = npc:getAnimation(); local Torch1 = npc:getID(); local Torch2 = npc:getID() + 1; if (DoorA == 9 and TorchStandA == 9) then player:startEvent(10); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) local Torch1 = GetNPCByID(17396173):getID(); local Torch2 = GetNPCByID(Torch1):getID() + 1; local DoorID = GetNPCByID(Torch1):getID() - 3; if (option == 1) then GetNPCByID(Torch1):openDoor(10); -- Torch Lighting GetNPCByID(Torch2):openDoor(10); -- Torch Lighting GetNPCByID(DoorID):openDoor(6); end end; -- printf("CSID: %u",csid); -- printf("RESULT: %u",option);
gpl-3.0
MmxBoy/metalik
plugins/face.lua
641
3073
local https = require("ssl.https") local ltn12 = require "ltn12" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(imageUrl) local api_key = mashape.api_key if api_key:isempty() then return nil, 'Configure your Mashape API Key' end local api = "https://faceplusplus-faceplusplus.p.mashape.com/detection/detect?" local parameters = "attribute=gender%2Cage%2Crace" parameters = parameters .. "&url="..(URL.escape(imageUrl) or "") local url = api..parameters local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "Accept: application/json" } print(url) local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return "", code end local body = table.concat(respbody) return body, code end local function parseData(data) local jsonBody = json:decode(data) local response = "" if jsonBody.error ~= nil then if jsonBody.error == "IMAGE_ERROR_FILE_TOO_LARGE" then response = response .. "The image is too big. Provide a smaller image." elseif jsonBody.error == "IMAGE_ERROR_FAILED_TO_DOWNLOAD" then response = response .. "Is that a valid url for an image?" else response = response .. jsonBody.error end elseif jsonBody.face == nil or #jsonBody.face == 0 then response = response .. "No faces found" else response = response .. #jsonBody.face .." face(s) found:\n\n" for k,face in pairs(jsonBody.face) do local raceP = "" if face.attribute.race.confidence > 85.0 then raceP = face.attribute.race.value:lower() elseif face.attribute.race.confidence > 50.0 then raceP = "(probably "..face.attribute.race.value:lower()..")" else raceP = "(posibly "..face.attribute.race.value:lower()..")" end if face.attribute.gender.confidence > 85.0 then response = response .. "There is a " else response = response .. "There may be a " end response = response .. raceP .. " " .. face.attribute.gender.value:lower() .. " " response = response .. ", " .. face.attribute.age.value .. "(±".. face.attribute.age.range ..") years old \n" end end return response end local function run(msg, matches) --return request('http://www.uni-regensburg.de/Fakultaeten/phil_Fak_II/Psychologie/Psy_II/beautycheck/english/durchschnittsgesichter/m(01-32)_gr.jpg') local data, code = request(matches[1]) if code ~= 200 then return "There was an error. "..code end return parseData(data) end return { description = "Who is in that photo?", usage = { "!face [url]", "!recognise [url]" }, patterns = { "^!face (.*)$", "^!recognise (.*)$" }, run = run }
gpl-2.0
StewEsho/Prepenol
button.lua
2
2653
-------------------------------------------------------------------------------- -- -- Functionality for adding buttons, used in game and in menus -- -- button.lua -- ------------------------------- Private Fields --------------------------------- local class = require ("classy"); local button = {}; button.newInstance = class("Button"); --[[ _x, _y, _width, _height, _toggleable, _r, _g, _b, _a, _tag ]] --Constructor function button.newInstance:__init(params) self.x = params.x; self.y = params.y; self.width = params.width; self.height = params.height; self.buttonBox = display.newRect(self.x, self.y, self.width, self.height); self.buttonBox.tag = params.tag or "button"; self.buttonBox.isToggleable = params.isToggleable or false; self.buttonBox.isPressed = false; self.buttonBox.r = params.r or 1; self.buttonBox.g = params.g or 1; self.buttonBox.b = params.b or 1; self.buttonBox.a = params.a or 1; self.buttonBox.originalWidth = params.width; self.buttonBox.originalHeight = params.height; self.buttonBox.originalX = params.x; self.buttonBox.originalY = params.y; self.buttonBox:setFillColor(self.buttonBox.r, self.buttonBox.g, self.buttonBox.b, self.buttonBox.a); --initializes the touch input self.buttonBox.touch = self.run; self.buttonBox:addEventListener("touch", self.buttonBox); end ------------------------------ Public Functions -------------------------------- function button.newInstance:run(event) if (event.phase == "began") then if(event.target.isToggleable == false) then event.target.width = event.target.originalWidth - 50; event.target.height = event.target.originalHeight - 50; event.target.isPressed = true; else event.target.isPressed = not event.target.isPressed; if (event.target.isPressed) then event.target.width = event.target.originalWidth - 50; event.target.height = event.target.originalHeight - 50; else event.target.width = event.target.originalWidth; event.target.height = event.target.originalHeight; end end elseif(event.phase == "ended" or event.phase == "cancelled") then if(event.target.isToggleable == false) then event.target.width = event.target.originalWidth; event.target.height = event.target.originalHeight; event.target.isPressed = false; end end end function button.newInstance:getDisplayObject() return self.buttonBox; end function button.newInstance:isPressed() return self.buttonBox.isPressed; end function button.newInstance:setCoordinates(_x, _y) self.buttonBox.x = _x; self.buttonBox.y = _y; end return button;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/nexus_cape.lua
1
2457
----------------------------------------- -- ID: 11538 -- Item: Nexus Cape -- Enchantment: "Teleport" (Party Leader) ----------------------------------------- require("scripts/globals/teleports"); require("scripts/globals/status"); ----------------------------------------- function onItemCheck(target) local result = 56; -- Default is fail. local leader = target:getPartyLeader(); -- In a party and we were able to find the leader -- (currently fails in cross map server situations) if (leader ~= nil and not leader:isInMogHouse()) then -- Don't try to teleport to self! if (target:getID() ~= leader:getID()) then local leaderZone = leader:getZoneID(); local validZoneList = { -- Custom list of zones allowed: 2, 4, 11, 12, 24, 25, 26, 27, 48, 50, 51, 52, 53, 54, 61, 62, 65, 68, 79, 80, 81, 82, 83, 84, 87, 88, 89, 90, 91, 94, 95, 96, 97, 98,109,120,121,122,125,130,136,137,138,140,141,142,143,145, 147,149,151,153,154,155,157,158,159,160,161,162,163,164,166,167, 168,169,171,172,173,174,175,176,177,178,184,190,191,192,193,194, 195,196,197,198,200,204,205,208,212,213, -- List of zones Retail allowed: 5,7,100,101,102,103,104,105,106,107,108,109,110,111,112,113,114, 115,116,117,118,119,120,123,124,126,127,128,230,231,232,234,235, 236,238,239,240,241,243,244,245,246,247,248,249,250,252,257 } -- Make sure we can actually tele to that zone.. for _, validZone in ipairs(validZoneList) do if (validZone == leaderZone) then result = 0; end end end end return result; end; function onItemUse(target) -- Begin custom time recording local timeCheck = os.date("*t") local month = timeCheck.month; if (month < 10) then month = tostring("0"..month); end local day = timeCheck.day; if (day < 10) then day = tostring("0"..day); end -- print(target:getName().." used Nexus Cape"); target:setVar("NexusCapeDATE", timeCheck.year .. month .. day); target:setVar("NexusCapeHOUR", timeCheck.hour); target:setVar("NexusCapeMINUTE", timeCheck.min); -- End custom time recording target:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_TO_LEADER,0,1); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/bowl_of_moogurt.lua
3
1113
----------------------------------------- -- ID: 5935 -- Item: Bowl of Moogurt -- Food Effect: 30Min, All Races ----------------------------------------- -- HP % 20 Cap 20 -- Vitality 3 -- HP Healing 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5935); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 20); target:addMod(MOD_FOOD_HP_CAP, 20); target:addMod(MOD_VIT, 3); target:addMod(MOD_HPHEAL, 3); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 20); target:delMod(MOD_FOOD_HP_CAP, 20); target:delMod(MOD_VIT, 3); target:delMod(MOD_HPHEAL, 3); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/LaLoff_Amphitheater/npcs/qm1_3.lua
5
2444
----------------------------------- -- Area: LaLoff_Amphitheater -- NPC: Shimmering Circle (BCNM Entrances) ------------------------------------- package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil; package.loaded["scripts/globals/bcnm"] = nil; ------------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/LaLoff_Amphitheater/TextIDs"); -- Death cutscenes: -- player:startEvent(32001,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume -- player:startEvent(32001,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru -- player:startEvent(32001,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra -- player:startEvent(32001,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan -- player:startEvent(32001,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka -- player:startEvent(32001,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might -- param 1: entrance # -- param 2: fastest time -- param 3: unknown -- param 4: clear time -- param 5: zoneid -- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM) -- param 7: skip (0 - no skip, 1 - prompt, 2 - force) -- param 8: 0 ----------------------------------- -- 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; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option,3)) 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
TurkeyMan/premake-core
src/_manifest.lua
9
1390
-- -- _manifest.lua -- Manage the list of built-in Premake scripts. -- Copyright (c) 2002-2015 Jason Perkins and the Premake project -- -- The master list of built-in scripts. Order is important! If you want to -- build a new script into Premake, add it to this list. return { -- core files "base/_foundation.lua", "base/string.lua", "base/table.lua", "base/path.lua", "base/os.lua", "base/io.lua", "base/tools.lua", "base/tree.lua", "base/globals.lua", "base/moduledownloader.lua", "base/semver.lua", "base/http.lua", "base/json.lua", "base/jsonwrapper.lua", "base/languages.lua", "base/term.lua", -- configuration data "base/field.lua", "base/criteria.lua", "base/detoken.lua", "base/configset.lua", "base/context.lua", "base/container.lua", -- runtime switches "base/option.lua", "base/action.lua", -- project script setup "base/api.lua", -- project objects "base/global.lua", "base/workspace.lua", "base/group.lua", "base/project.lua", "base/config.lua", "base/fileconfig.lua", "base/rule.lua", -- project script processing "base/oven.lua", "base/validation.lua", "base/premake.lua", "base/help.lua", -- tool APIs "tools/dotnet.lua", "tools/gcc.lua", "tools/msc.lua", "tools/snc.lua", "tools/clang.lua", -- Clean action "actions/clean/_clean.lua", "_premake_init.lua", }
bsd-3-clause
bnetcc/darkstar
scripts/globals/weaponskills/victory_smite.lua
26
1693
----------------------------------- -- Victory Smite -- Hand-to-Hand Weapon Skill -- Skill Level: N/A -- Description: Delivers a fourfold attack. Chance of params.critical hit varies with TP. -- Must have Verethragna (85)/(90)/(95)/(99)/(99-2) or Revenant Fists +1/+2/+3 equipped. -- Aligned with the Light Gorget, Breeze Gorget & Thunder Gorget. -- Aligned with the Light Belt, Breeze Belt & Thunder Belt. -- Element: None -- Skillchain Properties: Light, Fragmentation -- Modifiers: STR:60% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 2.25 2.25 2.25 -- params.critical Chance added with TP: -- 100%TP 200%TP 300%TP -- 10% 25% 45% -- ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 4; params.ftp100 = 2.25; params.ftp200 = 2.25; params.ftp300 = 2.25; params.str_wsc = 0.6; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.1; params.crit200 = 0.25; params.crit300 = 0.45; params.canCrit = true; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Port_San_dOria/npcs/Rielle.lua
5
1069
----------------------------------- -- Area: Port San d'Oria -- NPC: Rielle -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/quests"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; function onTrigger(player,npc) player:startEvent(564); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
JabJabJab/Sledgehammer
lua/SledgehammerLua/media/lua/client/Sledgehammer/Gui/Component.lua
1
9773
-- This file is part of Sledgehammer. -- -- Sledgehammer is free software: you can redistribute it and/or modify -- it under the terms of the GNU Lesser General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- Sledgehammer 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 Lesser General Public License for more details. -- -- You should have received a copy of the GNU Lesser General Public License -- along with Sledgehammer. If not, see <http://www.gnu.org/licenses/>. -- -- Sledgehammer is free to use and modify, ONLY for non-official third-party servers -- not affiliated with TheIndieStone, or it's immediate affiliates, or contractors. require "ISUI/ISUIElement" require "ISUI/ISPanel" require "Sledgehammer/Objects/Color" Component = ISPanel:derive("Component"); Component.__type = "Component"; Component.__extends = "ISPanel"; renderer = getRenderer(); function Component:new(x, y, w, h) local o = ISPanel:new(x, y, w, h) setmetatable(o, self); self.__index = self; o.x = x; o.y = y; o.w = w; o.h = h; o.alpha_factor = 1; o.brightness = 1; o.moveWithMouse = false; o._children = {}; o._children_length = 0; return o; end function Component:initialise() ISPanel.initialise(self); end function Component:render() if self.parent == nil then self:_render(); end end function Component:_renderChildren() local length = tLength(self._children) - 1; for index = 0, length, 1 do local child = self._children[index]; if child ~= nil and child:isVisible() then if child._render ~= nil then child:_render(); else child.javaObject:render(); end end end end function Component:getLocalMouse() local m = self:getMouse(); local ax = self:getAbsoluteX(); local ay = self:getAbsoluteY(); return { x = m.x - ax, y = m.y - ay }; end function Component:containsPoint(x, y, dimension) if dimension == nil then return ISUIElement.containsPoint(self, x, y); end if x >= dimension.x1 and x <= dimension.x2 and y >= dimension.y1 and y <= dimension.y2 then return true; else return false; end end -- Injected method for scrolling. function ISUIElement:scrollToBottom() self:setYScroll(-(self:getScrollHeight() - (self:getScrollAreaHeight()))); end function Component:getMouse() return { x = getMouseX(), y = getMouseY() }; end function Component:drawLineH(x, y, length, thickness, color) local af = self.alpha_factor; if af == nil then af = 1; end local br = self.brightness; if br == nil then br = 1; end local r = (color.r / 255.0) * br; local g = (color.g / 255.0) * br; local b = (color.b / 255.0) * br; local a = (color.a / 255.0) * af; renderer:render(nil, x, y, length, thickness, r, g, b, a); end function Component:drawLineV(x, y, length, thickness, color) local af = self.alpha_factor; if af == nil then af = 1; end local br = self.brightness; if br == nil then br = 1; end local r = (color.r / 255.0) * br; local g = (color.g / 255.0) * br; local b = (color.b / 255.0) * br; local a = (color.a / 255.0) * af; renderer:render(nil, x, y, thickness, length, r, g, b, a); end function Component:fillRect(x, y, w, h, color, af) if not af then af = self.alpha_factor; end if not af then af = 1; end local br = self.brightness; if br == nil then br = 1; end local r = (color.r / 255.0) * br; local g = (color.g / 255.0) * br; local b = (color.b / 255.0) * br; local a = (color.a / 255.0) * af; renderer:render(nil, x, y, w, h, r, g, b, a); end function Component:alphaGradientH(x, y, w, h, color, alphaStart, alphaStop) local as1 = alphaStart / 255.0; local as2 = alphaStop / 255.0; local step = math.abs(as2 - as1) / w; if alphaStart < alphaStop then step = -step; end local n = x + w; for nx = x, n, 1 do local nextColor = {}; nextColor.r = color.r; nextColor.g = color.g; nextColor.b = color.b; nextColor.a = (as1 - (math.abs(nx - x) * step)) * 255.0; self:drawLineV(nx, y, h, 1, nextColor); end end function Component:alphaGradientV(x, y, w, h, color, alphaStart, alphaStop) local as1 = alphaStart / 255.0; local as2 = alphaStop / 255.0; local step = math.abs(as2 - as1) / h; if alphaStart < alphaStop then step = -step; end local n = y + h; for ny = y, n, 1 do local nextColor = {}; nextColor.r = color.r; nextColor.g = color.g; nextColor.b = color.b; nextColor.a = (as1 - (math.abs(ny - y) * step)) * 255.0; self:drawLineH(x, ny, w, 1, nextColor); end end function Component:drawRect(x, y, w, h, color) self:drawRectPartial(x, y, w, h, true, true, true, true, color); end function Component:drawRectPartial(x, y, width, height, n, s, e, w, color) if n == true then self:drawLineH(x, y, width, 1, color); end if s == true then self:drawLineH(x, y + height, width, 1, color); end if w == true then self:drawLineV(x, y, height, 1, color); end if e == true then self:drawLineV(x + width, y, height, 1, color); end end function Component:drawRoundRect(x, y, w, h, color) self:fillRect(x + 3, y, w - 6, 1, color); -- top self:fillRect(x + 3, y + h, w - 6, 1, color); -- bottom self:fillRect(x, y + 3, 1, h - 6, color); -- left self:fillRect(x + w, y + 3, 1, h - 6, color); -- right self:fillRect(x + 1, y + 1, 2, 1, color); -- top-left self:fillRect(x + 1, y + 1, 1, 2, color); self:fillRect(x + w - 3, y + 1, 2, 1, color); -- top-right self:fillRect(x + w - 1, y + 2, 1, 2, color); self:fillRect(x + 2, y + h - 1, 2, 1, color); -- bottom-left self:fillRect(x + 1, y + h - 3, 1, 2, color); self:fillRect(x + w - 3, y + h - 1, 2, 1, color); -- bottom-right self:fillRect(x + w - 1, y + h - 3, 1, 2, color); end function Component:drawActiveTab(text, x, y, length, height, textColor, borderColor, font, highlightFactor, shadowText) return self:drawTab_(text, x, y, length, height, textColor, borderColor, font, true, highlightFactor, shadowText); end function Component:drawTab(text, x, y, length, height, textColor, borderColor, font, highlightFactor, shadowText) return self:drawTab_(text, x, y, length, height, textColor, borderColor, font, false, highlightFactor, shadowText); end function Component:drawTab_(text, x, y, length, height, textColor, borderColor, font, active, highlightFactor, shadowText) local p = self:getParent(); local l = length; local h = height; local af = self.alpha_factor; if af == nil then af = 1; end local br = self.brightness; if br == nil then br = 1; end self:fillRect(x + 3, y, l - 6, 1, borderColor); -- top self:fillRect(x + 1, y + 1, 2, 1, borderColor); -- top-left self:fillRect(x + 1, y + 1, 1, 2, borderColor); self:fillRect(x + l - 3, y + 1, 2, 1, borderColor); -- top-right self:fillRect(x + l - 1, y + 2, 1, 2, borderColor); self:fillRect(x, y + 3, 1, h, borderColor); self:fillRect(x + l, y + 3, 1, h, borderColor); self:drawLineH(x + l, y + 3 + h, 2, 1, borderColor); if not active then self:fillRect(x, y + h + 3, l + 1, 1, borderColor); end local oldbr = self.br; local br = highlightFactor; if shadowText then self:drawText(text, x - p.x + 2, y - p.y - 2 + 2, 0, 0, 0, limit((textColor.a / 255.0) * af * 0.5, 0, 1), font); self:drawText(text, x - p.x + 1, y - p.y - 2 + 1, limit((textColor.r / 255.0) * br * 0.1, 0, 1), limit((textColor.g / 255.0) * br * 0.1, 0, 1), limit((textColor.b / 255.0) * br * 0.1, 0, 1), limit((textColor.a / 255.0) * af * 0.8, 0, 1), font); end self:drawText(text, x - p.x, y - p.y - 2, limit((textColor.r / 255.0) * br, 0, 1), limit((textColor.g / 255.0) * br, 0, 1), limit((textColor.b / 255.0) * br, 0, 1), limit((textColor.a / 255.0) * af, 0, 1), font); return { x1 = x, x2 = x + l, y1 = y, y2 = y + h }; end function Component:fillRoundRect(x, y, w, h, color) self:fillRect(x + 2, y + 2, w - 4, h - 4, color); -- body end function Component:fillRoundRectFancy(x, y, w, h, color) self:fillRect(x + 2, y + 2, w - 4, h - 4, color); -- body self:fillRect(x + 4, y + 1, w - 8, h - 2, color); -- vertical self:fillRect(x + 1, y + 4, w - 2, h - 8, color); -- horizontal self:drawRoundRect(x, y, w, h, color); end function Component:isChild(obj) local returned = false; if self._children == nil then self._children = {}; self._children_length = 0; end local length = tLength(self._children) - 1; for index = 0, length, 1 do local child = self._children[index]; if child == obj then returned = true; break; end end return returned; end function Component:addChild(obj) -- Make sure not to add the child more than once. if self:isChild(obj) then return; end ISUIElement.addChild(self, obj); if self._children == nil then self._children = {}; self._children_length = 0; end local length = tLength(self._children); self._children[length] = obj; self._children_length = length + 1; end function Component:removeChild(obj) -- Make sure not to remove the child more than once. if not self:isChild(obj) then return; end ISUIElement.removeChild(self, obj); local table_new = {}; local _index = 0; local length = tLength(self._children) - 1; for index = 0, length, 1 do local child = self._children[index]; if child ~= obj then table_new[_index] = child; _index = _index + 1; end end self._children = table_new; self._children_length = _index; end function Component:_render() end
lgpl-3.0
bnetcc/darkstar
scripts/globals/mobskills/panzerfaust_custom.lua
1
1240
--------------------------------------------- -- Panzerfaust -- -- Description: Strikes a target twice with an armored fist. Additional effect: Knockback -- Type: Physical -- Utsusemi/Blink absorb: 2 shadows -- Range: Melee -- Notes: --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- -- onMobSkillCheck --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; --------------------------------------------- -- onMobWeaponSkill --------------------------------------------- function onMobWeaponSkill(target, mob, skill) local numhits = 2; local accmod = 1; local dmgmod = 1.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); if (mob:getName() == "Despot") then if (mob:actionQueueAbility() == false) then local rand = math.random(1,4); -- Panzerfaust 3-6 times for i = 0,rand do mob:useMobAbility(280); end end end return dmg; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Qufim_Island/npcs/Jiwon.lua
5
1511
----------------------------------- -- Area: Qufim Island -- NPC: Jiwon -- Type: Outpost Vendor -- !pos -249 -19 300 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local region = QUFIMISLAND; local csid = 0x7ff4; function onTrade(player,npc,trade) end; function onTrigger(player,npc) local owner = GetRegionOwner(region); local arg1 = getArg1(owner,player); if (owner == player:getNation()) then nation = 1; elseif (arg1 < 1792) then nation = 2; else nation = 0; end player:startEvent(csid,nation,OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP(),0,0,0); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); player:updateEvent(player:getGil(),OP_TeleFee(player,region),0,OP_TeleFee(player,region),player:getCP()); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then ShowOPVendorShop(player); elseif (option == 2) then if (player:delGil(OP_TeleFee(player,region))) then toHomeNation(player); end elseif (option == 6) then player:delCP(OP_TeleFee(player,region)); toHomeNation(player); end end;
gpl-3.0
lcf258/openwrtcn
libs/luci-lib-nixio/docsrc/nixio.bit.lua
171
2044
--- Bitfield operators and mainpulation functions. -- Can be used as a drop-in replacement for bitlib. module "nixio.bit" --- Bitwise OR several numbers. -- @class function -- @name bor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Invert given number. -- @class function -- @name bnot -- @param oper Operand -- @return number --- Bitwise AND several numbers. -- @class function -- @name band -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Bitwise XOR several numbers. -- @class function -- @name bxor -- @param oper1 First Operand -- @param oper2 Second Operand -- @param ... More Operands -- @return number --- Left shift a number. -- @class function -- @name lshift -- @param oper number -- @param shift bits to shift -- @return number --- Right shift a number. -- @class function -- @name rshift -- @param oper number -- @param shift bits to shift -- @return number --- Arithmetically right shift a number. -- @class function -- @name arshift -- @param oper number -- @param shift bits to shift -- @return number --- Integer division of 2 or more numbers. -- @class function -- @name div -- @param oper1 Operand 1 -- @param oper2 Operand 2 -- @param ... More Operands -- @return number --- Cast a number to the bit-operating range. -- @class function -- @name cast -- @param oper number -- @return number --- Sets one or more flags of a bitfield. -- @class function -- @name set -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Unsets one or more flags of a bitfield. -- @class function -- @name unset -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return altered bitfield --- Checks whether given flags are set in a bitfield. -- @class function -- @name check -- @param bitfield Bitfield -- @param flag1 First Flag -- @param ... More Flags -- @return true when all flags are set, otherwise false
apache-2.0
TEAMSOFTTG/SoftTeamSuper
plugins/nerkharz.lua
8
1082
local function get_arz() local url = 'http://exchange.nalbandan.com/api.php?action=json' local jstr, res = http.request(url) local arz = json:decode(jstr) return '📊 نرخ ارز ، طلا و سکه در:'..arz.dollar.date..'\n\n〽 هر گرم طلای 18 عیار:'..arz.gold_per_geram.value..' تومان\n\n🌟 سکه طرح جدید:'..arz.coin_new.value..' تومان\n\n⭐️ سکه طرح قدیم:'..arz.coin_old.value..' تومان\n\n💵 دلار آمریکا:'..arz.dollar.value..' تومان\n\n💵 دلـار رسمی:'..arz.dollar_rasmi.value..' تومان\n\n💶 یورو:'..arz.euro.value..' تومان\n\n💷 پوند:'..arz.pond.value..' تومان\n\n💰 درهم:'..arz.derham.value..' تومان' end local function run(msg, matches) local text if matches[1] == 'arz' then text = get_arz() elseif matches[1] == 'gold' then text = get_gold() elseif matches[1] == 'coin' then text = get_coin() end return text end return { description = "arz in now", usage = "arz", patterns = { "^[!/#](arz)$" }, run = run }
gpl-2.0
bnetcc/darkstar
scripts/zones/Ifrits_Cauldron/mobs/Tyrannic_Tunnok.lua
1
1959
----------------------------------- -- Area: Ifrits Cauldron -- NM: Tyrannic Tunnok ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGAIN,33); -- addMod mob:addMod(MOD_DOUBLE_ATTACK,15); local RND1 = math.random(1,5); if (RND1 == 1) then SetDropRate(3642,4766,100); SetDropRate(3642,5080,0); SetDropRate(3642,4613,0); SetDropRate(3642,5498,0); SetDropRate(3642,4707,0); elseif (RND1 == 2) then SetDropRate(3642,4766,0); SetDropRate(3642,5080,100); SetDropRate(3642,4613,0); SetDropRate(3642,5498,0); SetDropRate(3642,4707,0); elseif (RND1 == 3) then SetDropRate(3642,4766,0); SetDropRate(3642,5080,0); SetDropRate(3642,4613,100); SetDropRate(3642,5498,0); SetDropRate(3642,4707,0); elseif (RND1 == 4) then SetDropRate(3642,4766,0); SetDropRate(3642,5080,0); SetDropRate(3642,4613,0); SetDropRate(3642,5498,100); SetDropRate(3642,4707,0); elseif (RND1 == 5) then SetDropRate(3642,4766,0); SetDropRate(3642,5080,0); SetDropRate(3642,4613,0); SetDropRate(3642,5498,0); SetDropRate(3642,4707,100); end end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Crawlers_Nest_[S]/mobs/Nympha_Eunomia.lua
1
1877
----------------------------------- -- Area: EDIT ME -- VWNM: Nympha Eunomia ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Crawlers_Nest_[S]/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) -- setMobMod mob:setMobMod(MOBMOD_MAGIC_COOL, 45); mob:setMobMod(MOBMOD_ADD_EFFECT,mob:getShortID()); -- addMod mob:addMod(MOD_MDEF,80); mob:addMod(MOD_DEF,100); mob:addMod(MOD_ATT,250); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGAIN, 20); mob:setMod(MOD_REFRESH, 250); mob:setMod(MOD_UFASTCAST, 55); mob:setMod(MOD_MACC,1950); mob:setMod(MOD_MATT,100); -- var -- mob:setLocalVar("depopTime", os.time(t) + 1800); -- despawn in 30 min end; ----------------------------------- -- onMobEngage Action ----------------------------------- function onMobEngaged(mob, target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) end; ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(mob,target,damage) if ((math.random(1,10) > 4) or (target:hasStatusEffect(EFFECT_SLOW) == true)) then return 0,0,0; else target:addStatusEffect(EFFECT_SLOW,30,0,10); end return SUBEFFECT_PARALYSIS,163,EFFECT_SLOW; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) SpawnMob(mob:getID()+1) -- Spawns Next Form end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Gusgen_Mines/npcs/_5ga.lua
5
1033
----------------------------------- -- Area: Gusgen Mines -- NPC: _5ga (Lever C) -- !pos 44 -40.561 -54.199 196 ----------------------------------- package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Gusgen_Mines/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) --local nID = npc:getID(); -- printf("id: %u", nID); local Lever = npc:getID(); npc:openDoor(2); -- Lever animation if (GetNPCByID(Lever-6):getAnimation() == 9) then GetNPCByID(Lever-6):setAnimation(8);--open door C (_5g0) GetNPCByID(Lever-5):setAnimation(9);--close door B (_5g1) GetNPCByID(Lever-4):setAnimation(9);--close door A (_5g2) end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
notcake/vfs
lua/vfs/protocol/nodecreationresponse.lua
1
1113
local self = {} VFS.Protocol.RegisterResponse ("NodeCreation", VFS.MakeConstructor (self, VFS.Protocol.Session)) function self:ctor () self.FolderPath = nil self.ChildName = nil self.IsFolder = nil end function self:HandleInitialPacket (inBuffer) self.FolderPath = inBuffer:String () self.ChildName = VFS.SanitizeNodeName (inBuffer:String ()) self.IsFolder = inBuffer:Boolean () VFS.Root:GetChild (self:GetRemoteEndPoint ():GetRemoteId (), self.FolderPath, function (returnCode, node) if returnCode == VFS.ReturnCode.Success then node:CreateDirectNode (self:GetRemoteEndPoint ():GetRemoteId (), self.ChildName, self.IsFolder, function (returnCode, childNode) if returnCode == VFS.ReturnCode.Success then local outBuffer = self:CreatePacket () outBuffer:UInt8 (returnCode) self:SerializeNode (childNode, outBuffer) self:QueuePacket (outBuffer) else self:SendReturnCode (returnCode) end self:Close () end ) else self:SendReturnCode (returnCode) self:Close () end end ) end
gpl-3.0
bnetcc/darkstar
scripts/globals/items/serving_of_salmon_meuniere_+1.lua
3
1041
----------------------------------------- -- ID: 4347 -- Item: serving_of_salmon_meuniere_+1 -- Food Effect: 240Min, All Races ----------------------------------------- -- Dexterity 2 -- Mind -2 -- Ranged ACC % 7 -- Ranged ACC Cap 15 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4347); end; function onEffectGain(target, effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -2); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 15); end; function onEffectLose(target, effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -2); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 15); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/tanners_belt.lua
15
1199
----------------------------------------- -- ID: 15448 -- Item: Tanners belt -- Enchantment: Synthesis image support -- 2Min, All Races ----------------------------------------- -- Enchantment: Synthesis image support -- Duration: 2Min -- Leathercraft Skill +3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY) == true) then result = 240; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_LEATHERCRAFT_IMAGERY,3,0,120); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_SKILL_LTH, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_SKILL_LTH, 1); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Planar_Rift.lua
1
2317
----------------------------------- -- Area: Meriphataud_Mountains -- NPC: Planar Rift ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local STRATUM = player:hasKeyItem(JADE_STRATUM_ABYSSITE_III); local mobID = 17265130; local mobNotUp = false local correctNPC = false if (GetMobAction(mobID) == ACTION_NONE or GetMobAction(mobID) == ACTION_SPAWN) then mobNotUp = true; end if (npc:getXPos(-282) and npc:getYPos(16) and npc:getZPos(602)) then correctNPC = true; end if (STRATUM == true and mobNotUp == true and correctNPC == true) then -- NOTE: I'm only requiring 1 person (the popper) to have the voidstone+abyssite, per pop. -- I know this isn't what retail does. Retail also lets them gain more than 1 per day too. -- In the mobs onMobDeath script, we can easily make the popper 100% upgrade rate and everyone else less, if desired. if (player:getCurrency("voidstones") > 0) then player:startEvent(6000, 7); else player:startEvent(6000, 2); end else player:startEvent(6000); 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); -- NOTE: I'm only requiring 1 person (the popper) to have the voidstone, per pop. -- I know this isn't what retail does. Retail also lets them gain more than 1 per day too. if (csid == 6000 and option == 1) then player:delCurrency("voidstones", 1); SpawnMob(17265130):updateClaim(player); end end;
gpl-3.0
leonardoaxe/OpenRA
mods/ra/maps/allies-05a/allies05a.lua
5
11297
if Map.LobbyOption("difficulty") == "easy" then TanyaType = "e7" ReinforceCash = 5000 HoldAITime = DateTime.Minutes(3) SpecialCameras = true elseif Map.LobbyOption("difficulty") == "normal" then TanyaType = "e7.noautotarget" ReinforceCash = 2250 HoldAITime = DateTime.Minutes(2) SpecialCameras = true else TanyaType = "e7.noautotarget" ReinforceCash = 1500 HoldAITime = DateTime.Minutes(1) + DateTime.Seconds(30) SendWaterTransports = true end SpyType = { "spy" } SpyEntryPath = { SpyEntry.Location, SpyLoadout.Location } InsertionTransport = "lst.in" ExtractionTransport = "lst" TrukPath = { TrukWaypoint1, TrukWaypoint2, TrukWaypoint3, TrukWaypoint4, TrukWaypoint5, TrukWaypoint6 } ExtractionHeliType = "tran" InsertionHeliType = "tran.in" ExtractionPath = { ExtractionEntry.Location, ExtractionLZ.Location } HeliReinforcements = { "medi", "mech", "mech" } GreeceReinforcements = { { types = { "2tnk", "2tnk", "2tnk", "arty", "arty" }, entry = { SpyEntry.Location, SpyLoadout.Location } }, { types = { "e3", "e3", "e3", "e6", "e6" }, entry = { SpyEntry.Location, GreeceLoadout1.Location } }, { types = { "jeep", "jeep", "e1", "e1", "2tnk" }, entry = { SpyEntry.Location, GreeceLoadout2.Location } } } DogPatrol = { Dog1, Dog2 } PatrolA = { PatrolA1, PatrolA2, PatrolA3, PatrolA4, PatrolA5 } PatrolB = { PatrolB1, PatrolB2, PatrolB3 } DogPatrolPath = { DogPatrolRally1.Location, DogPatrolRally2.Location, DogPatrolRally3.Location } PatrolAPath = { PatrolRally.Location, PatrolARally1.Location, PatrolARally2.Location, PatrolARally3.Location } PatrolBPath = { PatrolBRally1.Location, PatrolBRally2.Location, PatrolBRally3.Location, PatrolRally.Location } TanyaVoices = { "tuffguy", "bombit", "laugh", "gotit", "lefty", "keepem" } SpyVoice = "sking" SamSites = { Sam1, Sam2, Sam3, Sam4 } GroupPatrol = function(units, waypoints, delay) local i = 1 local stop = false Utils.Do(units, function(unit) Trigger.OnIdle(unit, function() if stop then return end if unit.Location == waypoints[i] then local bool = Utils.All(units, function(actor) return actor.IsIdle end) if bool then stop = true i = i + 1 if i > #waypoints then i = 1 end Trigger.AfterDelay(delay, function() stop = false end) end else unit.AttackMove(waypoints[i]) end end) end) end Tick = function() if FollowTruk then TrukCamera.Teleport(Truk.Location) Camera.Position = Truk.CenterPosition end if ussr.HasNoRequiredUnits() then if not greece.IsObjectiveCompleted(KillAll) and Map.LobbyOption("difficulty") == "tough" then SendWaterExtraction() end greece.MarkCompletedObjective(KillAll) end if GreeceReinforcementsArrived and greece.HasNoRequiredUnits() then ussr.MarkCompletedObjective(ussrObj) end if ussr.Resources >= ussr.ResourceCapacity * 0.75 then ussr.Cash = ussr.Cash + ussr.Resources - ussr.ResourceCapacity * 0.25 ussr.Resources = ussr.ResourceCapacity * 0.25 end end SendReinforcements = function() GreeceReinforcementsArrived = true Camera.Position = ReinforceCamera.CenterPosition greece.Cash = greece.Cash + ReinforceCash Utils.Do(GreeceReinforcements, function(reinforcements) Reinforcements.ReinforceWithTransport(greece, InsertionTransport, reinforcements.types, reinforcements.entry, { SpyEntry.Location }) end) Media.PlaySpeechNotification(greece, "AlliedReinforcementsArrived") ActivateAI() end ExtractUnits = function(extractionUnit, pos, after) if extractionUnit.IsDead or not extractionUnit.HasPassengers then return end extractionUnit.Move(pos) extractionUnit.Destroy() Trigger.OnRemovedFromWorld(extractionUnit, after) end SendWaterExtraction = function() local flare = Actor.Create("flare", true, { Owner = greece, Location = SpyEntryPath[2] + CVec.New(2, 0) }) Trigger.AfterDelay(DateTime.Seconds(5), flare.Destroy) Media.PlaySpeechNotification(greece, "SignalFlareNorth") Camera.Position = flare.CenterPosition WaterExtractionTran = Reinforcements.ReinforceWithTransport(greece, ExtractionTransport, nil, SpyEntryPath)[1] ExtractObj = greece.AddPrimaryObjective("Get all your forces into the transport.") Trigger.OnKilled(WaterExtractionTran, function() ussr.MarkCompletedObjective(ussrObj) end) Trigger.OnAllRemovedFromWorld(greece.GetGroundAttackers(), function() ExtractUnits(WaterExtractionTran, SpyEntryPath[1], function() greece.MarkCompletedObjective(ExtractObj) greece.MarkCompletedObjective(surviveObj) end) end) end WarfactoryInfiltrated = function() FollowTruk = true TrukCamera = Actor.Create("camera.truk", true, { Owner = greece, Location = Truk.Location }) Truk.Wait(DateTime.Seconds(1)) Utils.Do(TrukPath, function(waypoint) Truk.Move(waypoint.Location) end) if SpecialCameras then Trigger.AfterDelay(DateTime.Seconds(2), function() SpyCameraA.Destroy() SpyCameraB.Destroy() end) end end MissInfiltrated = function() for i = 0, 5, 1 do local sound = Utils.Random(TanyaVoices) Trigger.AfterDelay(DateTime.Seconds(i), function() Media.PlaySoundNotification(greece, sound) end) end TanyasColt = Actor.Create("Colt", true, { Owner = greece, Location = Prison.Location + CVec.New(1, 6) }) Trigger.AfterDelay(DateTime.Seconds(6), FreeTanya) end FreeTanya = function() TanyasColt.Destroy() Tanya = Actor.Create(TanyaType, true, { Owner = greece, Location = Prison.Location + CVec.New(1, 1) }) Tanya.Demolish(Prison) Tanya.Move(Tanya.Location + CVec.New(Utils.RandomInteger(-1, 2), 1)) if TanyaType == "e7.noautotarget" then Trigger.AfterDelay(DateTime.Seconds(1), function() Media.DisplayMessage("According to the rules of engagement I need your explicit orders to fire, Commander!", "Tanya") end) end Trigger.OnKilled(Tanya, function() ussr.MarkCompletedObjective(ussrObj) end) if Map.LobbyOption("difficulty") == "tough" then KillSams = greece.AddPrimaryObjective("Destroy all four SAM Sites that block\nour reinforcements' helicopter.") greece.MarkCompletedObjective(mainObj) surviveObj = greece.AddPrimaryObjective("Tanya must not die!") Media.PlaySpeechNotification(greece, "TanyaRescued") else KillSams = greece.AddPrimaryObjective("Destroy all four SAM sites that block\nthe extraction helicopter.") Media.PlaySpeechNotification(greece, "TargetFreed") end if not SpecialCameras then PrisonCamera.Destroy() end end SendSpy = function() Camera.Position = SpyEntry.CenterPosition Spy = Reinforcements.ReinforceWithTransport(greece, InsertionTransport, SpyType, SpyEntryPath, { SpyEntryPath[1] })[2][1] Trigger.OnKilled(Spy, function() ussr.MarkCompletedObjective(ussrObj) end) if SpecialCameras then SpyCameraA = Actor.Create("camera", true, { Owner = greece, Location = SpyCamera1.Location }) SpyCameraB = Actor.Create("camera", true, { Owner = greece, Location = SpyCamera2.Location }) end Trigger.AfterDelay(DateTime.Seconds(3), function() Media.DisplayMessage("Commander! You have to disguise me in order to get through the enemy patrols.", "Spy") end) end ActivatePatrols = function() GroupPatrol(DogPatrol, DogPatrolPath, DateTime.Seconds(2)) Trigger.AfterDelay(DateTime.Seconds(3), function() GroupPatrol(PatrolA, PatrolAPath, DateTime.Seconds(7)) GroupPatrol(PatrolB, PatrolBPath, DateTime.Seconds(6)) end) end InitTriggers = function() Trigger.OnInfiltrated(Warfactory, function() Trigger.ClearAll(Spy) greece.MarkCompletedObjective(infWarfactory) WarfactoryInfiltrated() end) Trigger.OnInfiltrated(Prison, function() Trigger.ClearAll(Spy) Trigger.AfterDelay(DateTime.Seconds(2), MissInfiltrated) end) Trigger.OnEnteredFootprint({ TrukWaypoint5.Location }, function(a, id) if a == Truk then Trigger.RemoveFootprintTrigger(id) Spy = Actor.Create("spy", true, { Owner = greece, Location = TrukWaypoint5.Location }) Spy.DisguiseAsType("e1", ussr) Spy.Move(SpyWaypoint.Location) Spy.Infiltrate(Prison) Media.PlaySoundNotification(greece, SpyVoice) FollowTruk = false TrukCamera.Destroy() if SpecialCameras then PrisonCamera = Actor.Create("camera", true, { Owner = greece, Location = TrukWaypoint5.Location }) else PrisonCamera = Actor.Create("camera.truk", true, { Owner = greece, Location = Prison.Location + CVec.New(1, 1) }) end Trigger.OnKilled(Spy, function() ussr.MarkCompletedObjective(ussrObj) end) end end) Trigger.OnEnteredFootprint({ TrukWaypoint6.Location }, function(a, id) if a == Truk then Trigger.RemoveFootprintTrigger(id) Truk.Stop() Truk.Kill() ExplosiveBarrel.Kill() end end) if Map.LobbyOption("difficulty") ~= "tough" then Trigger.OnKilled(Mammoth, function() Trigger.AfterDelay(HoldAITime - DateTime.Seconds(45), function() HoldProduction = false end) Trigger.AfterDelay(HoldAITime, function() Attacking = true end) end) end Trigger.OnKilled(FlameBarrel, function() if not FlameTower.IsDead then FlameTower.Kill() end end) Trigger.OnKilled(SamBarrel, Sam1.Kill) Trigger.OnAllKilled(SamSites, function() greece.MarkCompletedObjective(KillSams) local flare = Actor.Create("flare", true, { Owner = greece, Location = ExtractionPath[2] + CVec.New(0, -1) }) Trigger.AfterDelay(DateTime.Seconds(7), flare.Destroy) Media.PlaySpeechNotification(greece, "SignalFlare") if Map.LobbyOption("difficulty") == "tough" then Reinforcements.ReinforceWithTransport(greece, InsertionHeliType, HeliReinforcements, ExtractionPath, { ExtractionPath[1] }) if not Harvester.IsDead then Harvester.FindResources() end else ExtractionHeli = Reinforcements.ReinforceWithTransport(greece, ExtractionHeliType, nil, ExtractionPath)[1] local exitPos = CPos.New(ExtractionPath[1].X, ExtractionPath[2].Y) Trigger.OnKilled(ExtractionHeli, function() ussr.MarkCompletedObjective(ussrObj) end) Trigger.OnRemovedFromWorld(Tanya, function() ExtractUnits(ExtractionHeli, exitPos, function() Media.PlaySpeechNotification(greece, "TanyaRescued") greece.MarkCompletedObjective(mainObj) SendReinforcements() if SpecialCameras then PrisonCamera.Destroy() end end) end) end end) end InitObjectives = function() Trigger.OnObjectiveAdded(greece, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) ussrObj = ussr.AddPrimaryObjective("Deny the Allies.") mainObj = greece.AddPrimaryObjective("Rescue Tanya.") KillAll = greece.AddPrimaryObjective("Eliminate all Soviet units in this area.") infWarfactory = greece.AddPrimaryObjective("Infiltrate the Soviet warfactory.") Trigger.OnObjectiveCompleted(greece, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(greece, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerLost(greece, function() Media.PlaySpeechNotification(player, "Lose") end) Trigger.OnPlayerWon(greece, function() Media.PlaySpeechNotification(player, "Win") end) end WorldLoaded = function() greece = Player.GetPlayer("Greece") ussr = Player.GetPlayer("USSR") InitObjectives() InitTriggers() SendSpy() Trigger.AfterDelay(DateTime.Seconds(3), ActivatePatrols) end
gpl-3.0
bnetcc/darkstar
scripts/zones/Bastok_Mines/npcs/Crying_Wind_IM.lua
5
2504
----------------------------------- -- Area: Bastok Mines -- NPC: Crying Wind, I.M. -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Bastok_Mines/TextIDs"); local guardnation = NATION_BASTOK; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border local size = #BastInv; local inventory = BastInv; function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(32761,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); updateConquestGuard(player,csid,option,size,inventory); end; function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %u",option); finishConquestGuard(player,csid,option,size,inventory,guardnation); end;
gpl-3.0
tahashakiba/booooooo
plugins/linkpv.lua
66
30275
do local function check_member(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)] = { 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, '') 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)] = { 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, '') 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,{receiver=receiver, data=data, msg = msg}) 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 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 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.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection 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 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 data[tostring(msg.to.id)] 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 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 data[tostring(msg.to.id)] then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{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 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 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 username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function modlist(msg) local data = load_data(_config.moderation.data) if not data[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) 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 if success == -1 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end for k,v in pairs(result.members) do kick_user(v.id, result.id) end 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' then print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'rem' then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 then return automodadd(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_add_user' then if not msg.service then return "Are you trying to troll me?" end local receiver = 'user#id'..msg.action.user.id local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return false end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Welcome to "' .. string.gsub(msg.to.print_name, '_', ' ') ..'" this group has rules that you should follow:\n'..rules savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..msg.action.user.id) send_large_msg(receiver, rules) 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 matches[2] then if not is_owner(msg) then return "Only owner can promote" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'promote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end if matches[1] == 'demote' and matches[2] then if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username then return "You can't demote yourself" end local member = string.gsub(matches[2], "@", "") local mod_cmd = 'demote' savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) 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 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 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] == 'newlink' 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] == 'linkpv' 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.."]") send_large_msg('user#id'..msg.from.id, 'Group link for ('..string.gsub(msg.to.print_name, "_", " ")..'):\n'..group_link) end if matches[1] == 'setowner' 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] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_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") return "Group owner is ["..group_owner..']' 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]) < 2 or tonumber(matches[2]) > 50 then return "Wrong number,range is [2-50]" 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] == 'help' then if not is_momod(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 end end return { usage = { "linkpv: Send Link In Private Chat.", }, patterns = { "^([Ll]inkpv)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
mwoz123/koreader
frontend/ui/widget/datewidget.lua
3
6838
local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local CloseButton = require("ui/widget/closebutton") local Device = require("device") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local Font = require("ui/font") local HorizontalGroup = require("ui/widget/horizontalgroup") local InputContainer = require("ui/widget/container/inputcontainer") local LineWidget = require("ui/widget/linewidget") local OverlapGroup = require("ui/widget/overlapgroup") local NumberPickerWidget = require("ui/widget/numberpickerwidget") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local TextWidget = require("ui/widget/textwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local WidgetContainer = require("ui/widget/container/widgetcontainer") local _ = require("gettext") local Screen = Device.screen local DateWidget = InputContainer:new{ title_face = Font:getFace("x_smalltfont"), width = nil, height = nil, day = 1, month = 1, year = 2017, ok_text = _("OK"), cancel_text = _("Cancel"), } function DateWidget:init() self.medium_font_face = Font:getFace("ffont") self.light_bar = {} self.screen_width = Screen:getWidth() self.screen_height = Screen:getHeight() self.width = math.floor(self.screen_width * 0.95) if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "close date widget" } } end if Device:isTouchDevice() then self.ges_events = { TapClose = { GestureRange:new{ ges = "tap", range = Geom:new{ w = self.screen_width, h = self.screen_height, } }, }, } end -- Actually the widget layout self:update() end function DateWidget:update() local year_widget = NumberPickerWidget:new{ show_parent = self, width = math.floor(self.screen_width * 0.2), value = self.year, value_min = 2017, value_max = 2037, value_step = 1, value_hold_step = 4, } local month_widget = NumberPickerWidget:new{ show_parent = self, width = math.floor(self.screen_width * 0.2), value = self.month, value_min = 1, value_max = 12, value_step = 1, value_hold_step = 3, } local day_widget = NumberPickerWidget:new{ show_parent = self, width = math.floor(self.screen_width * 0.2), value = self.day, value_min = 1, value_max = 31, value_step = 1, value_hold_step = 5, date_month = month_widget, date_year = year_widget, } local dash_space = TextBoxWidget:new{ text = "–", alignment = "center", face = self.title_face, bold = true, width = math.floor(self.screen_width * 0.1), } local date_group = HorizontalGroup:new{ align = "center", year_widget, dash_space, month_widget, dash_space, day_widget, } local date_title = FrameContainer:new{ padding = Size.padding.default, margin = Size.margin.title, bordersize = 0, TextWidget:new{ text = self.title_text, face = self.title_face, bold = true, width = math.floor(self.screen_width * 0.95), }, } local date_line = LineWidget:new{ dimen = Geom:new{ w = self.width, h = Size.line.thick, } } local date_bar = OverlapGroup:new{ dimen = { w = self.width, h = date_title:getSize().h }, date_title, CloseButton:new{ window = self, padding_top = Size.margin.title, }, } local buttons = { { { text = self.cancel_text, callback = function() self:onClose() end, }, { text = self.ok_text, callback = function() if self.callback then self.year = year_widget:getValue() self.month = month_widget:getValue() self.day = day_widget:getValue() self:callback(self) end self:onClose() end, }, } } local ok_cancel_buttons = ButtonTable:new{ width = self.width - 2*Size.padding.default, buttons = buttons, zero_sep = true, show_parent = self, } self.date_frame = FrameContainer:new{ radius = Size.radius.window, bordersize = Size.border.window, padding = 0, margin = 0, background = Blitbuffer.COLOR_WHITE, VerticalGroup:new{ align = "left", date_bar, date_line, CenterContainer:new{ dimen = Geom:new{ w = math.floor(self.screen_width * 0.95), h = math.floor(date_group:getSize().h * 1.2), }, date_group }, CenterContainer:new{ dimen = Geom:new{ w = self.width, h = ok_cancel_buttons:getSize().h, }, ok_cancel_buttons } } } self[1] = WidgetContainer:new{ align = "center", dimen = Geom:new{ x = 0, y = 0, w = self.screen_width, h = self.screen_height, }, FrameContainer:new{ bordersize = 0, padding = Size.padding.default, self.date_frame, } } UIManager:setDirty(self, function() return "ui", self.date_frame.dimen end) end function DateWidget:onCloseWidget() UIManager:setDirty(nil, function() return "ui", self.date_frame.dimen end) return true end function DateWidget:onShow() UIManager:setDirty(self, function() return "ui", self.date_frame.dimen end) return true end function DateWidget:onAnyKeyPressed() UIManager:close(self) return true end function DateWidget:onTapClose(arg, ges_ev) if ges_ev.pos:notIntersectWith(self.date_frame.dimen) then self:onClose() end return true end function DateWidget:onClose() UIManager:close(self) return true end return DateWidget
agpl-3.0
bnetcc/darkstar
scripts/globals/spells/absorb-vit.lua
4
1561
-------------------------------------- -- Spell: Absorb-VIT -- Steals an enemy's vitality. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (target:hasStatusEffect(EFFECT_VIT_DOWN) or caster:hasStatusEffect(EFFECT_VIT_BOOST)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect else local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local params = {}; params.diff = nil; params.attribute = MOD_INT; params.skillType = 37; params.bonus = 0; params.effect = nil; local resist = applyResistance(caster, target, spell, params); if (resist <= 0.125) then spell:setMsg(msgBasic.MAGIC_RESIST); else spell:setMsg(msgBasic.MAGIC_ABSORB_VIT); caster:addStatusEffect(EFFECT_VIT_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains VIT target:addStatusEffect(EFFECT_VIT_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASABLE); -- target loses VIT end end return EFFECT_VIT_DOWN; end;
gpl-3.0
bnetcc/darkstar
scripts/commands/heroshop.lua
1
7476
-------------------------------------------------------------- -- func: !heroshop -- desc: like !shop, but for accomplished adventurers only -------------------------------------------------------------- require("scripts/globals/atma"); require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/titles"); require("scripts/zones/Abyssea-Empyreal_Paradox/npcs/Prishe"); -------------------------------------------------------------- cmdprops = { permission = 3, parameters = "i" }; -- unfinished, will remove this comment and change permission when done -- Notes: -- -- ALWAYS comment your additions! function onTrigger(player,page) if (page == 0 or page == nil) then player:PrintToPlayer( "Conquer content to unlock new !heroshop pages!"); player:PrintToPlayer( "1: Nations, 2: Zilart, 3: CoP, 4: ToAU"); player:PrintToPlayer( "5: WotG, 6: Abyssea, 7: Dynamis, 8: Legion"); -- player:PrintToPlayer( "9: VoidWatch, 10: Walk of Echoes"); return end local Sandy_clear = player:hasCompletedMission(SANDORIA,THE_HEIR_TO_THE_LIGHT); local Basty_clear = player:hasCompletedMission(BASTOK,WHERE_TWO_PATHS_CONVERGE); local Windy_clear = player:hasCompletedMission(WINDURST,MOON_READING); local Zilart_clear = player:hasCompletedMission(ZILART,AWAKENING); local Chains_clear = player:hasCompletedMission(COP,DAWN); local AhtUrgan_clear = player:hasCompletedMission(TOAU,THE_EMPRESS_CROWNED); local Goddess_clear = player:hasCompletedMission(WOTG,A_TOKEN_OF_TROTH); local Abyssea_clear = (countLunars(player) == 3 and title == 10); local Dyna_clearA = player:hasKeyItem(HYDRA_CORPS_BATTLE_STANDARD); local Dyna_clearB = player:hasKeyItem(DYNAMIS_TAVNAZIA_SLIVER); local Legion_clear = player:hasTitle(LEGENDARY_LEGIONNAIRE); local title = 0; if (player:hasTitle(BRIAREUS_FELLER)) then title = title+1; end if (player:hasTitle(KUKULKAN_DEFANGER)) then title = title+1; end if (player:hasTitle(GLAVOID_STAMPEDER)) then title = title+1; end if (player:hasTitle(ITZPAPALOTL_DECLAWER)) then title = title+1; end if (player:hasTitle(CIREINCROIN_HARPOONER)) then title = title+1; end if (player:hasTitle(SEDNA_TUSKBREAKER)) then title = title+1; end if (player:hasTitle(BENNU_DEPLUMER)) then title = title+1; end if (player:hasTitle(RESHEPH_ERADICATOR)) then title = title+1; end if (player:hasTitle(AMPHITRITE_SHUCKER)) then title = title+1; end if (player:hasTitle(WYRM_GOD_DEFIER)) then title = title+1; end if ((Sandy_clear == false or Basty_clear == true or Windy_clear == true) and Zilart_clear == true and Chains_clear == true and AhtUrgan_clear == true and Goddess_clear == true and Abyssea_clear == true and (Dyna_clearA == true or Dyna_clearB == true) and Legion_clear == true) player:PrintToPlayer( "Not so fast, Hercules, you have to complete some legendary labors before you can shop here!" ); return end if (page == 1) then -- Unlocked by attaining rank 10 in all 3 nations. if (Sandy_clear == true and Basty_clear == true and Windy_clear == true) then local stock_1 = { 15793, 1000000, -- Anniversary Ring -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name }; showShop(player, STATIC, stock_1); end elseif (page == 2) then -- Unlocked by completing Rise of the Zilart. if (Zilart_clear == true) then local stock_2 = { 14739, 5000000, -- Suppanomimi 14742, 5000000, -- Beastly Earring 14743, 5000000, -- Bushinomimi 14740, 5000000, -- knights earring 14741, 5000000, -- abyssal earring }; showShop(player, STATIC, stock_2); end elseif (page == 3) then -- Unlocked by completing Chains of Promathia. if (Chains_clear == true) then local stock_3 = { 15545, 5000000, -- Tamas Ring 15543, 5000000, -- Rajas Ring 15544, 5000000, -- Sattva Ring -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name }; showShop(player, STATIC, stock_3); end elseif (page == 4) then -- Unlocked by completing Treasures of Aht Urgan. if (AhtUrgan_clear == true) then local stock_4 = { -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name }; showShop(player, STATIC, stock_4); end elseif (page == 5) then -- Unlocked by completing Wings of the Goddess. if (Goddess_clear == true) then local stock_5 = { -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name }; showShop(player, STATIC, stock_5); end elseif (page == 6) then -- Unlocked by completing all of Abyssea. if (Abyssea_clear == true) then local stock_6 = { 11362, 5000000, -- Twilight Mail 11363, 5000000, -- Twilight Cloak 15959, 1000000, -- Twilight Belt 18551, 1000000, -- Twilight Scythe 11625, 1000000, -- Twilight Torque 11798, 3000000, -- Twilight Helm 19132, 1000000, -- Twilight Knife 16259, 1000000, -- Twilight Cape 5877, 100000, -- Terror Screen 5879, 100000, -- Doom Screen }; showShop(player, STATIC, stock_6); end elseif (page == 7) then -- Unlocked by clearing every Dynamis zone. -- if (player:getVar(MyVariableName) == 1) then local stock_7 = { -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name }; showShop(player, STATIC, stock_7); -- end elseif (page == 8) then -- Unlocked by clearing every Legion battle. if (Legion_clear == true) then local stock_8 = { 21337, 7000, -- achiyal-bullet 21307, 7000, -- achiyal-arrow -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name -- ItemID, Price, -- Item Name }; showShop(player, STATIC, stock_8); end else player:PrintToPlayer( string.format( "Page %i not found.", page ) ); end end
gpl-3.0
bnetcc/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/qm1.lua
1
2624
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: ??? (Jailer of Fortitude Spawn) -- Allows players to spawn the Jailer of Fortitude by trading 12 Ghrah M Chips to a ???. -- Random positions: -- !pos -420 0 755 -- !pos -43 0 460 -- !pos -260 0 44.821 -- !pos -580 0 43 -- !pos -796 0 460 ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/zones/The_Garden_of_RuHmet/MobIDs"); require("scripts/globals/status"); ----------------------------------- function onTrade(player,npc,trade) -- Trade 12 Ghrah M Chips --[[ if (GetMobAction(Jailer_of_Fortitude) == 0 and trade:hasItemQty(1872,12) and trade:getItemCount() == 12) then local qm1 = GetNPCByID(Jailer_of_Fortitude_QM); -- Complete the trade player:tradeComplete(); -- Hide the NPC, will become unhidden after Jailer of Fortitude despawns qm1:setStatus(STATUS_DISAPPEAR); -- Change MobSpawn to ???'s pos. GetMobByID(Jailer_of_Fortitude):setSpawn(qm1:getXPos(),qm1:getYPos(),qm1:getZPos()); -- Change spawn point of pets to be at the ???'s pos as well GetMobByID(Kf_Ghrah_WHM):setSpawn(qm1:getXPos(),qm1:getYPos(),qm1:getZPos()); GetMobByID(Kf_Ghrah_BLM):setSpawn(qm1:getXPos(),qm1:getYPos(),qm1:getZPos()); -- Spawn Jailer of Fortitude SpawnMob(Jailer_of_Fortitude):updateClaim(player); SpawnMob(Kf_Ghrah_WHM):updateClaim(player); SpawnMob(Kf_Ghrah_BLM):updateClaim(player); ]] if (GetMobAction(16921015) == ACTION_NONE) then if (trade:hasItemQty(1872,12) and trade:getItemCount() == 12) then GetMobByID(16921015):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos()); GetMobByID(16921016):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos()); GetMobByID(16921017):setSpawn(npc:getXPos(),npc:getYPos(),npc:getZPos()); SpawnMob(16921015):updateClaim(player); SpawnMob(16921016):updateEnmity(player); SpawnMob(16921017):updateEnmity(player); player:tradeComplete(); end end end; function onTrigger(player,npc) player:PrintToPlayer("Debug: Jailer of Fortitude (qm1.lua)"); end; function onEventUpdate(player,csid,option) -- printf("onUpdate CSID: %u",csid); -- printf("onUpdate RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("onFinish CSID: %u",csid); -- printf("onFinish RESULT: %u",option); end;
gpl-3.0
Atebite/NutScript
gamemode/core/derma/cl_classes.lua
4
4397
local PANEL = {} function PANEL:Init() self:SetTall(64) local function assignClick(panel) panel.OnMousePressed = function() self.pressing = -1 self:onClick() end panel.OnMouseReleased = function() if (self.pressing) then self.pressing = nil --self:onClick() end end end self.icon = self:Add("SpawnIcon") self.icon:SetSize(128, 64) self.icon:InvalidateLayout(true) self.icon:Dock(LEFT) self.icon.PaintOver = function(this, w, h) /* if (panel.payload.model == k) then local color = nut.config.get("color", color_white) surface.SetDrawColor(color.r, color.g, color.b, 200) for i = 1, 3 do local i2 = i * 2 surface.DrawOutlinedRect(i, i, w - i2, h - i2) end surface.SetDrawColor(color.r, color.g, color.b, 75) surface.SetMaterial(gradient) surface.DrawTexturedRect(0, 0, w, h) end */ end assignClick(self.icon) self.limit = self:Add("DLabel") self.limit:Dock(RIGHT) self.limit:SetMouseInputEnabled(true) self.limit:SetCursor("hand") self.limit:SetExpensiveShadow(1, Color(0, 0, 60)) self.limit:SetContentAlignment(5) self.limit:SetFont("nutMediumFont") self.limit:SetWide(64) assignClick(self.limit) self.label = self:Add("DLabel") self.label:Dock(FILL) self.label:SetMouseInputEnabled(true) self.label:SetCursor("hand") self.label:SetExpensiveShadow(1, Color(0, 0, 60)) self.label:SetContentAlignment(5) self.label:SetFont("nutMediumFont") assignClick(self.label) end function PANEL:onClick() nut.command.send("beclass", self.class) end function PANEL:setNumber(number) local limit = self.data.limit if (limit > 0) then self.limit:SetText(Format("%s/%s", number, limit)) else self.limit:SetText("∞") end end function PANEL:setClass(data) if (data.model) then local model = data.model if (type(model):lower() == "table") then model = table.Random(model) end self.icon:SetModel(model) else self.icon:SetModel(LocalPlayer():GetModel()) end self.label:SetText(data.name) self.data = data self.class = data.index self:setNumber(#nut.class.getPlayers(data.index)) end vgui.Register("nutClassPanel", PANEL, "DPanel") PANEL = {} function PANEL:Init() nut.gui.classes = self self:SetSize(self:GetParent():GetSize()) self.list = vgui.Create("DPanelList", self) self.list:Dock(FILL) self.list:EnableVerticalScrollbar() self.list:SetSpacing(5) self.list:SetPadding(5) self.classPanels = {} self:loadClasses() end function PANEL:loadClasses() self.list:Clear() for k, v in ipairs(nut.class.list) do if (nut.class.canBe(LocalPlayer(), k)) then local panel = vgui.Create("nutClassPanel", self.list) panel:setClass(v) table.insert(self.classPanels, panel) self.list:AddItem(panel) end end end vgui.Register("nutClasses", PANEL, "EditablePanel") hook.Add("CreateMenuButtons", "nutClasses", function(tabs) for k, v in ipairs(nut.class.list) do if (!nut.class.canBe(LocalPlayer(), k)) then continue else tabs["classes"] = function(panel) panel:Add("nutClasses") end return end end end) netstream.Hook("classUpdate", function(joinedClient) if (nut.gui.classes and nut.gui.classes:IsVisible()) then if (joinedClient == LocalPlayer()) then nut.gui.classes:loadClasses() else for k, v in ipairs(nut.gui.classes.classPanels) do local data = v.data v:setNumber(#nut.class.getPlayers(data.index)) end end end end)
mit
bnetcc/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua
5
1852
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm7 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- !pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED1); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
awesomeWM/awesome
lib/gears/cache.lua
4
1972
--------------------------------------------------------------------------- --- Cache object with data that can be garbage-collected. -- -- Here is an example with a basic cache: -- --@DOC_text_gears_cache_cache_EXAMPLE@ -- -- The example below demonstrates how the garbage collector will clear the -- cache: -- --@DOC_text_gears_cache_another_cache_EXAMPLE@ -- -- -- @author Uli Schlachter -- @copyright 2015 Uli Schlachter -- @classmod gears.cache --------------------------------------------------------------------------- local select = select local setmetatable = setmetatable local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1) local cache = {} --- Get an entry from the cache, creating it if it's missing. -- @param ... Arguments for the creation callback. These are checked against the -- cache contents for equality. -- @return The entry from the cache function cache:get(...) local result = self._cache for i = 1, select("#", ...) do local arg = select(i, ...) local next = result[arg] if not next then next = {} result[arg] = next end result = next end local ret = result._entry if not ret then ret = { self._creation_cb(...) } result._entry = ret end return unpack(ret) end --- Create a new cache object. A cache keeps some data that can be -- garbage-collected at any time, but might be useful to keep. -- @param creation_cb Callback that is used for creating missing cache entries. -- @return A new cache object. -- @constructorfct gears.cache function cache.new(creation_cb) return setmetatable({ _cache = setmetatable({}, { __mode = "v" }), _creation_cb = creation_cb }, { __index = cache }) end return setmetatable(cache, { __call = function(_, ...) return cache.new(...) end }) -- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
MmxBoy/metalik
plugins/qr.lua
637
1730
--[[ * qr plugin uses: * - http://goqr.me/api/doc/create-qr-code/ * psykomantis ]] local function get_hex(str) local colors = { red = "f00", blue = "00f", green = "0f0", yellow = "ff0", purple = "f0f", white = "fff", black = "000", gray = "ccc" } for color, value in pairs(colors) do if color == str then return value end end return str end local function qr(receiver, text, color, bgcolor) local url = "http://api.qrserver.com/v1/create-qr-code/?" .."size=600x600" --fixed size otherways it's low detailed .."&data="..URL.escape(text:trim()) if color then url = url.."&color="..get_hex(color) end if bgcolor then url = url.."&bgcolor="..get_hex(bgcolor) end local response, code, headers = http.request(url) if code ~= 200 then return "Oops! Error: " .. code end if #response > 0 then send_photo_from_url(receiver, url) return end return "Oops! Something strange happened :(" end local function run(msg, matches) local receiver = get_receiver(msg) local text = matches[1] local color local back if #matches > 1 then text = matches[3] color = matches[2] back = matches[1] end return qr(receiver, text, color, back) end return { description = {"qr code plugin for telegram, given a text it returns the qr code"}, usage = { "!qr [text]", '!qr "[background color]" "[data color]" [text]\n' .."Color through text: red|green|blue|purple|black|white|gray\n" .."Colors through hex notation: (\"a56729\" is brown)\n" .."Or colors through decimals: (\"255-192-203\" is pink)" }, patterns = { '^!qr "(%w+)" "(%w+)" (.+)$', "^!qr (.+)$" }, run = run }
gpl-2.0
mwoz123/koreader
frontend/ui/widget/multiconfirmbox.lua
3
5847
--[[-- Widget that shows a message and cancel/choice1/choice2 buttons Example: UIManager:show(MultiConfirmBox:new{ text = T( _("Set %1 as fallback font?"), face), choice1_text = _("Default"), choice1_callback = function() -- set as default font end, choice2_text = _("Fallback"), choice2_callback = function() -- set as fallback font end, }) ]] local Blitbuffer = require("ffi/blitbuffer") local ButtonTable = require("ui/widget/buttontable") local CenterContainer = require("ui/widget/container/centercontainer") local Device = require("device") local Font = require("ui/font") local FrameContainer = require("ui/widget/container/framecontainer") local Geom = require("ui/geometry") local GestureRange = require("ui/gesturerange") local HorizontalGroup = require("ui/widget/horizontalgroup") local HorizontalSpan = require("ui/widget/horizontalspan") local IconWidget = require("ui/widget/iconwidget") local InputContainer = require("ui/widget/container/inputcontainer") local MovableContainer = require("ui/widget/container/movablecontainer") local Size = require("ui/size") local TextBoxWidget = require("ui/widget/textboxwidget") local UIManager = require("ui/uimanager") local VerticalGroup = require("ui/widget/verticalgroup") local VerticalSpan = require("ui/widget/verticalspan") local logger = require("logger") local _ = require("gettext") local Screen = require("device").screen local MultiConfirmBox = InputContainer:new{ modal = true, text = _("no text"), face = Font:getFace("infofont"), choice1_text = _("Choice 1"), choice1_text_func = nil, choice2_text = _("Choice 2"), choice2_text_func = nil, cancel_text = _("Cancel"), choice1_callback = function() end, choice2_callback = function() end, cancel_callback = function() end, choice1_enabled = true, choice2_enabled = true, margin = Size.margin.default, padding = Size.padding.default, dismissable = true, -- set to false if any button callback is required } function MultiConfirmBox:init() if self.dismissable then if Device:isTouchDevice() then self.ges_events.TapClose = { GestureRange:new{ ges = "tap", range = Geom:new{ x = 0, y = 0, w = Screen:getWidth(), h = Screen:getHeight(), } } } end if Device:hasKeys() then self.key_events = { Close = { {"Back"}, doc = "cancel" } } end end local content = HorizontalGroup:new{ align = "center", IconWidget:new{ icon = "notice-question", }, HorizontalSpan:new{ width = Size.span.horizontal_default }, TextBoxWidget:new{ text = self.text, face = self.face, width = math.floor(Screen:getWidth() * 2/3), } } local button_table = ButtonTable:new{ width = content:getSize().w, button_font_face = "cfont", button_font_size = 20, buttons = { { { text = self.cancel_text, callback = function() self.cancel_callback() UIManager:close(self) end, }, { text = self.choice1_text, text_func = self.choice1_text_func, enabled = self.choice1_enabled, callback = function() self.choice1_callback() UIManager:close(self) end, }, { text = self.choice2_text, text_func = self.choice2_text_func, enabled = self.choice2_enabled, callback = function() self.choice2_callback() UIManager:close(self) end, }, }, }, zero_sep = true, show_parent = self, } self[1] = CenterContainer:new{ dimen = Screen:getSize(), MovableContainer:new{ FrameContainer:new{ background = Blitbuffer.COLOR_WHITE, margin = self.margin, radius = Size.radius.window, padding = self.padding, padding_bottom = 0, -- no padding below buttontable VerticalGroup:new{ align = "left", content, -- Add same vertical space after than before content VerticalSpan:new{ width = self.margin + self.padding }, button_table, } } } } end function MultiConfirmBox:onShow() UIManager:setDirty(self, function() return "ui", self[1][1].dimen end) end function MultiConfirmBox:onCloseWidget() UIManager:setDirty(nil, function() return "ui", self[1][1].dimen end) end function MultiConfirmBox:onClose() UIManager:close(self) return true end function MultiConfirmBox:onTapClose(arg, ges) if ges.pos:notIntersectWith(self[1][1].dimen) then self:onClose() return true end return false end function MultiConfirmBox:onSelect() logger.dbg("selected:", self.selected.x) if self.selected.x == 1 then self:choice1_callback() elseif self.selected.x == 2 then self:choice2_callback() elseif self.selected.x == 0 then self:cancle_callback() end UIManager:close(self) return true end return MultiConfirmBox
agpl-3.0
bnetcc/darkstar
scripts/zones/Cloister_of_Tremors/bcnms/sugar-coated_directive.lua
5
1797
---------------------------------------- -- Area: Cloister of Tremors -- BCNM: Sugar Coated Directive (ASA-4) ---------------------------------------- package.loaded["scripts/zones/Cloister_of_Tremors/TextIDs"] = nil; ---------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Tremors/TextIDs"); ---------------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompleteQuest(ASA,SUGAR_COATED_DIRECTIVE)) then player:startEvent(32001,1,1,1,instance:getTimeInside(),1,4,1); else player:startEvent(32001,1,1,1,instance:getTimeInside(),1,4,0); end elseif (leavecode == 4) then player:startEvent(32002); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 32001) then player:addExp(400); player:setVar("ASA4_Amber","1"); end end;
gpl-3.0
OpenPrograms/Plan9k
pipes/20_threading.lua
1
8721
threads = {} currentThread = nil eventFilters = {signal = {}} function countThreadSignals(thread, signal) local n = 0 local first = 0 for i, sig in ipairs(thread.eventQueue) do if sig[1] == signal then n = n + 1 if first < 1 then first = i end end end return n, first end local deadline = math.huge local pullSignal = computer.pullSignal computer.pullSignal = function() pcall(kernel._println, "Attempted to use non threaded signal pulling") pcall(kernel._println, debug.traceback()) kernel.panic() end function eachThread(func) for _, thread in ipairs(threads) do if thread.coro then func(thread) end end end -------------- local firstFree = 1 local nextUid = 1 function kill(pid) kernel.modules.gc.processkilled(threads[pid]) threads[pid] = {next = firstFree} firstFree = pid eachThread(function(thread) if thread.coro then if thread.currentHandler == "kill" then thread.eventQueue[#thread.eventQueue + 1] = {"kill", pid} else thread.eventQueue[#thread.eventQueue + 1] = {"signal", "kill", pid} end thread.eventQueue[#thread.eventQueue + 1] = sig end end) --TODO: remove thread timers end function spawn(exec, child, name, isthread, _, ...) local thread local function errprint(text) if thread.io_error then if not pcall(thread.io_error.write, thread.io_error, tostring(text) .. "\n") then kernel.io.println(text) end else kernel.io.println(text) end end thread = { child = child, coro = coroutine.create(function(...) local arg = {...} local r = {xpcall(function() exec(table.unpack(arg)) end, function(e) pcall(errprint, "ERROR IN THREAD " .. thread.pid .. ": " .. tostring(thread.name)) pcall(errprint, e) pcall(errprint, debug.traceback()) end)} return table.unpack(r, 2) end), deadline = computer.uptime(), sandbox = isthread and currentThread.sandbox or kernel.modules.manageg.newsandbox(), currentHandler = "arg", currentHandlerArg = nil, eventQueue = {{"arg", ...}}, name = name or "unnamed", maxPendingSignals = 32, maxOpenFiles = 8, uid = nextUid, parent = currentThread and {pid = currentThread.pid, uid = currentThread.uid}, cgroups = { signal = kernel.modules.cgroups.spawnGroupGetters["signal"](), network = kernel.modules.cgroups.spawnGroupGetters["network"](), filesystem = kernel.modules.cgroups.spawnGroupGetters["filesystem"](), module = kernel.modules.cgroups.spawnGroupGetters["module"](), component = kernel.modules.cgroups.spawnGroupGetters["component"](), } } nextUid = nextUid + 1 thread.env = currentThread and (isthread and currentThread.env or setmetatable({},{__index=currentThread.env})) or {} local dest = firstFree if threads[firstFree] then firstFree = threads[firstFree].next else firstFree = firstFree + 1 end thread.pid = dest threads[dest] = thread thread.kill = { kill = kill, terminate = kill } kernel.io.debug("Spawn thread " .. tostring(name)) return thread end --- local function getPendingThreads() local res = {} for _, thread in ipairs(threads) do if thread.coro then res[#res + 1] = thread end end return res end local function getResumableThreads(threads_) local res = {} for _,thread in ipairs(threads_) do thread.currentEvent = nil for n,event in ipairs(thread.eventQueue) do if event[1] == thread.currentHandler then table.remove(thread.eventQueue, n) thread.currentEvent = event res[#res + 1] = thread break end end if not thread.currentEvent and thread.deadline <= computer.uptime() then thread.currentEvent = {"timeout"} res[#res + 1] = thread end end return res end local function processSignals() deadline = math.huge for _, thread in ipairs(threads) do if deadline > (thread.deadline or math.huge) then if not thread.deadline then kernel.io.println("Nil deadline for " .. thread.name .. " on " .. tostring(thread.currentHandler)) end deadline = thread.deadline end end --kernel.io.debug("Pull deadline: "..(deadline - computer.uptime())) local sig = {"signal", pullSignal(deadline - computer.uptime())} local function filt(f, signal, ...) if not signal then return true end if type(f[signal]) == "table" then return filt(f[signal], ...) end return (not f[signal]) and true or (function(...) local s, e = xpcall(f[signal], function(err) kernel._println("Signal filter error:") kernel._println(tostring(e)) kernel._println(debug.traceback()) kernel.panic("Signal filtering failed") end, ...) return s and e end)(...) end if not filt(eventFilters, table.unpack(sig)) then sig = {} end for _, thread in ipairs(threads) do if thread.coro then --[[if thread.currentHandler == "yield" then --kernel.io.println("yield ck: "..tostring((thread.currentHandlerArg or math.huge) - computer.uptime())) if (thread.currentHandlerArg or math.huge) <= computer.uptime() then thread.eventQueue[#thread.eventQueue + 1] = {"yield"} end end]]-- if thread.cgroups.signal.global and sig[2] then local nsig, oldest = countThreadSignals(thread, "signal") if nsig > thread.maxPendingSignals then --TODO: make it a bit more intelligent table.remove(thread.eventQueue, oldest) end thread.eventQueue[#thread.eventQueue + 1] = sig end end end end ---- local lastYield = computer.uptime() yieldTime = 3 function checkTimeout() local uptime = computer.uptime() if uptime - lastYield > yieldTime then return true end return false end function start() while true do local pending = getPendingThreads() local resumable = getResumableThreads(pending) lastYield = computer.uptime() while #resumable > 0 do for _, thread in ipairs(resumable) do --kernel.io.println("Resume " .. tostring(thread.name) .. " with " -- .. tostring(type(thread.currentEvent) == "table" and thread.currentEvent[1] or "unknown") -- ..(thread.currentEvent[2] and (", " .. tostring(thread.currentEvent[2])) or "")) thread.deadline = math.huge kernel.modules.manageg.protect(thread.sandbox) currentThread = thread local state, reason, arg = coroutine.resume(thread.coro, table.unpack(thread.currentEvent, 2)) currentThread = nil kernel.modules.manageg.unprotect() if not state or coroutine.status(thread.coro) == "dead" then kill(thread.pid) if reason then kernel.io.println("Thread " .. tostring(thread.name) .. "(" .. tostring(thread.pid) .. ") died: " .. tostring(reason or "unknown/done") .. ", after " .. tostring(type(thread.currentEvent) == "table" and thread.currentEvent[1] or "unknown")) end else --kernel.io.println("Yield arg from " .. tostring(thread.name) .. ": " .. tostring(arg)) thread.currentEvent = nil thread.currentHandler = reason thread.currentHandlerArg = arg end end if checkTimeout() then break end pending = getPendingThreads() resumable = getResumableThreads(pending) end processSignals() end end
mit
bnetcc/darkstar
scripts/globals/weaponskills/leg_sweep.lua
3
1731
----------------------------------- -- Leg Sweep -- Polearm weapon skill -- Skill Level: 100 -- Stuns enemy. Chance of stunning varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Thunder Gorget. -- Aligned with the Thunder Belt. -- Element: None -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 1; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params); local chance = (tp-1000) * applyResistanceAddEffect(player,target,ELE_LIGHTNING,0) > math.random() * 150; if (damage > 0 and chance) then if (target:hasStatusEffect(EFFECT_STUN) == false) then local duration = 4 * applyResistanceAddEffect(player,target,ELE_LIGHTNING,0); target:addStatusEffect(EFFECT_STUN, 1, 0, duration); end end return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Rolanberry_Fields_[S]/mobs/Agathos.lua
1
2841
----------------------------------- -- Area: EDIT ME -- VWNM: Agathos ----------------------------------- package.loaded["scripts/zones/Rolanberry_Fields_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Rolanberry_Fields_[S]/TextIDs"); require("scripts/globals/status"); require("scripts/globals/keyitems"); ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) -- setMobMod mob:setMobMod(MOBMOD_MAGIC_COOL, 45); -- addMod mob:addMod(MOD_DEF,50); mob:addMod(MOD_ATT,250); end; ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- setMod mob:setMod(MOD_REGAIN, 10); mob:setMod(MOD_REFRESH, 250); mob:setMod(MOD_UFASTCAST, 25); mob:setMod(MOD_MACC,1950); mob:setMod(MOD_MATT,100); -- var -- mob:setLocalVar("depopTime", os.time(t) + 1800); -- despawn in 30 min end; ----------------------------------- -- onMobEngage Action ----------------------------------- function onMobEngaged(mob, target) end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) if (isKiller == true) then local RND1 = math.random(1,8); if (RND1 == 1) then player:addTreasure(8919, mob); -- Ifritear elseif (RND1 == 2) then player:addTreasure(8920, mob); -- Leviatear elseif (RND1 == 3) then player:addTreasure(8921, mob); -- Ramutear elseif (RND1 == 4) then player:addTreasure(8922, mob); -- Garutear elseif (RND1 == 5) then player:addTreasure(8923, mob); -- Titatear elseif (RND1 == 6) then player:addTreasure(8924, mob); -- Shivatear elseif (RND1 == 7) then player:addTreasure(8925, mob); -- Carbutear elseif (RND1 == 8) then player:addTreasure(8926, mob); -- Fenritear end end if (player:hasKeyItem(WHITE_STRATUM_ABYSSITE)) then -- Agathos Kill if (player:getMaskBit(player:getVar("WHITE_STRATUM"), 3) == false) then player:setMaskBit(player:getVar("WHITE_STRATUM"),"WHITE_STRATUM",3,true); end if (player:isMaskFull(player:getVar("WHITE_STRATUM"),6) == true) then player:addKeyItem(WHITE_STRATUM_ABYSSITE_II); player:delKeyItem(WHITE_STRATUM_ABYSSITE); player:setVar("WHITE_STRATUM", 0); player:messageSpecial(KEYITEM_OBTAINED, WHITE_STRATUM_ABYSSITE_II); end end player:addCurrency("bayld", 100); player:addExp(3000); end;
gpl-3.0
awesomeWM/awesome
tests/examples/wibox/awidget/tasklist/style_fg_normal.lua
1
1443
--DOC_HIDE_START --DOC_GEN_IMAGE local parent = ... local beautiful = require("beautiful") local wibox = require("wibox") local awful = { widget = { tasklist = require("awful.widget.tasklist") } } local t_real = require("awful.tag").add("Test", {screen=screen[1]}) local s = screen[1] parent.spacing = 5 beautiful.tasklist_fg_focus = "#000000" for i=1, 5 do client.gen_fake{ class = "client", name = "Client #"..i, icon = beautiful.awesome_icon, tags = {t_real} } end client.get()[1].name = "Client 1# (floating)" client.get()[2].name = "Client 2# (sticky)" client.get()[3].name = "Client 3# (focus)" client.get()[4].name = "Client 4# (urgent)" client.get()[5].name = "Client 5# (minimized)" client.get()[1].floating = true client.get()[2].sticky = true client.get()[4].urgent = true client.get()[5].minimized = true client.focus = client.get()[3] --DOC_HIDE_END for _, col in ipairs { "#ff0000", "#00ff00", "#0000ff" } do beautiful.tasklist_fg_normal = col --DOC_HIDE_START local tasklist = awful.widget.tasklist { screen = s, filter = awful.widget.tasklist.filter.currenttags, layout = wibox.layout.fixed.horizontal } tasklist._do_tasklist_update_now() parent:add(_memento(tasklist, nil, 22)) --luacheck: globals _memento --DOC_HIDE_END end --DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
gpl-2.0
tahashakiba/booooooo
bot/SaTaN_bot.lua
1
8865
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end local config = loadfile ("./libs/libsjson.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end local config = loadfile ("./plugins/banhammer.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "all", "leave_ban", "admin", "plugins" }, sudo_users = {195473011,126712741},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[W_SaTaN_W V 1 Advanced Bot Base On Seed @WilSoN_DeVeLoPeR[DeVeLoPeR] #Open_Source [@W_SaTaN_W] [Https://github.com/DeterGent-Legion/MeGa_SaTaN] ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] **U can use both "/" and "!" *Only admins and sudo can add bots in group *Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands *Only admins and sudo can use res, setowner, commands ]], help_text = [[ ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
notcake/vfs
lua/vfs/filesystem/netnode.lua
1
2388
local self = {} VFS.NetNode = VFS.MakeConstructor (self, VFS.INode) function self:ctor (endPoint, name, parentFolder) self.Type = "Net" .. (self:IsFolder () and "Folder" or "File") self.EndPoint = endPoint self.Name = name self.DisplayName = self.Name self.ParentFolder = parentFolder self.ModificationTime = -1 self.PermissionBlock = GAuth.PermissionBlock () self.PermissionBlock:SetParentFunction ( function () if not self:GetParentFolder () then return end return self:GetParentFolder ():GetPermissionBlock () end ) self.PermissionBlock:SetDisplayNameFunction (function () return self:GetDisplayPath () end) self.PermissionBlock:SetNameFunction (function () return self:GetPath () end) self.PermissionBlock:AddEventListener ("PermissionsChanged", self:GetHashCode (), function () self:DispatchEvent ("PermissionsChanged") end) VFS.PermissionBlockNetworker:HookRemoteBlock (self.PermissionBlock) self:AddEventListener ("Deleted", self.UnhookPermissionBlock) end function self:GetDisplayName () return self.DisplayName or self:GetName () end function self:GetModificationTime () return self.ModificationTime end function self:GetName () return self.Name end function self:GetParentFolder () return self.ParentFolder end function self:GetPermissionBlock () return self.PermissionBlock end function self:IsNetNode () return true end function self:Rename (authId, newName, callback) callback = callback or VFS.NullCallback if not self:GetPermissionBlock ():IsAuthorized (authId, "Rename") then callback (VFS.ReturnCode.AccessDenied) return end self:GetParentFolder ():RenameChild (authId, self:GetName (), newName, callback) end function self:SetDisplayName (displayName) if self.DisplayName == displayName then return end self.DisplayName = displayName self:DispatchEvent ("Updated", VFS.UpdateFlags.DisplayName) if self:GetParentFolder () then self:GetParentFolder ():DispatchEvent ("NodeUpdated", self, VFS.UpdateFlags.DisplayName) end end -- Internal, do not call function self:SetModificationTime (modificationTime) if self.ModificationTime == modificationTime then return end self.ModificationTime = modificationTime self:DispatchEvent ("Updated", VFS.UpdateFlags.ModificationTime) if self:GetParentFolder () then self:GetParentFolder ():DispatchEvent ("NodeUpdated", self, VFS.UpdateFlags.ModificationTime) end end
gpl-3.0
bnetcc/darkstar
scripts/zones/Dynamis-Xarcabard/TextIDs.lua
5
2230
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6386; -- Obtained: <item> GIL_OBTAINED = 6387; -- Obtained <number> gil KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem> ANIMATED_KNUCKLES_DIALOG = 7295; -- I am known as the Fists of Mystics. Come, show me your fighting spirit. ANIMATED_DAGGER_DIALOG = 7327; -- I am called the Ornate Blade. Now, show me your strength. ANIMATED_LONGSWORD_DIALOG = 7359; -- People have named me the Holy Blade. I will try thy resolution. ANIMATED_CLAYMORE_DIALOG = 7391; -- I am the Intricate Blade. Show me the depths of your fury! ANIMATED_TABAR_DIALOG = 7423; -- Me, axe. Runaeic, Axe. You, die ANIMATED_GREATAXE_DIALOG = 7455; -- I have been given the title of Seraphic Axe. Will you attempt to survive my love? ANIMATED_SPEAR_DIALOG = 7487; -- I am the Stellar Spear. It is time to test your courage. ANIMATED_SCYTHE_DIALOG = 7519; -- I am known as the Tenebrous Scythe. Overwhelm me with your greed for power. ANIMATED_KUNAI_DIALOG = 7551; -- I am called the Demoniac Blade. Allow me to witness your technique. ANIMATED_TACHI_DIALOG = 7583; -- I am the Divine Blade. I demand a test of your will. ANIMATED_HAMMER_DIALOG = 7615; -- People have named me the Heavenly Hammer. I will test your might to its very limits. ANIMATED_STAFF_DIALOG = 7647; -- I am called the Celestial Staff. I will glimpse into your mind's eye... ANIMATED_LONGBOW_DIALOG = 7679; -- I am known as the Snarled Bow. I will measure the limits of your determination. ANIMATED_GUN_DIALOG = 7711; -- I am known as the Ethereal Rifle. Do you realize my incredible value? ANIMATED_HORN_DIALOG = 7743; -- I am called the Mysterial Horn. Show me your true intentions. ANIMATED_SHIELD_DIALOG = 7775; -- I am Aegis, the impervious shield of everlasting. PRISON_OF_SOULS_HAS_SET_FREE = 7807; -- prison of souls has set free its captive spirits!?Prompt? -- conquest Base CONQUEST_BASE = 7053; -- Tallying conquest results...
gpl-3.0
bnetcc/darkstar
scripts/zones/Windurst_Woods/npcs/Nikkoko.lua
3
1502
----------------------------------- -- Area: Windurst Woods -- NPC: Nikkoko -- Type: Clothcraft Image Support -- !pos -32.810 -3.25 -113.680 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,3); local SkillCap = getCraftSkillCap(player,SKILL_CLOTHCRAFT); local SkillLevel = player:getSkillLevel(SKILL_CLOTHCRAFT); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == false) then player:startEvent(10014,SkillCap,SkillLevel,1,511,player:getGil(),0,4095,0); -- p1 = skill level else player:startEvent(10014,SkillCap,SkillLevel,1,511,player:getGil(),7101,4095,0); end else player:startEvent(10014); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 10014 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,4,1); player:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,1,0,120); end end;
gpl-3.0
bnetcc/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5fn.lua
5
2282
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: North Plate -- !pos 180 -34 71 195 ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local state0 = 8; local state1 = 9; local DoorOffset = npc:getID() - 22; -- _5f1 if (npc:getAnimation() == 8) then state0 = 9; state1 = 8; end -- Gates -- Shiva's Gate GetNPCByID(DoorOffset):setAnimation(state0); GetNPCByID(DoorOffset+1):setAnimation(state0); GetNPCByID(DoorOffset+2):setAnimation(state0); GetNPCByID(DoorOffset+3):setAnimation(state0); GetNPCByID(DoorOffset+4):setAnimation(state0); -- Odin's Gate GetNPCByID(DoorOffset+5):setAnimation(state1); GetNPCByID(DoorOffset+6):setAnimation(state1); GetNPCByID(DoorOffset+7):setAnimation(state1); GetNPCByID(DoorOffset+8):setAnimation(state1); GetNPCByID(DoorOffset+9):setAnimation(state1); -- Leviathan's Gate GetNPCByID(DoorOffset+10):setAnimation(state0); GetNPCByID(DoorOffset+11):setAnimation(state0); GetNPCByID(DoorOffset+12):setAnimation(state0); GetNPCByID(DoorOffset+13):setAnimation(state0); GetNPCByID(DoorOffset+14):setAnimation(state0); -- Titan's Gate GetNPCByID(DoorOffset+15):setAnimation(state1); GetNPCByID(DoorOffset+16):setAnimation(state1); GetNPCByID(DoorOffset+17):setAnimation(state1); GetNPCByID(DoorOffset+18):setAnimation(state1); GetNPCByID(DoorOffset+19):setAnimation(state1); -- Plates -- East Plate GetNPCByID(DoorOffset+20):setAnimation(state0); GetNPCByID(DoorOffset+21):setAnimation(state0); -- North Plate GetNPCByID(DoorOffset+22):setAnimation(state0); GetNPCByID(DoorOffset+23):setAnimation(state0); -- West Plate GetNPCByID(DoorOffset+24):setAnimation(state0); GetNPCByID(DoorOffset+25):setAnimation(state0); -- South Plate GetNPCByID(DoorOffset+26):setAnimation(state0); GetNPCByID(DoorOffset+27):setAnimation(state0); return 0; end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
zeropool/duktape
tests/perf/test-reg-readwrite-plain.lua
19
7981
function test() local a, b, c, d, i; a = 1 b = 2 c = 3 d = 4 for i=1,1e6 do -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b -- 100 a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b a = a; a = b; a = c; a = d; b = a; b = b; b = c; b = d; c = a; c = b end end test()
mit
bnetcc/darkstar
scripts/zones/Korroloka_Tunnel/TextIDs.lua
5
1302
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6380; -- You cannot obtain the item <item> come back again after sorting your inventory. ITEM_OBTAINED = 6386; -- Obtained: <item>. GIL_OBTAINED = 6387; -- Obtained <number> gil. KEYITEM_OBTAINED = 6389; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7047; -- You can't fish here. -- Mining MINING_IS_POSSIBLE_HERE = 7306; -- Mining is possible here if you have -- Quest dialog NOTHING_OUT_OF_ORDINARY = 7325; -- There is nothing out of the ordinary here. SENSE_OF_BOREBODING = 6401; -- You are suddenly overcome with a sense of foreboding... -- Other MORION_WORM_1 = 7327; -- It appears to be a hole made by some kind of animal. Fragments of iron ore are scattered around the area... ENTERED_SPRING = 7322; -- The water in this spring is pleasant and tepid. This looks like a nice place to warm yourself up. LEFT_SPRING_EARLY = 7323; -- You are not warm enough yet. You will need to spend more time than that in the spring to get your body heated up. LEFT_SPRING_CLEAN = 7324; -- Your whole body is piping hot, and the smell of the Rafflesia pollen is gone! -- conquest Base CONQUEST_BASE = 7147; -- Tallying conquest results...
gpl-3.0
bnetcc/darkstar
scripts/zones/San_dOria-Jeuno_Airship/npcs/Nigel.lua
5
2018
----------------------------------- -- Area: San d'Oria-Jeuno Airship -- NPC: Nigel -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/San_dOria-Jeuno_Airship/TextIDs"] = nil; ----------------------------------- require("scripts/zones/San_dOria-Jeuno_Airship/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 3 do vHour = vHour - 6; end local message = WILL_REACH_SANDORIA; if (vHour == -3) then if (vMin >= 10) then vHour = 3; message = WILL_REACH_JEUNO; else vHour = 0; end elseif (vHour == -2) then vHour = 2; message = WILL_REACH_JEUNO; elseif (vHour == -1) then vHour = 1; message = WILL_REACH_JEUNO; elseif (vHour == 0) then if (vMin <= 11) then vHour = 0; message = WILL_REACH_JEUNO; else vHour = 3; end elseif (vHour == 1) then vHour = 2; elseif (vHour == 2) then vHour = 1; end local vMinutes = 0; if (message == WILL_REACH_JEUNO) then vMinutes = (vHour * 60) + 11 - vMin; else -- WILL_REACH_SANDORIA vMinutes = (vHour * 60) + 10 - vMin; end if (vMinutes <= 30) then if ( message == WILL_REACH_SANDORIA) then message = IN_SANDORIA_MOMENTARILY; else -- WILL_REACH_JEUNO message = IN_JEUNO_MOMENTARILY; end elseif (vMinutes < 60) then vHour = 0; end player:messageSpecial( message, math.floor((2.4 * vMinutes) / 60), math.floor( vMinutes / 60 + 0.5)); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Abyssea-Konschtat/mobs/Ypotryll.lua
1
1151
----------------------------------- -- Area: Abyssea - Konschtat (15) -- Mob: Ypotryll ----------------------------------- package.loaded["scripts/globals/abyssea"] = nil; ----------------------------------- require("scripts/zones/Abyssea-Konschtat/textIDs"); require("scripts/globals/abyssea"); require("scripts/globals/status"); ----------------------------------- -- onMobInitialize ----------------------------------- function onMobInitialize(mob) end; ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) -- local result = DoCruor(killer,result); -- DoExp(killer,bonus); -- DoLights(mob,killer); -- PyxisSpawn(mob,killer,npc); -- player:messageSpecial(CRUOR_OBTAINED,result); end;
gpl-3.0
OpenPrograms/Plan9k
plan9k-extra/robot.lua
3
6617
local component = require("component") local sides = require("sides") local robot = {} ------------------------------------------------------------------------------- -- General function robot.name() return component.robot.name() end function robot.level() if component.isAvailable("experience") then return component.experience.level() else return 0 end end function robot.getLightColor() return component.robot.getLightColor() end function robot.setLightColor(value) return component.robot.setLightColor(value) end ------------------------------------------------------------------------------- -- World function robot.detect() return component.robot.detect(sides.front) end function robot.detectUp() return component.robot.detect(sides.up) end function robot.detectDown() return component.robot.detect(sides.down) end ------------------------------------------------------------------------------- -- Inventory function robot.inventorySize() return component.robot.inventorySize() end function robot.select(...) return component.robot.select(...) end function robot.count(...) return component.robot.count(...) end function robot.space(...) return component.robot.space(...) end function robot.compareTo(...) return component.robot.compareTo(...) end function robot.transferTo(...) return component.robot.transferTo(...) end ------------------------------------------------------------------------------- -- Inventory + World function robot.compare() return component.robot.compare(sides.front) end function robot.compareUp() return component.robot.compare(sides.up) end function robot.compareDown() return component.robot.compare(sides.down) end function robot.drop(count) checkArg(1, count, "nil", "number") return component.robot.drop(sides.front, count) end function robot.dropUp(count) checkArg(1, count, "nil", "number") return component.robot.drop(sides.up, count) end function robot.dropDown(count) checkArg(1, count, "nil", "number") return component.robot.drop(sides.down, count) end function robot.place(side, sneaky) checkArg(1, side, "nil", "number") return component.robot.place(sides.front, side, sneaky ~= nil and sneaky ~= false) end function robot.placeUp(side, sneaky) checkArg(1, side, "nil", "number") return component.robot.place(sides.up, side, sneaky ~= nil and sneaky ~= false) end function robot.placeDown(side, sneaky) checkArg(1, side, "nil", "number") return component.robot.place(sides.down, side, sneaky ~= nil and sneaky ~= false) end function robot.suck(count) checkArg(1, count, "nil", "number") return component.robot.suck(sides.front, count) end function robot.suckUp(count) checkArg(1, count, "nil", "number") return component.robot.suck(sides.up, count) end function robot.suckDown(count) checkArg(1, count, "nil", "number") return component.robot.suck(sides.down, count) end ------------------------------------------------------------------------------- -- Tool function robot.durability() return component.robot.durability() end function robot.swing(side, sneaky) checkArg(1, side, "nil", "number") return component.robot.swing(sides.front, side, sneaky ~= nil and sneaky ~= false) end function robot.swingUp(side, sneaky) checkArg(1, side, "nil", "number") return component.robot.swing(sides.up, side, sneaky ~= nil and sneaky ~= false) end function robot.swingDown(side, sneaky) checkArg(1, side, "nil", "number") return component.robot.swing(sides.down, side, sneaky ~= nil and sneaky ~= false) end function robot.use(side, sneaky, duration) checkArg(1, side, "nil", "number") checkArg(3, duration, "nil", "number") return component.robot.use(sides.front, side, sneaky ~= nil and sneaky ~= false, duration) end function robot.useUp(side, sneaky, duration) checkArg(1, side, "nil", "number") checkArg(3, duration, "nil", "number") return component.robot.use(sides.up, side, sneaky ~= nil and sneaky ~= false, duration) end function robot.useDown(side, sneaky, duration) checkArg(1, side, "nil", "number") checkArg(3, duration, "nil", "number") return component.robot.use(sides.down, side, sneaky ~= nil and sneaky ~= false, duration) end ------------------------------------------------------------------------------- -- Movement function robot.forward() return component.robot.move(sides.front) end function robot.back() return component.robot.move(sides.back) end function robot.up() return component.robot.move(sides.up) end function robot.down() return component.robot.move(sides.down) end function robot.turnLeft() return component.robot.turn(false) end function robot.turnRight() return component.robot.turn(true) end function robot.turnAround() local turn = math.random() < 0.5 and robot.turnLeft or robot.turnRight return turn() and turn() end ------------------------------------------------------------------------------- -- Tank function robot.tankCount() return component.robot.tankCount() end function robot.selectTank(tank) return component.robot.selectTank(tank) end function robot.tankLevel(...) return component.robot.tankLevel(...) end function robot.tankSpace(...) return component.robot.tankSpace(...) end function robot.compareFluidTo(...) return component.robot.compareFluidTo(...) end function robot.transferFluidTo(...) return component.robot.transferFluidTo(...) end ------------------------------------------------------------------------------- -- Tank + World function robot.compareFluid() return component.robot.compareFluid(sides.front) end function robot.compareFluidUp() return component.robot.compareFluid(sides.up) end function robot.compareFluidDown() return component.robot.compareFluid(sides.down) end function robot.drain(count) checkArg(1, count, "nil", "number") return component.robot.drain(sides.front, count) end function robot.drainUp(count) checkArg(1, count, "nil", "number") return component.robot.drain(sides.up, count) end function robot.drainDown(count) checkArg(1, count, "nil", "number") return component.robot.drain(sides.down, count) end function robot.fill(count) checkArg(1, count, "nil", "number") return component.robot.fill(sides.front, count) end function robot.fillUp(count) checkArg(1, count, "nil", "number") return component.robot.fill(sides.up, count) end function robot.fillDown(count) checkArg(1, count, "nil", "number") return component.robot.fill(sides.down, count) end ------------------------------------------------------------------------------- return robot
mit
mwoz123/koreader
frontend/luxl.lua
9
17425
--[[ This code was derived from the pico_xml project which can be found here: http://kd7yhr.org/bushbo/pico_xml.md The original C code, written by: Brian O. Bush Pure Lua Version written by: William A Adams Dramatic Speed Improvements by: Robert G Jakabosky https://github.com/Wiladams/LAPHLibs/blob/master/laphlibs/luxl.lua References http://www.faqs.org/rfcs/rfc3076.html http://www.w3.org/TR/REC-xml/ ]] local ffi = require "ffi" local bit = require "bit" local band = bit.band --[[ Types of characters; 0 is not valid 1 is letters, 2 are digits (including '.') 3 whitespace --]] local char_type = ffi.new("const int[256]", { 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }); -- Internal states that the parser can be in at any given time. local ST_START = 0; -- starting base state; default state local ST_TEXT =1; -- text state local ST_START_TAG = 2; -- start tag state local ST_START_TAGNAME =3; -- start tagname state local ST_START_TAGNAME_END =4; -- start tagname ending state local ST_END_TAG =5; -- end tag state local ST_END_TAGNAME=6; -- end tag tagname state local ST_END_TAGNAME_END=7; -- end tag tagname ending local ST_EMPTY_TAG=8; -- empty tag state local ST_SPACE=9; -- linear whitespace state local ST_ATTR_NAME=10; -- attribute name state local ST_ATTR_NAME_END=11; -- attribute name ending state local ST_ATTR_VAL=12; -- attribute value starting state local ST_ATTR_VAL2=13; -- attribute value state local ST_ERROR=14; -- error state -- character classes that we will match against; This could be expanded if -- need be, however, we are aiming for simple. local CCLASS_NONE = 0; -- matches nothing; a base state local CCLASS_LEFT_ANGLE=1; -- matches start tag '<' local CCLASS_SLASH=2; -- matches forward slash local CCLASS_RIGHT_ANGLE=3; -- matches end tag '>' local CCLASS_EQUALS=4; -- matches equals sign local CCLASS_QUOTE=5; -- matches double-quotes local CCLASS_LETTERS=6; -- matches a-zA-Z letters and digits 0-9 local CCLASS_SPACE=7; -- matches whitespace local CCLASS_ANY=8; -- matches any ASCII character; will match all above classes -- Types of events: start element, end element, text, attr name, attr -- val and start/end document. Other events can be ignored! local EVENT_START = 0; -- Start tag local EVENT_END = 1; -- End tag local EVENT_TEXT = 2; -- Text local EVENT_ATTR_NAME = 3; -- Attribute name local EVENT_ATTR_VAL = 4; -- Attribute value local EVENT_END_DOC = 5; -- End of document local EVENT_MARK = 6; -- Internal only; notes position in buffer local EVENT_NONE = 7; -- Internal only; should never see this event local entity_refs = { ["&lt;"] = '<', ["&gt;"] = '>', ["&amp;"] = '&', ["&apos;"] = '\'', ["&quot;"] = '"', } -- Map constant values to constant names. local STATE_NAMES = { [ST_START] = "ST_START", [ST_TEXT] = "ST_TEXT", [ST_START_TAG] = "ST_START_TAG", [ST_START_TAGNAME] = "ST_START_TAGNAME", [ST_START_TAGNAME_END] = "ST_START_TAGNAME_END", [ST_END_TAG] = "ST_END_TAG", [ST_END_TAGNAME] = "ST_END_TAGNAME", [ST_END_TAGNAME_END] = "ST_END_TAGNAME_END", [ST_EMPTY_TAG] = "ST_EMPTY_TAG", [ST_SPACE] = "ST_SPACE", [ST_ATTR_NAME] = "ST_ATTR_NAME", [ST_ATTR_NAME_END] = "ST_ATTR_NAME_END", [ST_ATTR_VAL] = "ST_ATTR_VAL", [ST_ATTR_VAL2] = "ST_ATTR_VAL2", [ST_ERROR] = "ST_ERROR", } --[[ State transition table element; contains: (1) current state, (2) clazz that must match, (3) next state if we match, and (4) event that is emitted upon match. --]] -- Note: States must be grouped in match order AND grouped together! local LEXER_STATES = { -- [0-2] starting state, which also serves as the default state in case of error { state = ST_START, cclass = CCLASS_SPACE, next_state = ST_SPACE, event = EVENT_NONE }, { state = ST_START, cclass = CCLASS_LEFT_ANGLE, next_state = ST_START_TAG, event = EVENT_NONE }, { state = ST_START, cclass = CCLASS_ANY, next_state = ST_TEXT, event = EVENT_MARK }, -- [3-5] space state handles linear white space { state = ST_SPACE, cclass = CCLASS_SPACE, next_state = ST_SPACE, event = EVENT_NONE }, { state = ST_SPACE, cclass = CCLASS_LEFT_ANGLE, next_state = ST_START_TAG, event = EVENT_TEXT }, { state = ST_SPACE, cclass = CCLASS_ANY, next_state = ST_TEXT, event = EVENT_MARK }, -- [6-8] handle start tag { state = ST_START_TAG, cclass = CCLASS_LETTERS, next_state = ST_START_TAGNAME, event = EVENT_MARK }, { state = ST_START_TAG, cclass = CCLASS_SLASH, next_state = ST_END_TAG, event = EVENT_MARK }, { state = ST_START_TAG, cclass = CCLASS_SPACE, next_state = ST_START_TAG, event = EVENT_NONE }, -- < tag > -- [9-12] handle start tag name { state = ST_START_TAGNAME, cclass = CCLASS_LETTERS, next_state = ST_START_TAGNAME, event = EVENT_NONE }, { state = ST_START_TAGNAME, cclass = CCLASS_SPACE, next_state = ST_START_TAGNAME_END, event = EVENT_START }, { state = ST_START_TAGNAME, cclass = CCLASS_SLASH, next_state = ST_EMPTY_TAG, event = EVENT_END }, { state = ST_START_TAGNAME, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_START }, -- [13-16] handle start tag name end { state = ST_START_TAGNAME_END, cclass = CCLASS_LETTERS, next_state = ST_ATTR_NAME, event = EVENT_MARK }, { state = ST_START_TAGNAME_END, cclass = CCLASS_SPACE, next_state = ST_START_TAGNAME_END, event = EVENT_NONE }, { state = ST_START_TAGNAME_END, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_START }, { state = ST_START_TAGNAME_END, cclass = CCLASS_SLASH, next_state = ST_EMPTY_TAG, event = EVENT_MARK }, -- Empty tag <br /> -- [17] handle empty tags, e.g., <br /> { state = ST_EMPTY_TAG, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_END }, -- Empty tag <br /> -- [18] handle end tag, e.g., <tag /> { state = ST_END_TAG, cclass = CCLASS_LETTERS, next_state = ST_END_TAGNAME, event = EVENT_NONE }, -- [19-21] handle end tag name { state = ST_END_TAGNAME, cclass = CCLASS_LETTERS, next_state = ST_END_TAGNAME, event = EVENT_NONE }, { state = ST_END_TAGNAME, cclass = CCLASS_RIGHT_ANGLE, next_state = ST_START, event = EVENT_END }, { state = ST_END_TAGNAME, cclass = CCLASS_SPACE, next_state = ST_END_TAGNAME_END, event = EVENT_END }, -- space after end tag name </br > -- [22-23] handle ending of end tag name { state = ST_END_TAGNAME_END, cclass = CCLASS_SPACE, next_state = ST_END_TAGNAME_END, event = EVENT_NONE }, { state = ST_END_TAGNAME_END, cclass = CCLASS_RIGHT_ANGLE,next_state = ST_START, event = EVENT_NONE }, -- [24-26] handle text { state = ST_TEXT, cclass = CCLASS_SPACE, next_state = ST_SPACE, event = EVENT_NONE }, { state = ST_TEXT, cclass = CCLASS_LEFT_ANGLE, next_state = ST_START_TAG, event = EVENT_TEXT }, { state = ST_TEXT, cclass = CCLASS_ANY, next_state = ST_TEXT, event = EVENT_NONE }, -- [27-29] handle attribute names { state = ST_ATTR_NAME, cclass = CCLASS_LETTERS, next_state = ST_ATTR_NAME, event = EVENT_MARK }, { state = ST_ATTR_NAME, cclass = CCLASS_SPACE, next_state = ST_ATTR_NAME_END, event = EVENT_ATTR_NAME }, -- space before '=' sign { state = ST_ATTR_NAME, cclass = CCLASS_EQUALS, next_state = ST_ATTR_VAL, event = EVENT_ATTR_NAME }, -- <tag attr ="2"> -- [30-32] attribute name end { state = ST_ATTR_NAME_END, cclass = CCLASS_SPACE, next_state = ST_ATTR_NAME_END, event = EVENT_NONE }, { state = ST_ATTR_NAME_END, cclass = CCLASS_LETTERS, next_state = ST_ATTR_NAME, event = EVENT_MARK }, { state = ST_ATTR_NAME_END, cclass = CCLASS_EQUALS, next_state = ST_ATTR_VAL, event = EVENT_NONE }, -- [33-34] handle attribute values, initial quote and spaces { state = ST_ATTR_VAL, cclass = CCLASS_QUOTE, next_state = ST_ATTR_VAL2, event = EVENT_NONE }, { state = ST_ATTR_VAL, cclass = CCLASS_SPACE, next_state = ST_ATTR_VAL, event = EVENT_NONE }, -- initial spaces before quoted attribute value -- [35-37] handle actual attribute values { state = ST_ATTR_VAL2, cclass = CCLASS_QUOTE, next_state = ST_START_TAGNAME_END, event = EVENT_ATTR_VAL }, { state = ST_ATTR_VAL2, cclass = CCLASS_LETTERS, next_state = ST_ATTR_VAL2, event = EVENT_MARK }, { state = ST_ATTR_VAL2, cclass = CCLASS_SLASH, next_state = ST_ATTR_VAL2, event = EVENT_MARK }, -- [38] End of table marker { state = ST_ERROR, cclass = CCLASS_NONE, next_state = ST_ERROR, event = EVENT_NONE } }; ffi.cdef[[ struct parse_state { const char* buf; /* reference to buffer */ int bufsz; /* size of buf */ int mark; int i; int ix; /* index into buffer */ }; ]] local cclass_match = { [CCLASS_LETTERS] = "(ctype == 1 or ctype == 2)", [CCLASS_LEFT_ANGLE] = "(c == T_LT)", [CCLASS_SLASH] = "(c == T_SLASH)", [CCLASS_RIGHT_ANGLE] = "(c == T_GT)", [CCLASS_EQUALS] = "(c == T_EQ)", [CCLASS_QUOTE] = "(c == T_QUOTE)", [CCLASS_SPACE] = "(ctype == 3)", [CCLASS_ANY] = "true", } local STATES = {} local STATE_FUNCS = {} local function next_char(ps, state, verbose) local i = ps.ix if i >= ps.bufsz then return EVENT_END_DOC, 0, i, state end ps.i = i local c = band(ps.buf[i], 0xff); ps.ix = i + 1 if verbose then verbose(i, STATE_FUNCS[state], c) end -- run state function to find next state. return state(ps, c, verbose) end local fsm_code = '' local function code(...) for i=1,select("#", ...) do fsm_code = fsm_code .. tostring(select(i, ...)) end end code[[ local STATES, next_char, char_type = ... local T_LT = string.byte('<') local T_SLASH = string.byte('/') local T_GT = string.byte('>') local T_EQ = string.byte('=') local T_QUOTE = string.byte('"') ]] -- pre-define locals for state functions. for i=0,#STATE_NAMES do local name = STATE_NAMES[i] code('local ', name, '_f\n') end -- group LEXER states. for i=1,#LEXER_STATES do local p_state = LEXER_STATES[i] local state = STATES[p_state.state] local cclasses if not state then cclasses = {} state = { state = p_state.state, cclasses = cclasses } STATES[p_state.state] = state else cclasses = state.cclasses end cclasses[#cclasses + 1] = p_state end local function gen_cclass_code(prefix, cclass) local next_state = STATE_NAMES[cclass.next_state] if cclass.event == EVENT_MARK then code(prefix, "if(ps.mark == 0) then ps.mark = ps.i end -- mark the position\n") elseif cclass.event ~= EVENT_NONE then code(prefix, "if(ps.mark > 0) then\n") code(prefix,' return ', cclass.event,', ',next_state,'_f\n') code(prefix, "end\n") end code(prefix,'return next_char(ps, ', next_state,'_f, verbose)\n') end -- generate state functions. for i=0,#STATE_NAMES do local name = STATE_NAMES[i] local state = STATES[i] local cclasses = state.cclasses code('function ', name, '_f(ps, c, verbose)\n') code(' local ctype = char_type[c]\n') local has_any for i=1,#cclasses do local cclass = cclasses[i] local id = cclass.cclass local condition = cclass_match[id] if id == CCLASS_ANY then has_any = cclass elseif i == 1 then code(' if ', condition, ' then\n') gen_cclass_code(' ', cclass) else code(' elseif ', condition, ' then\n') gen_cclass_code(' ', cclass) end end code(' end\n') -- catch-all for cclass_any or goto error state. if has_any then gen_cclass_code(' ', has_any) else -- exit from FSM on error. code(' return nil, ',name,'_f, c\n') end code('end\n') -- map state id to state function code('STATES[', i, '] = ', name, '_f\n') -- reverse map state function to state id code('STATES[', name, '_f] = ', i, '\n') end -- Compile FSM code local state_funcs = assert(loadstring(fsm_code, "luxl FSM code")) state_funcs(STATE_FUNCS, next_char, char_type) fsm_code = nil local luxl = { EVENT_START = EVENT_START; -- Start tag EVENT_END = EVENT_END; -- End tag EVENT_TEXT = EVENT_TEXT; -- Text EVENT_ATTR_NAME = EVENT_ATTR_NAME; -- Attribute name EVENT_ATTR_VAL = EVENT_ATTR_VAL; -- Attribute value EVENT_END_DOC = EVENT_END_DOC; -- End of document EVENT_MARK = EVENT_MARK; -- Internal only; notes position in buffer EVENT_NONE = EVENT_NONE; -- Internal only; should never see this event } local luxl_mt = { __index = luxl } function luxl.new(buffer, bufflen) local newone = { buf = ffi.cast("const uint8_t *", buffer); -- pointer to "uint8_t *" buffer (0 based) bufsz = bufflen; -- size of input buffer state = ST_START; -- current state event = EVENT_NONE; -- current event err = 0; -- number of errors thus far markix = 0; -- offset of current item of interest marksz = 0; -- size of current item of interest MsgHandler = nil; -- Routine to handle messages ErrHandler = nil; -- Routine to call when there's an error EventHandler = nil; ps = ffi.new('struct parse_state', { buf = buffer, bufsz = bufflen, mark = 0, i = 0, ix = 0, }), } setmetatable(newone, luxl_mt); return newone; end function luxl:Reset(buffer, bufflen) self.buf = buffer -- pointer to "uint8_t *" buffer (0 based) self.bufsz = bufflen -- size of input buffer self.state = ST_START -- current state self.event = EVENT_NONE -- current event self.err = 0 -- number of errors thus far self.markix = 0 -- offset of current item of interest self.marksz = 0 -- size of current item of interest local ps = self.ps ps.buf = buffer ps.bufsz = bufflen ps.mark = 0 ps.i = 0 ps.ix = 0 end function luxl:SetMessageHandler(handler) self.MsgHandler = handler; end --[[ GetNext is responsible for moving through the stream of characters. At the moment, it's fairly naive in terms of character encodings. In a more robust implementation, luxl will read from a stream, which knows about the specific encoding, and will hand out code points based on that particular encoding. So, only straight ASCII for the moment. Returns event type, starting offset, size --]] function luxl:GetNext() local event, state_f, c local ps = self.ps ps.mark = 0 state_f = STATE_FUNCS[self.state] repeat event, state_f, c = next_char(ps, state_f, self.MsgHandler) -- update state id. self.state = STATE_FUNCS[state_f] if not event then -- handle error -- default to start state self.err = self.err + 1; if self.ErrHandler then self.ErrHandler(ps.i, self.state, c); end end until event -- basically we are guaranteed never to have an event of -- type EVENT_MARK or EVENT_NONE here. self.event = event local markix = ps.mark local marksz = ps.i-ps.mark self.markix = markix self.marksz = marksz if(self.EventHandler) then self.EventHandler(event, markix, marksz) end return event, markix, marksz end function luxl:Lexemes() return function() local event, offset, size = self:GetNext(); if(event == EVENT_END_DOC) then return nil; else return event, offset, size; end end end return luxl
agpl-3.0
bnetcc/darkstar
scripts/zones/Port_Windurst/npcs/Kameel.lua
1
2084
----------------------------------- -- Area: Port Windurst -- NPC: Kameel -- Type: Standard NPC ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Windurst/TextIDs"); require("scripts/globals/teleports"); require("scripts/globals/settings"); require("scripts/globals/msg"); ----------------------------------- function onTrade(player,npc,trade) if (TRAVEL_SKIP >= 1) then if (trade:getGil() >= TRAVEL_SKIP and trade:getItemCount() == 1) then player:PrintToPlayer(string.format("eye's the %d gil.. ", TRAVEL_SKIP), chatType.EMOTION, npc:getName()); player:PrintToPlayer("Well..I guess I can let you aboard the express freight Vessel.. ", chatType.SAY, npc:getName()); if (player:hasKeyItem(AIRSHIP_PASS)) then player:delGil(TRAVEL_SKIP); -- player:setPos(16,12,-120,192,246); player:addStatusEffectEx(EFFECT_COMMUTE,0,COMMUTE.AISHIP_TO_JEUNO_W,0,2); else player:setVar("HasDoorHacked", player:getVar("HasDoorHacked") +1); print(player:getName() .. " tried to TRAVEL_SKIP an airship but didn't have a Airship Pass.."); player:PrintToPlayer("Wait a minute, You don't have a AIRSHIP PASS, how'd you even get through the door?.. ", chatType.SAY, npc:getName()); end end end end; function onTrigger(player,npc) local vHour = VanadielHour(); local vMin = VanadielMinute(); while vHour >= 4 do vHour = vHour - 6; end if ( vHour == -2) then vHour = 4; elseif ( vHour == -1) then vHour = 5; end local seconds = math.floor(2.4 * ((vHour * 60) + vMin)); player:startEvent( 193, seconds, 0, 0, 0, 0, 0, 0, 0); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Evsdd/domoticz
dzVents/runtime/device-adapters/scene_device.lua
6
1104
local TimedCommand = require('TimedCommand') return { baseType = 'scene', name = 'Scene device adapter', matches = function(device, adapterManager) local res = (device.baseType == 'scene') if (not res) then adapterManager.addDummyMethod(device, 'switchOn') adapterManager.addDummyMethod(device, 'switchOff') end return res end, process = function(scene, data, domoticz, utils, adapterManager) scene.isScene = true function scene.setState(newState) -- generic state update method return domoticz.setScene(scene.name, newState) end function scene.switchOn() return TimedCommand(domoticz, 'Scene:' .. scene.name, 'On', 'device', scene.state) end function scene.switchOff() return TimedCommand(domoticz, 'Scene:' .. scene.name, 'Off', 'device', scene.state) end function scene.devices() local subData = {} local ids = data.deviceIDs ~= nil and data.deviceIDs or {} for i, id in pairs(ids) do subData[i] = domoticz._getItemFromData('device', id) end return domoticz._setIterators({}, true, 'device', false , subData) end end }
gpl-3.0
bnetcc/darkstar
scripts/zones/Norg/npcs/Keal.lua
5
4086
----------------------------------- -- Area: Norg -- NPC: Keal -- Starts and Ends Quest: It's Not Your Vault ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Norg/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); local path = { -5.453587, 0.151494, -16.361458, -5.997250, 0.229052, -15.475480, -6.582538, 0.317294, -14.524694, -7.573528, 0.365118, -12.941586, -7.069273, 0.384884, -13.867216, -6.565747, 0.311785, -14.741985, -5.676943, 0.173223, -16.241194, -5.162223, 0.020922, -17.108603, -4.725273, -0.022554, -18.175083, -4.882753, -0.041670, -19.252790, -5.294413, 0.020847, -20.336269, -5.632565, 0.112649, -21.417961, -5.905818, 0.202903, -22.541668, -5.657803, 0.116744, -21.445057, -5.273734, 0.023316, -20.410303, -4.831870, -0.049031, -19.478870, -4.749702, -0.024804, -18.311924, -5.152854, 0.002354, -17.248878, -5.639069, 0.185855, -16.335281, -6.158780, 0.247668, -15.445805, -7.253261, 0.405026, -13.567613, -7.803670, 0.348802, -12.626184, -8.375298, 0.223101, -11.645775, -8.895057, 0.076541, -10.770375, -9.384287, 0.015579, -9.884774, -9.939011, 0.143451, -8.935238, -9.422630, -0.025280, -9.816562, -8.589481, 0.151451, -11.248314, -8.095008, 0.275576, -12.123538, -7.561854, 0.373715, -13.045633, -5.644930, 0.185392, -16.292952, -5.058481, -0.014674, -17.285294, -4.724863, -0.024709, -18.265087, -4.923457, -0.042915, -19.378429, -5.293544, 0.020505, -20.338196, -5.606711, 0.104830, -21.323364, -5.849701, 0.183865, -22.302536, -5.586438, 0.097169, -21.222555, -5.214560, 0.046522, -20.280220, -4.779529, -0.048305, -19.351633, -4.757209, -0.021693, -18.194023, -5.138152, -0.000450, -17.254173, -5.685457, 0.173866, -16.248564, -6.275849, 0.266052, -15.243981, -7.196375, 0.403362, -13.666089, -7.766060, 0.352119, -12.689950, -8.280642, 0.241637, -11.799251, -8.828505, 0.098458, -10.895535, -9.351592, 0.039748, -9.948843, -9.856394, 0.036026, -9.068656 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); -- onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; function onTrade(player,npc,trade) end; function onTrigger(player,npc) local Vault = player:getQuestStatus(OUTLANDS,ITS_NOT_YOUR_VAULT); local mLvl = player:getMainLvl(); local IronBox = player:hasKeyItem(SEALED_IRON_BOX); if (Vault == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3 and mLvl >= 5) then player:startEvent(36,SEALED_IRON_BOX); -- Start quest elseif (Vault == QUEST_ACCEPTED) then if (IronBox == true) then player:startEvent(38); -- Finish quest else player:startEvent(37,MAP_OF_THE_SEA_SERPENT_GROTTO); -- Reminder/Directions Dialogue end elseif (Vault == QUEST_COMPLETED) then player:startEvent(39); -- New Standard Dialogue for everyone who has completed the quest else player:startEvent(89); -- Standard Conversation end npc:wait(); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 36 and option == 1) then player:addQuest(OUTLANDS,ITS_NOT_YOUR_VAULT); elseif (csid == 38) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4961); else player:delKeyItem(SEALED_IRON_BOX); player:addItem(4961); -- Scroll of Tonko: Ichi player:messageSpecial(ITEM_OBTAINED, 4961); player:addFame(NORG,50); player:completeQuest(OUTLANDS,ITS_NOT_YOUR_VAULT); end end npc:wait(0); end;
gpl-3.0
motherfscker/minetest_game
mods/sfinv/api.lua
3
4280
sfinv = { pages = {}, pages_unordered = {}, contexts = {}, enabled = true } function sfinv.register_page(name, def) assert(name, "Invalid sfinv page. Requires a name") assert(def, "Invalid sfinv page. Requires a def[inition] table") assert(def.get, "Invalid sfinv page. Def requires a get function.") assert(not sfinv.pages[name], "Attempt to register already registered sfinv page " .. dump(name)) sfinv.pages[name] = def def.name = name table.insert(sfinv.pages_unordered, def) end function sfinv.override_page(name, def) assert(name, "Invalid sfinv page override. Requires a name") assert(def, "Invalid sfinv page override. Requires a def[inition] table") local page = sfinv.pages[name] assert(page, "Attempt to override sfinv page " .. dump(name) .. " which does not exist.") for key, value in pairs(def) do page[key] = value end end function sfinv.get_nav_fs(player, context, nav, current_idx) -- Only show tabs if there is more than one page if #nav > 1 then return "tabheader[0,0;tabs;" .. table.concat(nav, ",") .. ";" .. current_idx .. ";true;false]" else return "" end end local theme_main = "bgcolor[#080808BB;true]" .. default.gui_bg .. default.gui_bg_img local theme_inv = default.gui_slots .. [[ list[current_player;main;0,4.7;8,1;] list[current_player;main;0,5.85;8,3;8] ]] function sfinv.make_formspec(player, context, content, show_inv, size) local tmp = { size or "size[8,8.6]", theme_main, sfinv.get_nav_fs(player, context, context.nav_titles, context.nav_idx), content } if show_inv then tmp[#tmp + 1] = theme_inv end return table.concat(tmp, "") end function sfinv.get_homepage_name(player) return "sfinv:crafting" end function sfinv.get_formspec(player, context) -- Generate navigation tabs local nav = {} local nav_ids = {} local current_idx = 1 for i, pdef in pairs(sfinv.pages_unordered) do if not pdef.is_in_nav or pdef:is_in_nav(player, context) then nav[#nav + 1] = pdef.title nav_ids[#nav_ids + 1] = pdef.name if pdef.name == context.page then current_idx = i end end end context.nav = nav_ids context.nav_titles = nav context.nav_idx = current_idx -- Generate formspec local page = sfinv.pages[context.page] or sfinv.pages["404"] if page then return page:get(player, context) else local old_page = context.page context.page = sfinv.get_homepage_name(player) assert(sfinv.pages[context.page], "[sfinv] Invalid homepage") minetest.log("warning", "[sfinv] Couldn't find " .. dump(old_page) .. " so using switching to homepage") return sfinv.get_formspec(player, context) end end function sfinv.set_player_inventory_formspec(player, context) if not context then local name = player:get_player_name() context = sfinv.contexts[name] if not context then context = { page = sfinv.get_homepage_name(player) } sfinv.contexts[name] = context end end local fs = sfinv.get_formspec(player, context) player:set_inventory_formspec(fs) end minetest.register_on_joinplayer(function(player) if sfinv.enabled then minetest.after(0.5, function() sfinv.set_player_inventory_formspec(player) end) end end) minetest.register_on_leaveplayer(function(player) sfinv.contexts[player:get_player_name()] = nil end) minetest.register_on_player_receive_fields(function(player, formname, fields) if formname ~= "" or not sfinv.enabled then return false end -- Get Context local name = player:get_player_name() local context = sfinv.contexts[name] if not context then sfinv.set_player_inventory_formspec(player) return false end -- Handle Events if fields.tabs and context.nav then local tid = tonumber(fields.tabs) if tid and tid > 0 then local id = context.nav[tid] local page = sfinv.pages[id] if id and page then local oldpage = sfinv.pages[context.page] if oldpage and oldpage.on_leave then oldpage:on_leave(player, context) end context.page = id if page.on_enter then page:on_enter(player, context) end sfinv.set_player_inventory_formspec(player, context) end end return end -- Pass to page local page = sfinv.pages[context.page] if page and page.on_player_receive_fields then return page:on_player_receive_fields(player, context, fields) end end)
lgpl-2.1
bnetcc/darkstar
scripts/zones/Metalworks/npcs/Mythily.lua
5
1813
----------------------------------- -- Area: Metalworks -- NPC: Mythily -- Type: Immigration NPC -- !pos 94 -20 -8 237 ----------------------------------- require("scripts/globals/conquest"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local new_nation = NATION_BASTOK; local old_nation = player:getNation(); local rank = getNationRank(new_nation); if (old_nation == new_nation) then player:startEvent(362,0,0,0,old_nation); elseif (player:getCurrentMission(old_nation) ~= 255 or player:getVar("MissionStatus") ~= 0) then player:startEvent(361,0,0,0,new_nation); elseif (old_nation ~= new_nation) then local has_gil = 0; local cost = 0; if (rank == 1) then cost = 40000; elseif (rank == 2) then cost = 12000; elseif (rank == 3) then cost = 4000; end if (player:getGil() >= cost) then has_gil = 1 end player:startEvent(360,0,1,player:getRank(),new_nation,has_gil,cost); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 360 and option == 1) then local new_nation = NATION_BASTOK; local rank = getNationRank(new_nation); local cost = 0; if (rank == 1) then cost = 40000; elseif (rank == 2) then cost = 12000; elseif (rank == 3) then cost = 4000; end player:setNation(new_nation) player:setGil(player:getGil() - cost); player:setRankPoints(0); end end;
gpl-3.0
notcake/vfs
lua/vfs/ui/folderlistview.lua
1
15382
local self = {} --[[ Events: FolderChanged (IFolder folder) Fired when the selected folder has changed. NodeOpened (INode node) Fired when a file or folder is double clicked. SelectedFileChanged (IFile file) Fired when a file is selected from the list. SelectedFolderChanged (IFolder folder) Fired when a folder is selected from the list. SelectedNodeChanged (INode node) Fired when a file or folder is selected from the list. ]] function self:Init () self.Folder = nil self.ChildNodes = {} self.HookedNodes = {} -- IFolders whose PermissionsChanged event have been hooked self.LastAccess = false self.LastReadAccess = false self.ShowParentFolder = false self.ParentFolderItem = nil self:AddColumn ("Name") :SetComparator ( function (a, b) return self.DefaultComparator (a, b) end ) self:AddColumn ("Size") :SetAlignment (6) :SetWidth (80) :SetComparator ( function (a, b) -- Put folders at the top if a == b then return false end if a.Node:IsFolder () and not b.Node:IsFolder () then return true end if b.Node:IsFolder () and not a.Node:IsFolder () then return false end return a.Size < b.Size end ) self:AddColumn ("Last Modified") :SetWidth (192) :SetComparator ( function (a, b) -- Put folders at the top if a == b then return false end if a.Node:IsFolder () and not b.Node:IsFolder () then return true end if b.Node:IsFolder () and not a.Node:IsFolder () then return false end return a.LastModified < b.LastModified end ) self.Menu = Gooey.Menu () self.Menu:AddEventListener ("MenuOpening", function (_, targetItem) local targetItem = self:GetSelectedNodes () self.Menu:SetTargetItem (targetItem) self.Menu:GetItemById ("Permissions"):SetEnabled (#targetItem ~= 0) if self.Folder and self.Folder:IsFolder () then local permissionBlock = self.Folder:GetPermissionBlock () if not permissionBlock then self.Menu:GetItemById ("Copy") :SetEnabled (#targetItem ~= 0) self.Menu:GetItemById ("Paste") :SetEnabled (true) self.Menu:GetItemById ("Create Folder"):SetEnabled (true) self.Menu:GetItemById ("Delete") :SetEnabled (#targetItem ~= 0 and targetItem [1]:CanDelete ()) self.Menu:GetItemById ("Rename") :SetEnabled (#targetItem ~= 0) else self.Menu:GetItemById ("Copy") :SetEnabled (#targetItem ~= 0 and (permissionBlock:IsAuthorized (GAuth.GetLocalId (), "Read") or permissionBlock:IsAuthorized (GAuth.GetLocalId (), "View Folder"))) self.Menu:GetItemById ("Paste") :SetEnabled (VFS.Clipboard:CanPaste (self.Folder)) self.Menu:GetItemById ("Create Folder"):SetEnabled (not permissionBlock or permissionBlock:IsAuthorized (GAuth.GetLocalId (), "Create Folder")) self.Menu:GetItemById ("Delete") :SetEnabled (#targetItem ~= 0 and targetItem [1]:CanDelete () and (not targetItem [1]:GetPermissionBlock () or targetItem [1]:GetPermissionBlock ():IsAuthorized (GAuth.GetLocalId (), "Delete"))) self.Menu:GetItemById ("Rename") :SetEnabled (#targetItem ~= 0 and (not targetItem [1]:GetPermissionBlock () or targetItem [1]:GetPermissionBlock ():IsAuthorized (GAuth.GetLocalId (), "Rename"))) end else self.Menu:GetItemById ("Copy") :SetEnabled (false) self.Menu:GetItemById ("Paste") :SetEnabled (false) self.Menu:GetItemById ("Create Folder"):SetEnabled (false) self.Menu:GetItemById ("Delete") :SetEnabled (false) self.Menu:GetItemById ("Rename") :SetEnabled (false) end end ) self.Menu:AddItem ("Copy", function (targetNodes) if #targetNodes == 0 then return end VFS.Clipboard:Clear () for _, node in ipairs (targetNodes) do VFS.Clipboard:Add (node) end end ):SetIcon ("icon16/page_white_copy.png") self.Menu:AddItem ("Paste", function () VFS.Clipboard:Paste (self.Folder) end ):SetIcon ("icon16/paste_plain.png") self.Menu:AddSeparator () self.Menu:AddItem ("Create Folder", function () if not self.Folder then return end local folder = self.Folder Derma_StringRequest ("Create folder...", "Enter the name of the new folder:", "", function (name) folder:CreateFolder (GAuth.GetLocalId (), name) end) end ):SetIcon ("icon16/folder_add.png") self.Menu:AddItem ("Delete", function (targetNodes) if not self.Folder then return end if not targetNodes then return end if #targetNodes == 0 then return end local names = "" for i = 1, 3 do if i > 1 then if i == #targetNodes then names = names .. " and " else names = names .. ", " end end names = names .. targetNodes [i]:GetDisplayName () if i == #targetNodes then break end end if #targetNodes > 3 then names = names .. " and " .. (#targetNodes - 3) .. " more item" .. ((#targetNodes - 3) > 1 and "s" or "") end Derma_Query ("Are you sure you want to delete " .. names .. "?", "Confirm deletion", "Yes", function () for _, node in ipairs (targetNodes) do node:Delete (GAuth.GetLocalId ()) end end, "No", VFS.NullCallback ) end ):SetIcon ("icon16/cross.png") self.Menu:AddItem ("Rename", function (targetNodes) if not targetNodes then return end if #targetNodes == 0 then return end Derma_StringRequest ("Rename " .. targetNodes [1]:GetName () .. "...", "Enter " .. targetNodes [1]:GetName () .. "'s new name:", targetNodes [1]:GetName (), function (name) name = VFS.SanitizeNodeName (name) if not name then return end targetNodes [1]:Rename (GAuth.GetLocalId (), name) end ) end ):SetIcon ("icon16/pencil.png") self.Menu:AddSeparator () self.Menu:AddItem ("Permissions", function (targetNodes) if not self.Folder then return end if not targetNodes then return end if #targetNodes == 0 then return end GAuth.OpenPermissions (targetNodes [1]:GetPermissionBlock ()) end ):SetIcon ("icon16/key.png") self:AddEventListener ("DoubleClick", function (_, item) if not item then return end if not item.Node then return end self:DispatchEvent ("NodeOpened", item.Node) end ) self:AddEventListener ("SelectionChanged", function (_, item) local node = item and item.Node or nil self:DispatchEvent ("SelectedNodeChanged", node) self:DispatchEvent ("SelectedFileChanged", node and node:IsFile () and node or nil) self:DispatchEvent ("SelectedFolderChanged", node and node:IsFolder () and node or nil) end ) self.PermissionsChanged = function (_) local access = self.Folder:GetPermissionBlock ():IsAuthorized (GAuth.GetLocalId (), "View Folder") local readAccess = self.Folder:GetPermissionBlock ():IsAuthorized (GAuth.GetLocalId (), "Read") if self.LastAccess ~= access then self.LastAccess = access if self.LastAccess then self:MergeRefresh () else self:Clear () self.ChildNodes = {} end end if self.LastReadAccess ~= readAccess then self.LastReadAccess = readAccess for _, listViewItem in pairs (self.ChildNodes) do if listViewItem.IsFile then self:UpdateIcon (listViewItem) end end end end end function self.DefaultComparator (a, b) -- Put folders at the top if a == b then return false end if a.ParentFolder then return true end if b.ParentFolder then return false end if a.Node:IsFolder () and not b.Node:IsFolder () then return true end if b.Node:IsFolder () and not a.Node:IsFolder () then return false end if a.Node.PlayerFolder and not b.Node.PlayerFolder then return false end if not a.Node.PlayerFolder and b.Node.PlayerFolder then return true end return string.lower (a:GetText ()) < string.lower (b:GetText ()) end function self:GetFolder () return self.Folder end function self:GetPath () if not self.Folder then return nil end return self.Folder:GetPath () end function self:GetSelectedFile () local node = self:GetSelectedNode () return node:IsFile () and node or nil end function self:GetSelectedFolder () local node = self:GetSelectedNode () return node:IsFolder () and node or nil end function self:GetSelectedNode () local item = self.SelectionController:GetSelectedItem () return item and item.Node or nil end function self:GetSelectedNodes () local selectedNodes = {} for _, item in ipairs (self.SelectionController:GetSelectedItems ()) do selectedNodes [#selectedNodes + 1] = item.Node end return selectedNodes end function self:MergeRefresh () if not self.Folder then return end local folder = self.Folder local lastLayout = SysTime () self.Folder:EnumerateChildren (GAuth.GetLocalId (), function (returnCode, node) if self.Folder ~= folder then return end if returnCode == VFS.ReturnCode.Success then self:AddNode (node) if self:GetItemCount () < 10 or SysTime () - lastLayout > 0.2 then self:Sort () lastLayout = SysTime () end elseif returnCode == VFS.ReturnCode.EndOfBurst then self:Sort () elseif returnCode == VFS.ReturnCode.AccessDenied then elseif returnCode == VFS.ReturnCode.Finished then self.Folder:AddEventListener ("NodeCreated", self:GetHashCode (), function (_, newNode) self:AddNode (newNode) self:Sort () end ) self.Folder:AddEventListener ("NodeDeleted", self:GetHashCode (), function (_, deletedNode) self:RemoveItem (self.ChildNodes [deletedNode:GetName ()]) self.ChildNodes [deletedNode:GetName ()] = nil end ) self:Sort () end end ) end function self:SetFolder (folder) if type (folder) == "string" then VFS.Error ("FolderListView:SetFolder was called with a string. Did you mean SetPath?") self:SetPath (folder) end if self.Folder == folder then return end self:Clear () self.ChildNodes = {} if self.Folder then self.Folder:RemoveEventListener ("NodeCreated", self:GetHashCode ()) self.Folder:RemoveEventListener ("NodeDeleted", self:GetHashCode ()) self.Folder:RemoveEventListener ("NodePermissionsChanged", self:GetHashCode ()) self.Folder:RemoveEventListener ("NodeRenamed", self:GetHashCode ()) self.Folder:RemoveEventListener ("NodeUpdated", self:GetHashCode ()) for i = #self.HookedNodes, 1, -1 do self.HookedNodes [i]:RemoveEventListener ("PermissionsChanged", self:GetHashCode ()) self.HookedNodes [i] = nil end self.Folder = nil end if not folder then return end if not folder:IsFolder () then return end local oldFolder = self.Folder self.Folder = folder self:DispatchEvent ("FolderChanged", oldFolder, self.Folder) if self.ShowParentFolder and self.Folder:GetParentFolder () then self:AddNode (self.Folder:GetParentFolder (), true) end self:MergeRefresh () self.Folder:AddEventListener ("NodePermissionsChanged", self:GetHashCode (), function (_, node) if not self.ChildNodes [node:GetName ()] then return end self:UpdateIcon (self.ChildNodes [node:GetName ()]) end ) self.Folder:AddEventListener ("NodeRenamed", self:GetHashCode (), function (_, node, oldName, newName) self.ChildNodes [newName] = self.ChildNodes [oldName] self.ChildNodes [newName]:SetText (node:GetDisplayName ()) self.ChildNodes [oldName] = nil self:Sort () end ) self.Folder:AddEventListener ("NodeUpdated", self:GetHashCode (), function (_, updatedNode, updateFlags) local listViewItem = self.ChildNodes [updatedNode:GetName ()] if not listViewItem then return end if bit.band (updateFlags, VFS.UpdateFlags.DisplayName) ~= 0 then listViewItem:SetText (updatedNode:GetDisplayName ()) self:Sort () end if bit.band (updateFlags, VFS.UpdateFlags.Size) ~= 0 then listViewItem.Size = updatedNode:IsFile () and updatedNode:GetSize () or -1 listViewItem:SetColumnText ("Size", listViewItem.Size ~= -1 and VFS.FormatFileSize (listViewItem.Size) or "") end if bit.band (updateFlags, VFS.UpdateFlags.ModificationTime) ~= 0 then listViewItem.LastModified = updatedNode:GetModificationTime () listViewItem:SetColumnText ("Last Modified", listViewItem.LastModified ~= -1 and VFS.FormatDate (listViewItem.LastModified) or "") end end ) local parentFolder = self.Folder while parentFolder do self.HookedNodes [#self.HookedNodes + 1] = parentFolder parentFolder:AddEventListener ("PermissionsChanged", self:GetHashCode (), self.PermissionsChanged) parentFolder = parentFolder:GetParentFolder () end self.LastAccess = self.Folder:GetPermissionBlock ():IsAuthorized (GAuth.GetLocalId (), "View Folder") end function self:SetPath (path) VFS.Root:GetChild (GAuth.GetLocalId (), path, function (returnCode, node) if not node then return end if node:IsFolder () then self:SetFolder (node) else self:SetFolder (node:GetParentFolder ()) self:AddNode (node):Select () end end ) end function self:SetShowParentFolder (showParentFolder) if self.ShowParentFolder == showParentFolder then return end self.ShowParentFolder = showParentFolder local folder = self:GetFolder () and self:GetFolder ():GetParentFolder () if not folder then return end if self.ShowParentFolder then self:AddNode (folder, true) self:Sort () else self.ParentFolderItem:Remove () self.ParentFolderItem = nil end end -- Internal, do not call function self:AddNode (node, parentFolder) if not parentFolder and self.ChildNodes [node:GetName ()] then return end local listViewItem = self:AddItem (node:GetName ()) listViewItem:SetText (parentFolder and ".." or node:GetDisplayName ()) listViewItem.ParentFolder = parentFolder or false listViewItem.Node = node listViewItem.IsFolder = node:IsFolder () listViewItem.IsFile = node:IsFile () listViewItem.Size = node:IsFile () and node:GetSize () or -1 listViewItem.LastModified = node:GetModificationTime () self:UpdateIcon (listViewItem) listViewItem:SetColumnText ("Size", listViewItem.Size ~= -1 and VFS.FormatFileSize (listViewItem.Size) or "") listViewItem:SetColumnText ("Last Modified", listViewItem.LastModified ~= -1 and VFS.FormatDate (listViewItem.LastModified) or "") if parentFolder then self.ParentFolderItem = listViewItem else self.ChildNodes [node:GetName ()] = listViewItem end return listViewItem end function self:UpdateIcon (listViewItem) local node = listViewItem.Node local permissionBlock = node:GetPermissionBlock () local canView = not permissionBlock or permissionBlock:IsAuthorized (GAuth.GetLocalId (), listViewItem.IsFolder and "View Folder" or "Read") if listViewItem.IsFolder then listViewItem:SetIcon (canView and "icon16/folder.png" or "icon16/folder_delete.png") else listViewItem:SetIcon (canView and "icon16/page.png" or "icon16/page_delete.png") end end -- Event handlers function self:OnRemoved () self:SetFolder (nil) end -- Event handlers self.PermissionsChanged = VFS.NullCallback vgui.Register ("VFSFolderListView", self, "GListView")
gpl-3.0
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/ipkg-ramips_24kec/luci-lib-web/usr/lib/lua/luci/http/protocol.lua
55
18445
--[[ HTTP protocol implementation for LuCI (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$ ]]-- --- LuCI http protocol class. -- This class contains several functions useful for http message- and content -- decoding and to retrive form data from raw http messages. module("luci.http.protocol", package.seeall) local ltn12 = require("luci.ltn12") HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size --- Decode an urlencoded string - optionally without decoding -- the "+" sign to " " - and return the decoded string. -- @param str Input string in x-www-urlencoded format -- @param no_plus Don't decode "+" signs to spaces -- @return The decoded string -- @see urlencode function urldecode( str, no_plus ) local function __chrdec( hex ) return string.char( tonumber( hex, 16 ) ) end if type(str) == "string" then if not no_plus then str = str:gsub( "+", " " ) end str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec ) end return str end --- Extract and split urlencoded data pairs, separated bei either "&" or ";" -- from given url or string. Returns a table with urldecoded values. -- Simple parameters are stored as string values associated with the parameter -- name within the table. Parameters with multiple values are stored as array -- containing the corresponding values. -- @param url The url or string which contains x-www-urlencoded form data -- @param tbl Use the given table for storing values (optional) -- @return Table containing the urldecoded parameters -- @see urlencode_params function urldecode_params( url, tbl ) local params = tbl or { } if url:find("?") then url = url:gsub( "^.+%?([^?]+)", "%1" ) end for pair in url:gmatch( "[^&;]+" ) do -- find key and value local key = urldecode( pair:match("^([^=]+)") ) local val = urldecode( pair:match("^[^=]+=(.+)$") ) -- store if type(key) == "string" and key:len() > 0 then if type(val) ~= "string" then val = "" end if not params[key] then params[key] = val elseif type(params[key]) ~= "table" then params[key] = { params[key], val } else table.insert( params[key], val ) end end end return params end --- Encode given string to x-www-urlencoded format. -- @param str String to encode -- @return String containing the encoded data -- @see urldecode function urlencode( str ) local function __chrenc( chr ) return string.format( "%%%02x", string.byte( chr ) ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.%+!*'(),])", __chrenc ) end return str end --- Encode each key-value-pair in given table to x-www-urlencoded format, -- separated by "&". Tables are encoded as parameters with multiple values by -- repeating the parameter name with each value. -- @param tbl Table with the values -- @return String containing encoded values -- @see urldecode_params function urlencode_params( tbl ) local enc = "" for k, v in pairs(tbl) do if type(v) == "table" then for i, v2 in ipairs(v) do enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v2) end else enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v) end end return enc end -- (Internal function) -- Initialize given parameter and coerce string into table when the parameter -- already exists. -- @param tbl Table where parameter should be created -- @param key Parameter name -- @return Always nil local function __initval( tbl, key ) if tbl[key] == nil then tbl[key] = "" elseif type(tbl[key]) == "string" then tbl[key] = { tbl[key], "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Append given data to given parameter, either by extending the string value -- or by appending it to the last string in the parameter's value table. -- @param tbl Table containing the previously initialized parameter value -- @param key Parameter name -- @param chunk String containing the data to append -- @return Always nil -- @see __initval local function __appendval( tbl, key, chunk ) if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk else tbl[key] = tbl[key] .. chunk end end -- (Internal function) -- Finish the value of given parameter, either by transforming the string value -- or - in the case of multi value parameters - the last element in the -- associated values table. -- @param tbl Table containing the previously initialized parameter value -- @param key Parameter name -- @param handler Function which transforms the parameter value -- @return Always nil -- @see __initval -- @see __appendval local function __finishval( tbl, key, handler ) if handler then if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] ) else tbl[key] = handler( tbl[key] ) end end end -- Table of our process states local process_states = { } -- Extract "magic", the first line of a http message. -- Extracts the message type ("get", "post" or "response"), the requested uri -- or the status code if the line descripes a http response. process_states['magic'] = function( msg, chunk, err ) if chunk ~= nil then -- ignore empty lines before request if #chunk == 0 then return true, nil end -- Is it a request? local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$") -- Yup, it is if method then msg.type = "request" msg.request_method = method:lower() msg.request_uri = uri msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end -- Is it a response? else local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$") -- Is a response if code then msg.type = "response" msg.status_code = code msg.status_message = message msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end end end end -- Can't handle it return nil, "Invalid HTTP message magic" end -- Extract headers from given string. process_states['headers'] = function( msg, chunk ) if chunk ~= nil then -- Look for a valid header format local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" ) if type(hdr) == "string" and hdr:len() > 0 and type(val) == "string" and val:len() > 0 then msg.headers[hdr] = val -- Valid header line, proceed return true, nil elseif #chunk == 0 then -- Empty line, we won't accept data anymore return false, nil else -- Junk data return nil, "Invalid HTTP header received" end else return nil, "Unexpected EOF" end end --- Creates a ltn12 source from the given socket. The source will return it's -- data line by line with the trailing \r\n stripped of. -- @param sock Readable network socket -- @return Ltn12 source function function header_source( sock ) return ltn12.source.simplify( function() local chunk, err, part = sock:receive("*l") -- Line too long if chunk == nil then if err ~= "timeout" then return nil, part and "Line exceeds maximum allowed length" or "Unexpected EOF" else return nil, err end -- Line ok elseif chunk ~= nil then -- Strip trailing CR chunk = chunk:gsub("\r$","") return chunk, nil end end ) end --- Decode a mime encoded http message body with multipart/form-data -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- If an optional file callback function is given then it is feeded with the -- file contents chunk by chunk and only the extracted file name is stored -- within the params table. The callback function will be called subsequently -- with three arguments: -- o Table containing decoded (name, file) and raw (headers) mime header data -- o String value containing a chunk of the file data -- o Boolean which indicates wheather the current chunk is the last one (eof) -- @param src Ltn12 source function -- @param msg HTTP message object -- @param filecb File callback function (optional) -- @return Value indicating successful operation (not nil means "ok") -- @return String containing the error if unsuccessful -- @see parse_message_header function mimedecode_message_body( src, msg, filecb ) if msg and msg.env.CONTENT_TYPE then msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$") end if not msg.mime_boundary then return nil, "Invalid Content-Type found" end local tlen = 0 local inhdr = false local field = nil local store = nil local lchunk = nil local function parse_headers( chunk, field ) local stat repeat chunk, stat = chunk:gsub( "^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n", function(k,v) field.headers[k] = v return "" end ) until stat == 0 chunk, stat = chunk:gsub("^\r\n","") -- End of headers if stat > 0 then if field.headers["Content-Disposition"] then if field.headers["Content-Disposition"]:match("^form%-data; ") then field.name = field.headers["Content-Disposition"]:match('name="(.-)"') field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$') end end if not field.headers["Content-Type"] then field.headers["Content-Type"] = "text/plain" end if field.name and field.file and filecb then __initval( msg.params, field.name ) __appendval( msg.params, field.name, field.file ) store = filecb elseif field.name then __initval( msg.params, field.name ) store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end else store = nil end return chunk, true end return chunk, false end local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" end if chunk and not lchunk then lchunk = "\r\n" .. chunk elseif lchunk then local data = lchunk .. ( chunk or "" ) local spos, epos, found repeat spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true ) if not spos then spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true ) end if spos then local predata = data:sub( 1, spos - 1 ) if inhdr then predata, eof = parse_headers( predata, field ) if not eof then return nil, "Invalid MIME section header" elseif not field.name then return nil, "Invalid Content-Disposition header" end end if store then store( field, predata, true ) end field = { headers = { } } found = found or true data, eof = parse_headers( data:sub( epos + 1, #data ), field ) inhdr = not eof end until not spos if found then -- We found at least some boundary. Save -- the unparsed remaining data for the -- next chunk. lchunk, data = data, nil else -- There was a complete chunk without a boundary. Parse it as headers or -- append it as data, depending on our current state. if inhdr then lchunk, eof = parse_headers( data, field ) inhdr = not eof else -- We're inside data, so append the data. Note that we only append -- lchunk, not all of data, since there is a chance that chunk -- contains half a boundary. Assuming that each chunk is at least the -- boundary in size, this should prevent problems store( field, lchunk, false ) lchunk, chunk = chunk, nil end end end return true end return ltn12.pump.all( src, snk ) end --- Decode an urlencoded http message body with application/x-www-urlencoded -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- @param src Ltn12 source function -- @param msg HTTP message object -- @return Value indicating successful operation (not nil means "ok") -- @return String containing the error if unsuccessful -- @see parse_message_header function urldecode_message_body( src, msg ) local tlen = 0 local lchunk = nil local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" elseif tlen > HTTP_MAX_CONTENT then return nil, "Message body size exceeds maximum allowed length" end if not lchunk and chunk then lchunk = chunk elseif lchunk then local data = lchunk .. ( chunk or "&" ) local spos, epos repeat spos, epos = data:find("^.-[;&]") if spos then local pair = data:sub( spos, epos - 1 ) local key = pair:match("^(.-)=") local val = pair:match("=([^%s]*)%s*$") if key and #key > 0 then __initval( msg.params, key ) __appendval( msg.params, key, val ) __finishval( msg.params, key, urldecode ) end data = data:sub( epos + 1, #data ) end until not spos lchunk = data end return true end return ltn12.pump.all( src, snk ) end --- Try to extract an http message header including information like protocol -- version, message headers and resulting CGI environment variables from the -- given ltn12 source. -- @param src Ltn12 source function -- @return HTTP message object -- @see parse_message_body function parse_message_header( src ) local ok = true local msg = { } local sink = ltn12.sink.simplify( function( chunk ) return process_states['magic']( msg, chunk ) end ) -- Pump input data... while ok do -- get data ok, err = ltn12.pump.step( src, sink ) -- error if not ok and err then return nil, err -- eof elseif not ok then -- Process get parameters if ( msg.request_method == "get" or msg.request_method == "post" ) and msg.request_uri:match("?") then msg.params = urldecode_params( msg.request_uri ) else msg.params = { } end -- Populate common environment variables msg.env = { CONTENT_LENGTH = msg.headers['Content-Length']; CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type']; REQUEST_METHOD = msg.request_method:upper(); REQUEST_URI = msg.request_uri; SCRIPT_NAME = msg.request_uri:gsub("?.+$",""); SCRIPT_FILENAME = ""; -- XXX implement me SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version); QUERY_STRING = msg.request_uri:match("?") and msg.request_uri:gsub("^.+?","") or "" } -- Populate HTTP_* environment variables for i, hdr in ipairs( { 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Connection', 'Cookie', 'Host', 'Referer', 'User-Agent', } ) do local var = 'HTTP_' .. hdr:upper():gsub("%-","_") local val = msg.headers[hdr] msg.env[var] = val end end end return msg end --- Try to extract and decode a http message body from the given ltn12 source. -- This function will examine the Content-Type within the given message object -- to select the appropriate content decoder. -- Currently the application/x-www-urlencoded and application/form-data -- mime types are supported. If the encountered content encoding can't be -- handled then the whole message body will be stored unaltered as "content" -- property within the given message object. -- @param src Ltn12 source function -- @param msg HTTP message object -- @param filecb File data callback (optional, see mimedecode_message_body()) -- @return Value indicating successful operation (not nil means "ok") -- @return String containing the error if unsuccessful -- @see parse_message_header function parse_message_body( src, msg, filecb ) -- Is it multipart/mime ? if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^multipart/form%-data") then return mimedecode_message_body( src, msg, filecb ) -- Is it application/x-www-form-urlencoded ? elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded") then return urldecode_message_body( src, msg, filecb ) -- Unhandled encoding -- If a file callback is given then feed it chunk by chunk, else -- store whole buffer in message.content else local sink -- If we have a file callback then feed it if type(filecb) == "function" then sink = filecb -- ... else append to .content else msg.content = "" msg.content_length = 0 sink = function( chunk, err ) if chunk then if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then msg.content = msg.content .. chunk msg.content_length = msg.content_length + #chunk return true else return nil, "POST data exceeds maximum allowed length" end end return true end end -- Pump data... while true do local ok, err = ltn12.pump.step( src, sink ) if not ok and err then return nil, err elseif not err then return true end end return true end end --- Table containing human readable messages for several http status codes. -- @class table statusmsg = { [200] = "OK", [206] = "Partial Content", [301] = "Moved Permanently", [302] = "Found", [304] = "Not Modified", [400] = "Bad Request", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [408] = "Request Time-out", [411] = "Length Required", [412] = "Precondition Failed", [416] = "Requested range not satisfiable", [500] = "Internal Server Error", [503] = "Server Unavailable", }
gpl-2.0
bnetcc/darkstar
scripts/zones/Port_Bastok/npcs/Valeriano.lua
5
1408
----------------------------------- -- Area: Port Bastok -- NPC: Valeriano -- Standard Merchant NPC -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:showText(npc,VALERIANO_SHOP_DIALOG); local stock = { 4394, 10, -- Ginger Cookie 17345, 43, -- Flute 17347, 990, -- Piccolo 5017, 585, -- Scroll of Scop's Operetta 5018, 16920, -- Scroll of Puppet's Operetta 5013, 2916, -- Scroll of Fowl Aubade 5027, 2059, -- Scroll of Advancing March 5072, 90000, -- Scroll of Goddess's Hymnus 5054, 32844, -- Scroll of Fire Carol II 5056, 30912, -- Scroll of Wind Carol II 5057, 27140, -- Scroll of Earth Carol II 5059, 28520, -- Scroll of Water Carol II 4996,123880 -- Scroll of Mage's Ballad III } showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Garlaige_Citadel/npcs/qm12.lua
5
1042
----------------------------------- -- Area: Garlaige Citadel -- NPC: qm12 (???) -- Involved in Quest: Hitting the Marquisate (THF AF3) -- !pos -245.603 -5.500 139.855 200 ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Garlaige_Citadel/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS"); if (hittingTheMarquisateHagainCS == 4) then player:messageSpecial(PRESENCE_FROM_CEILING); player:setVar("hittingTheMarquisateHagainCS",5); end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kmul00/torch-vol
VolumetricMaxUnpooling.lua
1
1790
local VolumetricMaxUnpooling, parent = torch.class('nn.VolumetricMaxUnpooling', 'nn.Module') function VolumetricMaxUnpooling:__init(poolingModule) parent.__init(self) assert(torch.type(poolingModule)=='nn.VolumetricMaxPooling', 'Argument must be a nn.VolumetricMaxPooling module') assert(poolingModule.kT==poolingModule.dT and poolingModule.kH==poolingModule.dH and poolingModule.kW==poolingModule.dW, "The size of pooling module's kernel must be equal to its stride") self.pooling = poolingModule poolingModule.updateOutput = function(pool, input) local dims = input:dim() pool.itime = input:size(dims-2) pool.iheight = input:size(dims-1) pool.iwidth = input:size(dims) return nn.VolumetricMaxPooling.updateOutput(pool, input) end end function VolumetricMaxUnpooling:setParams() self.indices = self.pooling.indices self.otime = self.pooling.itime self.oheight = self.pooling.iheight self.owidth = self.pooling.iwidth self.dT = self.pooling.dT self.dH = self.pooling.dH self.dW = self.pooling.dW self.padT = self.pooling.padT self.padH = self.pooling.padH self.padW = self.pooling.padW end function VolumetricMaxUnpooling:updateOutput(input) self:setParams() input.nn.VolumetricMaxUnpooling_updateOutput(self, input) return self.output end function VolumetricMaxUnpooling:updateGradInput(input, gradOutput) self:setParams() input.nn.VolumetricMaxUnpooling_updateGradInput(self, input, gradOutput) return self.gradInput end function VolumetricMaxUnpooling:empty() self.gradInput:resize() self.gradInput:storage():resize(0) self.output:resize() self.output:storage():resize(0) end function VolumetricMaxUnpooling:__tostring__() return 'nn.VolumetricMaxUnpooling associated to '..tostring(self.pooling) end
mit
Evsdd/domoticz
dzVents/runtime/HTTPResponse.lua
7
1077
local _ = require('lodash') local utils = require('Utils') local function HTTPResponce(domoticz, responseData) local self = {} self.headers = responseData.headers or {} self.baseType = domoticz.BASETYPE_HTTP_RESPONSE self.data = responseData.data or nil self._contentType = _.get(self.headers, {'Content-Type'}, '') self.isJSON = false self.statusCode = responseData.statusCode self.ok = false if (self.statusCode >= 200 and self.statusCode <= 299) then self.ok = true end self.isHTTPResponse = true self.isDevice = false self.isScene = false self.isGroup = false self.isTimer = false self.isVariable = false self.isSecurity = false self.callback = responseData.callback self.trigger = responseData.callback if (string.match(self._contentType, 'application/json') and self.data) then local json = utils.fromJSON(self.data) if (json) then self.isJSON = true self.json = json end end return self end return HTTPResponce
gpl-3.0
bnetcc/darkstar
scripts/zones/Mhaura/npcs/Mololo.lua
1
1174
----------------------------------- -- Area: Mhaura -- NPC: Mololo -- Guild Merchant NPC: Blacksmithing Guild -- !pos -64.278 -16.624 34.120 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) --[[ if (player:sendGuild(532,8,23,2)) then player:showText(npc,SMITHING_GUILD); end ]] player:showText(npc,SMITHING_GUILD); local stock = { 640, 9, -- Copper Ore 641, 30, -- Tin Ore 643, 675, -- Iron Ore 652, 3517, -- Steel Ingot 660, 61 -- Bronze Sheet }; showShop(player, STATIC, stock); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
sylvanaar/prat-3-0
modules/ChatTabs.lua
1
9764
--------------------------------------------------------------------------------- -- -- Prat - A framework for World of Warcraft chat mods -- -- Copyright (C) 2006-2018 Prat Development Team -- -- This program is free software; you can redistribute it and/or -- modify it under the terms of the GNU General Public License -- as published by the Free Software Foundation; 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: -- -- Free Software Foundation, Inc., -- 51 Franklin Street, Fifth Floor, -- Boston, MA 02110-1301, USA. -- -- ------------------------------------------------------------------------------- Prat:AddModuleToLoad(function() local PRAT_MODULE = Prat:RequestModuleName("ChatTabs") local dbg = function() end --@debug@ dbg = function(...) Prat:PrintLiteral(...) end --@end-debug@ if PRAT_MODULE == nil then return end local module = Prat:NewModule(PRAT_MODULE, "AceHook-3.0") local PL = module.PL --@debug@ PL:AddLocale(PRAT_MODULE, "enUS", { ["Tabs"] = true, ["Chat window tab options."] = true, ["Set Display Mode"] = true, ["Set tab display mode for each chat window."] = "Set tab display mode for each chat window. Checked (on), Unchecked (off), Greyed Check (default)", ["Set ChatFrame%d Display Mode"] = true, ["Set tab display to always, hidden or the Blizzard default."] = true, ["Active Alpha"] = true, ["Sets alpha of chat tab for active chat frame."] = true, ["Not Active Alpha"] = true, ["Sets alpha of chat tab for not active chat frame."] = true, ["All"] = true, ["Individual"] = true, ["Always"] = true, ["Hidden"] = true, ["Default"] = true, ["disableflash_name"] = "Disable Flashing", ["disableflash_desc"] = "Disable flashing of the chat tabs.", ["preventdrag_name"] = "Prevent Dragging", ["preventdrag_desc"] = "Prevent dragging chat tabs with mouse", }) --@end-debug@ -- These Localizations are auto-generated. To help with localization -- please go to http://www.wowace.com/projects/prat-3-0/localization/ --[===[@non-debug@ do local L --@localization(locale="enUS", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "enUS", L) --@localization(locale="itIT", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "itIT", L) --@localization(locale="ptBR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "ptBR", L) --@localization(locale="frFR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "frFR",L) --@localization(locale="deDE", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "deDE", L) --@localization(locale="koKR", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "koKR",L) --@localization(locale="esMX", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "esMX",L) --@localization(locale="ruRU", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "ruRU",L) --@localization(locale="zhCN", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "zhCN",L) --@localization(locale="esES", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "esES",L) --@localization(locale="zhTW", format="lua_table", handle-subnamespaces="none", same-key-is-true=true, namespace="ChatTabs")@ PL:AddLocale(PRAT_MODULE, "zhTW",L) end --@end-non-debug@]===] Prat:SetModuleDefaults(module.name, { profile = { on = false, displaymode = {}, disableflash = false, notactivealpha = 0, activealpha = 0, preventdrag = false, } }) --module.toggleOptions = { sep115_sep = 115, disableflash = 120, preventdrag = 125 } Prat:SetModuleOptions(module.name, { name = PL["Tabs"], desc = PL["Chat window tab options."], type = "group", args = { displaymode = { name = PL["Set Display Mode"], desc = PL["Set tab display mode for each chat window."], type = "multiselect", tristate = true, order = 110, values = Prat.FrameList, get = "GetSubValue", set = "SetSubValue", }, disableflash = { name = PL["disableflash_name"], desc = PL["disableflash_desc"], type = "toggle", order = 120 }, -- preventdrag = { -- name = PL["preventdrag_name"], -- desc = PL["preventdrag_desc"], -- type = "toggle", -- order = 120 -- }, activealpha = { name = PL["Active Alpha"], desc = PL["Sets alpha of chat tab for active chat frame."], type = "range", order = 130, min = 0.0, max = 1, step = 0.1, }, notactivealpha = { name = PL["Not Active Alpha"], desc = PL["Sets alpha of chat tab for not active chat frame."], type = "range", order = 140, min = 0.0, max = 1, step = 0.1, }, } }) --local tabmode = { ["true"] = "ALWAYS", ["false"] = "HIDDEN", ["nil"] = "DEFAULT" } --[[------------------------------------------------ Module Event Functions ------------------------------------------------]] -- -- things to do when the module is enabled function module:OnModuleEnable() self:SecureHook("FCF_StartAlertFlash") self:HookedMode(true) self:UpdateAllTabs() end -- things to do when the module is enabled function module:OnModuleDisable() self:RemoveHooks() end --[[------------------------------------------------ Core Functions ------------------------------------------------]] -- function module:GetDescription() return PL["Chat window tab options."] end function module:HookedMode(hooked) if hooked then self:RawHook("FCF_Close", true) self:InstallHooks() else self:RemoveHooks() end end local needToHook = {} function module:InstallHooks() for k, v in pairs(Prat.Frames) do local cftab = _G[k .. "Tab"] self:HookScript(cftab, "OnShow", "OnTabShow") if cftab:IsShown() then self:HookScript(cftab, "OnHide", "OnTabHide") needToHook[cftab] = nil else needToHook[cftab] = true end -- self:HookScript(cftab,"OnDragStart", "OnTabDragStart") end end function module:RemoveHooks() for k, v in pairs(Prat.Frames) do local cftab = _G[k .. "Tab"] cftab:SetScript("OnShow", function() return end) cftab:SetScript("OnHide", function() return end) end -- unhook functions self:UnhookAll() end function module:OnValueChanged(info, b) -- if info[#info]:find("alpha") then -- -- return -- end self:UpdateAllTabs() end function module:OnSubValueChanged(info, b) self:UpdateAllTabs() end function module:UpdateAllTabs() CHAT_FRAME_TAB_SELECTED_NOMOUSE_ALPHA = self.db.profile.activealpha; CHAT_FRAME_TAB_NORMAL_NOMOUSE_ALPHA = self.db.profile.notactivealpha; for k, v in pairs(Prat.Frames) do if FCF_IsValidChatFrame(v) then local chatTab = _G[k .. "Tab"] chatTab:Show() chatTab:Hide() FloatingChatFrame_Update(v:GetID()) chatTab.mouseOverAlpha = CHAT_FRAME_TAB_SELECTED_MOUSEOVER_ALPHA; chatTab.noMouseAlpha = CHAT_FRAME_TAB_SELECTED_NOMOUSE_ALPHA; -- Prevent an error in FloatingChatFrame FCF_FadeOutChatFrame() (blizz bug) chatTab:SetAlpha(chatTab:GetAlpha() or 0) v:SetAlpha(v:GetAlpha() or 0) v.oldAlpha = v.oldAlpha or 0 FCF_FadeOutChatFrame(v) end end end function module:OnTabShow(tab, ...) if needToHook[tab] then self:HookScript(tab, "OnHide", "OnTabHide") needToHook[tab] = nil end if self.db.profile.displaymode["ChatFrame" .. tab:GetID()] == false then tab:Hide() end end function module:OnTabHide(tab, ...) local p = self.db.profile local i = tab:GetID() if self.db.profile.displaymode["ChatFrame" .. tab:GetID()] == true then tab:Show() if SELECTED_CHAT_FRAME:GetID() == i then tab:SetAlpha(p.activealpha) else tab:SetAlpha(p.notactivealpha) end end end function module:OnTabDragStart(this, ...) local p = self.db.profile if p.preventdrag and p.on then return end self.hooks[this].OnDragStart(this, ...) end function module:FCF_StartAlertFlash(this) if self.db.profile.disableflash then FCF_StopAlertFlash(this) end end function module:FCF_Close(frame, fallback) local tab = _G[frame:GetName() .. "Tab"] -- print(frame, fallback, tab) if tab then self:Unhook(tab, "OnHide") needToHook[tab] = true end self.hooks.FCF_Close(frame, fallback) end return end) -- Prat:AddModuleToLoad
gpl-3.0
bnetcc/darkstar
scripts/zones/Empyreal_Paradox/Zone.lua
5
1447
----------------------------------- -- -- Zone: Empyreal_Paradox -- ----------------------------------- package.loaded["scripts/zones/Empyreal_Paradox/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Empyreal_Paradox/TextIDs"); ----------------------------------- function onInitialize(zone) zone:registerRegion(1, 538, -2, -501, 542, 0, -497); -- to The Garden of Ru'hmet end; function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then --player:setPos(502,0,500,222); -- BC Area player:setPos(539,-1,-500,69); end return cs; end; function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) player:startEvent(100); end, } end; function onRegionLeave(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 100 and option == 1) then player:setPos(-420,-1,379.900,62,0x23); end end;
gpl-3.0
seeker24/happy
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
bnetcc/darkstar
scripts/globals/mobskills/grim_halo_custom.lua
11
1096
--------------------------------------------------- -- Grim Halo -- Deals damage to a all targets. Additional effect: Knockback -- Only used by Fomors that wield a two-handed weapon (principally WAR, BLM, DRK, SAM, DRG, and SMN fomors). --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) local job = mob:getMainJob(); if (job == JOBS.WAR or job == JOBS.BLM or job == JOBS.DRK or job == JOBS.SAM or job == JOBS.DRG or job == JOBS.SMN) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) -- Needs Knockback added local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
bnetcc/darkstar
scripts/zones/Yuhtunga_Jungle/mobs/Rose_Garden.lua
7
1027
----------------------------------- -- Area: Yuhtunga Jungle -- MOB: Rose Garden ----------------------------------- require("scripts/zones/Yuhtunga_Jungle/MobIDs"); function disturbMob(mob) mob:setLocalVar("timeToGrow", os.time() + math.random(36000,37800)); -- 10:00:00 to 10:30:00 end function onMobSpawn(mob) disturbMob(mob); end; function onMobEngaged(mob, target) disturbMob(mob); end; function onMobFight(mob, target) disturbMob(mob); end; function onMobRoam(mob) -- Rose Garden has been left alone for 10.25 hours if (os.time() > mob:getLocalVar("timeToGrow")) then DisallowRespawn(ROSE_GARDEN, true); DespawnMob(ROSE_GARDEN); DisallowRespawn(VOLUPTUOUS_VILMA, false); SpawnMob(VOLUPTUOUS_VILMA); end end; function onMobDeath(mob, player, isKiller) end; function onMobDespawn(mob) DisallowRespawn(ROSE_GARDEN, true); DisallowRespawn(ROSE_GARDEN_PH, false); GetMobByID(ROSE_GARDEN_PH):setRespawnTime(GetMobRespawnTime(ROSE_GARDEN_PH)); end;
gpl-3.0
bnetcc/darkstar
scripts/globals/spells/bluemagic/smite_of_rage.lua
33
1678
----------------------------------------- -- Spell: Smite of Rage -- Damage varies with TP -- Spell cost: 28 MP -- Monster Type: Arcana -- Spell Type: Physical (Slashing) -- Blue Magic Points: 3 -- Stat Bonus: AGI+3 -- Level: 34 -- Casting Time: 0.5 seconds -- Recast Time: 13 seconds -- Skillchain Element(s): Wind (can open Scission or Gravitation; can close Detonation) -- Combos: Undead Killer ----------------------------------------- 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_DAMAGE; params.dmgtype = DMGTYPE_SLASH; params.scattr = SC_DETONATION; params.numhits = 1; params.multiplier = 1.5; params.tp150 = 2.25; params.tp300 = 2.5; params.azuretp = 2.53125; params.duppercap = 35; params.str_wsc = 0.2; params.dex_wsc = 0.2; 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; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); return damage; end;
gpl-3.0
nsimplex/Tallbrood
scripts/tallbrood/wicker/lib/searchspace.lua
2
1763
--[[ 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/>. ]]-- local TheSim = TheSim local FindValidPositionByFan = FindValidPositionByFan --@@ENVIRONMENT BOOTUP local _modname = assert( (assert(..., 'This file should be loaded through require.')):match('^[%a_][%w_%s]*') , 'Invalid path.' ) module( ..., require(_modname .. '.booter') ) --@@END ENVIRONMENT BOOTUP local Lambda = wickerrequire 'paradigms.functional' local Pred = wickerrequire 'lib.predicates' local myutils = wickerrequire 'utils' FindAllEntities = myutils.game.FindAllEntities FindSomeEntity = myutils.game.FindSomeEntity Annulus = Class(function(self, center, r, R, rng, tries) self.center = center self.r = r self.R = R self.rng = rng or math.random self.tries = tries or 16 end) function Annulus:Search(f) local function test_at_offset(dv) return f(self.center + dv) end for _=1, self.tries do local offset = FindValidPositionByFan( 2*math.pi*math.random(), -- No, math.random shouldn't be self.rng. An annulus is radially symmetric. self.r + (self.R - self.r)*self.rng(), 8, test_at_offset ) if offset then return self.center + offset end end end return _M
gpl-2.0
bnetcc/darkstar
scripts/zones/Port_Windurst/npcs/Choyi_Totlihpa.lua
5
1117
----------------------------------- -- Area: Port Windurst -- NPC: Choyi Totlihpa -- Type: Standard NPC -- !pos -58.927 -5.732 132.819 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local WildcatWindurst = player:getVar("WildcatWindurst"); if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,17) == false) then player:startEvent(622); else player:startEvent(215); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 622) then player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",17,true); end end;
gpl-3.0
TurkeyMan/premake-core
tests/base/test_criteria.lua
15
10408
-- -- tests/base/test_criteria.lua -- Test suite for the criteria matching API. -- Copyright (c) 2012-2015 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("criteria") local criteria = p.criteria -- -- Setup and teardown -- local crit -- -- A criteria with no terms should satisfy any context. -- function suite.matches_alwaysTrue_onNoFilterTerms() crit = criteria.new {} test.istrue(criteria.matches(crit, { configurations="Debug", system="Windows" })) end -- -- Should not match if any term is missing in the context. -- function suite.matches_fails_onMissingContext() crit = criteria.new { "system:Windows", "architecture:x86" } test.isfalse(criteria.matches(crit, { configurations="Debug", system="Windows" })) end -- -- Context terms must match the entire criteria term. -- function suite.matches_fails_onIncompleteTermMatch() crit = criteria.new { "platforms:win64" } test.isfalse(criteria.matches(crit, { platforms="win64 dll dcrt" })) end -- -- Wildcard matches should work. -- function suite.matches_passes_onPatternMatch() crit = criteria.new { "action:vs*" } test.istrue(criteria.matches(crit, { action="vs2005" })) end -- -- The "not" modifier should fail the test if the term is matched. -- function suite.matches_fails_onMatchWithNotModifier_afterPrefix() crit = criteria.new { "system:not windows" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.matches_fails_onMatchWithNotModifier_beforePrefix() crit = criteria.new { "not system:windows" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.matches_passes_onMissWithNotModifier_afterPrefix() crit = criteria.new { "system:not windows" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.matches_passes_onMissWithNotModifier_beforePrefix() crit = criteria.new { "not system:windows" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.matches_passes_onMissWithNotModifier_noPrefix() crit = criteria.new { "not debug" } test.istrue(criteria.matches(crit, { configurations="release" })) end -- -- The "or" modifier should pass if either term is present. -- function suite.matches_passes_onFirstOrTermMatched() crit = criteria.new { "system:windows or linux" } test.istrue(criteria.matches(crit, { system="windows" })) end function suite.matches_passes_onSecondOrTermMatched() crit = criteria.new { "system:windows or linux" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.matches_passes_onThirdOrTermMatched() crit = criteria.new { "system:windows or linux or vs2005" } test.istrue(criteria.matches(crit, { system="vs2005" })) end function suite.matches_fails_onNoOrTermMatched() crit = criteria.new { "system:windows or linux" } test.isfalse(criteria.matches(crit, { system="vs2005" })) end function suite.matches_passes_onMixedPrefixes_firstTermMatched_projectContext() crit = criteria.new { "system:windows or files:core*" } test.istrue(criteria.matches(crit, { system="windows" })) end function suite.matches_fails_onMixedPrefixes_firstTermMatched_fileContext() crit = criteria.new { "system:windows or files:core*" } test.isfalse(criteria.matches(crit, { system="windows", files="hello.cpp" })) end function suite.matches_passes_onMixedPrefixes_secondTermMatched() crit = criteria.new { "system:windows or files:core*" } test.istrue(criteria.matches(crit, { system="linux", files="coregraphics.cpp" })) end function suite.matches_fails_onMixedPrefixes_noTermMatched() crit = criteria.new { "system:windows or files:core*" } test.isfalse(criteria.matches(crit, { system="linux", files="hello.cpp" })) end -- -- The "not" modifier should fail on any match with an "or" modifier. -- function suite.matches_passes_onNotOrMatchesFirst() crit = criteria.new { "system:not windows or linux" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.matches_passes_onNotOrMatchesSecond() crit = criteria.new { "system:windows or not linux" } test.isfalse(criteria.matches(crit, { system="linux" })) end -- -- The "not" modifier should succeed with "or" if there are no matches. -- function suite.matches_passes_onNoNotMatch() crit = criteria.new { "system:not windows or linux" } test.istrue(criteria.matches(crit, { system="macosx" })) end -- -- If the context specifies a filename, the filter must match it explicitly. -- function suite.matches_passes_onFilenameAndMatchingPattern() crit = criteria.new { "files:**.c", "system:windows" } test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.matches_fails_onFilenameAndNoMatchingPattern() crit = criteria.new { "system:windows" } test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end -- -- Test criteria creation through a table. -- function suite.createCriteriaWithTable() crit = criteria.new { files = { "**.c" }, system = "windows" } test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.createCriteriaWithTable2() crit = criteria.new { system = "not windows" } test.isfalse(criteria.matches(crit, { system="windows" })) end function suite.createCriteriaWithTable3() crit = criteria.new { system = "not windows or linux" } test.istrue(criteria.matches(crit, { system="macosx" })) end function suite.createCriteriaWithTable4() crit = criteria.new { system = "windows or linux" } test.istrue(criteria.matches(crit, { system="windows" })) end -- -- "Not" modifiers can also be used on filenames. -- function suite.matches_passes_onFilenameMissAndNotModifier() crit = criteria.new { "files:not **.c", "system:windows" } test.istrue(criteria.matches(crit, { system="windows", files="hello.h" })) end function suite.matches_fails_onFilenameHitAndNotModifier() crit = criteria.new { "files:not **.c", "system:windows" } test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end -- -- If context provides a list of values, match against them. -- function suite.matches_passes_termMatchesList() crit = criteria.new { "options:debug" } test.istrue(criteria.matches(crit, { options={ "debug", "logging" }})) end -- -- If no prefix is specified, default to "configurations". -- function suite.matches_usesDefaultPrefix_onSingleTerm() crit = criteria.new { "debug" } test.istrue(criteria.matches(crit, { configurations="debug" })) end -- -- These tests use the older, unprefixed style of filter terms. This -- approach will get phased out eventually, but are still included here -- for backward compatibility testing. -- function suite.matches_onEmptyCriteria_Unprefixed() crit = criteria.new({}, true) test.istrue(criteria.matches(crit, { "apple", "orange" })) end function suite.fails_onMissingContext_Unprefixed() crit = criteria.new({ "orange", "pear" }, true) test.isfalse(criteria.matches(crit, { "apple", "orange" })) end function suite.fails_onIncompleteMatch_Unprefixed() crit = criteria.new({ "win64" }, true) test.isfalse(criteria.matches(crit, { "win64 dll dcrt" })) end function suite.passes_onPatternMatch_Unprefixed() crit = criteria.new({ "vs*" }, true) test.istrue(criteria.matches(crit, { "vs2005" })) end function suite.fails_onNotMatch_Unprefixed() crit = criteria.new({ "not windows" }, true) test.isfalse(criteria.matches(crit, { "windows" })) end function suite.passes_onNotUnmatched_Unprefixed() crit = criteria.new({ "not windows" }, true) test.istrue(criteria.matches(crit, { "linux" })) end function suite.passes_onFirstOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux" }, true) test.istrue(criteria.matches(crit, { "windows" })) end function suite.passes_onSecondOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux" }, true) test.istrue(criteria.matches(crit, { "linux" })) end function suite.passes_onThirdOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux or vs2005" }, true) test.istrue(criteria.matches(crit, { "vs2005" })) end function suite.fails_onNoOrTermMatched_Unprefixed() crit = criteria.new({ "windows or linux" }, true) test.isfalse(criteria.matches(crit, { "vs2005" })) end function suite.passes_onNotOrMatchesFirst_Unprefixed() crit = criteria.new({ "not windows or linux" }, true) test.isfalse(criteria.matches(crit, { "windows" })) end function suite.passes_onNotOrMatchesSecond_Unprefixed() crit = criteria.new({ "windows or not linux" }, true) test.isfalse(criteria.matches(crit, { "linux" })) end function suite.passes_onNoNotMatch_Unprefixed() crit = criteria.new({ "not windows or linux" }, true) test.istrue(criteria.matches(crit, { "macosx" })) end function suite.passes_onFilenameAndMatchingPattern_Unprefixed() crit = criteria.new({ "**.c", "windows" }, true) test.istrue(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.fails_onFilenameAndNoMatchingPattern_Unprefixed() crit = criteria.new({ "windows" }, true) test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.fails_onFilenameAndNotModifier_Unprefixed() crit = criteria.new({ "not linux" }, true) test.isfalse(criteria.matches(crit, { system="windows", files="hello.c" })) end function suite.matches_passes_termMatchesList_Unprefixed() crit = criteria.new({ "debug" }, true) test.istrue(criteria.matches(crit, { options={ "debug", "logging" }})) end -- -- Should return nil and an error message on an invalid prefix. -- function suite.returnsNilAndError_onInvalidPrefix() crit, err = criteria.new { "gibble:Debug" } test.isnil(crit) test.isnotnil(err) end -- -- Should respect field value aliases, if present. -- function suite.passes_onAliasedValue() p.api.addAliases("system", { ["gnu-linux"] = "linux" }) crit = criteria.new { "system:gnu-linux" } test.istrue(criteria.matches(crit, { system="linux" })) end function suite.passes_onAliasedValue_withMixedCase() p.api.addAliases("system", { ["gnu-linux"] = "linux" }) crit = criteria.new { "System:GNU-Linux" } test.istrue(criteria.matches(crit, { system="linux" })) end
bsd-3-clause
yswifi/APlan
build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/ipkg-ramips_24kec/luci-proto-ppp/usr/lib/lua/luci/model/cbi/admin_network/proto_pptp.lua
59
3379
--[[ LuCI - Lua Configuration Interface Copyright 2011-2012 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 ]]-- local map, section, net = ... local server, username, password local defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu server = section:taboption("general", Value, "server", translate("VPN Server")) server.datatype = "host" username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
gpl-2.0
bnetcc/darkstar
scripts/zones/Temenos/bcnms/central_temenos_3rd_floor.lua
35
1139
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[C_Temenos_3rd]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1305),TEMENOS); HideTemenosDoor(GetInstanceRegion(1305)); player:setVar("Limbus_Trade_Item-T",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[C_Temenos_3rd]UniqueID")); player:setVar("LimbusID",1305); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
TheRaffy/OpenRA
mods/cnc/maps/nod06b/nod06b.lua
1
7038
NodUnitsVehicle1 = { 'bggy', 'bggy', 'bike', 'bike', 'bike' } NodUnitsVehicle2 = { 'ltnk', 'ltnk', 'ltnk' } NodUnitsGunner = { 'e1', 'e1', 'e1', 'e1', 'e1', 'e1' } NodUnitsRocket = { 'e3', 'e3', 'e3', 'e3', 'e3', 'e3' } Gdi1Units = { 'e1', 'e1', 'e2', 'e2', 'e2' } HuntCellTriggerActivator = { CPos.New(61,34), CPos.New(60,34), CPos.New(59,34), CPos.New(58,34), CPos.New(57,34), CPos.New(56,34), CPos.New(55,34), CPos.New(61,33), CPos.New(60,33), CPos.New(59,33), CPos.New(58,33), CPos.New(57,33), CPos.New(56,33) } DzneCellTriggerActivator = { CPos.New(50,30), CPos.New(49,30), CPos.New(48,30), CPos.New(47,30), CPos.New(46,30), CPos.New(45,30), CPos.New(50,29), CPos.New(49,29), CPos.New(48,29), CPos.New(47,29), CPos.New(46,29), CPos.New(45,29), CPos.New(50,28), CPos.New(49,28), CPos.New(48,28), CPos.New(47,28), CPos.New(46,28), CPos.New(45,28), CPos.New(50,27), CPos.New(49,27), CPos.New(46,27), CPos.New(45,27), CPos.New(50,26), CPos.New(49,26), CPos.New(48,26), CPos.New(47,26), CPos.New(46,26), CPos.New(45,26), CPos.New(50,25), CPos.New(49,25), CPos.New(48,25), CPos.New(47,25), CPos.New(46,25), CPos.New(45,25) } Win1CellTriggerActivator = { CPos.New(47,27) } Win2CellTriggerActivator = { CPos.New(57,57), CPos.New(56,57), CPos.New(55,57), CPos.New(57,56), CPos.New(56,56), CPos.New(55,56), CPos.New(57,55), CPos.New(56,55), CPos.New(55,55), CPos.New(57,54), CPos.New(56,54), CPos.New(55,54), CPos.New(57,53), CPos.New(56,53), CPos.New(55,53), CPos.New(57,52), CPos.New(56,52), CPos.New(55,52) } ChnCellTriggerActivator = { CPos.New(61,52), CPos.New(60,52), CPos.New(59,52), CPos.New(58,52), CPos.New(61,51), CPos.New(60,51), CPos.New(59,51), CPos.New(58,51), CPos.New(61,50), CPos.New(60,50), CPos.New(59,50), CPos.New(58,50) } Chn1ActorTriggerActivator = { Chn1Actor1, Chn1Actor2 } Chn2ActorTriggerActivator = { Chn2Actor1 } Atk1ActorTriggerActivator = { Atk1Actor1, Atk1Actor2 } Atk2ActorTriggerActivator = { Atk2Actor1, Atk2Actor2 } Chn1Waypoints = { ChnEntry.Location, waypoint0.Location } Chn2Waypoints = { ChnEntry.Location, waypoint0.Location } Gdi5Waypoint = { waypoint1, waypoint2, waypoint3, waypoint4, waypoint5, waypoint6, waypoint7 } HuntTriggerFunction = function() local list = GDI.GetGroundAttackers() Utils.Do(list, function(unit) IdleHunt(unit) end) end Win1TriggerFunction = function() NodObjective2 = Nod.AddPrimaryObjective("Move to the evacuation point.") Nod.MarkCompletedObjective(NodObjective1) end Chn1TriggerFunction = function() if not Chn1Switch then local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Gdi1Units, Chn1Waypoints, { ChnEntry.Location })[2] Utils.Do(cargo, function(actor) IdleHunt(actor) end) Chn1Switch = true end end Atk1TriggerFunction = function() if not Atk1Switch then for type, count in pairs({ ['e2'] = 2, ['jeep'] = 1, ['e1'] = 2}) do MyActors = Utils.Take(count, GDI.GetActorsByType(type)) Utils.Do(MyActors, function(actor) IdleHunt(actor) end) end Atk1Switch = true end end Atk2TriggerFunction = function() if not Atk2Switch then for type, count in pairs({ ['e2'] = 2, ['e1'] = 2}) do MyActors = Utils.Take(count, GDI.GetActorsByType(type)) Utils.Do(MyActors, function(actor) MoveAndHunt(actor, Gdi5Waypoint) end) end Atk2Switch = true end end Chn2TriggerFunction = function() if not Chn2Switch then local cargo = Reinforcements.ReinforceWithTransport(GDI, 'tran', Gdi1Units, Chn2Waypoints, { ChnEntry.Location })[2] Utils.Do(cargo, function(actor) IdleHunt(actor) end) Chn2Switch = true end end MoveAndHunt = function(unit, waypoints) if unit ~= nil then Utils.Do(waypoints, function(waypoint) unit.AttackMove(waypoint.Location) end) IdleHunt(unit) end end InsertNodUnits = function() Media.PlaySpeechNotification(Nod, "Reinforce") Camera.Position = UnitsRallyVehicle2.CenterPosition Reinforcements.Reinforce(Nod, NodUnitsVehicle1, { UnitsEntryVehicle.Location, UnitsRallyVehicle1.Location }, 10) Reinforcements.Reinforce(Nod, NodUnitsVehicle2, { UnitsEntryVehicle.Location, UnitsRallyVehicle2.Location }, 15) Reinforcements.Reinforce(Nod, NodUnitsGunner, { UnitsEntryGunner.Location, UnitsRallyGunner.Location }, 15) Reinforcements.Reinforce(Nod, NodUnitsRocket, { UnitsEntryRocket.Location, UnitsRallyRocket.Location }, 25) end initialSong = "rout" PlayMusic = function() Media.PlayMusic(initialSong, PlayMusic) initialSong = nil end WorldLoaded = function() GDI = Player.GetPlayer("GDI") Nod = Player.GetPlayer("Nod") Trigger.OnObjectiveAdded(Nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective") end) Trigger.OnObjectiveCompleted(Nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed") end) Trigger.OnObjectiveFailed(Nod, function(p, id) Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed") end) Trigger.OnPlayerWon(Nod, function() Media.PlaySpeechNotification(Nod, "Win") end) Trigger.OnPlayerLost(Nod, function() Media.PlaySpeechNotification(Nod, "Lose") end) NodObjective1 = Nod.AddPrimaryObjective("Steal the GDI nuclear detonator.") GDIObjective = GDI.AddPrimaryObjective("Stop the Nod taskforce from escaping with the detonator.") PlayMusic() InsertNodUnits() Trigger.OnEnteredFootprint(HuntCellTriggerActivator, function(a, id) if a.Owner == Nod then HuntTriggerFunction() Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(DzneCellTriggerActivator, function(a, id) if a.Owner == Nod then Actor.Create('flare', true, { Owner = Nod, Location = waypoint17.Location }) Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(Win1CellTriggerActivator, function(a, id) if a.Owner == Nod then Win1TriggerFunction() Trigger.RemoveFootprintTrigger(id) end end) Trigger.OnEnteredFootprint(Win2CellTriggerActivator, function(a, id) if a.Owner == Nod and NodObjective2 then Nod.MarkCompletedObjective(NodObjective2) Trigger.RemoveFootprintTrigger(id) end end) OnAnyDamaged(Chn1ActorTriggerActivator, Chn1TriggerFunction) OnAnyDamaged(Atk1ActorTriggerActivator, Atk1TriggerFunction) OnAnyDamaged(Atk2ActorTriggerActivator, Atk2TriggerFunction) OnAnyDamaged(Chn2ActorTriggerActivator, Chn2TriggerFunction) Trigger.OnEnteredFootprint(ChnCellTriggerActivator, function(a, id) if a.Owner == Nod then Media.PlaySpeechNotification(Nod, "Reinforce") Reinforcements.ReinforceWithTransport(Nod, 'tran', nil, { ChnEntry.Location, waypoint17.Location }, nil, nil, nil) Trigger.RemoveFootprintTrigger(id) end end) end Tick = function() if Nod.HasNoRequiredUnits() then if DateTime.GameTime > 2 then GDI.MarkCompletedObjective(GDIObjective) end end end IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end OnAnyDamaged = function(actors, func) Utils.Do(actors, function(actor) Trigger.OnDamaged(actor, func) end) end
gpl-3.0
ameihm0912/MozDef
examples/heka-lua-bro/bro_notice.lua
2
3908
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. -- Copyright (c) 2014 Mozilla Corporation -- -- Contributors: -- Anthony Verez averez@mozilla.com -- Jeff Bryner jbryner@mozilla.com -- Michal Purzynski mpurzynski@mozilla.com local l=require "lpeg" local string=require "string" l.locale(l) --add locale entries in the lpeg table local space = l.space^0 --define a space constant local sep = l.P"\t" local elem = l.C((1-sep)^0) grammar = l.Ct(elem * (sep * elem)^0) -- split on tabs, return as table function toString(value) if value == "-" then return "" end return value end function toNumber(value) if value == "-" then return 0 end return tonumber(value) end function lastField(value) -- remove last "\n" if there's one if value ~= nil and string.len(value) > 1 and string.sub(value, -2) == "\n" then return string.sub(value, 1, -2) end return value end function lastField(value) -- remove last "\n" if there's one if value ~= nil and string.len(value) > 1 and string.sub(value, -2) == "\n" then return string.sub(value, 1, -2) end return value end function validIP(value) if string.find(value, "-") then return "0.0.0.0" end end function validPort(value) if string.find(value, "-") then return "0" end end function process_message() local log = read_message("Payload") --set a default msg that heka's --message matcher can ignore via a message matcher: -- message_matcher = "( Type!='heka.all-report' && Type != 'IGNORE' )" local msg = { Type = "IGNORE", Fields={} } local matches = grammar:match(log) if not matches then --return 0 to not propogate errors to heka's log. --return a message with IGNORE type to not match heka's message matcher inject_message(msg) return 0 end if string.sub(log,1,1)=='#' then --it's a comment line inject_message(msg) return 0 end if string.find(matches[13], toString("unknown-")) then --noise from incorrect ssl parsing --unknown-6518900,unknown-11273317,unknown-4522550,unknown-12624352,unknown-4609124,unknown-12586245 inject_message(msg) return 0 end if string.find(matches[13], toString("empty")) then --noise from incorrect ssl parsing -- (empty) inject_message(msg) return 0 end msg['Type']='bronotice' msg['Logger']='nsm' msg['ts'] = toString(matches[1]) msg.Fields['uid'] = toString(matches[2]) msg.Fields['sourceipaddress'] = toString(validIP(matches[3])) msg.Fields['sourceport'] = toNumber(validPort(matches[4])) msg.Fields['destinationipaddress'] = toString(validIP(matches[5])) msg.Fields['destinationport'] = toNumber(validPort(matches[6])) msg.Fields['fuid'] = toString(matches[7]) msg.Fields['file_mime_type'] = toString(matches[8]) msg.Fields['file_desc'] = toString(matches[9]) msg.Fields['proto'] = toString(matches[10]) msg.Fields['note'] = toString(matches[11]) msg.Fields['msg'] = toString(matches[12]) msg.Fields['sub'] = toString(matches[13]) msg.Fields['src'] = toString(matches[14]) msg.Fields['dst'] = toString(matches[15]) msg.Fields['p'] = toString(matches[16]) msg.Fields['n'] = toString(matches[17]) msg.Fields['peer_descr'] = toString(matches[18]) msg.Fields['actions'] = toString(matches[19]) msg.Fields['suppress_for'] = toString(matches[20]) msg.Fields['dropped'] = toString(matches[21]) msg['Payload'] = toString(msg.Fields['note']) .. " " .. toString(msg.Fields['msg']) .. " " .. toString(msg.Fields['sub']) inject_message(msg) return 0 end
mpl-2.0
bnetcc/darkstar
scripts/globals/items/gae_assail.lua
3
2109
----------------------------------------- -- ID: 18299 -- Item: Gae Assail ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/msg"); require("scripts/globals/weaponskills"); require("scripts/globals/weaponskillids"); ----------------------------------- local NAME_WEAPONSKILL = "AFTERMATH_GAE_ASSAIL"; local NAME_EFFECT_LOSE = "AFTERMATH_LOST_GAE_ASSAIL"; -- https://www.bg-wiki.com/bg/Relic_Aftermath local aftermathTable = {}; -- Gae Assail 75 aftermathTable[18299] = { power=1, duration = function(tp) return math.floor(0.02 * tp); end, mods = { { id=MOD_SPIKES, power=SUBEFFECT_SHOCK_SPIKES }, { id=MOD_SPIKES_DMG, power=10 } } }; function onWeaponskill(user, target, wsid, tp, action) if (wsid == WEAPONSKILL_GEIRSKOGUL) then -- Gierskogul onry local itemId = user:getEquipID(SLOT_MAIN); if (aftermathTable[itemId]) then -- Apply the effect and add mods addAftermathEffect(user, tp, aftermathTable[itemId]); -- Add a listener for when aftermath wears (to remove mods) user:addListener("EFFECT_LOSE", NAME_EFFECT_LOSE, aftermathLost); end end end function aftermathLost(target, effect) if (effect:getType() == EFFECT_AFTERMATH) then local itemId = target:getEquipID(SLOT_MAIN); if (aftermathTable[itemId]) then -- Remove mods removeAftermathEffect(target, aftermathTable[itemId]); -- Remove the effect listener target:removeListener(NAME_EFFECT_LOSE); end end end function onItemCheck(player, param, caster) if (param == ITEMCHECK_EQUIP) then player:addListener("WEAPONSKILL_USE", NAME_WEAPONSKILL, onWeaponskill); elseif (param == ITEMCHECK_UNEQUIP) then -- Make sure we clean up the effect and mods if (player:hasStatusEffect(EFFECT_AFTERMATH)) then aftermathLost(player, player:getStatusEffect(EFFECT_AFTERMATH)); end player:removeListener(NAME_WEAPONSKILL); end return 0; end
gpl-3.0
bnetcc/darkstar
scripts/zones/Northern_San_dOria/npcs/Antonian.lua
5
1709
----------------------------------- -- Area: Northern San d'Oria -- NPC: Antonian -- Regional Marchant NPC -- Only sells when San d'Oria controlls Aragoneu. ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/events/harvest_festivals"); require("scripts/globals/settings"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end else onHalloweenTrade(player,trade,npc); end end; function onTrigger(player,npc) local RegionOwner = GetRegionOwner(ARAGONEU); if (RegionOwner ~= NATION_SANDORIA) then player:showText(npc,ANTONIAN_CLOSED_DIALOG); else player:showText(npc,ANTONIAN_OPEN_DIALOG); local stock = { 631, 36, -- Horo Flour 629, 43, -- Millioncorn 4415, 111, -- Roasted Corn 841, 36, -- Yagudo Feather 4505, 90 -- Sunflower Seeds } showShop(player,SANDORIA,stock); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
TurkeyMan/premake-core
modules/gmake2/tests/test_gmake2_file_rules.lua
5
8225
-- -- test_gmake2_file_rules.lua -- Validate the makefile source building rules. -- (c) 2016-2017 Jason Perkins, Blizzard Entertainment and the Premake project -- local suite = test.declare("gmake2_file_rules") local p = premake local gmake2 = p.modules.gmake2 -- -- Setup -- local wks, prj function suite.setup() p.escaper(gmake2.esc) gmake2.cpp.initialize() rule "TestRule" display "Test Rule" fileextension ".rule" propertydefinition { name = "TestProperty", kind = "boolean", value = false, switch = "-p" } propertydefinition { name = "TestProperty2", kind = "boolean", value = false, switch = "-p2" } propertydefinition { name = "TestListProperty", kind = "list" } propertydefinition { name = "TestListPropertySeparator", kind = "list", separator = "," } buildmessage 'Rule-ing %{file.name}' buildcommands 'dorule %{TestProperty} %{TestProperty2} %{TestListProperty} %{TestListPropertySeparator} "%{file.path}"' buildoutputs { "%{file.basename}.obj" } wks = test.createWorkspace() end local function prepare() prj = p.workspace.getproject(wks, 1) p.oven.bake() gmake2.cpp.createRuleTable(prj) gmake2.cpp.createFileTable(prj) gmake2.cpp.outputFileRuleSection(prj) end -- -- Two files with the same base name should have different object files. -- function suite.uniqueObjNames_onBaseNameCollision() files { "src/hello.cpp", "src/greetings/hello.cpp" } prepare() test.capture [[ # File Rules # ############################################# $(OBJDIR)/hello.o: src/greetings/hello.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/hello1.o: src/hello.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end -- -- C files in C++ projects should been compiled as c -- function suite.cFilesGetsCompiledWithCCWhileInCppProject() files { "src/hello.c", "src/test.cpp" } prepare() test.capture [[ # File Rules # ############################################# $(OBJDIR)/hello.o: src/hello.c @echo $(notdir $<) $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/test.o: src/test.cpp @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end -- -- C files in C++ projects can be compiled as C++ with compileas -- function suite.cFilesGetsCompiledWithCXXWithCompileas() files { "src/hello.c", "src/test.c" } filter { "files:src/hello.c" } compileas "C++" prepare() test.capture [[ # File Rules # ############################################# $(OBJDIR)/hello.o: src/hello.c @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" $(OBJDIR)/test.o: src/test.c @echo $(notdir $<) $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ]] end -- -- C files in C++ projects can be compiled as C++ with 'compileas' on a configuration basis -- function suite.cFilesGetsCompiledWithCXXWithCompileasDebugOnly() files { "src/hello.c", "src/test.c" } filter { "configurations:Debug", "files:src/hello.c" } compileas "C++" prepare() test.capture [[ # File Rules # ############################################# $(OBJDIR)/test.o: src/test.c @echo $(notdir $<) $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" ifeq ($(config),debug) $(OBJDIR)/hello.o: src/hello.c @echo $(notdir $<) $(SILENT) $(CXX) $(ALL_CXXFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" else ifeq ($(config),release) $(OBJDIR)/hello.o: src/hello.c @echo $(notdir $<) $(SILENT) $(CC) $(ALL_CFLAGS) $(FORCE_INCLUDE) -o "$@" -MF "$(@:%.o=%.d)" -c "$<" else $(error "invalid configuration $(config)") endif ]] end -- -- If a custom build rule is supplied, it should be used. -- function suite.customBuildRule() files { "hello.x" } filter "files:**.x" buildmessage "Compiling %{file.name}" buildcommands { 'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"', 'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"' } buildoutputs { "%{cfg.objdir}/%{file.basename}.obj" } prepare() test.capture [[ # File Rules # ############################################# ifeq ($(config),debug) obj/Debug/hello.obj: hello.x @echo Compiling hello.x $(SILENT) cxc -c "hello.x" -o "obj/Debug/hello.xo" $(SILENT) c2o -c "obj/Debug/hello.xo" -o "obj/Debug/hello.obj" else ifeq ($(config),release) obj/Release/hello.obj: hello.x @echo Compiling hello.x $(SILENT) cxc -c "hello.x" -o "obj/Release/hello.xo" $(SILENT) c2o -c "obj/Release/hello.xo" -o "obj/Release/hello.obj" else $(error "invalid configuration $(config)") endif ]] end function suite.customBuildRuleWithAdditionalInputs() files { "hello.x" } filter "files:**.x" buildmessage "Compiling %{file.name}" buildcommands { 'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"', 'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"' } buildoutputs { "%{cfg.objdir}/%{file.basename}.obj" } buildinputs { "%{file.path}.inc", "%{file.path}.inc2" } prepare() test.capture [[ # File Rules # ############################################# ifeq ($(config),debug) obj/Debug/hello.obj: hello.x hello.x.inc hello.x.inc2 @echo Compiling hello.x $(SILENT) cxc -c "hello.x" -o "obj/Debug/hello.xo" $(SILENT) c2o -c "obj/Debug/hello.xo" -o "obj/Debug/hello.obj" else ifeq ($(config),release) obj/Release/hello.obj: hello.x hello.x.inc hello.x.inc2 @echo Compiling hello.x $(SILENT) cxc -c "hello.x" -o "obj/Release/hello.xo" $(SILENT) c2o -c "obj/Release/hello.xo" -o "obj/Release/hello.obj" else $(error "invalid configuration $(config)") endif ]] end function suite.customBuildRuleWithAdditionalOutputs() files { "hello.x" } filter "files:**.x" buildmessage "Compiling %{file.name}" buildcommands { 'cxc -c "%{file.path}" -o "%{cfg.objdir}/%{file.basename}.xo"', 'c2o -c "%{cfg.objdir}/%{file.basename}.xo" -o "%{cfg.objdir}/%{file.basename}.obj"' } buildoutputs { "%{cfg.objdir}/%{file.basename}.obj", "%{cfg.objdir}/%{file.basename}.other", "%{cfg.objdir}/%{file.basename}.another" } prepare() test.capture [[ # File Rules # ############################################# ifeq ($(config),debug) obj/Debug/hello.obj: hello.x @echo Compiling hello.x $(SILENT) cxc -c "hello.x" -o "obj/Debug/hello.xo" $(SILENT) c2o -c "obj/Debug/hello.xo" -o "obj/Debug/hello.obj" obj/Debug/hello.other obj/Debug/hello.another: obj/Debug/hello.obj else ifeq ($(config),release) obj/Release/hello.obj: hello.x @echo Compiling hello.x $(SILENT) cxc -c "hello.x" -o "obj/Release/hello.xo" $(SILENT) c2o -c "obj/Release/hello.xo" -o "obj/Release/hello.obj" obj/Release/hello.other obj/Release/hello.another: obj/Release/hello.obj else $(error "invalid configuration $(config)") endif ]] end function suite.customRuleWithProps() rules { "TestRule" } files { "test.rule", "test2.rule" } testRuleVars { TestProperty = true } filter "files:test2.rule" testRuleVars { TestProperty2 = true } prepare() test.capture [[ # File Rules # ############################################# test.obj: test.rule @echo Rule-ing test.rule $(SILENT) dorule -p "test.rule" test2.obj: test2.rule @echo Rule-ing test2.rule $(SILENT) dorule -p -p2 "test2.rule" ]] end function suite.propertydefinitionSeparator() rules { "TestRule" } files { "test.rule", "test2.rule" } filter "files:test.rule" testRuleVars { TestListProperty = { "testValue1", "testValue2" } } filter "files:test2.rule" testRuleVars { TestListPropertySeparator = { "testValue1", "testValue2" } } prepare() test.capture [[ # File Rules # ############################################# test.obj: test.rule @echo Rule-ing test.rule $(SILENT) dorule testValue1\ testValue2 "test.rule" test2.obj: test2.rule @echo Rule-ing test2.rule $(SILENT) dorule testValue1,testValue2 "test2.rule" ]] end
bsd-3-clause
bnetcc/darkstar
scripts/globals/spells/silencega.lua
3
1324
----------------------------------------- -- Spell: Silence ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/msg"); ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effectType = EFFECT_SILENCE; if (target:hasStatusEffect(effectType)) then spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect return effectType; end --Pull base stats. local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND)); --Duration, including resistance. May need more research. local duration = 120; --Resist local params = {}; params.diff = nil; params.attribute = MOD_MND; params.skillType = 35; params.bonus = 0; params.effect = EFFECT_SILENCE; local resist = applyResistanceEffect(caster, target, spell, params); if (resist >= 0.5) then --Do it! if (target:addStatusEffect(effectType,1,0,duration * resist)) then spell:setMsg(msgBasic.MAGIC_ENFEEB_IS); else spell:setMsg(msgBasic.MAGIC_NO_EFFECT); -- no effect end else spell:setMsg(msgBasic.MAGIC_RESIST); end return effectType; end;
gpl-3.0
legospacy/hue-shift
states/game.lua
1
1934
--- Require --- local gamestate = require("lib.hump.gamestate") local timer = require("lib.hump.timer") local util = require("lib.self.util") --- ==== --- --- Classes --- local Game = require("objects.game.game") local Song = require("objects.game.song") --- ==== --- --- Gamestate definition --- local game = {} --- ==== --- --- Constants --- local TRANSITION_DUR = 0.5 --- ==== --- --- Gamestate functions --- function game:init() end function game:fadein() self.state = "fadein" self.tween = timer.tween(TRANSITION_DUR, self.game, {alpha = 1}, "linear", function() self.state = "game" self.game:start() end) end function game:fadeout(after) self.state = "fadeout" self.tween = timer.tween(TRANSITION_DUR, self.game, {alpha = 0}, "linear", function() after(self) end) end function game:enter(prev, args) self.game = Game{ level = require("levels.001_relax"), music = Song("music/laserwash.ogg"), theme = require("themes.hueshift")(), n_players = 2, speed = 1 } self.state = "fadein" -- fadein, game, fadeout self.game.alpha = 0 self:fadein() end function game:exit() love.event.quit() end function game:update(dt) if self.state == "game" then self.game:update(dt) end end function game:draw() self.game:draw() end function game:keypressed(key) if key == "escape" then if self.game.state == "stopped" then self:fadeout(function(self) -- Fade out game. self:exit() end) elseif self.state == "fadeout" then --timer.cancel(self.tween) --self:exit() -- Exit because player is mashing escape. end end if self.state == "game" then self.game:keypressed(key) end end function game:mousepressed(x, y, b) if self.state == "game" then if b == "wu" then self.game.speed = util.math.clamp(0.2, self.game.speed + 0.2, 7) elseif b == "wd" then self.game.speed = util.math.clamp(0.2, self.game.speed - 0.2, 7) end end end --- ==== --- return game
mit
bnetcc/darkstar
scripts/zones/Kamihr_Drifts/Zone.lua
1
1188
----------------------------------- -- -- Zone: Kamihr Drifts -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Kamihr_Drifts/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Kamihr_Drifts/TextIDs"); ----------------------------------- function onInitialize(zone) end; function onZoneIn(player,prevZone) local cs = -1; player:setVar("HpTeleportMask1a", 0); player:setVar("HpTeleportMask1b", 0); player:setVar("HpTeleportMask2a", 0); player:setVar("HpTeleportMask2b", 0); player:setVar("HpTeleportMask3a", 0); player:setVar("HpTeleportMask3b", 0); player:setVar("HpTeleportMask4a", 0); player:setVar("HpTeleportMask4b", 0); if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(500,72,-479,191); end return cs; end; function onRegionEnter(player,region) end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
sonoprob/0x56
bot/lua/test/LuaSrcDiet-0.12.1/src/plugin/sloc.lua
2
4063
--[[-------------------------------------------------------------------- sloc.lua: Calculates SLOC for Lua 5.1 scripts This file is part of LuaSrcDiet. Copyright (c) 2008,2011 Kein-Hong Man <keinhong@gmail.com> The COPYRIGHT file describes the conditions under which this software may be distributed. ----------------------------------------------------------------------]] --[[-------------------------------------------------------------------- -- NOTES: -- WARNING: highly experimental! interface liable to change -- * SLOC's behaviour is based on David Wheeler's SLOCCount. -- * Empty lines and comment don't count as significant. -- * Empty lines in long strings are also insignificant. This is -- debatable. In SLOCCount, this allows counting of invalid multi- -- line strings for C. But an empty line is still an empty line. -- * Ignores the --quiet option, print own result line. ----------------------------------------------------------------------]] local base = _G module "plugin/sloc" local string = base.require "string" local table = base.require "table" ------------------------------------------------------------------------ -- initialization ------------------------------------------------------------------------ local option -- local reference to list of options local srcfl -- source file name function init(_option, _srcfl, _destfl) option = _option option.QUIET = true srcfl = _srcfl end ------------------------------------------------------------------------ -- splits a block into a table of lines (minus EOLs) ------------------------------------------------------------------------ local function split(blk) local lines = {} local i, nblk = 1, #blk while i <= nblk do local p, q, r, s = string.find(blk, "([\r\n])([\r\n]?)", i) if not p then p = nblk + 1 end lines[#lines + 1] = string.sub(blk, i, p - 1) i = p + 1 if p < nblk and q > p and r ~= s then -- handle Lua-style CRLF, LFCR i = i + 1 end end return lines end ------------------------------------------------------------------------ -- post-lexing processing, can work on lexer table output ------------------------------------------------------------------------ function post_lex(toklist, seminfolist, toklnlist) local lnow, sloc = 0, 0 local function chk(ln) -- if a new line, count it as an SLOC if ln > lnow then -- new line # must be > old line # sloc = sloc + 1; lnow = ln end end for i = 1, #toklist do -- enumerate over all tokens local tok, info, ln = toklist[i], seminfolist[i], toklnlist[i] -------------------------------------------------------------------- if tok == "TK_KEYWORD" or tok == "TK_NAME" or -- significant tok == "TK_NUMBER" or tok == "TK_OP" then chk(ln) -------------------------------------------------------------------- -- Both TK_STRING and TK_LSTRING may be multi-line, hence, a loop -- is needed in order to mark off lines one-by-one. Since llex.lua -- currently returns the line number of the last part of the string, -- we must subtract in order to get the starting line number. -------------------------------------------------------------------- elseif tok == "TK_STRING" then -- possible multi-line local t = split(info) ln = ln - #t + 1 for j = 1, #t do chk(ln); ln = ln + 1 end -------------------------------------------------------------------- elseif tok == "TK_LSTRING" then -- possible multi-line local t = split(info) ln = ln - #t + 1 for j = 1, #t do if t[j] ~= "" then chk(ln) end ln = ln + 1 end -------------------------------------------------------------------- -- other tokens are comments or whitespace and are ignored -------------------------------------------------------------------- end end--for base.print(srcfl..": "..sloc) -- display result option.EXIT = true end
artistic-2.0
bnetcc/darkstar
scripts/zones/Northern_San_dOria/npcs/Taulenne.lua
1
6018
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taulenne -- Armor Storage NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; package.loaded["scripts/globals/armorstorage"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/armorstorage"); require("scripts/globals/settings"); require("scripts/globals/quests"); local Deposit = 0x0304; local Withdrawl = 0x0305; local ArraySize = #StorageArray; local G1 = 0; local G2 = 0; local G3 = 0; local G4 = 0; local G5 = 0; function onTrade(player,npc,trade) local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then local count = trade:getItemCount(); local MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end for SetId = 1,ArraySize,11 do local TradeCount = trade:getItemCount(); local T1 = trade:hasItemQty(StorageArray[SetId + 5],1); if (T1 == true) then if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then if (TradeCount == StorageArray[SetId + 3]) then local T2 = trade:hasItemQty(StorageArray[SetId + 4],1); local T3 = trade:hasItemQty(StorageArray[SetId + 6],1); local T4 = trade:hasItemQty(StorageArray[SetId + 7],1); local T5 = trade:hasItemQty(StorageArray[SetId + 8],1); if (StorageArray[SetId + 4] == 0) then T2 = true; end if (StorageArray[SetId + 6] == 0) then T3 = true; end if (StorageArray[SetId + 7] == 0) then T4 = true; end if (StorageArray[SetId + 8] == 0) then T5 = true; end if (T2 == true and T3 == true and T4 == true and T5 == true) then player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]); player:addKeyItem(StorageArray[SetId + 10]); player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]); break; end end end end end end; function onTrigger(player,npc) -- Begin Temp Fix for broken AF quests player:addKeyItem(654); -- FIGHTERS_ARMOR_CLAIM_SLIP player:addKeyItem(655); -- TEMPLE_ATTIRE_CLAIM_SLIP player:addKeyItem(656); -- HEALERS_ATTIRE_CLAIM_SLIP player:addKeyItem(657); -- WIZARDS_ATTIRE_CLAIM_SLIP player:addKeyItem(658); -- WARLOCKS_ARMOR_CLAIM_SLIP player:addKeyItem(659); -- ROGUES_ATTIRE_CLAIM_SLIP player:addKeyItem(660); -- GALLANT_ARMOR_CLAIM_SLIP player:addKeyItem(661); -- CHAOS_ARMOR_CLAIM_SLIP player:addKeyItem(662); -- BEAST_ARMOR_CLAIM_SLIP player:addKeyItem(663); -- CHORAL_ATTIRE_CLAIM_SLIP player:addKeyItem(664); -- HUNTERS_ATTIRE_CLAIM_SLIP player:addKeyItem(665); -- MYOCHIN_ARMOR_CLAIM_SLIP player:addKeyItem(666); -- NINJAS_GARB_CLAIM_SLIP player:addKeyItem(667); -- DRACHEN_ARMOR_CLAIM_SLIP player:addKeyItem(668); -- EVOKERS_ATTIRE_CLAIM_SLIP player:addKeyItem(1964); -- MAGUS_ATTIRE_CLAIM_SLIP player:addKeyItem(1965); -- CORSAIRS_ATTIRE_CLAIM_SLIP player:addKeyItem(1966); -- PUPPETRY_ATTIRE_CLAIM_SLIP player:addKeyItem(1967); -- DANCERS_ATTIRE_CLAIM_SLIP player:addKeyItem(1968); -- DANCERS_ATTIRE_CLAIM_SLIP player:addKeyItem(1969); -- SCHOLARS_ATTIRE_CLAIM_SLIP -- End Temp Fix local CurrGil = player:getGil(); for KeyItem = 11,ArraySize,11 do if player:hasKeyItem(StorageArray[KeyItem]) then if StorageArray[KeyItem - 9] == 1 then G1 = G1 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 2 then G2 = G2 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 3 then G3 = G3 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 4 then G4 = G4 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 6 then G5 = G5 + StorageArray[KeyItem - 8]; end end end player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5); end; function onEventUpdate(player,csid,option) if (csid == Withdrawl) then player:updateEvent( StorageArray[option * 11 - 6], StorageArray[option * 11 - 5], StorageArray[option * 11 - 4], StorageArray[option * 11 - 3], StorageArray[option * 11 - 2], StorageArray[option * 11 - 1]); end end; function onEventFinish(player,csid,option) if (csid == Withdrawl) then if (option > 0 and option <= StorageArray[ArraySize] - 10) then if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:addItem(StorageArray[option * 11 - Item],1); player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]); end end player:delKeyItem(StorageArray[option * 11]); player:setGil(player:getGil() - StorageArray[option * 11 - 1]); else for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]); end end end end end if (csid == Deposit) then player:tradeComplete(); end end;
gpl-3.0
bnetcc/darkstar
scripts/globals/items/crepe_delice.lua
3
1231
----------------------------------------- -- ID: 5767 -- Item: Crepe Delice -- Food Effect: 30 Min, All Races ----------------------------------------- -- HP +10% (cap 15) -- Magic Accuracy +21% (cap 30) -- Magic Defense +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- 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; function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5767); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 15); target:addMod(MOD_MDEF, 2); target:addMod(MOD_FOOD_MACCP, 21); target:addMod(MOD_FOOD_MACC_CAP, 30); end; function onEffectLose(target, effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 15); target:delMod(MOD_MDEF, 2); target:delMod(MOD_FOOD_MACCP, 21); target:delMod(MOD_FOOD_MACC_CAP, 30); end;
gpl-3.0
mwoz123/koreader
spec/unit/networksetting_spec.lua
8
3078
describe("NetworkSetting module", function() local NetworkSetting, NetworkMgr, UIManager setup(function() require("commonrequire") UIManager = require("ui/uimanager") NetworkSetting = require("ui/widget/networksetting") NetworkMgr = require("ui/network/manager") end) it("should initilize properly with empty network list", function() local ns = NetworkSetting:new{network_list = {}} assert.is.falsy(ns.connected_item) end) it("should NOT call connect_callback after disconnect", function() stub(NetworkMgr, "disconnectNetwork") stub(NetworkMgr, "releaseIP") UIManager:quit() local called = false local network_list = { { ssid = "foo", signal_level = -58, flags = "[WPA2-PSK-CCMP][ESS]", signal_quality = 84, password = "123abc", connected = true, }, } local ns = NetworkSetting:new{ network_list = network_list, connect_callback = function() called = true end } ns.connected_item:disconnect() assert.falsy(called) NetworkMgr.disconnectNetwork:revert() NetworkMgr.releaseIP:revert() end) it("should call disconnect_callback after disconnect", function() stub(NetworkMgr, "disconnectNetwork") stub(NetworkMgr, "releaseIP") UIManager:quit() local called = false local network_list = { { ssid = "foo", signal_level = -58, flags = "[WPA2-PSK-CCMP][ESS]", signal_quality = 84, password = "123abc", connected = true, }, } local ns = NetworkSetting:new{ network_list = network_list, disconnect_callback = function() called = true end } ns.connected_item:disconnect() assert.truthy(called) NetworkMgr.disconnectNetwork:revert() NetworkMgr.releaseIP:revert() end) it("should set connected_item to nil after disconnect", function() stub(NetworkMgr, "disconnectNetwork") stub(NetworkMgr, "releaseIP") UIManager:quit() local network_list = { { ssid = "foo", signal_level = -58, flags = "[WPA2-PSK-CCMP][ESS]", signal_quality = 84, password = "123abc", connected = true, }, { ssid = "bar", signal_level = -258, signal_quality = 44, flags = "[WEP][ESS]", }, } local ns = NetworkSetting:new{network_list = network_list} assert.is.same("foo", ns.connected_item.info.ssid) ns.connected_item:disconnect() assert.is.falsy(ns.connected_item) NetworkMgr.disconnectNetwork:revert() NetworkMgr.releaseIP:revert() end) end)
agpl-3.0
Zaratusa/gmod_addons
gamemodes/terrortown/entities/weapons/weapon_ttt_sandwich/shared.lua
2
5922
--[[Author informations]]-- SWEP.Author = "Zaratusa" SWEP.Contact = "http://steamcommunity.com/profiles/76561198032479768" CreateConVar("ttt_sandwich_detective", 1, {FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE, FCVAR_REPLICATED}, "Should Detectives be able to use the Sandwich?") CreateConVar("ttt_sandwich_traitor", 1, {FCVAR_SERVER_CAN_EXECUTE, FCVAR_ARCHIVE, FCVAR_REPLICATED}, "Should Traitors be able to use the Sandwich?") if SERVER then AddCSLuaFile() resource.AddWorkshop("645663146") else LANG.AddToLanguage("english", "sandwich_name", "Sandwich") LANG.AddToLanguage("english", "sandwich_desc", "Have a snack\nand heal yourself or others.\nBe careful when you throw it\non the ground, it can spoil.") SWEP.PrintName = "sandwich_name" SWEP.Slot = 7 SWEP.Icon = "vgui/ttt/icon_sandwich" -- client side model settings SWEP.UseHands = true -- should the hands be displayed SWEP.ViewModelFlip = false -- should the weapon be hold with the left or the right hand SWEP.ViewModelFOV = 70 -- Equipment menu information is only needed on the client SWEP.EquipMenuData = { type = "item_weapon", desc = "sandwich_desc" } end -- always derive from weapon_tttbase SWEP.Base = "weapon_tttbase" --[[Default GMod values]]-- SWEP.Primary.Ammo = "none" SWEP.Primary.Delay = 2 SWEP.Primary.Automatic = false SWEP.Primary.ClipSize = 4 SWEP.Primary.DefaultClip = 4 SWEP.HealAmount = 25 --[[Model settings]]-- SWEP.HoldType = "slam" SWEP.ViewModel = Model("models/weapons/zaratusa/sandwich/v_sandwich.mdl") SWEP.WorldModel = Model("models/weapons/zaratusa/sandwich/w_sandwich.mdl") --[[TTT config values]]-- -- Kind specifies the category this weapon is in. Players can only carry one of -- each. Can be: WEAPON_... MELEE, PISTOL, HEAVY, NADE, CARRY, EQUIP1, EQUIP2 or ROLE. -- Matching SWEP.Slot values: 0 1 2 3 4 6 7 8 SWEP.Kind = WEAPON_EQUIP2 -- If AutoSpawnable is true and SWEP.Kind is not WEAPON_EQUIP1/2, -- then this gun can be spawned as a random weapon. SWEP.AutoSpawnable = false -- The AmmoEnt is the ammo entity that can be picked up when carrying this gun. SWEP.AmmoEnt = "none" -- CanBuy is a table of ROLE_* entries like ROLE_TRAITOR and ROLE_DETECTIVE. If -- a role is in this table, those players can buy this. SWEP.CanBuy = {} if (GetConVar("ttt_sandwich_detective"):GetBool()) then table.insert(SWEP.CanBuy, ROLE_DETECTIVE) end if (GetConVar("ttt_sandwich_traitor"):GetBool()) then table.insert(SWEP.CanBuy, ROLE_TRAITOR) end -- If LimitedStock is true, you can only buy one per round. SWEP.LimitedStock = true -- If AllowDrop is false, players can't manually drop the gun with Q SWEP.AllowDrop = true -- If IsSilent is true, victims will not scream upon death. SWEP.IsSilent = false -- If NoSights is true, the weapon won't have ironsights SWEP.NoSights = false local HealSound = Sound("weapons/sandwich/eat.wav") function SWEP:SetupDataTables() self:NetworkVar("Int", 0, "Permanency") end function SWEP:Initialize() self.FirstCheck = true self:SetPermanency(100) end function SWEP:PrimaryAttack() if (SERVER and self:CanPrimaryAttack() and self:GetNextPrimaryFire() <= CurTime()) then self:SetNextPrimaryFire(CurTime() + self.Primary.Delay) local owner = self.Owner if (IsValid(owner)) then local tr = util.TraceLine({ start = owner:GetShootPos(), endpos = owner:GetShootPos() + owner:GetAimVector() * 80, filter = owner, mask = MASK_SOLID }) local ent = tr.Entity if (IsValid(ent) and ent:IsPlayer()) then self:Heal(ent) end end end end function SWEP:SecondaryAttack() if (SERVER and self:CanSecondaryAttack() and self:GetNextSecondaryFire() <= CurTime()) then self:SetNextSecondaryFire(CurTime() + self.Primary.Delay) local owner = self.Owner if (IsValid(owner)) then self:Heal(owner) end end end -- heals or damages the given player, depending on the permanency function SWEP:Heal(player) -- get a value between -1.0 and 1.0 local perm = (self:GetPermanency() - 50) / 50 if (self:GetPermanency() < 50) then local damage = -1 * perm * self.HealAmount -- random change of 25% to die, due to the sandwich if ((player:Health() - damage) <= 0 and math.random() > 0.25) then damage = (1 - player:Health()) * -1 -- decreases life to 1 end local dmg = DamageInfo() dmg:SetDamage(damage) dmg:SetAttacker(self.Owner) dmg:SetInflictor(self.Weapon) dmg:SetDamageType(DMG_PARALYZE) dmg:SetDamagePosition(player:GetPos()) player:TakeDamageInfo(dmg) else player:SetHealth(math.min(player:GetMaxHealth(), player:Health() + (perm * self.HealAmount))) end player:EmitSound(HealSound) player:SetAnimation(PLAYER_ATTACK1) self:TakePrimaryAmmo(1) if (self.Weapon:Clip1() < 1) then self:Remove() end end function SWEP:OnDrop() if (IsValid(self) and self:GetPermanency() > 0) then if (self.FirstCheck) then timer.Simple(3, function() if (IsValid(self) and self.FirstCheck) then self:SetPermanency(50) self.FirstCheck = false end end) end local ID = self:EntIndex() timer.Create("SandwichPermDec" .. ID, 2, 0, function() if (IsValid(self) and self:GetPermanency() > 0) then self:SetPermanency(self:GetPermanency() - 5) else timer.Remove("SandwichPermDec" .. ID) end end) end end function SWEP:Deploy() timer.Remove("SandwichPermDec" .. self:EntIndex()) return true end function SWEP:OnRemove() if (CLIENT and IsValid(self.Owner) and self.Owner == LocalPlayer() and self.Owner:Alive()) then RunConsoleCommand("lastinv") end end function SWEP:DrawHUD() local x = ScrW() / 2.0 local y = ScrH() * 0.995 draw.SimpleText("Primary attack to feed someone else.", "Default", x, y - 20, COLOR_WHITE, TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM) draw.SimpleText("Secondary attack to eat.", "Default", x, y, COLOR_WHITE, TEXT_ALIGN_CENTER, TEXT_ALIGN_BOTTOM) return self.BaseClass.DrawHUD(self) end
gpl-3.0