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 |
|---|---|---|---|---|---|
nyczducky/darkstar | scripts/globals/items/bowl_of_turtle_soup.lua | 12 | 1552 | -----------------------------------------
-- ID: 4418
-- Item: Turtle Soup
-- Food Effect: 3hours, All Races
-----------------------------------------
-- HP + 10% (200 Cap)
-- Dexterity +4
-- Vitality +6
-- Mind -3
-- HP Recovered While Healing +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4418);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 10);
target:addMod(MOD_FOOD_HP_CAP, 200);
target:addMod(MOD_DEX, 4);
target:addMod(MOD_VIT, 6);
target:addMod(MOD_MND, -3);
target:addMod(MOD_HPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 10);
target:delMod(MOD_FOOD_HP_CAP, 200);
target:delMod(MOD_DEX, 4);
target:delMod(MOD_VIT, 6);
target:delMod(MOD_MND, -3);
target:delMod(MOD_HPHEAL, 5);
end;
| gpl-3.0 |
pouria346/selfbot2 | plugins/ctrl.lua | 1 | 2305 | local function reload_plugins( )
plugins = {}
return load_plugins()
end
function run_bash(command)
local cmd = io.popen(command)
local result = cmd:read('*all')
cmd:close()
return result
end
local function is_channel_disabled( receiver )
if not _config.disabled_channels then
return false
end
if _config.disabled_channels[receiver] == nil then
return false
end
return _config.disabled_channels[receiver]
end
local function enable_channel(receiver, to_id)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
if _config.disabled_channels[receiver] == nil then
return 'سلف بات روشن شد'
end
_config.disabled_channels[receiver] = false
save_config()
return 'سلف بات روشن شد'
end
local function disable_channel(receiver, to_id)
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return 'سلف بات خاموش شد'
end
local function pre_process(msg)
local receiver = get_receiver(msg)
-- If sender is sudo then re-enable the channel
if is_sudo(msg) then
if msg.text == "#bot on" then
enable_channel(receiver, msg.to.id)
end
end
if is_channel_disabled(receiver) then
msg.text = ""
end
return msg
end
local function run(msg, matches)
if permissions(msg.from.id, msg.to.id, "bot") then
local receiver = get_receiver(msg)
-- Enable a channel
if matches[1] == 'on' then
return enable_channel(receiver, msg.to.id)
end
-- Disable a channel
if matches[1] == 'off' then
return disable_channel(receiver, msg.to.id)
end
else
return
end
if matches[1] == 'up' then
if not is_sudo(msg) then
return nil
end
local receiver = get_receiver(msg)
if string.match then
local command = 'git pull'
text = run_bash(command)
local text = text..'Updates were applied GitHub\n@BeatBot_Team'
return text
end
end
if matches[1] == 'rl' and is_sudo(msg) then
receiver = get_receiver(msg)
reload_plugins(true)
post_msg(receiver, "Reloaded!", ok_cb, false)
return "All plugins reloaded!"
end
end
return {
patterns = {
"^#bot? (on)$",
"^#bot? (off)$",
"^#bot? (up)$",
"^#bot (rl)$",
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
jamesbdunlop/iction | frames/insanityFrame.lua | 1 | 2475 | local iction = iction
iction.ictInsanityData = {
uiName = "iction_insanityFrame",
nameAttr = "iction_insanityFrame",
uiInherits = nil,
userPlaced = true,
movable = true,
enableMouse = false,
SetClampedToScreen = true,
w = 100,
h = iction.bh/2,
bgCol = {r = 0, g = 1, b= 0, a = .5},
strata = "MEDIUM",
pointPosition = {point = "BOTTOM",
relativeTo = nil,
relativePoint = "CENTER",
x = 0, y = 80},
textures = { [1] = {name = "insanityMOVEFRAME", allPoints = true, level = "ARTWORK",
texture= "Interface\\ChatFrame\\ChatFrameBackground",
vr = 1, vg = 1, vb = 1, va = .1 },
[2] = { name = "insanity",
allPoints = false,
anchorPoint = "LEFT",
apX = -3,
apY = 0,
w = 106,
h= iction.bh/1.8,
level = "BACKGROUND",
texture= "Interface\\ChatFrame\\ChatFrameBackground",
vr = 0, vg = 0, vb = 0, va = 1},
[3] = { name = "insanity2",
allPoints = false,
anchorPoint = "LEFT",
apX = 0,
apY = 0,
w = 1,
h= iction.bh/2,
level = "BACKGROUND",
texture= "Interface\\ChatFrame\\ChatFrameBackground",
vr = 0.5, vg = 0.1, vb = 1, va = 1 }
}
}
| apache-2.0 |
nyczducky/darkstar | scripts/zones/Windurst_Woods/npcs/Bozack.lua | 14 | 1049 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Bozack
-- Type: Event Replayer
-- @zone 241
-- @pos 92.591 -5.58 -31.529
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0264);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Pashhow_Marshlands_[S]/Zone.lua | 12 | 2041 | -----------------------------------
--
-- Zone: Pashhow_Marshlands_[S] (90)
--
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Pashhow_Marshlands_[S]/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/weather");
require("scripts/globals/status");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(547.841,23.192,696.323,134);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onZoneWeatherChange
-----------------------------------
function onZoneWeatherChange(weather)
local npc = GetNPCByID(17146627); -- Indescript Markings (BOOTS)
if (npc ~= nil) then
if (weather == WEATHER_RAIN or weather == WEATHER_THUNDER) then
npc:setStatus(STATUS_DISAPPEAR);
else
npc:setStatus(STATUS_NORMAL);
end
end
npc = GetNPCByID(17146628); -- Indescript Markings (BODY)
if (npc ~= nil) then
if (weather == WEATHER_RAIN) then
npc:setStatus(STATUS_DISAPPEAR);
else
npc:setStatus(STATUS_NORMAL);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
guangbin79/Lua_5.1.5-iOS | lua-script/copas/limit.lua | 2 | 3397 | --------------------------------------------------------------
-- Limits resource usage while executing tasks.
-- Tasks added will be run in parallel, with a maximum of
-- simultaneous tasks to prevent consuming all/too many resources.
-- Every task added will immediately be scheduled (if there is room)
-- using the `wait` method one can wait for completion.
local copas = require("copas")
local pack = table.pack or function(...) return {n=select('#',...),...} end
local unpack = function(t) return (table.unpack or unpack)(t, 1, t.n or #t) end
local pcall = pcall
if _VERSION=="Lua 5.1" then -- obsolete: only for Lua 5.1 compatibility
pcall = require("coxpcall").pcall
end
-- Add a task to the queue, returns the coroutine created
-- identical to `copas.addthread`. Can be called while the
-- set of tasks is executing.
local function add(self, task, ...)
local carg = pack(...)
local coro = copas.addthread(function()
copas.sleep(-1) -- go to sleep until being woken
local suc, err = pcall(task, unpack(carg)) -- start the task
self:removethread(coroutine.running()) -- dismiss ourselves
if not suc then error(err) end -- rethrow error
end)
table.insert(self.queue, coro) -- store in list
self:next()
return coro
end
-- remove a task from the queue. Can be called while the
-- set of tasks is executing. Will NOT stop the task if
-- it is already running.
local function remove(self, coro)
self.queue[coro] = nil
if self.running[coro] then
-- it is in the already running set
self.running[coro] = nil
self.count = self.count - 1
else
-- check the queue and remove if found
for i, item in ipairs(self.queue) do
if coro == item then
table.remove(self.queue, i)
break
end
end
end
self:next()
end
-- schedules the next task (if any) for execution, signals completeness
local function nxt(self)
while self.count < self.maxt do
local coro = self.queue[1]
if not coro then break end -- queue is empty, so nothing to add
-- move it to running and restart the task
table.remove(self.queue, 1)
self.running[coro] = coro
self.count = self.count + 1
copas.wakeup(coro)
end
if self.count == 0 and next(self.waiting) then
-- all tasks done, resume the waiting tasks so they can unblock/return
for coro in pairs(self.waiting) do
copas.wakeup(coro)
end
end
end
-- Waits for the tasks. Yields until all are finished
local function wait(self)
if self.count == 0 then return end -- There's nothing to do...
local coro = coroutine.running()
-- now store this coroutine (so we know which to wakeup) and go to sleep
self.waiting[coro] = true
copas.sleep(-1)
self.waiting[coro] = nil
end
-- creats a new tasksrunner, with maximum maxt simultaneous threads
local function new(maxt)
return {
maxt = maxt or 99999, -- max simultaneous tasks
count = 0, -- count of running tasks
queue = {}, -- tasks waiting (list/array)
running = {}, -- tasks currently running (indexed by coroutine)
waiting = {}, -- coroutines, waiting for all tasks being finished (indexed by coro)
addthread = add,
removethread = remove,
next = nxt,
wait = wait,
}
end
return { new = new }
| mit |
moltafet35/senatorv2 | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
Arashbrsh/lifeeee | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
abcdefg30/OpenRA | mods/ra/maps/fall-of-greece-2-evacuation/evacuation.lua | 7 | 8783 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AlliedReinforcementsA = { "jeep", "jeep" }
AlliedReinforcementsB = { "e1", "e1", "e1", "e3", "e3" }
AlliedReinforcementsC = { "jeep", "mcv" }
IslandPatrol = { SubPatrol1.Location, SubPatrol2.Location, SubPatrol3.Location, SubPatrol4.Location }
Submarines = { Sub1, Sub2, Sub3, Sub4, Sub5, Sub6, Sub7, Sub8 }
RifleSquad = { Rifle1, Rifle2, Rifle3 }
NWVillageTrigger = { CPos.New(31, 64), CPos.New(32, 64), CPos.New(34, 51), CPos.New(35, 51), CPos.New(36, 51) }
SWVillageTrigger = { CPos.New(44, 97), CPos.New(45, 97), CPos.New(46, 97), CPos.New(47, 97) }
MiddleVillageTrigger = { CPos.New(52, 70), CPos.New(53, 70), CPos.New(54, 70) }
EastVillageTrigger = { CPos.New(78, 61), CPos.New(79, 61), CPos.New(80, 61), CPos.New(81, 61), CPos.New(82, 61) }
CivilianTypes = { "c2", "c3", "c4", "c5", "c6", "c8", "c9", "c10", "c11" }
NWVillage = { NWChurch, NWHouse1, NWHouse2, NWHouse3 }
SWVillage = { SWChurch, SWHouse1, SWHouse2, SWHouse3, SWHouse4 }
MiddleVillage = { MiddleChurch, MiddleHouse1, MiddleHouse2, MiddleHouse3, MiddleHouse4 }
EastVillage = { EastChurch, EastHouse1, EastHouse2, EastHouse3 }
MissionStart = function()
Reinforcements.Reinforce(Allies, AlliedReinforcementsA, { AlliedSpawn.Location, AlliedBase.Location }, 5)
Trigger.AfterDelay(DateTime.Seconds(2), function()
AlliesArrived = true
Reinforcements.Reinforce(Allies, AlliedReinforcementsB, { AlliedSpawn.Location, AlliedBase.Location }, 2)
Utils.Do(RifleSquad, function(actor)
if not actor.IsDead then
actor.AttackMove(AlliedBase.Location)
actor.Hunt()
end
end)
end)
Sub1.Patrol(IslandPatrol, true, 1)
Trigger.AfterDelay(DateTime.Seconds(5), function()
Reinforcements.Reinforce(Allies, AlliedReinforcementsC, { AlliedSpawn.Location, AlliedBase.Location }, 5)
end)
Trigger.OnKilled(NWChurch, function()
if not NWChurchEmpty then
CiviliansKilled = CiviliansKilled + 5
end
end)
Trigger.OnKilled(EastChurch, function()
if not EastChurchEmpty then
CiviliansKilled = CiviliansKilled + 5
end
end)
Trigger.OnKilled(MiddleChurch, function()
if not MiddleChurchEmpty then
CiviliansKilled = CiviliansKilled + 5
end
end)
Trigger.OnKilled(SWChurch, function()
if not SWChurchEmpty then
CiviliansKilled = CiviliansKilled + 5
end
end)
Trigger.OnAllKilled(Submarines, function()
Allies.MarkCompletedObjective(ClearWaterway)
end)
end
VillageSetup = function()
local foot1Triggered
Trigger.OnEnteredFootprint(NWVillageTrigger, function(actor, id)
if actor.Owner == Allies and not foot1Triggered then
Trigger.RemoveFootprintTrigger(id)
foot1Triggered = true
Utils.Do(NWVillage, function(building)
building.Owner = Allies
end)
Civs1 = Reinforcements.Reinforce(Allies, Utils.Take(5, Utils.Shuffle(CivilianTypes)), { ChurchNorthwest.Location, VillageNorthwest.Location }, 0)
if not NWChurch.IsDead then
Utils.Do(Civs1, function(civ)
Trigger.OnKilled(civ, function()
CiviliansKilled = CiviliansKilled + 1
end)
end)
NWChurchEmpty = true
end
end
Trigger.AfterDelay(DateTime.Seconds(30), function()
local nwAttackers = Reinforcements.Reinforce(USSR, { "3tnk", "3tnk", "3tnk" }, { NWVillageAttack.Location, VillageNorthwest.Location }, 20)
Utils.Do(nwAttackers, IdleHunt)
end)
end)
local foot2Triggered
Trigger.OnEnteredFootprint(EastVillageTrigger, function(actor, id)
if actor.Owner == Allies and not foot2Triggered then
Trigger.RemoveFootprintTrigger(id)
foot2Triggered = true
Utils.Do(EastVillage, function(building)
building.Owner = Allies
end)
Civs2 = Reinforcements.Reinforce(Allies, Utils.Take(5, Utils.Shuffle(CivilianTypes)), { ChurchEast.Location, VillageEast.Location }, 0)
if not EastChurch.IsDead then
Utils.Do(Civs2, function(civ)
Trigger.OnKilled(civ, function()
CiviliansKilled = CiviliansKilled + 1
end)
end)
EastChurchEmpty = true
end
local villageDrop = FlamerDrop.TargetParatroopers(VillageEast.CenterPosition, Angle.North)
Utils.Do(villageDrop, function(a)
Trigger.OnPassengerExited(a, function(t, p)
IdleHunt(p)
end)
end)
end
end)
local foot3Triggered
Trigger.OnEnteredFootprint(MiddleVillageTrigger, function(actor, id)
if actor.Owner == Allies and not foot3Triggered then
Trigger.RemoveFootprintTrigger(id)
foot3Triggered = true
Utils.Do(MiddleVillage, function(building)
building.Owner = Allies
end)
Civs3 = Reinforcements.Reinforce(Allies, Utils.Take(5, Utils.Shuffle(CivilianTypes)), { ChurchMiddle.Location, VillageMiddle.Location }, 0)
if not MiddleChurch.IsDead then
Utils.Do(Civs3, function(civ)
Trigger.OnKilled(civ, function()
CiviliansKilled = CiviliansKilled + 1
end)
end)
MiddleChurchEmpty = true
end
local proxy = Actor.Create("powerproxy.parabombs", false, { Owner = USSR })
proxy.TargetAirstrike(ChurchMiddle.CenterPosition, Angle.NorthWest)
end
end)
local foot4Triggered
Trigger.OnEnteredFootprint(SWVillageTrigger, function(actor, id)
if actor.Owner == Allies and not foot4Triggered then
Trigger.RemoveFootprintTrigger(id)
foot4Triggered = true
Utils.Do(SWVillage, function(building)
building.Owner = Allies
end)
Civs4 = Reinforcements.Reinforce(Allies, Utils.Take(5, Utils.Shuffle(CivilianTypes)), { ChurchSouthwest.Location, VillageSouthwest.Location }, 0)
if not SWChurch.IsDead then
Utils.Do(Civs4, function(civ)
Trigger.OnKilled(civ, function()
CiviliansKilled = CiviliansKilled + 1
end)
end)
SWChurchEmpty = true
end
end
Trigger.AfterDelay(DateTime.Seconds(30), function()
local swAttackers = Reinforcements.Reinforce(USSR, { "3tnk", "3tnk", "3tnk", "ttnk", "e4", "e4", "e4" }, { SWVillageAttack.Location, VillageSouthwest.Location }, 20)
Utils.Do(swAttackers, IdleHunt)
end)
end)
end
CiviliansEvacuatedThreshold =
{
hard = 20,
normal = 15,
easy = 10
}
CiviliansKilledThreshold =
{
hard = 1,
normal = 6,
easy = 11
}
CiviliansEvacuated = 0
CiviliansKilled = 0
EvacuateCivilians = function()
Trigger.OnInfiltrated(SafeHouse, function()
CiviliansEvacuated = CiviliansEvacuated + 1
UserInterface.SetMissionText(CiviliansEvacuated .. "/" .. CiviliansEvacuatedThreshold .. " civilians evacuated.", TextColor)
end)
Trigger.OnKilled(SafeHouse, function()
USSR.MarkCompletedObjective(SovietObj)
end)
local enemyBase = Utils.Where(USSR.GetActors(), function(actor)
return
actor.HasProperty("Sell") and
actor.Type ~= "brik"
end)
Trigger.OnAllKilled(enemyBase, function()
Media.PlaySoundNotification(Allies, "AlertBleep")
Media.DisplayMessage("Alfa Niner this is Pegasus. We are on site and ready to assist with the evacuation.", "Chinook pilot")
Reinforcements.Reinforce(Allies, { "tran" }, { ChinookEntry.Location, ChinookLZ.Location })
end)
end
Tick = function()
USSR.Cash = 10000
if CiviliansEvacuated >= CiviliansEvacuatedThreshold then
Allies.MarkCompletedObjective(RescueCivilians)
end
if CiviliansKilled >= CiviliansKilledThreshold then
Allies.MarkFailedObjective(RescueCivilians)
end
if AlliesArrived and Allies.HasNoRequiredUnits() then
USSR.MarkCompletedObjective(SovietObj)
end
end
WorldLoaded = function()
Allies = Player.GetPlayer("Allies")
USSR = Player.GetPlayer("USSR")
InitObjectives(Allies)
if Difficulty == "easy" then
RescueCivilians = Allies.AddObjective("Evacuate at least half of the civilians to the island\nshelter.")
elseif Difficulty == "normal" then
RescueCivilians = Allies.AddObjective("Evacuate at least three quarters of the civilians to\nthe island shelter.")
else
RescueCivilians = Allies.AddObjective("Evacuate all civilians to the island shelter.")
end
ClearWaterway = Allies.AddObjective("Clear the area of enemy submarine activity.", "Secondary", false)
SovietObj = USSR.AddObjective("Defeat Allies.")
CiviliansEvacuatedThreshold = CiviliansEvacuatedThreshold[Difficulty]
CiviliansKilledThreshold = CiviliansKilledThreshold[Difficulty]
TextColor = Allies.Color
UserInterface.SetMissionText(CiviliansEvacuated .. "/" .. CiviliansEvacuatedThreshold .. " civilians evacuated.", TextColor)
StandardDrop = Actor.Create("paradrop", false, { Owner = USSR })
FlamerDrop = Actor.Create("flamerdrop", false, { Owner = USSR })
Camera.Position = DefaultCameraPosition.CenterPosition
MissionStart()
VillageSetup()
EvacuateCivilians()
ActivateAI()
end
| gpl-3.0 |
lgeek/koreader | frontend/device/kobo/powerd.lua | 1 | 11157 | local BasePowerD = require("device/generic/powerd")
local NickelConf = require("device/kobo/nickel_conf")
local PluginShare = require("pluginshare")
local SysfsLight = require ("device/kobo/sysfs_light")
local batt_state_folder =
"/sys/devices/platform/pmic_battery.1/power_supply/mc13892_bat/"
-- Here, we only deal with the real hw intensity.
-- Dealing with toggling and remembering/restoring
-- previous intensity when toggling/untoggling is done
-- by BasePowerD.
local KoboPowerD = BasePowerD:new{
fl_min = 0, fl_max = 100,
fl = nil,
batt_capacity_file = batt_state_folder .. "capacity",
is_charging_file = batt_state_folder .. "status",
fl_warmth = nil,
auto_warmth = false,
max_warmth_hour = 23,
}
-- TODO: Remove KOBO_LIGHT_ON_START
function KoboPowerD:_syncKoboLightOnStart()
local new_intensity = nil
local is_frontlight_on = nil
local new_warmth = nil
local auto_warmth = nil
local kobo_light_on_start = tonumber(KOBO_LIGHT_ON_START)
if kobo_light_on_start then
if kobo_light_on_start > 0 then
new_intensity = math.min(kobo_light_on_start, 100)
is_frontlight_on = true
elseif kobo_light_on_start == 0 then
new_intensity = 0
is_frontlight_on = false
elseif kobo_light_on_start == -2 then -- get values from NickelConf
new_intensity = NickelConf.frontLightLevel.get()
is_frontlight_on = NickelConf.frontLightState:get()
if self.fl_warmth ~= nil then
local new_color = NickelConf.colorSetting.get()
if new_color ~= nil then
-- ColorSetting is in [1500,6400], with '1500'
-- being maximum warmth, so normalize this to [0,100]
new_warmth = (100 - math.floor((new_color - 1500) / 49))
end
auto_warmth = NickelConf.autoColorEnabled.get()
end
if is_frontlight_on == nil then
-- this device does not support frontlight toggle,
-- we set the value based on frontlight intensity.
if new_intensity > 0 then
is_frontlight_on = true
else
is_frontlight_on = false
end
end
if is_frontlight_on == false and new_intensity == 0 then
-- frontlight was toggled off in nickel, and we have no
-- level-before-toggle-off (firmware without "FrontLightState"):
-- use the one from koreader settings
new_intensity = G_reader_settings:readSetting("frontlight_intensity")
end
else -- if kobo_light_on_start == -1 or other unexpected value then
-- As we can't read value from the OS or hardware, use last values
-- stored in koreader settings
new_intensity = G_reader_settings:readSetting("frontlight_intensity")
is_frontlight_on = G_reader_settings:readSetting("is_frontlight_on")
if self.fl_warmth ~= nil then
new_warmth = G_reader_settings:readSetting("frontlight_warmth")
auto_warmth = G_reader_settings:readSetting("frontlight_auto_warmth")
end
end
end
if new_intensity ~= nil then
self.hw_intensity = new_intensity
end
if is_frontlight_on ~= nil then
-- will only be used to give initial state to BasePowerD:_decideFrontlightState()
self.initial_is_fl_on = is_frontlight_on
end
-- This is always read from G_reader_settings, since we do not
-- support reading 'BedTime' from NickelConf.
local max_warmth_hour =
G_reader_settings:readSetting("frontlight_max_warmth_hour")
if max_warmth_hour then
self.max_warmth_hour = max_warmth_hour
end
if auto_warmth then
self.auto_warmth = true
self:calculateAutoWarmth()
elseif new_warmth ~= nil then
self.fl_warmth = new_warmth
end
-- In any case frontlight is off, ensure intensity is non-zero so untoggle works
if self.initial_is_fl_on == false and self.hw_intensity == 0 then
self.hw_intensity = 1
end
end
function KoboPowerD:init()
-- Default values in case self:_syncKoboLightOnStart() does not find
-- any previously saved setting (and for unit tests where it will
-- not be called)
self.hw_intensity = 20
self.initial_is_fl_on = true
self.autowarmth_job_running = false
if self.device.hasFrontlight() then
-- If this device has natural light (currently only KA1)
-- use the SysFS interface, and ioctl otherwise.
if self.device.hasNaturalLight() then
local nl_config = G_reader_settings:readSetting("natural_light_config")
if nl_config then
for key,val in pairs(nl_config) do
self.device.frontlight_settings[key] = val
end
end
self.fl = SysfsLight:new(self.device.frontlight_settings)
self.fl_warmth = 0
self:_syncKoboLightOnStart()
else
local kobolight = require("ffi/kobolight")
local ok, light = pcall(kobolight.open)
if ok then
self.fl = light
self:_syncKoboLightOnStart()
end
end
end
end
function KoboPowerD:saveSettings()
if self.device.hasFrontlight() then
-- Store BasePowerD values into settings (and not our hw_intensity, so
-- that if frontlight was toggled off, we save and restore the previous
-- untoggled intensity and toggle state at next startup)
local cur_intensity = self.fl_intensity
local cur_is_fl_on = self.is_fl_on
local cur_warmth = self.fl_warmth
local cur_auto_warmth = self.auto_warmth
local cur_max_warmth_hour = self.max_warmth_hour
-- Save intensity to koreader settings
G_reader_settings:saveSetting("frontlight_intensity", cur_intensity)
G_reader_settings:saveSetting("is_frontlight_on", cur_is_fl_on)
if cur_warmth ~= nil then
G_reader_settings:saveSetting("frontlight_warmth", cur_warmth)
G_reader_settings:saveSetting("frontlight_auto_warmth", cur_auto_warmth)
G_reader_settings:saveSetting("frontlight_max_warmth_hour", cur_max_warmth_hour)
end
-- And to "Kobo eReader.conf" if needed
if KOBO_SYNC_BRIGHTNESS_WITH_NICKEL then
if NickelConf.frontLightState.get() ~= nil then
if NickelConf.frontLightState.get() ~= cur_is_fl_on then
NickelConf.frontLightState.set(cur_is_fl_on)
end
else -- no support for frontlight state
if not cur_is_fl_on then -- if toggled off, save intensity as 0
cur_intensity = self.fl_min
end
end
if NickelConf.frontLightLevel.get() ~= cur_intensity then
NickelConf.frontLightLevel.set(cur_intensity)
end
if cur_warmth ~= nil then
local warmth_rescaled = (100 - cur_warmth) * 49 + 1500
if NickelConf.colorSetting.get() ~= warmth_rescaled then
NickelConf.colorSetting.set(warmth_rescaled)
end
if NickelConf.autoColorEnabled.get() ~= cur_auto_warmth then
NickelConf.autoColorEnabled.set(cur_auto_warmth)
end
end
end
end
end
function KoboPowerD:frontlightIntensityHW()
return self.hw_intensity
end
function KoboPowerD:isFrontlightOnHW()
if self.initial_is_fl_on ~= nil then -- happens only once after init()
-- give initial state to BasePowerD, which will
-- reset our self.hw_intensity to 0 if self.initial_is_fl_on is false
local ret = self.initial_is_fl_on
self.initial_is_fl_on = nil
return ret
end
return self.hw_intensity > 0
end
function KoboPowerD:turnOffFrontlightHW()
self:_setIntensity(0) -- will call setIntensityHW(0)
end
function KoboPowerD:setIntensityHW(intensity)
if self.fl == nil then return end
if self.fl_warmth == nil then
self.fl:setBrightness(intensity)
else
self.fl:setNaturalBrightness(intensity, self.fl_warmth)
end
self.hw_intensity = intensity
-- Now that we have set intensity, we need to let BasePowerD
-- know about possibly changed frontlight state (if we came
-- from light toggled off to some intensity > 0).
self:_decideFrontlightState()
end
function KoboPowerD:setWarmth(warmth)
if self.fl == nil then return end
if not warmth and self.auto_warmth then
self:calculateAutoWarmth()
end
self.fl_warmth = warmth or self.fl_warmth
self.fl:setWarmth(self.fl_warmth)
end
-- Sets fl_warmth according to current hour and max_warmth_hour
-- and starts background job if necessary.
function KoboPowerD:calculateAutoWarmth()
local current_time = os.date("%H") + os.date("%M")/60
local max_hour = self.max_warmth_hour
local diff_time = max_hour - current_time
if diff_time < 0 then
diff_time = diff_time + 24
end
if diff_time < 12 then
-- We are before bedtime. Use a slower progression over 5h.
self.fl_warmth = math.max(20 * (5 - diff_time), 0)
elseif diff_time > 22 then
-- Keep warmth at maximum for two hours after bedtime.
self.fl_warmth = 100
else
-- Between 2-4h after bedtime, return to zero.
self.fl_warmth = math.max(100 - 50 * (22 - diff_time), 0)
end
self.fl_warmth = math.floor(self.fl_warmth + 0.5)
-- Enable background job for setting Warmth, if not already done.
if not self.autowarmth_job_running then
table.insert(PluginShare.backgroundJobs, {
when = 180,
repeated = true,
executable = function()
if self.auto_warmth then
self:setWarmth()
end
end,
})
self.autowarmth_job_running = true
end
end
function KoboPowerD:getCapacityHW()
return self:read_int_file(self.batt_capacity_file)
end
function KoboPowerD:isChargingHW()
return self:read_str_file(self.is_charging_file) == "Charging\n"
end
-- Turn off front light before suspend.
function KoboPowerD:beforeSuspend()
if self.fl == nil then return end
-- just turn off frontlight without remembering its state
self.fl:setBrightness(0)
end
-- Restore front light state after resume.
function KoboPowerD:afterResume()
if self.fl == nil then return end
-- just re-set it to self.hw_intensity that we haven't change on Suspend
if self.fl_warmth == nil then
self.fl:setBrightness(self.hw_intensity)
else
if self.auto_warmth then
self:calculateAutoWarmth()
end
self.fl:setNaturalBrightness(self.hw_intensity, self.fl_warmth)
end
end
return KoboPowerD
| agpl-3.0 |
nyczducky/darkstar | scripts/globals/items/rolanberry_(881_ce).lua | 12 | 1192 | -----------------------------------------
-- ID: 4529
-- Item: rolanberry_881_ce)
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility -3
-- Intelligence 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4529);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, -3);
target:addMod(MOD_INT, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, -3);
target:delMod(MOD_INT, 1);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/spells/aurorastorm.lua | 32 | 1189 | --------------------------------------
-- Spell: Aurorastorm
-- Changes the weather around target party member to "auroras."
--------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
target:delStatusEffectSilent(EFFECT_FIRESTORM);
target:delStatusEffectSilent(EFFECT_SANDSTORM);
target:delStatusEffectSilent(EFFECT_RAINSTORM);
target:delStatusEffectSilent(EFFECT_WINDSTORM);
target:delStatusEffectSilent(EFFECT_HAILSTORM);
target:delStatusEffectSilent(EFFECT_THUNDERSTORM);
target:delStatusEffectSilent(EFFECT_AURORASTORM);
target:delStatusEffectSilent(EFFECT_VOIDSTORM);
local merit = caster:getMerit(MERIT_STORMSURGE);
local power = 0;
if merit > 0 then
power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2;
end
target:addStatusEffect(EFFECT_AURORASTORM,power,0,180);
return EFFECT_AURORASTORM;
end; | gpl-3.0 |
ArmanIr/restore | plugins/banhammer.lua | 294 | 10470 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No 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 get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'kickme' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "!kickme : Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id> : Remove user from whitelist",
"!whitelist delete chat : Remove chat from whitelist",
"!ban user <user_id> : Kick user from chat and kicks it if joins chat again",
"!ban user <username> : Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id> : Unban user",
"!kick <user_id> : Kick user from chat group by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (.*)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (.*)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (.*)$",
"^!(ban) (delete) (.*)$",
"^!(superban) (user) (.*)$",
"^!(superban) (delete) (.*)$",
"^!(kick) (.*)$",
"^!(kickme)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
mynameiscraziu/mycaty | plugins/banhammer.lua | 294 | 10470 | local function is_user_whitelisted(id)
local hash = 'whitelist:user#id'..id
local white = redis:get(hash) or false
return white
end
local function is_chat_whitelisted(id)
local hash = 'whitelist:chat#id'..id
local white = redis:get(hash) or false
return white
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
local function ban_user(user_id, chat_id)
-- Save to redis
local hash = 'banned:'..chat_id..':'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function superban_user(user_id, chat_id)
-- Save to redis
local hash = 'superbanned:'..user_id
redis:set(hash, true)
-- Kick from chat
kick_user(user_id, chat_id)
end
local function is_banned(user_id, chat_id)
local hash = 'banned:'..chat_id..':'..user_id
local banned = redis:get(hash)
return banned or false
end
local function is_super_banned(user_id)
local hash = 'superbanned:'..user_id
local superbanned = redis:get(hash)
return superbanned or false
end
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat
if action == 'chat_add_user' or action == 'chat_add_user_link' then
local user_id
if msg.action.link_issuer then
user_id = msg.from.id
else
user_id = msg.action.user.id
end
print('Checking invited user '..user_id)
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, msg.to.id)
if superbanned or banned then
print('User is banned!')
kick_user(user_id, msg.to.id)
end
end
-- No further checks
return msg
end
-- BANNED USER TALKING
if msg.to.type == 'chat' then
local user_id = msg.from.id
local chat_id = msg.to.id
local superbanned = is_super_banned(user_id)
local banned = is_banned(user_id, chat_id)
if superbanned then
print('SuperBanned user talking!')
superban_user(user_id, chat_id)
msg.text = ''
end
if banned then
print('Banned user talking!')
ban_user(user_id, chat_id)
msg.text = ''
end
end
-- WHITELIST
local hash = 'whitelist:enabled'
local whitelist = redis:get(hash)
local issudo = is_sudo(msg)
-- Allow all sudo users even if whitelist is allowed
if whitelist and not issudo then
print('Whitelist enabled and not sudo')
-- Check if user or chat is whitelisted
local allowed = is_user_whitelisted(msg.from.id)
if not allowed then
print('User '..msg.from.id..' not whitelisted')
if msg.to.type == 'chat' then
allowed = is_chat_whitelisted(msg.to.id)
if not allowed then
print ('Chat '..msg.to.id..' not whitelisted')
else
print ('Chat '..msg.to.id..' whitelisted :)')
end
end
else
print('User '..msg.from.id..' allowed :)')
end
if not allowed then
msg.text = ''
end
else
print('Whitelist not enabled or is sudo')
end
return msg
end
local function username_id(cb_extra, success, result)
local get_cmd = cb_extra.get_cmd
local receiver = cb_extra.receiver
local chat_id = cb_extra.chat_id
local member = cb_extra.member
local text = 'No 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 get_cmd == 'kick' then
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'superban user' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!')
return superban_user(member_id, chat_id)
elseif get_cmd == 'whitelist user' then
local hash = 'whitelist:user#id'..member_id
redis:set(hash, true)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted')
elseif get_cmd == 'whitelist delete user' then
local hash = 'whitelist:user#id'..member_id
redis:del(hash)
return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist')
end
end
end
return send_large_msg(receiver, text)
end
local function run(msg, matches)
if matches[1] == 'kickme' then
kick_user(msg.from.id, msg.to.id)
end
if not is_momod(msg) then
return nil
end
local receiver = get_receiver(msg)
if matches[4] then
get_cmd = matches[1]..' '..matches[2]..' '..matches[3]
elseif matches[3] then
get_cmd = matches[1]..' '..matches[2]
else
get_cmd = matches[1]
end
if matches[1] == 'ban' then
local user_id = matches[3]
local chat_id = msg.to.id
if msg.to.type == 'chat' then
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
ban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'banned:'..chat_id..':'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'superban' and is_admin(msg) then
local user_id = matches[3]
local chat_id = msg.to.id
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
superban_user(user_id, chat_id)
send_large_msg(receiver, 'User '..user_id..' globally banned!')
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member})
end
end
if matches[2] == 'delete' then
local hash = 'superbanned:'..user_id
redis:del(hash)
return 'User '..user_id..' unbanned'
end
end
if matches[1] == 'kick' then
if msg.to.type == 'chat' then
if string.match(matches[2], '^%d+$') then
kick_user(matches[2], msg.to.id)
else
local member = string.gsub(matches[2], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
else
return 'This isn\'t a chat group'
end
end
if matches[1] == 'whitelist' then
if matches[2] == 'enable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:set(hash, true)
return 'Enabled whitelist'
end
if matches[2] == 'disable' and is_sudo(msg) then
local hash = 'whitelist:enabled'
redis:del(hash)
return 'Disabled whitelist'
end
if matches[2] == 'user' then
if string.match(matches[3], '^%d+$') then
local hash = 'whitelist:user#id'..matches[3]
redis:set(hash, true)
return 'User '..matches[3]..' whitelisted'
else
local member = string.gsub(matches[3], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:set(hash, true)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted'
end
if matches[2] == 'delete' and matches[3] == 'user' then
if string.match(matches[4], '^%d+$') then
local hash = 'whitelist:user#id'..matches[4]
redis:del(hash)
return 'User '..matches[4]..' removed from whitelist'
else
local member = string.gsub(matches[4], '@', '')
chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member})
end
end
if matches[2] == 'delete' and matches[3] == 'chat' then
if msg.to.type ~= 'chat' then
return 'This isn\'t a chat group'
end
local hash = 'whitelist:chat#id'..msg.to.id
redis:del(hash)
return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist'
end
end
end
return {
description = "Plugin to manage bans, kicks and white/black lists.",
usage = {
user = "!kickme : Exit from group",
moderator = {
"!whitelist <enable>/<disable> : Enable or disable whitelist mode",
"!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled",
"!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled",
"!whitelist delete user <user_id> : Remove user from whitelist",
"!whitelist delete chat : Remove chat from whitelist",
"!ban user <user_id> : Kick user from chat and kicks it if joins chat again",
"!ban user <username> : Kick user from chat and kicks it if joins chat again",
"!ban delete <user_id> : Unban user",
"!kick <user_id> : Kick user from chat group by id",
"!kick <username> : Kick user from chat group by username",
},
admin = {
"!superban user <user_id> : Kick user from all chat and kicks it if joins again",
"!superban user <username> : Kick user from all chat and kicks it if joins again",
"!superban delete <user_id> : Unban user",
},
},
patterns = {
"^!(whitelist) (enable)$",
"^!(whitelist) (disable)$",
"^!(whitelist) (user) (.*)$",
"^!(whitelist) (chat)$",
"^!(whitelist) (delete) (user) (.*)$",
"^!(whitelist) (delete) (chat)$",
"^!(ban) (user) (.*)$",
"^!(ban) (delete) (.*)$",
"^!(superban) (user) (.*)$",
"^!(superban) (delete) (.*)$",
"^!(kick) (.*)$",
"^!(kickme)$",
"^!!tgservice (.+)$",
},
run = run,
pre_process = pre_process
} | gpl-2.0 |
sevu/wesnoth | data/lua/wml/modify_unit.lua | 3 | 4011 | local utils = wesnoth.require "wml-utils"
local wml_actions = wesnoth.wml_actions
-- The [modify_unit] implementation.
-- Implementation detail: every affected unit is passed through [unstore_unit], so gets
-- that tag's implementation's handling of special cases such as x,y=recall,recall.
function wml_actions.modify_unit(cfg)
local unit_variable = "LUA_modify_unit"
local replace_mode = cfg.mode == "replace"
local function handle_attributes(cfg, unit_path, toplevel)
for current_key, current_value in pairs(wml.shallow_parsed(cfg)) do
if type(current_value) ~= "table" and (not toplevel or (current_key ~= "type" and current_key ~= "mode")) then
wml.variables[string.format("%s.%s", unit_path, current_key)] = current_value
end
end
end
local function handle_child(cfg, unit_path)
local children_handled = {}
local cfg = wml.shallow_parsed(cfg)
handle_attributes(cfg, unit_path)
for current_index, current_table in ipairs(cfg) do
local current_tag = current_table[1]
local tag_index = children_handled[current_tag] or 0
handle_child(current_table[2], string.format("%s.%s[%u]",
unit_path, current_tag, tag_index))
children_handled[current_tag] = tag_index + 1
end
end
local filter = wml.get_child(cfg, "filter") or wml.error "[modify_unit] missing required [filter] tag"
local function handle_unit(unit_num)
local children_handled = {}
local unit_path = string.format("%s[%u]", unit_variable, unit_num)
local this_unit = wml.variables[unit_path]
wml.variables["this_unit"] = this_unit
handle_attributes(cfg, unit_path, true)
for current_index, current_table in ipairs(wml.shallow_parsed(cfg)) do
local current_tag = current_table[1]
if current_tag == "filter" then
-- nothing
elseif current_tag == "object" or current_tag == "trait" or current_tag == "advancement" then
local mod = current_table[2]
if mod.delayed_variable_substitution then
mod = wml.literal(mod)
else
mod = wml.parsed(mod)
end
local unit = wml.variables[unit_path]
unit = wesnoth.units.create(unit)
unit:add_modification(current_tag, mod)
unit = unit.__cfg;
wml.variables[unit_path] = unit
elseif current_tag == "effect" then
local mod = current_table[2]
local apply_to = mod.apply_to
if wesnoth.effects[apply_to] then
local unit = wml.variables[unit_path]
unit = wesnoth.units.create(unit)
wesnoth.effects[apply_to](unit, mod)
unit = unit.__cfg;
wml.variables[unit_path] = unit
else
wml.error("[modify_unit] had invalid [effect]apply_to value")
end
elseif current_tag == "set_variable" then
local unit = wesnoth.units.create(wml.variables[unit_path])
wesnoth.wml_actions.set_variable(current_table[2], unit.variables)
wml.variables[unit_path] = unit.__cfg
elseif current_tag == "clear_variable" then
local unit = wesnoth.units.create(wml.variables[unit_path])
wesnoth.wml_actions.clear_variable(current_table[2], unit.variables)
wml.variables[unit_path] = unit.__cfg
else
if replace_mode then
wml.variables[string.format("%s.%s", unit_path, current_tag)] = {}
end
local tag_index = children_handled[current_tag] or 0
handle_child(current_table[2], string.format("%s.%s[%u]",
unit_path, current_tag, tag_index))
children_handled[current_tag] = tag_index + 1
end
end
if cfg.type then
if cfg.type ~= "" then wml.variables[unit_path .. ".advances_to"] = cfg.type end
wml.variables[unit_path .. ".experience"] = wml.variables[unit_path .. ".max_experience"]
end
wml_actions.kill({ id = this_unit.id, animate = false })
wml_actions.unstore_unit { variable = unit_path }
end
wml_actions.store_unit { {"filter", filter}, variable = unit_variable }
local max_index = wml.variables[unit_variable .. ".length"] - 1
local this_unit <close> = utils.scoped_var("this_unit")
for current_unit = 0, max_index do
handle_unit(current_unit)
end
wml.variables[unit_variable] = nil
end
| gpl-2.0 |
esbullington/snabbp4 | syntax/parser.lua | 1 | 10221 | local lexer = require("snabbp4.syntax.lexer")
local utils = require("snabbp4.syntax.utils.debug")
local class = require("snabbp4.syntax.utils.middleclass")
local symbols = require("snabbp4.syntax.symbols")
local assertions = require("snabbp4.syntax.assertions")
-- precedence values
local precedence = require("snabbp4.syntax.precedence")
local M = {}
local dispatcher = function(token,parser)
--print("TOKENIZING VALUE: " .. (token.value or "none") .. ", TYPE: " ..token.token_type)
if token.token_type == "decimal_value" or
token.token_type == "binary_value" or
token.token_type == "hexadecimal_value" then
assertions.check_post_literal(parser)
return symbols.UnsignedValue(token,parser)
elseif token.token_type == "constant_value" then
assertions.check_post_literal(parser)
return symbols.ConstantValue(token,parser)
elseif token.token_type == "data_type" then
return symbols.DataType(token,parser)
elseif token.token_type == "identifier" then
return symbols.Identifier(token,parser)
elseif token.token_type == "punctuator" then
if token.value == ';' then
return symbols.Semicolon(token,parser)
elseif token.value == ':' then
return symbols.Colon(token,parser)
elseif token.value == ',' then
return symbols.Comma(token,parser)
elseif token.value == '{' then
return symbols.LBrace(token,parser)
elseif token.value == '}' then
assertions.check_post_rbrace(parser)
return symbols.RBrace(token,parser)
elseif token.value == '(' then
return symbols.LParen(token,parser)
elseif token.value == ')' then
assertions.check_post_rparen(parser)
return symbols.RParen(token,parser)
else
return error("Unknown punctuator: " .. token.value)
end
elseif token.token_type == "op" then
if token.value == '+' then
return symbols.Add(token,parser)
elseif token.value == '-' then
return symbols.Subtract(token,parser)
elseif token.value == '*' then
return symbols.Multiply(token,parser)
elseif token.value == '<<' then
return symbols.LShift(token,parser)
elseif token.value == '>>' then
return symbols.RShift(token,parser)
elseif token.value == '.' then
return symbols.Accessor(token,parser)
else
return error("Unknown op: " .. token.value)
end
elseif token.token_type == "keyword" then
if token.value == "header_type" then
return symbols.HeaderType(token,parser)
elseif token.value == "fields" then
return symbols.FieldDeclaration(token,parser)
elseif token.value == "header" then
return symbols.HeaderInstance(token,parser)
elseif token.value == "metadata" then
return symbols.MetadataInstance(token,parser)
elseif token.value == "parser" then
return symbols.ParserFunctionDeclaration(token,parser)
elseif token.value == "set_metadata" then
return symbols.SetStatement(token,parser)
elseif token.value == "extract" then
return symbols.ExtractStatement(token,parser)
elseif token.value == "return" then
return symbols.ReturnStatement(token,parser)
elseif token.value == "action" then
return symbols.ActionFunctionDeclaration(token,parser)
elseif token.value == "primitive_action" then
return symbols.PrimitiveActionDeclaration(token,parser)
elseif token.value == "action_profile" then
return symbols.ActionProfileDeclaration(token,parser)
elseif token.value == "dynamic_action_selection" then
return symbols.DynamicActionSelection(token,parser)
elseif token.value == "actions" then
return symbols.ActionSpecification(token,parser)
elseif token.value == "size" then
return symbols.Size(token,parser)
elseif token.value == "field_list" then
return symbols.FieldListDeclaration(token,parser)
elseif token.value == "field_list_calculation" then
return symbols.FieldListCalculationDeclaration(token,parser)
elseif token.value == "calculated_field" then
return symbols.CalculatedFieldDeclaration(token,parser)
elseif token.value == "update" or token.value == "verify" then
return symbols.UpdateVerifySpec(token,parser)
elseif token.value == "parser_value_set" then
return symbols.ValueSetDeclaration(token,parser)
elseif token.value == "parser_exception" then
return symbols.ParserExceptionDeclaration(token,parser)
elseif token.value == "parser_drop" then
return symbols.ReturnOrDrop(token,parser)
elseif token.value == "meter" then
return symbols.MeterDeclaration(token,parser)
elseif token.value == "control" then
return symbols.ControlFunctionDeclaration(token,parser)
elseif token.value == "apply" then
return symbols.ApplyCall(token,parser)
elseif token.value == "hit" then
return symbols.Hit(token,parser)
elseif token.value == "miss" then
return symbols.Miss(token,parser)
elseif token.value == "result" then
return symbols.Result(token,parser)
elseif token.value == "register" then
return symbols.RegisterDeclaration(token,parser)
-- table declaration
elseif token.value == "table" then
return symbols.TableDeclaration(token,parser)
elseif token.value == "reads" then
return symbols.Reads(token,parser)
elseif token.value == "min_size" then
return symbols.MinSize(token,parser)
elseif token.value == "max_size" then
return symbols.MaxSize(token,parser)
elseif token.value == "support_timeout" then
return symbols.SupportTimeout(token,parser)
-- end table declaration
-- extern declaration
elseif token.value == "extern_type" then
return symbols.ExternTypeDeclaration(token,parser)
elseif token.value == "method" then
return symbols.MethodDeclaration(token,parser)
elseif token.value == "attribute" then
return symbols.AttributeDeclaration(token,parser)
elseif token.value == "extern" then
return symbols.ExternInstanceDeclaration(token,parser)
elseif token.value == "optional" then
return symbols.Optional(token,parser)
-- end extern declaration
elseif token.value == "width" then
return symbols.WidthDeclaration(token,parser)
elseif token.value == "layout" then
return symbols.LayoutDeclaration(token,parser)
elseif token.value == "if" then
return symbols.IfCond(token,parser)
elseif token.value == "counter" then
return symbols.CounterDeclaration(token,parser)
elseif token.value == "type" then
return symbols.TypeStatement(token,parser)
elseif token.value == "static" or token.value == "direct" then
return symbols.DirectOrStatic(token,parser)
elseif token.value == "instance_count" then
return symbols.InstanceCount(token,parser)
elseif token.value == "min_width" then
return symbols.MinWidth(token,parser)
elseif token.value == "saturating" then
return symbols.Saturating(token,parser)
elseif token.value == "bytes" or token.value == "packets" then
return symbols.CounterType(token,parser)
elseif token.value == "valid" then
return symbols.Valid(token,parser)
elseif token.value == "input" then
return symbols.Input(token,parser)
elseif token.value == "algorithm" then
return symbols.Algorithm(token,parser)
elseif token.value == "output_width" then
return symbols.OutputWidth(token,parser)
elseif token.value == "select" then
return symbols.SelectStatement(token,parser)
elseif token.value == "in" or token.value == "inout" then
return symbols.ParamQualifier(token,parser)
elseif token.value == "length" then
return symbols.Length(token,parser)
elseif token.value == "latest" then
return symbols.Latest(token,parser)
elseif token.value == "next" then
return symbols.Next(token,parser)
elseif token.value == "and" then
return symbols.LogicalAnd(token,parser)
elseif token.value == "or" then
return symbols.LogicalOr(token,parser)
elseif token.value == "true" or token.value == "false" then
return symbols.BooleanValue(token,parser)
elseif token.value == "parser_error" then
return symbols.ParserError(token,parser)
elseif token.value == "default" then
return symbols.Default(token,parser)
else
return error("Unknown keyword: " .. token.value)
end
else
return symbols.EndToken(token,parser)
end
end
local Parser = class("ListIter")
function Parser:initialize(t)
self.t = t
self.i = 0
self.n = table.getn(t)
self.current_symbol = nil
self.current_pos = nil
self.prior_symbol = nil
end
function Parser:advance()
self.i = self.i + 1
if self.i <= self.n then
local current_simple_token = self.t[self.i]
self.current_pos = current_simple_token.pos
self.prior_symbol = self.current_symbol
self.current_symbol = dispatcher(current_simple_token, self)
return self.current_symbol
end
end
-- match function for symbols, throw error if no match
-- consume symbol that is matched
function Parser:match(sym)
local sym = sym or nil
if sym and (sym ~= self.current_symbol.class.name) then
error('Expected ' .. sym .. ' received ' .. self.current_symbol.class.name)
end
self:advance()
end
function Parser:peek_token()
local i = self.i + 1
return self.t[i]
end
function Parser:expression(rbp)
local rbp = rbp or 0
self:advance()
assert(type(self.current_symbol) == "table", "Missing switch entry for token.")
local left = self.prior_symbol:nud()
assert(type(rbp) == "number", "Passed in rbp for class '" .. self.current_symbol.class.name .. "' is not a number")
assert(type(self.current_symbol.lbp) == "number", "lbp for class '" .. self.current_symbol.class.name .. "' is not a number")
while rbp < self.current_symbol.lbp and self.current_symbol.class.name ~= "Semicolon" do
self:advance()
left = self.prior_symbol:led(left)
end
return left
end
function Parser:statement()
local n = self.current_symbol
if (n.std) then
return n:std()
end
local v = self:expression()
self:match('Semicolon')
return v
end
function Parser:statements()
local a = {}
while true do
if self.current_symbol.class.name == "RBrace" or self.current_symbol.class.name == "EndToken" then
break
end
local s = self:statement()
if (s) then
a[#a+1] = s
end
end
if #a == 0 then
return nil
else
return a
end
end
M.parse = function(input, config)
local t = lexer.lex(input, config)
-- Add EOF token for dispatcher
t[#t+1] = {token_type="EOF", value="eof"}
local parser = Parser(t)
parser:advance()
return parser:statements()
end
return M
| apache-2.0 |
abosalah22/memo | plugins/all.lua | 41 | 4395 | do
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.\nUse /type in the group to set type.'
end
return group_type
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(msg,target,receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
if group_type == "Group" or group_type == "Realm" then
local settings = show_group_settingsmod(msg,target)
text = text.."\n\n"..settings
elseif group_type == "SuperGroup" then
local settings = show_supergroup_settingsmod(msg,target)
text = text..'\n\n'..settings
end
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local mutes_list = mutes_list(target)
text = text.."\n\n"..mutes_list
local muted_user_list = muted_user_list(target)
text = text.."\n\n"..muted_user_list
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
local function run(msg, matches)
if matches[1] == "العمل" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(msg,target,receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "العمل" and not matches[2] then
local receiver = get_receiver(msg)
return all(msg,msg.to.id,receiver)
end
end
return {
patterns = {
"^/(العمل)$",
"^/(العمل) (%d+)$"
},
run = run
}
end
-- arabic : @mohammedzedan | gpl-2.0 |
nyczducky/darkstar | scripts/zones/Jugner_Forest_[S]/npcs/Roiloux_RK.lua | 14 | 1045 | -----------------------------------
-- Area: Jugner Forest (S)
-- NPC: Roiloux, R.K.
-- Type: Campaign Arbiter
-- @pos 70.493 -0.602 -9.185 82
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Jugner_Forest_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01c2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Travonce.lua | 14 | 1060 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Travonce
-- Type: Standard NPC
-- @zone 26
-- @pos -89.068 -14.367 -0.030
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00d2);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
abcdefg30/OpenRA | mods/ra/maps/ant-01/ant-attack.lua | 7 | 2347 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
timeTracker = 0
amount = 1
SendAnts = true
AttackAngles = {
{ waypoint4.Location, waypoint18.Location, waypoint5.Location, waypoint15.Location },
{ waypoint20.Location, waypoint2.Location },
{ waypoint21.Location, waypoint10.Location, waypoint2.Location },
{ waypoint7.Location, waypoint17.Location, waypoint1.Location },
{ waypoint8.Location, waypoint9.Location, waypoint19.Location }
}
AttackInterval = {
easy = DateTime.Seconds(40),
normal = DateTime.Seconds(30),
hard = DateTime.Seconds(25)
}
AntTypes = {
"scoutant",
"fireant"
}
MaxAnts = {
easy = 3,
normal = 5,
hard = 6
}
MaxFireAnts = {
easy = 2,
normal = 3,
hard = 4
}
StartAntAttack = function()
local path = Utils.Random(AttackAngles)
local antType = "scoutant"
local index = 0
local amount = 1
local timeTracker = GetTicks()
if timeTracker > DateTime.Minutes(6) then
antType = Utils.Random(AntTypes)
end
if antType == "warriorant" and Difficulty == "easy" then
antType = "scoutant"
end
if Difficulty == "normal" and timeTracker < DateTime.Minutes(6) and antType == "scoutant" then
antType = "warriorant"
elseif Difficulty == "hard" and timeTracker < DateTime.Minutes(8) and antType == "scoutant" then
antType = "warriorant"
end
local max = MaxAnts[Difficulty] - math.ceil(timeTracker / DateTime.Minutes(6))
if timeTracker > DateTime.Minutes(3) and antType == "fireant" then
amount = Utils.RandomInteger(1, MaxFireAnts[Difficulty])
elseif timeTracker > 15 and antType == "fireant" then
antType = "scoutant"
else
amount = Utils.RandomInteger(1, max)
end
for i = 0,amount,1 do
Reinforcements.Reinforce(AntMan, { antType }, path, DateTime.Seconds(5), function(actor)
actor.AttackMove(CPos.New(65, 65))
Trigger.OnIdle(actor, function()
actor.Hunt()
end)
end)
end
-- Setup next wave
if SendAnts then
Trigger.AfterDelay(AttackInterval[Difficulty], function()
StartAntAttack()
end)
end
end
EndAntAttack = function()
SendAnts = false
end
| gpl-3.0 |
micdah/LrControl | Source/LrControl.Plugin/ChangeObserverParameters.lua | 1 | 4990 |
--[[----------------------------------------------------------------------------
Copyright ? 2016 Michael Dahl
This file is part of LrControl.
LrControl 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 3 of the License, or
(at your option) any later version.
LrControl 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 LrControl. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------]]
local LrDevelopController = import 'LrDevelopController'
local cache = {}
local function registerValue(parameter, value)
cache[parameter] = value
end
local function hasChanged(parameter)
local currentValue = LrDevelopController.getValue(parameter)
local cacheValue = cache[parameter]
if cacheValue == nil or (type(currentValue) == "number" and math.abs(currentValue-cacheValue) >= 0.01) or (type(currentValue) ~= "number" and currentValue ~= cacheValue) then
registerValue(parameter, currentValue)
return true
else
return false
end
end
local parameters = {
"WhiteBalance",
"Temperature",
"Tint",
"Exposure",
"Contrast",
"Highlights",
"Shadows",
"Whites",
"Blacks",
"Clarity",
"Vibrance",
"Saturation",
"CameraProfile",
"ShadowTint",
"RedHue",
"RedSaturation",
"GreenHue",
"GreenSaturation",
"BlueHue",
"BlueSaturation",
"straightenAngle",
"CropAngle",
"CropLeft",
"CropRight",
"CropTop",
"CropBottom",
"Sharpness",
"SharpenRadius",
"SharpenDetail",
"SharpenEdgeMasking",
"LuminanceSmoothing",
"LuminanceNoiseReductionDetail",
"LuminanceNoiseReductionContrast",
"ColorNoiseReduction",
"ColorNoiseReductionDetail",
"ColorNoiseReductionSmoothness",
"PostCropVignetteStyle",
"PostCropVignetteAmount",
"PostCropVignetteMidpoint",
"PostCropVignetteRoundness",
"PostCropVignetteFeather",
"PostCropVignetteHighlightContrast",
"GrainAmount",
"GrainSize",
"GrainFrequency",
"Dehaze",
"EnableToneCurve",
"EnableColorAdjustments",
"EnableSplitToning",
"EnableDetail",
"EnableLensCorrections",
"EnableEffects",
"EnableCalibration",
"EnableRetouch",
"EnableRedEye",
"EnableGradientBasedCorrections",
"EnableCircularGradientBasedCorrections",
"EnablePaintBasedCorrections",
"EnableGrayscaleMix",
"LensProfileDistortionScale",
"LensProfileVignettingScale",
"LensProfileChromaticAberrationScale",
"DefringePurpleAmount",
"DefringePurpleHueLo",
"DefringePurpleHueHi",
"DefringeGreenAmount",
"DefringeGreenHueLo",
"DefringeGreenHueHi",
"LensManualDistortionAmount",
"PerspectiveVertical",
"PerspectiveHorizontal",
"PerspectiveRotate",
"PerspectiveScale",
"PerspectiveAspect",
"PerspectiveUpright",
"local_Temperature",
"local_Tint",
"local_Exposure",
"local_Contrast",
"local_Highlights",
"local_Shadows",
"local_Whites2012",
"local_Blacks2012",
"local_Clarity",
"local_Dehaze",
"local_Saturation",
"local_Sharpness",
"local_LuminanceNoise",
"local_Moire",
"local_Defringe",
"SaturationAdjustmentRed",
"SaturationAdjustmentOrange",
"SaturationAdjustmentYellow",
"SaturationAdjustmentGreen",
"SaturationAdjustmentAqua",
"SaturationAdjustmentBlue",
"SaturationAdjustmentPurple",
"SaturationAdjustmentMagenta",
"HueAdjustmentRed",
"HueAdjustmentOrange",
"HueAdjustmentYellow",
"HueAdjustmentGreen",
"HueAdjustmentAqua",
"HueAdjustmentBlue",
"HueAdjustmentPurple",
"HueAdjustmentMagenta",
"LuminanceAdjustmentRed",
"LuminanceAdjustmentOrange",
"LuminanceAdjustmentYellow",
"LuminanceAdjustmentGreen",
"LuminanceAdjustmentAqua",
"LuminanceAdjustmentBlue",
"LuminanceAdjustmentPurple",
"LuminanceAdjustmentMagenta",
"GrayMixerRed",
"GrayMixerOrange",
"GrayMixerYellow",
"GrayMixerGreen",
"GrayMixerAqua",
"GrayMixerBlue",
"GrayMixerPurple",
"GrayMixerMagenta",
"ConvertToGrayscale",
"SplitToningHighlightHue",
"SplitToningHighlightSaturation",
"SplitToningBalance",
"SplitToningShadowHue",
"SplitToningShadowSaturation",
"ParametricHighlights",
"ParametricLights",
"ParametricDarks",
"ParametricShadows",
"ParametricShadowSplit",
"ParametricMidtoneSplit",
"ParametricHighlightSplit",
}
return {
Parameters = parameters,
HasChanged = hasChanged,
RegisterValue = registerValue,
} | gpl-3.0 |
melfi19/OpenRA | mods/ra/maps/soviet-04b/main.lua | 15 | 4003 |
RunInitialActivities = function()
Harvester.FindResources()
Helper.Destroy()
IdlingUnits()
Trigger.AfterDelay(DateTime.Seconds(1), function()
BringPatrol1()
Trigger.AfterDelay(DateTime.Seconds(5), function()
BringPatrol2()
end)
BuildBase()
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == Greece and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == Greece and building.Health < 3/4 * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Trigger.OnKilled(Powr, function(building)
BaseBuildings[1][4] = false
end)
Trigger.OnKilled(Barr, function(building)
BaseBuildings[2][4] = false
end)
Trigger.OnKilled(Proc, function(building)
BaseBuildings[3][4] = false
end)
Trigger.OnKilled(Weap, function(building)
BaseBuildings[4][4] = false
end)
Trigger.OnEnteredFootprint(VillageCamArea, function(actor, id)
if actor.Owner == player then
local camera = Actor.Create("camera", true, { Owner = player, Location = VillagePoint.Location })
Trigger.RemoveFootprintTrigger(id)
Trigger.OnAllKilled(Village, function()
camera.Destroy()
end)
end
end)
Trigger.OnAnyKilled(Civs, function()
Trigger.ClearAll(civ1)
Trigger.ClearAll(civ2)
Trigger.ClearAll(civ3)
Trigger.ClearAll(civ4)
local units = Reinforcements.Reinforce(Greece, Avengers, { NRoadPoint.Location }, 0)
Utils.Do(units, function(unit)
unit.Hunt()
end)
end)
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor)
if Map.Difficulty == "Hard" or Map.Difficulty == "Medium" then
Trigger.AfterDelay(DateTime.Seconds(5), ReinfInf)
end
Trigger.AfterDelay(DateTime.Minutes(1), ReinfInf)
Trigger.AfterDelay(DateTime.Minutes(3), ReinfInf)
Trigger.AfterDelay(DateTime.Minutes(2), ReinfArmor)
end
Tick = function()
if Greece.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillAll)
player.MarkCompletedObjective(KillRadar)
end
if player.HasNoRequiredUnits() then
Greece.MarkCompletedObjective(BeatUSSR)
end
if Greece.Resources >= Greece.ResourceCapacity * 0.75 then
Greece.Cash = Greece.Cash + Greece.Resources - Greece.ResourceCapacity * 0.25
Greece.Resources = Greece.ResourceCapacity * 0.25
end
if RCheck then
RCheck = false
if Map.Difficulty == "Hard" then
Trigger.AfterDelay(DateTime.Seconds(150), ReinfArmor)
elseif Map.Difficulty == "Medium" then
Trigger.AfterDelay(DateTime.Minutes(5), ReinfArmor)
else
Trigger.AfterDelay(DateTime.Minutes(8), ReinfArmor)
end
end
end
WorldLoaded = function()
player = Player.GetPlayer("USSR")
Greece = Player.GetPlayer("Greece")
RunInitialActivities()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
KillAll = player.AddPrimaryObjective("Defeat the Allied forces.")
BeatUSSR = Greece.AddPrimaryObjective("Defeat the Soviet forces.")
KillRadar = player.AddSecondaryObjective("Destroy Allied Radar Dome to stop enemy\nreinforcements.")
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnKilled(Radar, function()
player.MarkCompletedObjective(KillRadar)
Media.PlaySpeechNotification(player, "ObjectiveMet")
end)
Trigger.OnDamaged(Harvester, function()
Utils.Do(Guards, function(unit)
if not unit.IsDead and not Harvester.IsDead then
unit.AttackMove(Harvester.Location)
end
end)
end)
Camera.Position = StartCamPoint.CenterPosition
end
| gpl-3.0 |
jbeich/Aquaria | files/scripts/maps/node_gasp.lua | 6 | 1109 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
node_setCursorActivation(me, true)
end
function activate(me)
emote(EMOTE_NAIJAWOW)
entity_idle(getNaija())
cam_toNode(me)
watch(1)
cam_toEntity(getNaija())
end
function update(me, dt)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/La_Theine_Plateau/mobs/Bloodtear_Baldurf.lua | 13 | 1668 | -----------------------------------
-- Area: La Theine Plateau
-- MOB: Bloodtear_Baldurf
-----------------------------------
require("scripts/globals/titles");
require("scripts/zones/La_Theine_Plateau/MobIDs");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ALWAYS_AGGRO, 1);
mob:setMobMod(MOBMOD_MAIN_2HOUR, 1);
mob:setMobMod(MOBMOD_2HOUR_MULTI, 1);
mob:setMobMod(MOBMOD_DRAW_IN, 1);
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:addTitle(THE_HORNSPLITTER);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
local mobID = mob:getID();
local chanceForLambert = 0;
if (GetServerVariable("[POP]Lumbering_Lambert") <= os.time(t)) then
chanceForLambert = math.random(1,100);
end
if (chanceForLambert > 95 and GetMobAction(Battering_Ram) == ACTION_NONE and GetMobAction(Lumbering_Lambert) == ACTION_NONE) then
UpdateNMSpawnPoint(Lumbering_Lambert);
GetMobByID(Lumbering_Lambert):setRespawnTime(GetMobRespawnTime(Battering_Ram));
DeterMob(mobID, true);
else
GetMobByID(Battering_Ram):setRespawnTime(GetMobRespawnTime(Battering_Ram));
DeterMob(mobID, true);
end
SetServerVariable("[POP]Bloodtear_Baldurf", os.time(t) + math.random(75600, 86400)); -- 21-24hours repop
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/The_Shrine_of_RuAvitau/npcs/qm2.lua | 14 | 1568 | -----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: ??? (Spawn Kirin)
-- @pos -81 32 2 178
-----------------------------------
package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Validate traded items are all needed seals and ensure Kirin is not alive
if (GetMobAction(17506670) == 0 and trade:hasItemQty(1404, 1) and trade:hasItemQty(1405, 1) and trade:hasItemQty(1406, 1) and trade:hasItemQty(1407, 1) and trade:getItemCount() == 4) then
-- Complete the trade..
player:tradeComplete();
-- Spawn Kirin..
local mob = SpawnMob(17506670, 180);
player:showText(npc, KIRIN_OFFSET);
mob:updateClaim(player);
npc:setStatus(STATUS_DISAPPEAR);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0064);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/rolanberry_daifuku_+1.lua | 12 | 2292 | -----------------------------------------
-- ID: 6340
-- Item: rolanberry_daifuku_+1
-- Food Effect: 60 Min, All Races
-----------------------------------------
-- HP +30
-- VIT +4
-- Accuracy +11% (cap 54)
-- Ranged Accuracy +11% (cap 54)
-- Magic Accuracy +4
-- Pet:
-- HP +30
-- VIT +4
-- Accuracy +11% (cap 81)
-- Ranged Accuracy +11% (cap 81)
-- Magic Accuracy +15
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD)) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,6340);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_FOOD_ACCP, 11);
target:addMod(MOD_FOOD_ACC_CAP, 54);
target:addMod(MOD_FOOD_RACCP, 11);
target:addMod(MOD_FOOD_RACC_CAP, 54);
target:addMod(MOD_MACC, 4);
target:addPetMod(MOD_HP, 30);
target:addPetMod(MOD_VIT, 4);
target:addPetMod(MOD_FOOD_ACCP, 11);
target:addPetMod(MOD_FOOD_ACC_CAP, 81);
target:addPetMod(MOD_FOOD_RACCP, 11);
target:addPetMod(MOD_FOOD_RACC_CAP, 81);
target:addPetMod(MOD_MACC, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_FOOD_ACCP, 11);
target:delMod(MOD_FOOD_ACC_CAP, 54);
target:delMod(MOD_FOOD_RACCP, 11);
target:delMod(MOD_FOOD_RACC_CAP, 54);
target:delMod(MOD_MACC, 4);
target:delPetMod(MOD_HP, 30);
target:delPetMod(MOD_VIT, 4);
target:delPetMod(MOD_FOOD_ACCP, 11);
target:delPetMod(MOD_FOOD_ACC_CAP, 81);
target:delPetMod(MOD_FOOD_RACCP, 11);
target:delPetMod(MOD_FOOD_RACC_CAP, 81);
target:delPetMod(MOD_MACC, 15);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Hieroglyphics.lua | 7 | 2737 | -----------------------------------
-- Area: Tavnazian_Safehold
-- NPC: Hieroglyphics
-- Notes: Dynamis Tavnazia Enter
-- @pos 3.674 -7.278 -27.856 26
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/globals/missions");
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if ((player:hasCompletedMission(COP,DARKNESS_NAMED) or FREE_COP_DYNAMIS == 1) and player:hasKeyItem(VIAL_OF_SHROUDED_SAND) and
player:hasKeyItem(DYNAMIS_BUBURIMU_SLIVER) and player:hasKeyItem(DYNAMIS_QUFIM_SLIVER) and player:hasKeyItem(DYNAMIS_VALKURM_SLIVER)) then
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
local dynaUniqueID = GetServerVariable("[DynaTavnazia]UniqueID");
if (checkFirstDyna(player,10)) then
player:startEvent(0x0266);
elseif (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or (player:getVar("DynamisID") == dynaUniqueID and dynaUniqueID > 0)) then
player:startEvent(0x024C,10,0,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,10);
end
else
player:messageSpecial(MYSTERIOUS_VOICE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("finishRESULT: %u",option);
if (csid == 0x0266) then
if (checkFirstDyna(player,10)) then
player:setVar("Dynamis_Status",bit.bor(player:getVar("Dynamis_Status"),1024));
end
elseif (csid == 0x024C and option == 0) then
player:setVar("enteringDynamis",1);
player:setPos(0.1,-7,-21,190,42);
end
end; | gpl-3.0 |
abcdefg30/OpenRA | mods/ra/maps/allies-05b/allies05b.lua | 7 | 12709 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
SpyType = { "spy" }
SpyEntryPath = { SpyEntry.Location, SpyLoadout.Location }
InsertionTransport = "lst.in"
TrukPath1 = { SpyCamera1, TrukWaypoint1, TrukWaypoint2, TrukWaypoint3, TrukWaypoint4 }
TrukPath2 = { TruckWaypoint5, TruckCrash }
ExtractionHeliType = "tran"
ExtractionPath = { ExtractionEntry.Location, ExtractionLZ.Location }
GreeceReinforcements =
{
{ types = { "e3", "e3", "e1", "e1", "e1" }, entry = { SpyEntry.Location, SpyLoadout.Location } },
{ types = { "jeep", "1tnk", "1tnk", "2tnk", "2tnk" }, entry = { GreeceEntry1.Location, GreeceLoadout1.Location } },
{ types = { "e6", "e6", "e6", "e6", "e6" }, entry = { GreeceEntry2.Location, GreeceLoadout2.Location } }
}
FlameTowerDogs = { FlameTowerDog1, FlameTowerDog2 }
PatrolA = { PatrolA1, PatrolA2, PatrolA3 }
PatrolB = { PatrolB1, PatrolB2, PatrolB3 }
PatrolC = { PatrolC1, PatrolC2, PatrolC3 }
PatrolAPath = { APatrol1.Location, CPatrol1.Location, APatrol2.Location }
PatrolBPath = { BPatrol1.Location, BPatrol2.Location, SpyCamera2.Location }
PatrolCPath = { CPatrol1.Location, CPatrol2.Location, CPatrol3.Location }
CheckpointDogs = { CheckpointDog1, CheckpointDog2 }
CheckpointRifles = { CheckpointRifle1, CheckpointRifle2 }
BridgePatrol = { CheckpointDog1, CheckpointDog2, CheckpointRifle1, CheckpointRifle2 }
BridgePatrolPath = { TrukWaypoint4.Location, BridgePatrolWay.Location }
TanyaVoices = { "tuffguy", "bombit", "laugh", "gotit", "lefty", "keepem" }
SpyVoice = "sking"
CivVoice = "guyokay"
DogBark = "dogy"
SamSites = { Sam1, Sam2, Sam3, Sam4 }
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)
Trigger.AfterDelay(DateTime.Seconds(3), function()
Media.DisplayMessage("Commander! You have to disguise me in order to get through the enemy patrols.", "Spy")
if SpecialCameras then
SpyCameraA = Actor.Create("camera", true, { Owner = Greece, Location = SpyCamera1.Location })
SpyCameraB = Actor.Create("camera", true, { Owner = Greece, Location = SpyCamera2.Location })
SpyCameraC = Actor.Create("camera", true, { Owner = Greece, Location = BPatrol2.Location })
else
SpyCameraHard = Actor.Create("camera.small", true, { Owner = Greece, Location = FlameTowerDogRally.Location + CVec.New(2, 0) })
end
end)
end
ChurchFootprint = function()
Trigger.OnEnteredProximityTrigger(ChurchSpawn.CenterPosition, WDist.FromCells(2), function(actor, id)
if actor.Type == "spy" and not Greece.IsObjectiveCompleted(MainObj) then
Trigger.RemoveProximityTrigger(id)
ChurchSequence()
end
end)
end
ChurchSequence = function()
Media.PlaySoundNotification(Greece, CivVoice)
Hero = Actor.Create("c1", true, { Owner = GoodGuy, Location = ChurchSpawn.Location })
Hero.Attack(TargetBarrel)
Trigger.OnKilled(ResponseBarrel, function()
if not Hero.IsDead then
Hero.Stop()
Hero.Move(SouthVillage.Location)
BarrelsTower.Kill()
Utils.Do(FlameTowerDogs, function(dogs)
if not dogs.IsDead then
dogs.Stop()
dogs.AttackMove(SouthVillage.Location)
end
end)
Utils.Do(PatrolA, function(patrol1)
if not patrol1.IsDead then
patrol1.Stop()
patrol1.AttackMove(SouthVillage.Location)
end
end)
Utils.Do(PatrolB, function(patrol2)
if not patrol2.IsDead then
patrol2.Stop()
patrol2.AttackMove(SouthVillage.Location)
end
end)
end
end)
end
ActivatePatrols = function()
Utils.Do(FlameTowerDogs, function(dogs)
dogs.AttackMove(FlameTowerDogRally.Location)
end)
Trigger.AfterDelay(DateTime.Seconds(3), function()
GroupPatrol(PatrolA, PatrolAPath, DateTime.Seconds(7))
GroupPatrol(PatrolB, PatrolBPath, DateTime.Seconds(6))
GroupPatrol(PatrolC, PatrolCPath, DateTime.Seconds(6))
end)
end
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
WarfactoryInfiltrated = function()
FollowTruk = true
Truk.GrantCondition("hijacked")
Truk.Wait(DateTime.Seconds(1))
Utils.Do(TrukPath1, function(waypoint)
Truk.Move(waypoint.Location)
end)
Trigger.AfterDelay(DateTime.Seconds(2), function()
if SpecialCameras then
SpyCameraA.Destroy()
SpyCameraB.Destroy()
SpyCameraC.Destroy()
else
SpyCameraHard.Destroy()
end
end)
Trigger.OnEnteredProximityTrigger(TrukWaypoint4.CenterPosition, WDist.FromCells(1), function(actor, id)
if actor.Type == "truk.mission" then
Trigger.RemoveProximityTrigger(id)
Utils.Do(CheckpointDogs, function(dog)
dog.Move(TrukInspect.Location)
end)
end
end)
Trigger.OnEnteredProximityTrigger(TrukWaypoint4.CenterPosition, WDist.FromCells(1), function(actor, id)
if actor.Type == "dog" then
Trigger.RemoveProximityTrigger(id)
Media.PlaySoundNotification(Greece, DogBark)
Utils.Do(CheckpointRifles, function(guard)
guard.Move(TrukInspect.Location)
end)
Trigger.AfterDelay(DateTime.Seconds(2), function()
Utils.Do(TrukPath2, function(waypoint)
Truk.Move(waypoint.Location)
end)
end)
end
end)
Trigger.OnEnteredFootprint({ SpyJumpOut.Location }, function(a, id)
if a == Truk then
Trigger.RemoveFootprintTrigger(id)
Spy = Actor.Create("spy", true, { Owner = Greece, Location = SpyJumpOut.Location })
Spy.DisguiseAsType("e1", USSR)
Spy.Move(TruckWaypoint5.Location)
Spy.Infiltrate(Prison)
Media.PlaySoundNotification(Greece, SpyVoice)
FollowTruk = false
if SpecialCameras then
PrisonCamera = Actor.Create("camera", true, { Owner = Greece, Location = SpyJumpOut.Location })
else
PrisonCamera = Actor.Create("camera.small", true, { Owner = Greece, Location = Prison.Location + CVec.New(1, 1) })
end
Trigger.OnKilled(Spy, function() USSR.MarkCompletedObjective(USSRObj) end)
end
end)
Trigger.OnEnteredFootprint({ TruckCrash.Location }, function(a, id)
if a == Truk then
Trigger.RemoveFootprintTrigger(id)
Truk.Stop()
Truk.Kill()
CrashTower.Kill()
CrashBarrel.Kill()
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
Prison.Attack(Prison)
Trigger.AfterDelay(DateTime.Seconds(6), FreeTanya)
end
FreeTanya = function()
Prison.Stop()
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))
GroupPatrol(BridgePatrol, BridgePatrolPath, DateTime.Seconds(7))
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
local escapeResponse1 = Reinforcements.Reinforce(USSR, { "e1", "e2", "e2" }, { RaxSpawn.Location, TrukWaypoint4.Location })
Utils.Do(escapeResponse1, function(units)
IdleHunt(units)
end)
Trigger.AfterDelay(DateTime.Seconds(10), function()
local escapeResponse2 = Reinforcements.Reinforce(USSR, { "e1", "e2", "e2" }, { RaxSpawn.Location, TrukWaypoint4.Location })
Utils.Do(escapeResponse2, function(units)
IdleHunt(units)
end)
end)
KillSams = Greece.AddObjective("Destroy all four SAM sites that block\nthe extraction helicopter.")
Trigger.OnKilled(Tanya, function() USSR.MarkCompletedObjective(USSRObj) end)
if not SpecialCameras and PrisonCamera and PrisonCamera.IsInWorld then
PrisonCamera.Destroy()
end
end
SendReinforcements = function()
GreeceReinforcementsArrived = true
Camera.Position = SpyLoadout.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
InitTriggers = function()
Trigger.OnInfiltrated(Warfactory, function()
if Greece.IsObjectiveCompleted(InfWarfactory) then
return
elseif Truk.IsDead then
if not Greece.IsObjectiveCompleted(MainObj) then
USSR.MarkCompletedObjective(USSRObj)
end
return
end
Trigger.ClearAll(Spy)
Greece.MarkCompletedObjective(InfWarfactory)
WarfactoryInfiltrated()
end)
Trigger.OnKilled(Truk, function()
if not Greece.IsObjectiveCompleted(InfWarfactory) then
Greece.MarkFailedObjective(InfWarfactory)
elseif FollowTruk then
USSR.MarkCompletedObjective(USSRObj)
end
end)
Trigger.OnInfiltrated(Prison, function()
if Greece.IsObjectiveCompleted(MainObj) then
return
end
if not Greece.IsObjectiveCompleted(InfWarfactory) then
Media.DisplayMessage("Good work! But next time skip the heroics!", "Battlefield Control")
Greece.MarkCompletedObjective(InfWarfactory)
end
if not PrisonCamera then
if SpecialCameras then
PrisonCamera = Actor.Create("camera", true, { Owner = Greece, Location = SpyJumpOut.Location })
else
PrisonCamera = Actor.Create("camera.small", true, { Owner = Greece, Location = Prison.Location + CVec.New(1, 1) })
end
end
if SpecialCameras and SpyCameraA and not SpyCameraA.IsDead then
SpyCameraA.Destroy()
SpyCameraB.Destroy()
SpyCameraC.Destroy()
end
Trigger.ClearAll(Spy)
Trigger.AfterDelay(DateTime.Seconds(2), MissInfiltrated)
end)
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")
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)
Trigger.AfterDelay(DateTime.Seconds(2), function()
SendReinforcements()
end)
if PrisonCamera and PrisonCamera.IsInWorld then
PrisonCamera.Destroy()
end
end)
end)
end)
end
Tick = function()
if FollowTruk and not Truk.IsDead then
Camera.Position = Truk.CenterPosition
end
if USSR.HasNoRequiredUnits() then
Greece.MarkCompletedObjective(KillAll)
end
if GreeceReinforcementsArrived and Greece.HasNoRequiredUnits() then
USSR.MarkCompletedObjective(USSRObj)
end
end
WorldLoaded = function()
Greece = Player.GetPlayer("Greece")
USSR = Player.GetPlayer("USSR")
GoodGuy = Player.GetPlayer("GoodGuy")
InitObjectives(Greece)
USSRObj = USSR.AddObjective("Deny the Allies.")
MainObj = Greece.AddObjective("Rescue Tanya.")
KillAll = Greece.AddObjective("Eliminate all Soviet units in this area.")
InfWarfactory = Greece.AddObjective("Infiltrate the Soviet warfactory.", "Secondary", false)
InitTriggers()
SendSpy()
ChurchFootprint()
if Difficulty == "easy" then
TanyaType = "e7"
ReinforceCash = 5000
USSR.Cash = 8000
SpecialCameras = true
elseif Difficulty == "normal" then
TanyaType = "e7.noautotarget"
ReinforceCash = 2250
USSR.Cash = 15000
SpecialCameras = true
else
TanyaType = "e7.noautotarget"
ReinforceCash = 1500
USSR.Cash = 25000
end
Trigger.AfterDelay(DateTime.Seconds(3), ActivatePatrols)
end
| gpl-3.0 |
cliffano/swaggy-jenkins | clients/lua/generated/openapiclient/api/blue_ocean_api.lua | 1 | 56098 | --[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.5.1-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
--package openapiclient
local http_request = require "http.request"
local http_util = require "http.util"
local dkjson = require "dkjson"
local basexx = require "basexx"
-- model import
local openapiclient_branch_impl = require "openapiclient.model.branch_impl"
local openapiclient_favorite_impl = require "openapiclient.model.favorite_impl"
local openapiclient_github_organization = require "openapiclient.model.github_organization"
local openapiclient_github_scm = require "openapiclient.model.github_scm"
local openapiclient_multibranch_pipeline = require "openapiclient.model.multibranch_pipeline"
local openapiclient_organisation = require "openapiclient.model.organisation"
local openapiclient_pipeline = require "openapiclient.model.pipeline"
local openapiclient_pipeline_activity = require "openapiclient.model.pipeline_activity"
local openapiclient_pipeline_folder_impl = require "openapiclient.model.pipeline_folder_impl"
local openapiclient_pipeline_impl = require "openapiclient.model.pipeline_impl"
local openapiclient_pipeline_run = require "openapiclient.model.pipeline_run"
local openapiclient_pipeline_run_node = require "openapiclient.model.pipeline_run_node"
local openapiclient_pipeline_step_impl = require "openapiclient.model.pipeline_step_impl"
local openapiclient_queue_item_impl = require "openapiclient.model.queue_item_impl"
local openapiclient_user = require "openapiclient.model.user"
local blue_ocean_api = {}
local blue_ocean_api_mt = {
__name = "blue_ocean_api";
__index = blue_ocean_api;
}
local function new_blue_ocean_api(authority, basePath, schemes)
local schemes_map = {}
for _,v in ipairs(schemes) do
schemes_map[v] = v
end
local default_scheme = schemes_map.https or schemes_map.http
local host, port = http_util.split_authority(authority, default_scheme)
return setmetatable({
host = host;
port = port;
basePath = basePath or "http://localhost";
schemes = schemes_map;
default_scheme = default_scheme;
http_username = nil;
http_password = nil;
api_key = {};
access_token = nil;
}, blue_ocean_api_mt)
end
function blue_ocean_api:delete_pipeline_queue_item(organization, pipeline, queue)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/queue/%s",
self.basePath, organization, pipeline, queue);
})
-- set HTTP verb
req.headers:upsert(":method", "DELETE")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
return nil, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_authenticated_user(organization)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/user",
self.basePath, organization);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_user.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_classes(class)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/classes/%s",
self.basePath, class);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_json_web_key(key)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jwt-auth/jwks/%s",
self.basePath, key);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_json_web_token(expiry_time_in_mins, max_expiry_time_in_mins)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/jwt-auth/token?expiryTimeInMins=%s&maxExpiryTimeInMins=%s",
self.basePath, http_util.encodeURIComponent(expiry_time_in_mins), http_util.encodeURIComponent(max_expiry_time_in_mins));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_organisation(organization)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s",
self.basePath, organization);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_organisation.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_organisations()
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations",
self.basePath);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_organisation.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline(organization, pipeline)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_activities(organization, pipeline)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/activities",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_pipeline_activity.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_branch(organization, pipeline, branch)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/branches/%s",
self.basePath, organization, pipeline, branch);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_branch_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_branch_run(organization, pipeline, branch, run)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/branches/%s/runs/%s",
self.basePath, organization, pipeline, branch, run);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_run.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_branches(organization, pipeline)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/branches",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_multibranch_pipeline.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_folder(organization, folder)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s",
self.basePath, organization, folder);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_folder_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_folder_pipeline(organization, pipeline, folder)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/pipelines/%s",
self.basePath, organization, pipeline, folder);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_queue(organization, pipeline)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/queue",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_queue_item_impl.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run(organization, pipeline, run)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s",
self.basePath, organization, pipeline, run);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_run.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run_log(organization, pipeline, run, start, download)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/log?start=%s&download=%s",
self.basePath, organization, pipeline, run, http_util.encodeURIComponent(start), http_util.encodeURIComponent(download));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run_node(organization, pipeline, run, node)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/nodes/%s",
self.basePath, organization, pipeline, run, node);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_run_node.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run_node_step(organization, pipeline, run, node, step)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/nodes/%s/steps/%s",
self.basePath, organization, pipeline, run, node, step);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_step_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run_node_step_log(organization, pipeline, run, node, step)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/nodes/%s/steps/%s/log",
self.basePath, organization, pipeline, run, node, step);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run_node_steps(organization, pipeline, run, node)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/nodes/%s/steps",
self.basePath, organization, pipeline, run, node);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_pipeline_step_impl.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_run_nodes(organization, pipeline, run)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/nodes",
self.basePath, organization, pipeline, run);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_pipeline_run_node.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipeline_runs(organization, pipeline)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_pipeline_run.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_pipelines(organization)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines",
self.basePath, organization);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_pipeline.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_scm(organization, scm)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/scm/%s",
self.basePath, organization, scm);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_github_scm.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_scm_organisation_repositories(organization, scm, scm_organisation, credential_id, page_size, page_number)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/scm/%s/organizations/%s/repositories?credentialId=%s&pageSize=%s&pageNumber=%s",
self.basePath, organization, scm, scm_organisation, http_util.encodeURIComponent(credential_id), http_util.encodeURIComponent(page_size), http_util.encodeURIComponent(page_number));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_github_organization.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_scm_organisation_repository(organization, scm, scm_organisation, repository, credential_id)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/scm/%s/organizations/%s/repositories/%s?credentialId=%s",
self.basePath, organization, scm, scm_organisation, repository, http_util.encodeURIComponent(credential_id));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_github_organization.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_scm_organisations(organization, scm, credential_id)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/scm/%s/organizations?credentialId=%s",
self.basePath, organization, scm, http_util.encodeURIComponent(credential_id));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_github_organization.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_user(organization, user)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/users/%s",
self.basePath, organization, user);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_user.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_user_favorites(user)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/users/%s/favorites",
self.basePath, user);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
for _, ob in ipairs(result) do
openapiclient_favorite_impl.cast(ob)
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:get_users(organization)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/users",
self.basePath, organization);
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_user.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:post_pipeline_run(organization, pipeline, run)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/replay",
self.basePath, organization, pipeline, run);
})
-- set HTTP verb
req.headers:upsert(":method", "POST")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_queue_item_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:post_pipeline_runs(organization, pipeline)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "POST")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_queue_item_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:put_pipeline_favorite(organization, pipeline, body)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/favorite",
self.basePath, organization, pipeline);
})
-- set HTTP verb
req.headers:upsert(":method", "PUT")
-- TODO: create a function to select proper accept
--local var_content_type = { "application/json" }
req.headers:upsert("accept", "application/json")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
req:set_body(dkjson.encode(body))
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_favorite_impl.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:put_pipeline_run(organization, pipeline, run, blocking, time_out_in_secs)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/organizations/%s/pipelines/%s/runs/%s/stop?blocking=%s&timeOutInSecs=%s",
self.basePath, organization, pipeline, run, http_util.encodeURIComponent(blocking), http_util.encodeURIComponent(time_out_in_secs));
})
-- set HTTP verb
req.headers:upsert(":method", "PUT")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return openapiclient_pipeline_run.cast(result), headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:search(q)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/search?q=%s",
self.basePath, http_util.encodeURIComponent(q));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
function blue_ocean_api:search_classes(q)
local req = http_request.new_from_uri({
scheme = self.default_scheme;
host = self.host;
port = self.port;
path = string.format("%s/blue/rest/classes?q=%s",
self.basePath, http_util.encodeURIComponent(q));
})
-- set HTTP verb
req.headers:upsert(":method", "GET")
-- TODO: create a function to select proper content-type
--local var_accept = { "application/json" }
req.headers:upsert("content-type", "application/json")
-- HTTP basic auth
req.readers:upsert("authorization", "Basic " .. basexx.to_base64(self.http_username .. " " .. self.http_password))
-- make the HTTP call
local headers, stream, errno = req:go()
if not headers then
return nil, stream, errno
end
local http_status = headers:get(":status")
if http_status:sub(1,1) == "2" then
local body, err, errno2 = stream:get_body_as_string()
-- exception when getting the HTTP body
if not body then
return nil, err, errno2
end
stream:shutdown()
local result, _, err3 = dkjson.decode(body)
-- exception when decoding the HTTP body
if result == nil then
return nil, err3
end
return result, headers
else
local body, err, errno2 = stream:get_body_as_string()
if not body then
return nil, err, errno2
end
stream:shutdown()
-- return the error message (http body)
return nil, http_status, body
end
end
return {
new = new_blue_ocean_api;
}
| mit |
nyczducky/darkstar | scripts/zones/Upper_Jeuno/npcs/Mhao_Kehtsoruho.lua | 14 | 1054 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Mhao Kehtsoruho
-- Type: Past Event Watcher
-- @zone 244
-- @pos -73.032 -1 146.919
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x27bd);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
andreiribas/google-diff-match-patch | lua/diff_match_patch.lua | 265 | 73869 | --[[
* Diff Match and Patch
*
* Copyright 2006 Google Inc.
* http://code.google.com/p/google-diff-match-patch/
*
* Based on the JavaScript implementation by Neil Fraser.
* Ported to Lua by Duncan Cross.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
--]]
--[[
-- Lua 5.1 and earlier requires the external BitOp library.
-- This library is built-in from Lua 5.2 and later as 'bit32'.
require 'bit' -- <http://bitop.luajit.org/>
local band, bor, lshift
= bit.band, bit.bor, bit.lshift
--]]
local band, bor, lshift
= bit32.band, bit32.bor, bit32.lshift
local type, setmetatable, ipairs, select
= type, setmetatable, ipairs, select
local unpack, tonumber, error
= unpack, tonumber, error
local strsub, strbyte, strchar, gmatch, gsub
= string.sub, string.byte, string.char, string.gmatch, string.gsub
local strmatch, strfind, strformat
= string.match, string.find, string.format
local tinsert, tremove, tconcat
= table.insert, table.remove, table.concat
local max, min, floor, ceil, abs
= math.max, math.min, math.floor, math.ceil, math.abs
local clock = os.clock
-- Utility functions.
local percentEncode_pattern = '[^A-Za-z0-9%-=;\',./~!@#$%&*%(%)_%+ %?]'
local function percentEncode_replace(v)
return strformat('%%%02X', strbyte(v))
end
local function tsplice(t, idx, deletions, ...)
local insertions = select('#', ...)
for i = 1, deletions do
tremove(t, idx)
end
for i = insertions, 1, -1 do
-- do not remove parentheses around select
tinsert(t, idx, (select(i, ...)))
end
end
local function strelement(str, i)
return strsub(str, i, i)
end
local function indexOf(a, b, start)
if (#b == 0) then
return nil
end
return strfind(a, b, start, true)
end
local htmlEncode_pattern = '[&<>\n]'
local htmlEncode_replace = {
['&'] = '&', ['<'] = '<', ['>'] = '>', ['\n'] = '¶<br>'
}
-- Public API Functions
-- (Exported at the end of the script)
local diff_main,
diff_cleanupSemantic,
diff_cleanupEfficiency,
diff_levenshtein,
diff_prettyHtml
local match_main
local patch_make,
patch_toText,
patch_fromText,
patch_apply
--[[
* The data structure representing a diff is an array of tuples:
* {{DIFF_DELETE, 'Hello'}, {DIFF_INSERT, 'Goodbye'}, {DIFF_EQUAL, ' world.'}}
* which means: delete 'Hello', add 'Goodbye' and keep ' world.'
--]]
local DIFF_DELETE = -1
local DIFF_INSERT = 1
local DIFF_EQUAL = 0
-- Number of seconds to map a diff before giving up (0 for infinity).
local Diff_Timeout = 1.0
-- Cost of an empty edit operation in terms of edit characters.
local Diff_EditCost = 4
-- At what point is no match declared (0.0 = perfection, 1.0 = very loose).
local Match_Threshold = 0.5
-- How far to search for a match (0 = exact location, 1000+ = broad match).
-- A match this many characters away from the expected location will add
-- 1.0 to the score (0.0 is a perfect match).
local Match_Distance = 1000
-- When deleting a large block of text (over ~64 characters), how close do
-- the contents have to be to match the expected contents. (0.0 = perfection,
-- 1.0 = very loose). Note that Match_Threshold controls how closely the
-- end points of a delete need to match.
local Patch_DeleteThreshold = 0.5
-- Chunk size for context length.
local Patch_Margin = 4
-- The number of bits in an int.
local Match_MaxBits = 32
function settings(new)
if new then
Diff_Timeout = new.Diff_Timeout or Diff_Timeout
Diff_EditCost = new.Diff_EditCost or Diff_EditCost
Match_Threshold = new.Match_Threshold or Match_Threshold
Match_Distance = new.Match_Distance or Match_Distance
Patch_DeleteThreshold = new.Patch_DeleteThreshold or Patch_DeleteThreshold
Patch_Margin = new.Patch_Margin or Patch_Margin
Match_MaxBits = new.Match_MaxBits or Match_MaxBits
else
return {
Diff_Timeout = Diff_Timeout;
Diff_EditCost = Diff_EditCost;
Match_Threshold = Match_Threshold;
Match_Distance = Match_Distance;
Patch_DeleteThreshold = Patch_DeleteThreshold;
Patch_Margin = Patch_Margin;
Match_MaxBits = Match_MaxBits;
}
end
end
-- ---------------------------------------------------------------------------
-- DIFF API
-- ---------------------------------------------------------------------------
-- The private diff functions
local _diff_compute,
_diff_bisect,
_diff_halfMatchI,
_diff_halfMatch,
_diff_cleanupSemanticScore,
_diff_cleanupSemanticLossless,
_diff_cleanupMerge,
_diff_commonPrefix,
_diff_commonSuffix,
_diff_commonOverlap,
_diff_xIndex,
_diff_text1,
_diff_text2,
_diff_toDelta,
_diff_fromDelta
--[[
* Find the differences between two texts. Simplifies the problem by stripping
* any common prefix or suffix off the texts before diffing.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} opt_checklines Has no effect in Lua.
* @param {number} opt_deadline Optional time when the diff should be complete
* by. Used internally for recursive calls. Users should set DiffTimeout
* instead.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
--]]
function diff_main(text1, text2, opt_checklines, opt_deadline)
-- Set a deadline by which time the diff must be complete.
if opt_deadline == nil then
if Diff_Timeout <= 0 then
opt_deadline = 2 ^ 31
else
opt_deadline = clock() + Diff_Timeout
end
end
local deadline = opt_deadline
-- Check for null inputs.
if text1 == nil or text1 == nil then
error('Null inputs. (diff_main)')
end
-- Check for equality (speedup).
if text1 == text2 then
if #text1 > 0 then
return {{DIFF_EQUAL, text1}}
end
return {}
end
-- LUANOTE: Due to the lack of Unicode support, Lua is incapable of
-- implementing the line-mode speedup.
local checklines = false
-- Trim off common prefix (speedup).
local commonlength = _diff_commonPrefix(text1, text2)
local commonprefix
if commonlength > 0 then
commonprefix = strsub(text1, 1, commonlength)
text1 = strsub(text1, commonlength + 1)
text2 = strsub(text2, commonlength + 1)
end
-- Trim off common suffix (speedup).
commonlength = _diff_commonSuffix(text1, text2)
local commonsuffix
if commonlength > 0 then
commonsuffix = strsub(text1, -commonlength)
text1 = strsub(text1, 1, -commonlength - 1)
text2 = strsub(text2, 1, -commonlength - 1)
end
-- Compute the diff on the middle block.
local diffs = _diff_compute(text1, text2, checklines, deadline)
-- Restore the prefix and suffix.
if commonprefix then
tinsert(diffs, 1, {DIFF_EQUAL, commonprefix})
end
if commonsuffix then
diffs[#diffs + 1] = {DIFF_EQUAL, commonsuffix}
end
_diff_cleanupMerge(diffs)
return diffs
end
--[[
* Reduce the number of edits by eliminating semantically trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupSemantic(diffs)
local changes = false
local equalities = {} -- Stack of indices where equalities are found.
local equalitiesLength = 0 -- Keeping our own length var is faster.
local lastequality = nil
-- Always equal to diffs[equalities[equalitiesLength]][2]
local pointer = 1 -- Index of current position.
-- Number of characters that changed prior to the equality.
local length_insertions1 = 0
local length_deletions1 = 0
-- Number of characters that changed after the equality.
local length_insertions2 = 0
local length_deletions2 = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
length_insertions1 = length_insertions2
length_deletions1 = length_deletions2
length_insertions2 = 0
length_deletions2 = 0
lastequality = diffs[pointer][2]
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_INSERT then
length_insertions2 = length_insertions2 + #(diffs[pointer][2])
else
length_deletions2 = length_deletions2 + #(diffs[pointer][2])
end
-- Eliminate an equality that is smaller or equal to the edits on both
-- sides of it.
if lastequality
and (#lastequality <= max(length_insertions1, length_deletions1))
and (#lastequality <= max(length_insertions2, length_deletions2)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
-- Throw away the previous equality (it needs to be reevaluated).
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
length_insertions1, length_deletions1 = 0, 0 -- Reset the counters.
length_insertions2, length_deletions2 = 0, 0
lastequality = nil
changes = true
end
end
pointer = pointer + 1
end
-- Normalize the diff.
if changes then
_diff_cleanupMerge(diffs)
end
_diff_cleanupSemanticLossless(diffs)
-- Find any overlaps between deletions and insertions.
-- e.g: <del>abcxxx</del><ins>xxxdef</ins>
-- -> <del>abc</del>xxx<ins>def</ins>
-- e.g: <del>xxxabc</del><ins>defxxx</ins>
-- -> <ins>def</ins>xxx<del>abc</del>
-- Only extract an overlap if it is as big as the edit ahead or behind it.
pointer = 2
while diffs[pointer] do
if (diffs[pointer - 1][1] == DIFF_DELETE and
diffs[pointer][1] == DIFF_INSERT) then
local deletion = diffs[pointer - 1][2]
local insertion = diffs[pointer][2]
local overlap_length1 = _diff_commonOverlap(deletion, insertion)
local overlap_length2 = _diff_commonOverlap(insertion, deletion)
if (overlap_length1 >= overlap_length2) then
if (overlap_length1 >= #deletion / 2 or
overlap_length1 >= #insertion / 2) then
-- Overlap found. Insert an equality and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(insertion, 1, overlap_length1)})
diffs[pointer - 1][2] =
strsub(deletion, 1, #deletion - overlap_length1)
diffs[pointer + 1][2] = strsub(insertion, overlap_length1 + 1)
pointer = pointer + 1
end
else
if (overlap_length2 >= #deletion / 2 or
overlap_length2 >= #insertion / 2) then
-- Reverse overlap found.
-- Insert an equality and swap and trim the surrounding edits.
tinsert(diffs, pointer,
{DIFF_EQUAL, strsub(deletion, 1, overlap_length2)})
diffs[pointer - 1] = {DIFF_INSERT,
strsub(insertion, 1, #insertion - overlap_length2)}
diffs[pointer + 1] = {DIFF_DELETE,
strsub(deletion, overlap_length2 + 1)}
pointer = pointer + 1
end
end
pointer = pointer + 1
end
pointer = pointer + 1
end
end
--[[
* Reduce the number of edits by eliminating operationally trivial equalities.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function diff_cleanupEfficiency(diffs)
local changes = false
-- Stack of indices where equalities are found.
local equalities = {}
-- Keeping our own length var is faster.
local equalitiesLength = 0
-- Always equal to diffs[equalities[equalitiesLength]][2]
local lastequality = nil
-- Index of current position.
local pointer = 1
-- The following four are really booleans but are stored as numbers because
-- they are used at one point like this:
--
-- (pre_ins + pre_del + post_ins + post_del) == 3
--
-- ...i.e. checking that 3 of them are true and 1 of them is false.
-- Is there an insertion operation before the last equality.
local pre_ins = 0
-- Is there a deletion operation before the last equality.
local pre_del = 0
-- Is there an insertion operation after the last equality.
local post_ins = 0
-- Is there a deletion operation after the last equality.
local post_del = 0
while diffs[pointer] do
if diffs[pointer][1] == DIFF_EQUAL then -- Equality found.
local diffText = diffs[pointer][2]
if (#diffText < Diff_EditCost) and (post_ins == 1 or post_del == 1) then
-- Candidate found.
equalitiesLength = equalitiesLength + 1
equalities[equalitiesLength] = pointer
pre_ins, pre_del = post_ins, post_del
lastequality = diffText
else
-- Not a candidate, and can never become one.
equalitiesLength = 0
lastequality = nil
end
post_ins, post_del = 0, 0
else -- An insertion or deletion.
if diffs[pointer][1] == DIFF_DELETE then
post_del = 1
else
post_ins = 1
end
--[[
* Five types to be split:
* <ins>A</ins><del>B</del>XY<ins>C</ins><del>D</del>
* <ins>A</ins>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<ins>C</ins>
* <ins>A</del>X<ins>C</ins><del>D</del>
* <ins>A</ins><del>B</del>X<del>C</del>
--]]
if lastequality and (
(pre_ins+pre_del+post_ins+post_del == 4)
or
(
(#lastequality < Diff_EditCost / 2)
and
(pre_ins+pre_del+post_ins+post_del == 3)
)) then
-- Duplicate record.
tinsert(diffs, equalities[equalitiesLength],
{DIFF_DELETE, lastequality})
-- Change second copy to insert.
diffs[equalities[equalitiesLength] + 1][1] = DIFF_INSERT
-- Throw away the equality we just deleted.
equalitiesLength = equalitiesLength - 1
lastequality = nil
if (pre_ins == 1) and (pre_del == 1) then
-- No changes made which could affect previous entry, keep going.
post_ins, post_del = 1, 1
equalitiesLength = 0
else
-- Throw away the previous equality.
equalitiesLength = equalitiesLength - 1
pointer = (equalitiesLength > 0) and equalities[equalitiesLength] or 0
post_ins, post_del = 0, 0
end
changes = true
end
end
pointer = pointer + 1
end
if changes then
_diff_cleanupMerge(diffs)
end
end
--[[
* Compute the Levenshtein distance; the number of inserted, deleted or
* substituted characters.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {number} Number of changes.
--]]
function diff_levenshtein(diffs)
local levenshtein = 0
local insertions, deletions = 0, 0
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if (op == DIFF_INSERT) then
insertions = insertions + #data
elseif (op == DIFF_DELETE) then
deletions = deletions + #data
elseif (op == DIFF_EQUAL) then
-- A deletion and an insertion is one substitution.
levenshtein = levenshtein + max(insertions, deletions)
insertions = 0
deletions = 0
end
end
levenshtein = levenshtein + max(insertions, deletions)
return levenshtein
end
--[[
* Convert a diff array into a pretty HTML report.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} HTML representation.
--]]
function diff_prettyHtml(diffs)
local html = {}
for x, diff in ipairs(diffs) do
local op = diff[1] -- Operation (insert, delete, equal)
local data = diff[2] -- Text of change.
local text = gsub(data, htmlEncode_pattern, htmlEncode_replace)
if op == DIFF_INSERT then
html[x] = '<ins style="background:#e6ffe6;">' .. text .. '</ins>'
elseif op == DIFF_DELETE then
html[x] = '<del style="background:#ffe6e6;">' .. text .. '</del>'
elseif op == DIFF_EQUAL then
html[x] = '<span>' .. text .. '</span>'
end
end
return tconcat(html)
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE DIFF FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Find the differences between two texts. Assumes that the texts do not
* have any common prefix or suffix.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {boolean} checklines Has no effect in Lua.
* @param {number} deadline Time when the diff should be complete by.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_compute(text1, text2, checklines, deadline)
if #text1 == 0 then
-- Just add some text (speedup).
return {{DIFF_INSERT, text2}}
end
if #text2 == 0 then
-- Just delete some text (speedup).
return {{DIFF_DELETE, text1}}
end
local diffs
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
local i = indexOf(longtext, shorttext)
if i ~= nil then
-- Shorter text is inside the longer text (speedup).
diffs = {
{DIFF_INSERT, strsub(longtext, 1, i - 1)},
{DIFF_EQUAL, shorttext},
{DIFF_INSERT, strsub(longtext, i + #shorttext)}
}
-- Swap insertions for deletions if diff is reversed.
if #text1 > #text2 then
diffs[1][1], diffs[3][1] = DIFF_DELETE, DIFF_DELETE
end
return diffs
end
if #shorttext == 1 then
-- Single character string.
-- After the previous speedup, the character can't be an equality.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
-- Check to see if the problem can be split in two.
do
local
text1_a, text1_b,
text2_a, text2_b,
mid_common = _diff_halfMatch(text1, text2)
if text1_a then
-- A half-match was found, sort out the return data.
-- Send both pairs off for separate processing.
local diffs_a = diff_main(text1_a, text2_a, checklines, deadline)
local diffs_b = diff_main(text1_b, text2_b, checklines, deadline)
-- Merge the results.
local diffs_a_len = #diffs_a
diffs = diffs_a
diffs[diffs_a_len + 1] = {DIFF_EQUAL, mid_common}
for i, b_diff in ipairs(diffs_b) do
diffs[diffs_a_len + 1 + i] = b_diff
end
return diffs
end
end
return _diff_bisect(text1, text2, deadline)
end
--[[
* Find the 'middle snake' of a diff, split the problem in two
* and return the recursively constructed diff.
* See Myers 1986 paper: An O(ND) Difference Algorithm and Its Variations.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisect(text1, text2, deadline)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
local _sub, _element
local max_d = ceil((text1_length + text2_length) / 2)
local v_offset = max_d
local v_length = 2 * max_d
local v1 = {}
local v2 = {}
-- Setting all elements to -1 is faster in Lua than mixing integers and nil.
for x = 0, v_length - 1 do
v1[x] = -1
v2[x] = -1
end
v1[v_offset + 1] = 0
v2[v_offset + 1] = 0
local delta = text1_length - text2_length
-- If the total number of characters is odd, then
-- the front path will collide with the reverse path.
local front = (delta % 2 ~= 0)
-- Offsets for start and end of k loop.
-- Prevents mapping of space beyond the grid.
local k1start = 0
local k1end = 0
local k2start = 0
local k2end = 0
for d = 0, max_d - 1 do
-- Bail out if deadline is reached.
if clock() > deadline then
break
end
-- Walk the front path one step.
for k1 = -d + k1start, d - k1end, 2 do
local k1_offset = v_offset + k1
local x1
if (k1 == -d) or ((k1 ~= d) and
(v1[k1_offset - 1] < v1[k1_offset + 1])) then
x1 = v1[k1_offset + 1]
else
x1 = v1[k1_offset - 1] + 1
end
local y1 = x1 - k1
while (x1 <= text1_length) and (y1 <= text2_length)
and (strelement(text1, x1) == strelement(text2, y1)) do
x1 = x1 + 1
y1 = y1 + 1
end
v1[k1_offset] = x1
if x1 > text1_length + 1 then
-- Ran off the right of the graph.
k1end = k1end + 2
elseif y1 > text2_length + 1 then
-- Ran off the bottom of the graph.
k1start = k1start + 2
elseif front then
local k2_offset = v_offset + delta - k1
if k2_offset >= 0 and k2_offset < v_length and v2[k2_offset] ~= -1 then
-- Mirror x2 onto top-left coordinate system.
local x2 = text1_length - v2[k2_offset] + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
-- Walk the reverse path one step.
for k2 = -d + k2start, d - k2end, 2 do
local k2_offset = v_offset + k2
local x2
if (k2 == -d) or ((k2 ~= d) and
(v2[k2_offset - 1] < v2[k2_offset + 1])) then
x2 = v2[k2_offset + 1]
else
x2 = v2[k2_offset - 1] + 1
end
local y2 = x2 - k2
while (x2 <= text1_length) and (y2 <= text2_length)
and (strelement(text1, -x2) == strelement(text2, -y2)) do
x2 = x2 + 1
y2 = y2 + 1
end
v2[k2_offset] = x2
if x2 > text1_length + 1 then
-- Ran off the left of the graph.
k2end = k2end + 2
elseif y2 > text2_length + 1 then
-- Ran off the top of the graph.
k2start = k2start + 2
elseif not front then
local k1_offset = v_offset + delta - k2
if k1_offset >= 0 and k1_offset < v_length and v1[k1_offset] ~= -1 then
local x1 = v1[k1_offset]
local y1 = v_offset + x1 - k1_offset
-- Mirror x2 onto top-left coordinate system.
x2 = text1_length - x2 + 1
if x1 > x2 then
-- Overlap detected.
return _diff_bisectSplit(text1, text2, x1, y1, deadline)
end
end
end
end
end
-- Diff took too long and hit the deadline or
-- number of diffs equals number of characters, no commonality at all.
return {{DIFF_DELETE, text1}, {DIFF_INSERT, text2}}
end
--[[
* Given the location of the 'middle snake', split the diff in two parts
* and recurse.
* @param {string} text1 Old string to be diffed.
* @param {string} text2 New string to be diffed.
* @param {number} x Index of split point in text1.
* @param {number} y Index of split point in text2.
* @param {number} deadline Time at which to bail if not yet complete.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @private
--]]
function _diff_bisectSplit(text1, text2, x, y, deadline)
local text1a = strsub(text1, 1, x - 1)
local text2a = strsub(text2, 1, y - 1)
local text1b = strsub(text1, x)
local text2b = strsub(text2, y)
-- Compute both diffs serially.
local diffs = diff_main(text1a, text2a, false, deadline)
local diffsb = diff_main(text1b, text2b, false, deadline)
local diffs_len = #diffs
for i, v in ipairs(diffsb) do
diffs[diffs_len + i] = v
end
return diffs
end
--[[
* Determine the common prefix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the start of each
* string.
--]]
function _diff_commonPrefix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0) or (strbyte(text1, 1) ~= strbyte(text2, 1))
then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerstart = 1
while (pointermin < pointermid) do
if (strsub(text1, pointerstart, pointermid)
== strsub(text2, pointerstart, pointermid)) then
pointermin = pointermid
pointerstart = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine the common suffix of two strings.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of each string.
--]]
function _diff_commonSuffix(text1, text2)
-- Quick check for common null cases.
if (#text1 == 0) or (#text2 == 0)
or (strbyte(text1, -1) ~= strbyte(text2, -1)) then
return 0
end
-- Binary search.
-- Performance analysis: http://neil.fraser.name/news/2007/10/09/
local pointermin = 1
local pointermax = min(#text1, #text2)
local pointermid = pointermax
local pointerend = 1
while (pointermin < pointermid) do
if (strsub(text1, -pointermid, -pointerend)
== strsub(text2, -pointermid, -pointerend)) then
pointermin = pointermid
pointerend = pointermin
else
pointermax = pointermid
end
pointermid = floor(pointermin + (pointermax - pointermin) / 2)
end
return pointermid
end
--[[
* Determine if the suffix of one string is the prefix of another.
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {number} The number of characters common to the end of the first
* string and the start of the second string.
* @private
--]]
function _diff_commonOverlap(text1, text2)
-- Cache the text lengths to prevent multiple calls.
local text1_length = #text1
local text2_length = #text2
-- Eliminate the null case.
if text1_length == 0 or text2_length == 0 then
return 0
end
-- Truncate the longer string.
if text1_length > text2_length then
text1 = strsub(text1, text1_length - text2_length + 1)
elseif text1_length < text2_length then
text2 = strsub(text2, 1, text1_length)
end
local text_length = min(text1_length, text2_length)
-- Quick check for the worst case.
if text1 == text2 then
return text_length
end
-- Start by looking for a single character match
-- and increase length until no match is found.
-- Performance analysis: http://neil.fraser.name/news/2010/11/04/
local best = 0
local length = 1
while true do
local pattern = strsub(text1, text_length - length + 1)
local found = strfind(text2, pattern, 1, true)
if found == nil then
return best
end
length = length + found - 1
if found == 1 or strsub(text1, text_length - length + 1) ==
strsub(text2, 1, length) then
best = length
length = length + 1
end
end
end
--[[
* Does a substring of shorttext exist within longtext such that the substring
* is at least half the length of longtext?
* This speedup can produce non-minimal diffs.
* Closure, but does not reference any external variables.
* @param {string} longtext Longer string.
* @param {string} shorttext Shorter string.
* @param {number} i Start index of quarter length substring within longtext.
* @return {?Array.<string>} Five element Array, containing the prefix of
* longtext, the suffix of longtext, the prefix of shorttext, the suffix
* of shorttext and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatchI(longtext, shorttext, i)
-- Start with a 1/4 length substring at position i as a seed.
local seed = strsub(longtext, i, i + floor(#longtext / 4))
local j = 0 -- LUANOTE: do not change to 1, was originally -1
local best_common = ''
local best_longtext_a, best_longtext_b, best_shorttext_a, best_shorttext_b
while true do
j = indexOf(shorttext, seed, j + 1)
if (j == nil) then
break
end
local prefixLength = _diff_commonPrefix(strsub(longtext, i),
strsub(shorttext, j))
local suffixLength = _diff_commonSuffix(strsub(longtext, 1, i - 1),
strsub(shorttext, 1, j - 1))
if #best_common < suffixLength + prefixLength then
best_common = strsub(shorttext, j - suffixLength, j - 1)
.. strsub(shorttext, j, j + prefixLength - 1)
best_longtext_a = strsub(longtext, 1, i - suffixLength - 1)
best_longtext_b = strsub(longtext, i + prefixLength)
best_shorttext_a = strsub(shorttext, 1, j - suffixLength - 1)
best_shorttext_b = strsub(shorttext, j + prefixLength)
end
end
if #best_common * 2 >= #longtext then
return {best_longtext_a, best_longtext_b,
best_shorttext_a, best_shorttext_b, best_common}
else
return nil
end
end
--[[
* Do the two texts share a substring which is at least half the length of the
* longer text?
* @param {string} text1 First string.
* @param {string} text2 Second string.
* @return {?Array.<string>} Five element Array, containing the prefix of
* text1, the suffix of text1, the prefix of text2, the suffix of
* text2 and the common middle. Or nil if there was no match.
* @private
--]]
function _diff_halfMatch(text1, text2)
if Diff_Timeout <= 0 then
-- Don't risk returning a non-optimal diff if we have unlimited time.
return nil
end
local longtext = (#text1 > #text2) and text1 or text2
local shorttext = (#text1 > #text2) and text2 or text1
if (#longtext < 4) or (#shorttext * 2 < #longtext) then
return nil -- Pointless.
end
-- First check if the second quarter is the seed for a half-match.
local hm1 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 4))
-- Check again based on the third quarter.
local hm2 = _diff_halfMatchI(longtext, shorttext, ceil(#longtext / 2))
local hm
if not hm1 and not hm2 then
return nil
elseif not hm2 then
hm = hm1
elseif not hm1 then
hm = hm2
else
-- Both matched. Select the longest.
hm = (#hm1[5] > #hm2[5]) and hm1 or hm2
end
-- A half-match was found, sort out the return data.
local text1_a, text1_b, text2_a, text2_b
if (#text1 > #text2) then
text1_a, text1_b = hm[1], hm[2]
text2_a, text2_b = hm[3], hm[4]
else
text2_a, text2_b = hm[1], hm[2]
text1_a, text1_b = hm[3], hm[4]
end
local mid_common = hm[5]
return text1_a, text1_b, text2_a, text2_b, mid_common
end
--[[
* Given two strings, compute a score representing whether the internal
* boundary falls on logical boundaries.
* Scores range from 6 (best) to 0 (worst).
* @param {string} one First string.
* @param {string} two Second string.
* @return {number} The score.
* @private
--]]
function _diff_cleanupSemanticScore(one, two)
if (#one == 0) or (#two == 0) then
-- Edges are the best.
return 6
end
-- Each port of this function behaves slightly differently due to
-- subtle differences in each language's definition of things like
-- 'whitespace'. Since this function's purpose is largely cosmetic,
-- the choice has been made to use each language's native features
-- rather than force total conformity.
local char1 = strsub(one, -1)
local char2 = strsub(two, 1, 1)
local nonAlphaNumeric1 = strmatch(char1, '%W')
local nonAlphaNumeric2 = strmatch(char2, '%W')
local whitespace1 = nonAlphaNumeric1 and strmatch(char1, '%s')
local whitespace2 = nonAlphaNumeric2 and strmatch(char2, '%s')
local lineBreak1 = whitespace1 and strmatch(char1, '%c')
local lineBreak2 = whitespace2 and strmatch(char2, '%c')
local blankLine1 = lineBreak1 and strmatch(one, '\n\r?\n$')
local blankLine2 = lineBreak2 and strmatch(two, '^\r?\n\r?\n')
if blankLine1 or blankLine2 then
-- Five points for blank lines.
return 5
elseif lineBreak1 or lineBreak2 then
-- Four points for line breaks.
return 4
elseif nonAlphaNumeric1 and not whitespace1 and whitespace2 then
-- Three points for end of sentences.
return 3
elseif whitespace1 or whitespace2 then
-- Two points for whitespace.
return 2
elseif nonAlphaNumeric1 or nonAlphaNumeric2 then
-- One point for non-alphanumeric.
return 1
end
return 0
end
--[[
* Look for single edits surrounded on both sides by equalities
* which can be shifted sideways to align the edit to a word boundary.
* e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupSemanticLossless(diffs)
local pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while diffs[pointer + 1] do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local equality1 = prevDiff[2]
local edit = diff[2]
local equality2 = nextDiff[2]
-- First, shift the edit as far left as possible.
local commonOffset = _diff_commonSuffix(equality1, edit)
if commonOffset > 0 then
local commonString = strsub(edit, -commonOffset)
equality1 = strsub(equality1, 1, -commonOffset - 1)
edit = commonString .. strsub(edit, 1, -commonOffset - 1)
equality2 = commonString .. equality2
end
-- Second, step character by character right, looking for the best fit.
local bestEquality1 = equality1
local bestEdit = edit
local bestEquality2 = equality2
local bestScore = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
while strbyte(edit, 1) == strbyte(equality2, 1) do
equality1 = equality1 .. strsub(edit, 1, 1)
edit = strsub(edit, 2) .. strsub(equality2, 1, 1)
equality2 = strsub(equality2, 2)
local score = _diff_cleanupSemanticScore(equality1, edit)
+ _diff_cleanupSemanticScore(edit, equality2)
-- The >= encourages trailing rather than leading whitespace on edits.
if score >= bestScore then
bestScore = score
bestEquality1 = equality1
bestEdit = edit
bestEquality2 = equality2
end
end
if prevDiff[2] ~= bestEquality1 then
-- We have an improvement, save it back to the diff.
if #bestEquality1 > 0 then
diffs[pointer - 1][2] = bestEquality1
else
tremove(diffs, pointer - 1)
pointer = pointer - 1
end
diffs[pointer][2] = bestEdit
if #bestEquality2 > 0 then
diffs[pointer + 1][2] = bestEquality2
else
tremove(diffs, pointer + 1, 1)
pointer = pointer - 1
end
end
end
pointer = pointer + 1
end
end
--[[
* Reorder and merge like edit sections. Merge equalities.
* Any edit section can move as long as it doesn't cross an equality.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
--]]
function _diff_cleanupMerge(diffs)
diffs[#diffs + 1] = {DIFF_EQUAL, ''} -- Add a dummy entry at the end.
local pointer = 1
local count_delete, count_insert = 0, 0
local text_delete, text_insert = '', ''
local commonlength
while diffs[pointer] do
local diff_type = diffs[pointer][1]
if diff_type == DIFF_INSERT then
count_insert = count_insert + 1
text_insert = text_insert .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_DELETE then
count_delete = count_delete + 1
text_delete = text_delete .. diffs[pointer][2]
pointer = pointer + 1
elseif diff_type == DIFF_EQUAL then
-- Upon reaching an equality, check for prior redundancies.
if count_delete + count_insert > 1 then
if (count_delete > 0) and (count_insert > 0) then
-- Factor out any common prefixies.
commonlength = _diff_commonPrefix(text_insert, text_delete)
if commonlength > 0 then
local back_pointer = pointer - count_delete - count_insert
if (back_pointer > 1) and (diffs[back_pointer - 1][1] == DIFF_EQUAL)
then
diffs[back_pointer - 1][2] = diffs[back_pointer - 1][2]
.. strsub(text_insert, 1, commonlength)
else
tinsert(diffs, 1,
{DIFF_EQUAL, strsub(text_insert, 1, commonlength)})
pointer = pointer + 1
end
text_insert = strsub(text_insert, commonlength + 1)
text_delete = strsub(text_delete, commonlength + 1)
end
-- Factor out any common suffixies.
commonlength = _diff_commonSuffix(text_insert, text_delete)
if commonlength ~= 0 then
diffs[pointer][2] =
strsub(text_insert, -commonlength) .. diffs[pointer][2]
text_insert = strsub(text_insert, 1, -commonlength - 1)
text_delete = strsub(text_delete, 1, -commonlength - 1)
end
end
-- Delete the offending records and add the merged ones.
if count_delete == 0 then
tsplice(diffs, pointer - count_insert,
count_insert, {DIFF_INSERT, text_insert})
elseif count_insert == 0 then
tsplice(diffs, pointer - count_delete,
count_delete, {DIFF_DELETE, text_delete})
else
tsplice(diffs, pointer - count_delete - count_insert,
count_delete + count_insert,
{DIFF_DELETE, text_delete}, {DIFF_INSERT, text_insert})
end
pointer = pointer - count_delete - count_insert
+ (count_delete>0 and 1 or 0) + (count_insert>0 and 1 or 0) + 1
elseif (pointer > 1) and (diffs[pointer - 1][1] == DIFF_EQUAL) then
-- Merge this equality with the previous one.
diffs[pointer - 1][2] = diffs[pointer - 1][2] .. diffs[pointer][2]
tremove(diffs, pointer)
else
pointer = pointer + 1
end
count_insert, count_delete = 0, 0
text_delete, text_insert = '', ''
end
end
if diffs[#diffs][2] == '' then
diffs[#diffs] = nil -- Remove the dummy entry at the end.
end
-- Second pass: look for single edits surrounded on both sides by equalities
-- which can be shifted sideways to eliminate an equality.
-- e.g: A<ins>BA</ins>C -> <ins>AB</ins>AC
local changes = false
pointer = 2
-- Intentionally ignore the first and last element (don't need checking).
while pointer < #diffs do
local prevDiff, nextDiff = diffs[pointer - 1], diffs[pointer + 1]
if (prevDiff[1] == DIFF_EQUAL) and (nextDiff[1] == DIFF_EQUAL) then
-- This is a single edit surrounded by equalities.
local diff = diffs[pointer]
local currentText = diff[2]
local prevText = prevDiff[2]
local nextText = nextDiff[2]
if strsub(currentText, -#prevText) == prevText then
-- Shift the edit over the previous equality.
diff[2] = prevText .. strsub(currentText, 1, -#prevText - 1)
nextDiff[2] = prevText .. nextDiff[2]
tremove(diffs, pointer - 1)
changes = true
elseif strsub(currentText, 1, #nextText) == nextText then
-- Shift the edit over the next equality.
prevDiff[2] = prevText .. nextText
diff[2] = strsub(currentText, #nextText + 1) .. nextText
tremove(diffs, pointer + 1)
changes = true
end
end
pointer = pointer + 1
end
-- If shifts were made, the diff needs reordering and another shift sweep.
if changes then
-- LUANOTE: no return value, but necessary to use 'return' to get
-- tail calls.
return _diff_cleanupMerge(diffs)
end
end
--[[
* loc is a location in text1, compute and return the equivalent location in
* text2.
* e.g. 'The cat' vs 'The big cat', 1->1, 5->8
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @param {number} loc Location within text1.
* @return {number} Location within text2.
--]]
function _diff_xIndex(diffs, loc)
local chars1 = 1
local chars2 = 1
local last_chars1 = 1
local last_chars2 = 1
local x
for _x, diff in ipairs(diffs) do
x = _x
if diff[1] ~= DIFF_INSERT then -- Equality or deletion.
chars1 = chars1 + #diff[2]
end
if diff[1] ~= DIFF_DELETE then -- Equality or insertion.
chars2 = chars2 + #diff[2]
end
if chars1 > loc then -- Overshot the location.
break
end
last_chars1 = chars1
last_chars2 = chars2
end
-- Was the location deleted?
if diffs[x + 1] and (diffs[x][1] == DIFF_DELETE) then
return last_chars2
end
-- Add the remaining character length.
return last_chars2 + (loc - last_chars1)
end
--[[
* Compute and return the source text (all equalities and deletions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Source text.
--]]
function _diff_text1(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_INSERT then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Compute and return the destination text (all equalities and insertions).
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Destination text.
--]]
function _diff_text2(diffs)
local text = {}
for x, diff in ipairs(diffs) do
if diff[1] ~= DIFF_DELETE then
text[#text + 1] = diff[2]
end
end
return tconcat(text)
end
--[[
* Crush the diff into an encoded string which describes the operations
* required to transform text1 into text2.
* E.g. =3\t-2\t+ing -> Keep 3 chars, delete 2 chars, insert 'ing'.
* Operations are tab-separated. Inserted text is escaped using %xx notation.
* @param {Array.<Array.<number|string>>} diffs Array of diff tuples.
* @return {string} Delta text.
--]]
function _diff_toDelta(diffs)
local text = {}
for x, diff in ipairs(diffs) do
local op, data = diff[1], diff[2]
if op == DIFF_INSERT then
text[x] = '+' .. gsub(data, percentEncode_pattern, percentEncode_replace)
elseif op == DIFF_DELETE then
text[x] = '-' .. #data
elseif op == DIFF_EQUAL then
text[x] = '=' .. #data
end
end
return tconcat(text, '\t')
end
--[[
* Given the original text1, and an encoded string which describes the
* operations required to transform text1 into text2, compute the full diff.
* @param {string} text1 Source string for the diff.
* @param {string} delta Delta text.
* @return {Array.<Array.<number|string>>} Array of diff tuples.
* @throws {Errorend If invalid input.
--]]
function _diff_fromDelta(text1, delta)
local diffs = {}
local diffsLength = 0 -- Keeping our own length var is faster
local pointer = 1 -- Cursor in text1
for token in gmatch(delta, '[^\t]+') do
-- Each token begins with a one character parameter which specifies the
-- operation of this token (delete, insert, equality).
local tokenchar, param = strsub(token, 1, 1), strsub(token, 2)
if (tokenchar == '+') then
local invalidDecode = false
local decoded = gsub(param, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in _diff_fromDelta: ' .. param)
end
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_INSERT, decoded}
elseif (tokenchar == '-') or (tokenchar == '=') then
local n = tonumber(param)
if (n == nil) or (n < 0) then
error('Invalid number in _diff_fromDelta: ' .. param)
end
local text = strsub(text1, pointer, pointer + n - 1)
pointer = pointer + n
if (tokenchar == '=') then
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_EQUAL, text}
else
diffsLength = diffsLength + 1
diffs[diffsLength] = {DIFF_DELETE, text}
end
else
error('Invalid diff operation in _diff_fromDelta: ' .. token)
end
end
if (pointer ~= #text1 + 1) then
error('Delta length (' .. (pointer - 1)
.. ') does not equal source text length (' .. #text1 .. ').')
end
return diffs
end
-- ---------------------------------------------------------------------------
-- MATCH API
-- ---------------------------------------------------------------------------
local _match_bitap, _match_alphabet
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc'.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
--]]
function match_main(text, pattern, loc)
-- Check for null inputs.
if text == nil or pattern == nil or loc == nil then
error('Null inputs. (match_main)')
end
if text == pattern then
-- Shortcut (potentially not guaranteed by the algorithm)
return 1
elseif #text == 0 then
-- Nothing to match.
return -1
end
loc = max(1, min(loc, #text))
if strsub(text, loc, loc + #pattern - 1) == pattern then
-- Perfect match at the perfect spot! (Includes case of null pattern)
return loc
else
-- Do a fuzzy compare.
return _match_bitap(text, pattern, loc)
end
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE MATCH FUNCTIONS
-- ---------------------------------------------------------------------------
--[[
* Initialise the alphabet for the Bitap algorithm.
* @param {string} pattern The text to encode.
* @return {Object} Hash of character locations.
* @private
--]]
function _match_alphabet(pattern)
local s = {}
local i = 0
for c in gmatch(pattern, '.') do
s[c] = bor(s[c] or 0, lshift(1, #pattern - i - 1))
i = i + 1
end
return s
end
--[[
* Locate the best instance of 'pattern' in 'text' near 'loc' using the
* Bitap algorithm.
* @param {string} text The text to search.
* @param {string} pattern The pattern to search for.
* @param {number} loc The location to search around.
* @return {number} Best match index or -1.
* @private
--]]
function _match_bitap(text, pattern, loc)
if #pattern > Match_MaxBits then
error('Pattern too long.')
end
-- Initialise the alphabet.
local s = _match_alphabet(pattern)
--[[
* Compute and return the score for a match with e errors and x location.
* Accesses loc and pattern through being a closure.
* @param {number} e Number of errors in match.
* @param {number} x Location of match.
* @return {number} Overall score for match (0.0 = good, 1.0 = bad).
* @private
--]]
local function _match_bitapScore(e, x)
local accuracy = e / #pattern
local proximity = abs(loc - x)
if (Match_Distance == 0) then
-- Dodge divide by zero error.
return (proximity == 0) and 1 or accuracy
end
return accuracy + (proximity / Match_Distance)
end
-- Highest score beyond which we give up.
local score_threshold = Match_Threshold
-- Is there a nearby exact match? (speedup)
local best_loc = indexOf(text, pattern, loc)
if best_loc then
score_threshold = min(_match_bitapScore(0, best_loc), score_threshold)
-- LUANOTE: Ideally we'd also check from the other direction, but Lua
-- doesn't have an efficent lastIndexOf function.
end
-- Initialise the bit arrays.
local matchmask = lshift(1, #pattern - 1)
best_loc = -1
local bin_min, bin_mid
local bin_max = #pattern + #text
local last_rd
for d = 0, #pattern - 1, 1 do
-- Scan for the best match; each iteration allows for one more error.
-- Run a binary search to determine how far from 'loc' we can stray at this
-- error level.
bin_min = 0
bin_mid = bin_max
while (bin_min < bin_mid) do
if (_match_bitapScore(d, loc + bin_mid) <= score_threshold) then
bin_min = bin_mid
else
bin_max = bin_mid
end
bin_mid = floor(bin_min + (bin_max - bin_min) / 2)
end
-- Use the result from this iteration as the maximum for the next.
bin_max = bin_mid
local start = max(1, loc - bin_mid + 1)
local finish = min(loc + bin_mid, #text) + #pattern
local rd = {}
for j = start, finish do
rd[j] = 0
end
rd[finish + 1] = lshift(1, d) - 1
for j = finish, start, -1 do
local charMatch = s[strsub(text, j - 1, j - 1)] or 0
if (d == 0) then -- First pass: exact match.
rd[j] = band(bor((rd[j + 1] * 2), 1), charMatch)
else
-- Subsequent passes: fuzzy match.
-- Functions instead of operators make this hella messy.
rd[j] = bor(
band(
bor(
lshift(rd[j + 1], 1),
1
),
charMatch
),
bor(
bor(
lshift(bor(last_rd[j + 1], last_rd[j]), 1),
1
),
last_rd[j + 1]
)
)
end
if (band(rd[j], matchmask) ~= 0) then
local score = _match_bitapScore(d, j - 1)
-- This match will almost certainly be better than any existing match.
-- But check anyway.
if (score <= score_threshold) then
-- Told you so.
score_threshold = score
best_loc = j - 1
if (best_loc > loc) then
-- When passing loc, don't exceed our current distance from loc.
start = max(1, loc * 2 - best_loc)
else
-- Already passed loc, downhill from here on in.
break
end
end
end
end
-- No hope for a (better) match at greater error levels.
if (_match_bitapScore(d + 1, loc) > score_threshold) then
break
end
last_rd = rd
end
return best_loc
end
-- -----------------------------------------------------------------------------
-- PATCH API
-- -----------------------------------------------------------------------------
local _patch_addContext,
_patch_deepCopy,
_patch_addPadding,
_patch_splitMax,
_patch_appendText,
_new_patch_obj
--[[
* Compute a list of patches to turn text1 into text2.
* Use diffs if provided, otherwise compute it ourselves.
* There are four ways to call this function, depending on what data is
* available to the caller:
* Method 1:
* a = text1, b = text2
* Method 2:
* a = diffs
* Method 3 (optimal):
* a = text1, b = diffs
* Method 4 (deprecated, use method 3):
* a = text1, b = text2, c = diffs
*
* @param {string|Array.<Array.<number|string>>} a text1 (methods 1,3,4) or
* Array of diff tuples for text1 to text2 (method 2).
* @param {string|Array.<Array.<number|string>>} opt_b text2 (methods 1,4) or
* Array of diff tuples for text1 to text2 (method 3) or undefined (method 2).
* @param {string|Array.<Array.<number|string>>} opt_c Array of diff tuples for
* text1 to text2 (method 4) or undefined (methods 1,2,3).
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function patch_make(a, opt_b, opt_c)
local text1, diffs
local type_a, type_b, type_c = type(a), type(opt_b), type(opt_c)
if (type_a == 'string') and (type_b == 'string') and (type_c == 'nil') then
-- Method 1: text1, text2
-- Compute diffs from text1 and text2.
text1 = a
diffs = diff_main(text1, opt_b, true)
if (#diffs > 2) then
diff_cleanupSemantic(diffs)
diff_cleanupEfficiency(diffs)
end
elseif (type_a == 'table') and (type_b == 'nil') and (type_c == 'nil') then
-- Method 2: diffs
-- Compute text1 from diffs.
diffs = a
text1 = _diff_text1(diffs)
elseif (type_a == 'string') and (type_b == 'table') and (type_c == 'nil') then
-- Method 3: text1, diffs
text1 = a
diffs = opt_b
elseif (type_a == 'string') and (type_b == 'string') and (type_c == 'table')
then
-- Method 4: text1, text2, diffs
-- text2 is not used.
text1 = a
diffs = opt_c
else
error('Unknown call format to patch_make.')
end
if (diffs[1] == nil) then
return {} -- Get rid of the null case.
end
local patches = {}
local patch = _new_patch_obj()
local patchDiffLength = 0 -- Keeping our own length var is faster.
local char_count1 = 0 -- Number of characters into the text1 string.
local char_count2 = 0 -- Number of characters into the text2 string.
-- Start with text1 (prepatch_text) and apply the diffs until we arrive at
-- text2 (postpatch_text). We recreate the patches one by one to determine
-- context info.
local prepatch_text, postpatch_text = text1, text1
for x, diff in ipairs(diffs) do
local diff_type, diff_text = diff[1], diff[2]
if (patchDiffLength == 0) and (diff_type ~= DIFF_EQUAL) then
-- A new patch starts here.
patch.start1 = char_count1 + 1
patch.start2 = char_count2 + 1
end
if (diff_type == DIFF_INSERT) then
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length2 = patch.length2 + #diff_text
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. diff_text .. strsub(postpatch_text, char_count2 + 1)
elseif (diff_type == DIFF_DELETE) then
patch.length1 = patch.length1 + #diff_text
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
postpatch_text = strsub(postpatch_text, 1, char_count2)
.. strsub(postpatch_text, char_count2 + #diff_text + 1)
elseif (diff_type == DIFF_EQUAL) then
if (#diff_text <= Patch_Margin * 2)
and (patchDiffLength ~= 0) and (#diffs ~= x) then
-- Small equality inside a patch.
patchDiffLength = patchDiffLength + 1
patch.diffs[patchDiffLength] = diff
patch.length1 = patch.length1 + #diff_text
patch.length2 = patch.length2 + #diff_text
elseif (#diff_text >= Patch_Margin * 2) then
-- Time for a new patch.
if (patchDiffLength ~= 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
patch = _new_patch_obj()
patchDiffLength = 0
-- Unlike Unidiff, our patch lists have a rolling context.
-- http://code.google.com/p/google-diff-match-patch/wiki/Unidiff
-- Update prepatch text & pos to reflect the application of the
-- just completed patch.
prepatch_text = postpatch_text
char_count1 = char_count2
end
end
end
-- Update the current character count.
if (diff_type ~= DIFF_INSERT) then
char_count1 = char_count1 + #diff_text
end
if (diff_type ~= DIFF_DELETE) then
char_count2 = char_count2 + #diff_text
end
end
-- Pick up the leftover patch if not empty.
if (patchDiffLength > 0) then
_patch_addContext(patch, prepatch_text)
patches[#patches + 1] = patch
end
return patches
end
--[[
* Merge a set of patches onto the text. Return a patched text, as well
* as a list of true/false values indicating which patches were applied.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @param {string} text Old text.
* @return {Array.<string|Array.<boolean>>} Two return values, the
* new text and an array of boolean values.
--]]
function patch_apply(patches, text)
if patches[1] == nil then
return text, {}
end
-- Deep copy the patches so that no changes are made to originals.
patches = _patch_deepCopy(patches)
local nullPadding = _patch_addPadding(patches)
text = nullPadding .. text .. nullPadding
_patch_splitMax(patches)
-- delta keeps track of the offset between the expected and actual location
-- of the previous patch. If there are patches expected at positions 10 and
-- 20, but the first patch was found at 12, delta is 2 and the second patch
-- has an effective expected position of 22.
local delta = 0
local results = {}
for x, patch in ipairs(patches) do
local expected_loc = patch.start2 + delta
local text1 = _diff_text1(patch.diffs)
local start_loc
local end_loc = -1
if #text1 > Match_MaxBits then
-- _patch_splitMax will only provide an oversized pattern in
-- the case of a monster delete.
start_loc = match_main(text,
strsub(text1, 1, Match_MaxBits), expected_loc)
if start_loc ~= -1 then
end_loc = match_main(text, strsub(text1, -Match_MaxBits),
expected_loc + #text1 - Match_MaxBits)
if end_loc == -1 or start_loc >= end_loc then
-- Can't find valid trailing context. Drop this patch.
start_loc = -1
end
end
else
start_loc = match_main(text, text1, expected_loc)
end
if start_loc == -1 then
-- No match found. :(
results[x] = false
-- Subtract the delta for this failed patch from subsequent patches.
delta = delta - patch.length2 - patch.length1
else
-- Found a match. :)
results[x] = true
delta = start_loc - expected_loc
local text2
if end_loc == -1 then
text2 = strsub(text, start_loc, start_loc + #text1 - 1)
else
text2 = strsub(text, start_loc, end_loc + Match_MaxBits - 1)
end
if text1 == text2 then
-- Perfect match, just shove the replacement text in.
text = strsub(text, 1, start_loc - 1) .. _diff_text2(patch.diffs)
.. strsub(text, start_loc + #text1)
else
-- Imperfect match. Run a diff to get a framework of equivalent
-- indices.
local diffs = diff_main(text1, text2, false)
if (#text1 > Match_MaxBits)
and (diff_levenshtein(diffs) / #text1 > Patch_DeleteThreshold) then
-- The end points match, but the content is unacceptably bad.
results[x] = false
else
_diff_cleanupSemanticLossless(diffs)
local index1 = 1
local index2
for y, mod in ipairs(patch.diffs) do
if mod[1] ~= DIFF_EQUAL then
index2 = _diff_xIndex(diffs, index1)
end
if mod[1] == DIFF_INSERT then
text = strsub(text, 1, start_loc + index2 - 2)
.. mod[2] .. strsub(text, start_loc + index2 - 1)
elseif mod[1] == DIFF_DELETE then
text = strsub(text, 1, start_loc + index2 - 2) .. strsub(text,
start_loc + _diff_xIndex(diffs, index1 + #mod[2] - 1))
end
if mod[1] ~= DIFF_DELETE then
index1 = index1 + #mod[2]
end
end
end
end
end
end
-- Strip the padding off.
text = strsub(text, #nullPadding + 1, -#nullPadding - 1)
return text, results
end
--[[
* Take a list of patches and return a textual representation.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} Text representation of patches.
--]]
function patch_toText(patches)
local text = {}
for x, patch in ipairs(patches) do
_patch_appendText(patch, text)
end
return tconcat(text)
end
--[[
* Parse a textual representation of patches and return a list of patch objects.
* @param {string} textline Text representation of patches.
* @return {Array.<_new_patch_obj>} Array of patch objects.
* @throws {Error} If invalid input.
--]]
function patch_fromText(textline)
local patches = {}
if (#textline == 0) then
return patches
end
local text = {}
for line in gmatch(textline, '([^\n]*)') do
text[#text + 1] = line
end
local textPointer = 1
while (textPointer <= #text) do
local start1, length1, start2, length2
= strmatch(text[textPointer], '^@@ %-(%d+),?(%d*) %+(%d+),?(%d*) @@$')
if (start1 == nil) then
error('Invalid patch string: "' .. text[textPointer] .. '"')
end
local patch = _new_patch_obj()
patches[#patches + 1] = patch
start1 = tonumber(start1)
length1 = tonumber(length1) or 1
if (length1 == 0) then
start1 = start1 + 1
end
patch.start1 = start1
patch.length1 = length1
start2 = tonumber(start2)
length2 = tonumber(length2) or 1
if (length2 == 0) then
start2 = start2 + 1
end
patch.start2 = start2
patch.length2 = length2
textPointer = textPointer + 1
while true do
local line = text[textPointer]
if (line == nil) then
break
end
local sign; sign, line = strsub(line, 1, 1), strsub(line, 2)
local invalidDecode = false
local decoded = gsub(line, '%%(.?.?)',
function(c)
local n = tonumber(c, 16)
if (#c ~= 2) or (n == nil) then
invalidDecode = true
return ''
end
return strchar(n)
end)
if invalidDecode then
-- Malformed URI sequence.
error('Illegal escape in patch_fromText: ' .. line)
end
line = decoded
if (sign == '-') then
-- Deletion.
patch.diffs[#patch.diffs + 1] = {DIFF_DELETE, line}
elseif (sign == '+') then
-- Insertion.
patch.diffs[#patch.diffs + 1] = {DIFF_INSERT, line}
elseif (sign == ' ') then
-- Minor equality.
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, line}
elseif (sign == '@') then
-- Start of next patch.
break
elseif (sign == '') then
-- Blank line? Whatever.
else
-- WTF?
error('Invalid patch mode "' .. sign .. '" in: ' .. line)
end
textPointer = textPointer + 1
end
end
return patches
end
-- ---------------------------------------------------------------------------
-- UNOFFICIAL/PRIVATE PATCH FUNCTIONS
-- ---------------------------------------------------------------------------
local patch_meta = {
__tostring = function(patch)
local buf = {}
_patch_appendText(patch, buf)
return tconcat(buf)
end
}
--[[
* Class representing one patch operation.
* @constructor
--]]
function _new_patch_obj()
return setmetatable({
--[[ @type {Array.<Array.<number|string>>} ]]
diffs = {};
--[[ @type {?number} ]]
start1 = 1; -- nil;
--[[ @type {?number} ]]
start2 = 1; -- nil;
--[[ @type {number} ]]
length1 = 0;
--[[ @type {number} ]]
length2 = 0;
}, patch_meta)
end
--[[
* Increase the context until it is unique,
* but don't let the pattern expand beyond Match_MaxBits.
* @param {_new_patch_obj} patch The patch to grow.
* @param {string} text Source text.
* @private
--]]
function _patch_addContext(patch, text)
if (#text == 0) then
return
end
local pattern = strsub(text, patch.start2, patch.start2 + patch.length1 - 1)
local padding = 0
-- LUANOTE: Lua's lack of a lastIndexOf function results in slightly
-- different logic here than in other language ports.
-- Look for the first two matches of pattern in text. If two are found,
-- increase the pattern length.
local firstMatch = indexOf(text, pattern)
local secondMatch = nil
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
end
while (#pattern == 0 or secondMatch ~= nil)
and (#pattern < Match_MaxBits - Patch_Margin - Patch_Margin) do
padding = padding + Patch_Margin
pattern = strsub(text, max(1, patch.start2 - padding),
patch.start2 + patch.length1 - 1 + padding)
firstMatch = indexOf(text, pattern)
if (firstMatch ~= nil) then
secondMatch = indexOf(text, pattern, firstMatch + 1)
else
secondMatch = nil
end
end
-- Add one chunk for good luck.
padding = padding + Patch_Margin
-- Add the prefix.
local prefix = strsub(text, max(1, patch.start2 - padding), patch.start2 - 1)
if (#prefix > 0) then
tinsert(patch.diffs, 1, {DIFF_EQUAL, prefix})
end
-- Add the suffix.
local suffix = strsub(text, patch.start2 + patch.length1,
patch.start2 + patch.length1 - 1 + padding)
if (#suffix > 0) then
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, suffix}
end
-- Roll back the start points.
patch.start1 = patch.start1 - #prefix
patch.start2 = patch.start2 - #prefix
-- Extend the lengths.
patch.length1 = patch.length1 + #prefix + #suffix
patch.length2 = patch.length2 + #prefix + #suffix
end
--[[
* Given an array of patches, return another array that is identical.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {Array.<_new_patch_obj>} Array of patch objects.
--]]
function _patch_deepCopy(patches)
local patchesCopy = {}
for x, patch in ipairs(patches) do
local patchCopy = _new_patch_obj()
local diffsCopy = {}
for i, diff in ipairs(patch.diffs) do
diffsCopy[i] = {diff[1], diff[2]}
end
patchCopy.diffs = diffsCopy
patchCopy.start1 = patch.start1
patchCopy.start2 = patch.start2
patchCopy.length1 = patch.length1
patchCopy.length2 = patch.length2
patchesCopy[x] = patchCopy
end
return patchesCopy
end
--[[
* Add some padding on text start and end so that edges can match something.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
* @return {string} The padding string added to each side.
--]]
function _patch_addPadding(patches)
local paddingLength = Patch_Margin
local nullPadding = ''
for x = 1, paddingLength do
nullPadding = nullPadding .. strchar(x)
end
-- Bump all the patches forward.
for x, patch in ipairs(patches) do
patch.start1 = patch.start1 + paddingLength
patch.start2 = patch.start2 + paddingLength
end
-- Add some padding on start of first diff.
local patch = patches[1]
local diffs = patch.diffs
local firstDiff = diffs[1]
if (firstDiff == nil) or (firstDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
tinsert(diffs, 1, {DIFF_EQUAL, nullPadding})
patch.start1 = patch.start1 - paddingLength -- Should be 0.
patch.start2 = patch.start2 - paddingLength -- Should be 0.
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #firstDiff[2]) then
-- Grow first equality.
local extraLength = paddingLength - #firstDiff[2]
firstDiff[2] = strsub(nullPadding, #firstDiff[2] + 1) .. firstDiff[2]
patch.start1 = patch.start1 - extraLength
patch.start2 = patch.start2 - extraLength
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
-- Add some padding on end of last diff.
patch = patches[#patches]
diffs = patch.diffs
local lastDiff = diffs[#diffs]
if (lastDiff == nil) or (lastDiff[1] ~= DIFF_EQUAL) then
-- Add nullPadding equality.
diffs[#diffs + 1] = {DIFF_EQUAL, nullPadding}
patch.length1 = patch.length1 + paddingLength
patch.length2 = patch.length2 + paddingLength
elseif (paddingLength > #lastDiff[2]) then
-- Grow last equality.
local extraLength = paddingLength - #lastDiff[2]
lastDiff[2] = lastDiff[2] .. strsub(nullPadding, 1, extraLength)
patch.length1 = patch.length1 + extraLength
patch.length2 = patch.length2 + extraLength
end
return nullPadding
end
--[[
* Look through the patches and break up any which are longer than the maximum
* limit of the match algorithm.
* Intended to be called only from within patch_apply.
* @param {Array.<_new_patch_obj>} patches Array of patch objects.
--]]
function _patch_splitMax(patches)
local patch_size = Match_MaxBits
local x = 1
while true do
local patch = patches[x]
if patch == nil then
return
end
if patch.length1 > patch_size then
local bigpatch = patch
-- Remove the big old patch.
tremove(patches, x)
x = x - 1
local start1 = bigpatch.start1
local start2 = bigpatch.start2
local precontext = ''
while bigpatch.diffs[1] do
-- Create one of several smaller patches.
local patch = _new_patch_obj()
local empty = true
patch.start1 = start1 - #precontext
patch.start2 = start2 - #precontext
if precontext ~= '' then
patch.length1, patch.length2 = #precontext, #precontext
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, precontext}
end
while bigpatch.diffs[1] and (patch.length1 < patch_size-Patch_Margin) do
local diff_type = bigpatch.diffs[1][1]
local diff_text = bigpatch.diffs[1][2]
if (diff_type == DIFF_INSERT) then
-- Insertions are harmless.
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
patch.diffs[#(patch.diffs) + 1] = bigpatch.diffs[1]
tremove(bigpatch.diffs, 1)
empty = false
elseif (diff_type == DIFF_DELETE) and (#patch.diffs == 1)
and (patch.diffs[1][1] == DIFF_EQUAL)
and (#diff_text > 2 * patch_size) then
-- This is a large deletion. Let it pass in one chunk.
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
empty = false
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
tremove(bigpatch.diffs, 1)
else
-- Deletion or equality.
-- Only take as much as we can stomach.
diff_text = strsub(diff_text, 1,
patch_size - patch.length1 - Patch_Margin)
patch.length1 = patch.length1 + #diff_text
start1 = start1 + #diff_text
if (diff_type == DIFF_EQUAL) then
patch.length2 = patch.length2 + #diff_text
start2 = start2 + #diff_text
else
empty = false
end
patch.diffs[#patch.diffs + 1] = {diff_type, diff_text}
if (diff_text == bigpatch.diffs[1][2]) then
tremove(bigpatch.diffs, 1)
else
bigpatch.diffs[1][2]
= strsub(bigpatch.diffs[1][2], #diff_text + 1)
end
end
end
-- Compute the head context for the next patch.
precontext = _diff_text2(patch.diffs)
precontext = strsub(precontext, -Patch_Margin)
-- Append the end context for this patch.
local postcontext = strsub(_diff_text1(bigpatch.diffs), 1, Patch_Margin)
if postcontext ~= '' then
patch.length1 = patch.length1 + #postcontext
patch.length2 = patch.length2 + #postcontext
if patch.diffs[1]
and (patch.diffs[#patch.diffs][1] == DIFF_EQUAL) then
patch.diffs[#patch.diffs][2] = patch.diffs[#patch.diffs][2]
.. postcontext
else
patch.diffs[#patch.diffs + 1] = {DIFF_EQUAL, postcontext}
end
end
if not empty then
x = x + 1
tinsert(patches, x, patch)
end
end
end
x = x + 1
end
end
--[[
* Emulate GNU diff's format.
* Header: @@ -382,8 +481,9 @@
* @return {string} The GNU diff string.
--]]
function _patch_appendText(patch, text)
local coords1, coords2
local length1, length2 = patch.length1, patch.length2
local start1, start2 = patch.start1, patch.start2
local diffs = patch.diffs
if length1 == 1 then
coords1 = start1
else
coords1 = ((length1 == 0) and (start1 - 1) or start1) .. ',' .. length1
end
if length2 == 1 then
coords2 = start2
else
coords2 = ((length2 == 0) and (start2 - 1) or start2) .. ',' .. length2
end
text[#text + 1] = '@@ -' .. coords1 .. ' +' .. coords2 .. ' @@\n'
local op
-- Escape the body of the patch with %xx notation.
for x, diff in ipairs(patch.diffs) do
local diff_type = diff[1]
if diff_type == DIFF_INSERT then
op = '+'
elseif diff_type == DIFF_DELETE then
op = '-'
elseif diff_type == DIFF_EQUAL then
op = ' '
end
text[#text + 1] = op
.. gsub(diffs[x][2], percentEncode_pattern, percentEncode_replace)
.. '\n'
end
return text
end
-- Expose the API
local _M = {}
_M.DIFF_DELETE = DIFF_DELETE
_M.DIFF_INSERT = DIFF_INSERT
_M.DIFF_EQUAL = DIFF_EQUAL
_M.diff_main = diff_main
_M.diff_cleanupSemantic = diff_cleanupSemantic
_M.diff_cleanupEfficiency = diff_cleanupEfficiency
_M.diff_levenshtein = diff_levenshtein
_M.diff_prettyHtml = diff_prettyHtml
_M.match_main = match_main
_M.patch_make = patch_make
_M.patch_toText = patch_toText
_M.patch_fromText = patch_fromText
_M.patch_apply = patch_apply
-- Expose some non-API functions as well, for testing purposes etc.
_M.diff_commonPrefix = _diff_commonPrefix
_M.diff_commonSuffix = _diff_commonSuffix
_M.diff_commonOverlap = _diff_commonOverlap
_M.diff_halfMatch = _diff_halfMatch
_M.diff_bisect = _diff_bisect
_M.diff_cleanupMerge = _diff_cleanupMerge
_M.diff_cleanupSemanticLossless = _diff_cleanupSemanticLossless
_M.diff_text1 = _diff_text1
_M.diff_text2 = _diff_text2
_M.diff_toDelta = _diff_toDelta
_M.diff_fromDelta = _diff_fromDelta
_M.diff_xIndex = _diff_xIndex
_M.match_alphabet = _match_alphabet
_M.match_bitap = _match_bitap
_M.new_patch_obj = _new_patch_obj
_M.patch_addContext = _patch_addContext
_M.patch_splitMax = _patch_splitMax
_M.patch_addPadding = _patch_addPadding
_M.settings = settings
return _M
| apache-2.0 |
dtrip/awesome | tests/examples/awful/tooltip/textclock2.lua | 6 | 1112 | --DOC_GEN_IMAGE
--DOC_NO_USAGE
require("_date") --DOC_HIDE
screen[1]._resize {width = 300, height = 75} --DOC_HIDE
local awful = {tooltip = require("awful.tooltip"), wibar = require("awful.wibar")} --DOC_HIDE
local wibox = { widget = { textclock = require("wibox.widget.textclock") }, --DOC_HIDE
layout = { align = require("wibox.layout.align") } } --DOC_HIDE
local mytextclock = wibox.widget.textclock()
--DOC_NEWLINE
local wb = awful.wibar { position = "top" } --DOC_HIDE
wb:setup { layout = wibox.layout.align.horizontal, --DOC_HIDE
nil, nil, mytextclock} --DOC_HIDE
require("gears.timer").run_delayed_calls_now() --DOC_HIDE the hierarchy is async
local myclock_t = awful.tooltip { }
--DOC_NEWLINE
myclock_t:add_to_object(mytextclock)
--DOC_NEWLINE
mytextclock:connect_signal("mouse::enter", function()
myclock_t.text = os.date("Today is %A %B %d %Y\nThe time is %T")
end)
require("gears.timer").run_delayed_calls_now() --DOC_HIDE
mouse.coords{x=250, y= 10} --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(myclock_t.wibox and myclock_t.wibox.visible) --DOC_HIDE
| gpl-2.0 |
shanyou/mlua | src/libmlua/libs/mobdebug.lua | 1 | 64831 | --
-- MobDebug 0.606
-- Copyright 2011-14 Paul Kulchenko
-- Based on RemDebug 1.0 Copyright Kepler Project 2005
--
-- use loaded modules or load explicitly on those systems that require that
local require = require
local io = io or require "io"
local table = table or require "table"
local string = string or require "string"
local coroutine = coroutine or require "coroutine"
local debug = require "debug"
-- protect require "os" as it may fail on embedded systems without os module
local os = os or (function(module)
local ok, res = pcall(require, module)
return ok and res or nil
end)("os")
local mobdebug = {
_NAME = "mobdebug",
_VERSION = 0.606,
_COPYRIGHT = "Paul Kulchenko",
_DESCRIPTION = "Mobile Remote Debugger for the Lua programming language",
port = os and os.getenv and tonumber((os.getenv("MOBDEBUG_PORT"))) or 8172,
checkcount = 200,
yieldtimeout = 0.02, -- yield timeout (s)
connecttimeout = 2, -- connect timeout (s)
}
local error = error
local getfenv = getfenv
local setfenv = setfenv
local loadstring = loadstring or load -- "load" replaced "loadstring" in Lua 5.2
local pairs = pairs
local setmetatable = setmetatable
local tonumber = tonumber
local unpack = table.unpack or unpack
local rawget = rawget
-- if strict.lua is used, then need to avoid referencing some global
-- variables, as they can be undefined;
-- use rawget to avoid complaints from strict.lua at run-time.
-- it's safe to do the initialization here as all these variables
-- should get defined values (if any) before the debugging starts.
-- there is also global 'wx' variable, which is checked as part of
-- the debug loop as 'wx' can be loaded at any time during debugging.
local genv = _G or _ENV
local jit = rawget(genv, "jit")
local MOAICoroutine = rawget(genv, "MOAICoroutine")
-- ngx_lua debugging requires a special handling as its coroutine.*
-- methods use a different mechanism that doesn't allow resume calls
-- from debug hook handlers.
-- Instead, the "original" coroutine.* methods are used.
-- `rawget` needs to be used to protect against `strict` checks, but
-- ngx_lua hides those in a metatable, so need to use that.
local metagindex = getmetatable(genv) and getmetatable(genv).__index
local ngx = type(metagindex) == "table" and metagindex.rawget and metagindex:rawget("ngx") or nil
local corocreate = ngx and coroutine._create or coroutine.create
local cororesume = ngx and coroutine._resume or coroutine.resume
local coroyield = ngx and coroutine._yield or coroutine.yield
local corostatus = ngx and coroutine._status or coroutine.status
if not setfenv then -- Lua 5.2
-- based on http://lua-users.org/lists/lua-l/2010-06/msg00314.html
-- this assumes f is a function
local function findenv(f)
local level = 1
repeat
local name, value = debug.getupvalue(f, level)
if name == '_ENV' then return level, value end
level = level + 1
until name == nil
return nil end
getfenv = function (f) return(select(2, findenv(f)) or _G) end
setfenv = function (f, t)
local level = findenv(f)
if level then debug.setupvalue(f, level, t) end
return f end
end
-- check for OS and convert file names to lower case on windows
-- (its file system is case insensitive, but case preserving), as setting a
-- breakpoint on x:\Foo.lua will not work if the file was loaded as X:\foo.lua.
-- OSX and Windows behave the same way (case insensitive, but case preserving).
-- OSX can be configured to be case-sensitive, so check for that. This doesn't
-- handle the case of different partitions having different case-sensitivity.
local win = os and os.getenv and (os.getenv('WINDIR') or (os.getenv('OS') or ''):match('[Ww]indows')) and true or false
local mac = not win and (os and os.getenv and os.getenv('DYLD_LIBRARY_PATH') or not io.open("/proc")) and true or false
local iscasepreserving = win or (mac and io.open('/library') ~= nil)
-- turn jit off based on Mike Pall's comment in this discussion:
-- http://www.freelists.org/post/luajit/Debug-hooks-and-JIT,2
-- "You need to turn it off at the start if you plan to receive
-- reliable hook calls at any later point in time."
if jit and jit.off then jit.off() end
local socket = require "socket"
local coro_debugger
local coro_debugee
local coroutines = {}; setmetatable(coroutines, {__mode = "k"}) -- "weak" keys
local events = { BREAK = 1, WATCH = 2, RESTART = 3, STACK = 4 }
local breakpoints = {}
local watches = {}
local lastsource
local lastfile
local watchescnt = 0
local abort -- default value is nil; this is used in start/loop distinction
local seen_hook = false
local checkcount = 0
local step_into = false
local step_over = false
local step_level = 0
local stack_level = 0
local server
local buf
local outputs = {}
local iobase = {print = print}
local basedir = ""
local deferror = "execution aborted at default debugee"
local debugee = function ()
local a = 1
for _ = 1, 10 do a = a + 1 end
error(deferror)
end
local function q(s) return s:gsub('([%(%)%.%%%+%-%*%?%[%^%$%]])','%%%1') end
local serpent = (function() ---- include Serpent module for serialization
local n, v = "serpent", 0.272 -- (C) 2012-13 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return syms[s] end)) end
local function safestr(s) return type(s) == "number" and (huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..maxn.."d"):format(d) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local f, res = (loadstring or load)('return '..data)
if not f then f, res = (loadstring or load)(data) end
if not f then return f, res end
if opts and opts.safe == false then return pcall(f) end
local count, thread = 0, coroutine.running()
local h, m, c = debug.gethook(thread)
debug.sethook(function (e, l) count = count + 1
if count >= 3 then error("cannot call functions") end
end, "c")
local res = {pcall(f)}
count = 0 -- set again, otherwise it's tripped on the next sethook
debug.sethook(thread, h, m, c)
return (table.unpack or unpack)(res)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
end)() ---- end of Serpent module
mobdebug.line = serpent.line
mobdebug.dump = serpent.dump
mobdebug.linemap = nil
mobdebug.loadstring = loadstring
local function removebasedir(path, basedir)
if iscasepreserving then
-- check if the lowercased path matches the basedir
-- if so, return substring of the original path (to not lowercase it)
return path:lower():find('^'..q(basedir:lower()))
and path:sub(#basedir+1) or path
else
return string.gsub(path, '^'..q(basedir), '')
end
end
local function stack(start)
local function vars(f)
local func = debug.getinfo(f, "f").func
local i = 1
local locals = {}
while true do
local name, value = debug.getlocal(f, i)
if not name then break end
if string.sub(name, 1, 1) ~= '(' then locals[name] = {value, tostring(value)} end
i = i + 1
end
i = 1
local ups = {}
while func and true do -- check for func as it may be nil for tail calls
local name, value = debug.getupvalue(func, i)
if not name then break end
ups[name] = {value, tostring(value)}
i = i + 1
end
return locals, ups
end
local stack = {}
local linemap = mobdebug.linemap
for i = (start or 0), 100 do
local source = debug.getinfo(i, "Snl")
if not source then break end
local src = source.source
if src:find("@") == 1 then
src = src:sub(2):gsub("\\", "/")
if src:find("%./") == 1 then src = src:sub(3) end
end
table.insert(stack, { -- remove basedir from source
{source.name, removebasedir(src, basedir),
linemap and linemap(source.linedefined, source.source) or source.linedefined,
linemap and linemap(source.currentline, source.source) or source.currentline,
source.what, source.namewhat, source.short_src},
vars(i+1)})
if source.what == 'main' then break end
end
return stack
end
local function set_breakpoint(file, line)
if file == '-' and lastfile then file = lastfile
elseif iscasepreserving then file = string.lower(file) end
if not breakpoints[line] then breakpoints[line] = {} end
breakpoints[line][file] = true
end
local function remove_breakpoint(file, line)
if file == '-' and lastfile then file = lastfile
elseif iscasepreserving then file = string.lower(file) end
if breakpoints[line] then breakpoints[line][file] = nil end
end
local function has_breakpoint(file, line)
return breakpoints[line]
and breakpoints[line][iscasepreserving and string.lower(file) or file]
end
local function restore_vars(vars)
if type(vars) ~= 'table' then return end
-- locals need to be processed in the reverse order, starting from
-- the inner block out, to make sure that the localized variables
-- are correctly updated with only the closest variable with
-- the same name being changed
-- first loop find how many local variables there is, while
-- the second loop processes them from i to 1
local i = 1
while true do
local name = debug.getlocal(3, i)
if not name then break end
i = i + 1
end
i = i - 1
local written_vars = {}
while i > 0 do
local name = debug.getlocal(3, i)
if not written_vars[name] then
if string.sub(name, 1, 1) ~= '(' then
debug.setlocal(3, i, rawget(vars, name))
end
written_vars[name] = true
end
i = i - 1
end
i = 1
local func = debug.getinfo(3, "f").func
while true do
local name = debug.getupvalue(func, i)
if not name then break end
if not written_vars[name] then
if string.sub(name, 1, 1) ~= '(' then
debug.setupvalue(func, i, rawget(vars, name))
end
written_vars[name] = true
end
i = i + 1
end
end
local function capture_vars(level)
local vars = {}
local func = debug.getinfo(level or 3, "f").func
local i = 1
while true do
local name, value = debug.getupvalue(func, i)
if not name then break end
if string.sub(name, 1, 1) ~= '(' then vars[name] = value end
i = i + 1
end
i = 1
while true do
local name, value = debug.getlocal(level or 3, i)
if not name then break end
if string.sub(name, 1, 1) ~= '(' then vars[name] = value end
i = i + 1
end
-- returned 'vars' table plays a dual role: (1) it captures local values
-- and upvalues to be restored later (in case they are modified in "eval"),
-- and (2) it provides an environment for evaluated chunks.
-- getfenv(func) is needed to provide proper environment for functions,
-- including access to globals, but this causes vars[name] to fail in
-- restore_vars on local variables or upvalues with `nil` values when
-- 'strict' is in effect. To avoid this `rawget` is used in restore_vars.
setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) })
return vars
end
local function stack_depth(start_depth)
for i = start_depth, 0, -1 do
if debug.getinfo(i, "l") then return i+1 end
end
return start_depth
end
local function is_safe(stack_level)
-- the stack grows up: 0 is getinfo, 1 is is_safe, 2 is debug_hook, 3 is user function
if stack_level == 3 then return true end
for i = 3, stack_level do
-- return if it is not safe to abort
local info = debug.getinfo(i, "S")
if not info then return true end
if info.what == "C" then return false end
end
return true
end
local function in_debugger()
local this = debug.getinfo(1, "S").source
-- only need to check few frames as mobdebug frames should be close
for i = 3, 7 do
local info = debug.getinfo(i, "S")
if not info then return false end
if info.source == this then return true end
end
return false
end
local function is_pending(peer)
-- if there is something already in the buffer, skip check
if not buf and checkcount >= mobdebug.checkcount then
peer:settimeout(0) -- non-blocking
buf = peer:receive(1)
peer:settimeout() -- back to blocking
checkcount = 0
end
return buf
end
local function readnext(peer, num)
peer:settimeout(0) -- non-blocking
local res, err, partial = peer:receive(num)
peer:settimeout() -- back to blocking
return res or partial or '', err
end
local function handle_breakpoint(peer)
-- check if the buffer has the beginning of SETB/DELB command;
-- this is to avoid reading the entire line for commands that
-- don't need to be handled here.
if not buf or not (buf:sub(1,1) == 'S' or buf:sub(1,1) == 'D') then return end
-- check second character to avoid reading STEP or other S* and D* commands
if #buf == 1 then buf = buf .. readnext(peer, 1) end
if buf:sub(2,2) ~= 'E' then return end
-- need to read few more characters
buf = buf .. readnext(peer, 5-#buf)
if buf ~= 'SETB ' and buf ~= 'DELB ' then return end
local res, _, partial = peer:receive() -- get the rest of the line; blocking
if not res then
if partial then buf = buf .. partial end
return
end
local _, _, cmd, file, line = (buf..res):find("^([A-Z]+)%s+(.-)%s+(%d+)%s*$")
if cmd == 'SETB' then set_breakpoint(file, tonumber(line))
elseif cmd == 'DELB' then remove_breakpoint(file, tonumber(line))
else
-- this looks like a breakpoint command, but something went wrong;
-- return here to let the "normal" processing to handle,
-- although this is likely to not go well.
return
end
buf = nil
end
local function debug_hook(event, line)
-- (1) LuaJIT needs special treatment. Because debug_hook is set for
-- *all* coroutines, and not just the one being debugged as in regular Lua
-- (http://lua-users.org/lists/lua-l/2011-06/msg00513.html),
-- need to avoid debugging mobdebug's own code as LuaJIT doesn't
-- always correctly generate call/return hook events (there are more
-- calls than returns, which breaks stack depth calculation and
-- 'step' and 'step over' commands stop working; possibly because
-- 'tail return' events are not generated by LuaJIT).
-- the next line checks if the debugger is run under LuaJIT and if
-- one of debugger methods is present in the stack, it simply returns.
if jit then
-- when luajit is compiled with LUAJIT_ENABLE_LUA52COMPAT,
-- coroutine.running() returns non-nil for the main thread.
local coro, main = coroutine.running()
if not coro or main then coro = 'main' end
local disabled = coroutines[coro] == false
or coroutines[coro] == nil and coro ~= (coro_debugee or 'main')
if coro_debugee and disabled or not coro_debugee and (disabled or in_debugger())
then return end
end
-- (2) check if abort has been requested and it's safe to abort
if abort and is_safe(stack_level) then error(abort) end
-- (3) also check if this debug hook has not been visited for any reason.
-- this check is needed to avoid stepping in too early
-- (for example, when coroutine.resume() is executed inside start()).
if not seen_hook and in_debugger() then return end
if event == "call" then
stack_level = stack_level + 1
elseif event == "return" or event == "tail return" then
stack_level = stack_level - 1
elseif event == "line" then
if mobdebug.linemap then
local ok, mappedline = pcall(mobdebug.linemap, line, debug.getinfo(2, "S").source)
if ok then line = mappedline end
if not line then return end
end
-- may need to fall through because of the following:
-- (1) step_into
-- (2) step_over and stack_level <= step_level (need stack_level)
-- (3) breakpoint; check for line first as it's known; then for file
-- (4) socket call (only do every Xth check)
-- (5) at least one watch is registered
if not (
step_into or step_over or breakpoints[line] or watchescnt > 0
or is_pending(server)
) then checkcount = checkcount + 1; return end
checkcount = mobdebug.checkcount -- force check on the next command
-- this is needed to check if the stack got shorter or longer.
-- unfortunately counting call/return calls is not reliable.
-- the discrepancy may happen when "pcall(load, '')" call is made
-- or when "error()" is called in a function.
-- in either case there are more "call" than "return" events reported.
-- this validation is done for every "line" event, but should be "cheap"
-- as it checks for the stack to get shorter (or longer by one call).
-- start from one level higher just in case we need to grow the stack.
-- this may happen after coroutine.resume call to a function that doesn't
-- have any other instructions to execute. it triggers three returns:
-- "return, tail return, return", which needs to be accounted for.
stack_level = stack_depth(stack_level+1)
local caller = debug.getinfo(2, "S")
-- grab the filename and fix it if needed
local file = lastfile
if (lastsource ~= caller.source) then
file, lastsource = caller.source, caller.source
-- technically, users can supply names that may not use '@',
-- for example when they call loadstring('...', 'filename.lua').
-- Unfortunately, there is no reliable/quick way to figure out
-- what is the filename and what is the source code.
-- The following will work if the supplied filename uses Unix path.
if file:find("^@") then
file = file:gsub("^@", ""):gsub("\\", "/")
-- need this conversion to be applied to relative and absolute
-- file names as you may write "require 'Foo'" to
-- load "foo.lua" (on a case insensitive file system) and breakpoints
-- set on foo.lua will not work if not converted to the same case.
if iscasepreserving then file = string.lower(file) end
if file:find("%./") == 1 then file = file:sub(3)
else file = file:gsub("^"..q(basedir), "") end
-- some file systems allow newlines in file names; remove these.
file = file:gsub("\n", ' ')
else
-- this is either a file name coming from loadstring("chunk", "file"),
-- or the actual source code that needs to be serialized (as it may
-- include newlines); assume it's a file name if it's all on one line.
if file:find("[\r\n]") then
file = mobdebug.line(file)
else
if iscasepreserving then file = string.lower(file) end
file = file:gsub("\\", "/"):gsub(file:find("^%./") and "^%./" or "^"..q(basedir), "")
end
end
-- set to true if we got here; this only needs to be done once per
-- session, so do it here to at least avoid setting it for every line.
seen_hook = true
lastfile = file
end
if is_pending(server) then handle_breakpoint(server) end
local vars, status, res
if (watchescnt > 0) then
vars = capture_vars()
for index, value in pairs(watches) do
setfenv(value, vars)
local ok, fired = pcall(value)
if ok and fired then
status, res = cororesume(coro_debugger, events.WATCH, vars, file, line, index)
break -- any one watch is enough; don't check multiple times
end
end
end
-- need to get into the "regular" debug handler, but only if there was
-- no watch that was fired. If there was a watch, handle its result.
local getin = (status == nil) and
(step_into
-- when coroutine.running() return `nil` (main thread in Lua 5.1),
-- step_over will equal 'main', so need to check for that explicitly.
or (step_over and step_over == (coroutine.running() or 'main') and stack_level <= step_level)
or has_breakpoint(file, line)
or is_pending(server))
if getin then
vars = vars or capture_vars()
step_into = false
step_over = false
status, res = cororesume(coro_debugger, events.BREAK, vars, file, line)
end
-- handle 'stack' command that provides stack() information to the debugger
if status and res == 'stack' then
while status and res == 'stack' do
-- resume with the stack trace and variables
if vars then restore_vars(vars) end -- restore vars so they are reflected in stack values
-- this may fail if __tostring method fails at run-time
local ok, snapshot = pcall(stack, ngx and 5 or 4)
status, res = cororesume(coro_debugger, ok and events.STACK or events.BREAK, snapshot, file, line)
end
end
-- need to recheck once more as resume after 'stack' command may
-- return something else (for example, 'exit'), which needs to be handled
if status and res and res ~= 'stack' then
if not abort and res == "exit" then os.exit(1, true); return end
abort = res
-- only abort if safe; if not, there is another (earlier) check inside
-- debug_hook, which will abort execution at the first safe opportunity
if is_safe(stack_level) then error(abort) end
elseif not status and res then
error(res, 2) -- report any other (internal) errors back to the application
end
if vars then restore_vars(vars) end
-- last command requested Step Over/Out; store the current thread
if step_over == true then step_over = coroutine.running() or 'main' end
end
end
local function stringify_results(status, ...)
if not status then return status, ... end -- on error report as it
local t = {...}
for i,v in pairs(t) do -- stringify each of the returned values
local ok, res = pcall(mobdebug.line, v, {nocode = true, comment = 1})
t[i] = ok and res or ("%q"):format(res):gsub("\010","n"):gsub("\026","\\026")
end
-- stringify table with all returned values
-- this is done to allow each returned value to be used (serialized or not)
-- intependently and to preserve "original" comments
return pcall(mobdebug.dump, t, {sparse = false})
end
local function isrunning()
return coro_debugger and (corostatus(coro_debugger) == 'suspended' or corostatus(coro_debugger) == 'running')
end
-- this is a function that removes all hooks and closes the socket to
-- report back to the controller that the debugging is done.
-- the script that called `done` can still continue.
local function done()
if not (isrunning() and server) then return end
if not jit then
for co, debugged in pairs(coroutines) do
if debugged then debug.sethook(co) end
end
end
debug.sethook()
server:close()
coro_debugger = nil -- to make sure isrunning() returns `false`
seen_hook = nil -- to make sure that the next start() call works
abort = nil -- to make sure that callback calls use proper "abort" value
end
local function debugger_loop(sev, svars, sfile, sline)
local command
local app, osname
local eval_env = svars or {}
local function emptyWatch () return false end
local loaded = {}
for k in pairs(package.loaded) do loaded[k] = true end
while true do
local line, err
local wx = rawget(genv, "wx") -- use rawread to make strict.lua happy
if (wx or mobdebug.yield) and server.settimeout then server:settimeout(mobdebug.yieldtimeout) end
while true do
line, err = server:receive()
if not line and err == "timeout" then
-- yield for wx GUI applications if possible to avoid "busyness"
app = app or (wx and wx.wxGetApp and wx.wxGetApp())
if app then
local win = app:GetTopWindow()
local inloop = app:IsMainLoopRunning()
osname = osname or wx.wxPlatformInfo.Get():GetOperatingSystemFamilyName()
if win and not inloop then
-- process messages in a regular way
-- and exit as soon as the event loop is idle
if osname == 'Unix' then wx.wxTimer(app):Start(10, true) end
local exitLoop = function()
win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_IDLE)
win:Disconnect(wx.wxID_ANY, wx.wxID_ANY, wx.wxEVT_TIMER)
app:ExitMainLoop()
end
win:Connect(wx.wxEVT_IDLE, exitLoop)
win:Connect(wx.wxEVT_TIMER, exitLoop)
app:MainLoop()
end
elseif mobdebug.yield then mobdebug.yield()
end
elseif not line and err == "closed" then
error("Debugger connection closed", 0)
else
-- if there is something in the pending buffer, prepend it to the line
if buf then line = buf .. line; buf = nil end
break
end
end
if server.settimeout then server:settimeout() end -- back to blocking
command = string.sub(line, string.find(line, "^[A-Z]+"))
if command == "SETB" then
local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$")
if file and line then
set_breakpoint(file, tonumber(line))
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "DELB" then
local _, _, _, file, line = string.find(line, "^([A-Z]+)%s+(.-)%s+(%d+)%s*$")
if file and line then
remove_breakpoint(file, tonumber(line))
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "EXEC" then
local _, _, chunk = string.find(line, "^[A-Z]+%s+(.+)$")
if chunk then
local func, res = mobdebug.loadstring(chunk)
local status
if func then
setfenv(func, eval_env)
status, res = stringify_results(pcall(func))
end
if status then
server:send("200 OK " .. #res .. "\n")
server:send(res)
else
server:send("401 Error in Expression " .. #res .. "\n")
server:send(res)
end
else
server:send("400 Bad Request\n")
end
elseif command == "LOAD" then
local _, _, size, name = string.find(line, "^[A-Z]+%s+(%d+)%s+(%S.-)%s*$")
size = tonumber(size)
if abort == nil then -- no LOAD/RELOAD allowed inside start()
if size > 0 then server:receive(size) end
if sfile and sline then
server:send("201 Started " .. sfile .. " " .. sline .. "\n")
else
server:send("200 OK 0\n")
end
else
-- reset environment to allow required modules to load again
-- remove those packages that weren't loaded when debugger started
for k in pairs(package.loaded) do
if not loaded[k] then package.loaded[k] = nil end
end
if size == 0 and name == '-' then -- RELOAD the current script being debugged
server:send("200 OK 0\n")
coroyield("load")
else
-- receiving 0 bytes blocks (at least in luasocket 2.0.2), so skip reading
local chunk = size == 0 and "" or server:receive(size)
if chunk then -- LOAD a new script for debugging
local func, res = mobdebug.loadstring(chunk, "@"..name)
if func then
server:send("200 OK 0\n")
debugee = func
coroyield("load")
else
server:send("401 Error in Expression " .. #res .. "\n")
server:send(res)
end
else
server:send("400 Bad Request\n")
end
end
end
elseif command == "SETW" then
local _, _, exp = string.find(line, "^[A-Z]+%s+(.+)%s*$")
if exp then
local func, res = mobdebug.loadstring("return(" .. exp .. ")")
if func then
watchescnt = watchescnt + 1
local newidx = #watches + 1
watches[newidx] = func
server:send("200 OK " .. newidx .. "\n")
else
server:send("401 Error in Expression " .. #res .. "\n")
server:send(res)
end
else
server:send("400 Bad Request\n")
end
elseif command == "DELW" then
local _, _, index = string.find(line, "^[A-Z]+%s+(%d+)%s*$")
index = tonumber(index)
if index > 0 and index <= #watches then
watchescnt = watchescnt - (watches[index] ~= emptyWatch and 1 or 0)
watches[index] = emptyWatch
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "RUN" then
server:send("200 OK\n")
local ev, vars, file, line, idx_watch = coroyield()
eval_env = vars
if ev == events.BREAK then
server:send("202 Paused " .. file .. " " .. line .. "\n")
elseif ev == events.WATCH then
server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
elseif ev == events.RESTART then
-- nothing to do
else
server:send("401 Error in Execution " .. #file .. "\n")
server:send(file)
end
elseif command == "STEP" then
server:send("200 OK\n")
step_into = true
local ev, vars, file, line, idx_watch = coroyield()
eval_env = vars
if ev == events.BREAK then
server:send("202 Paused " .. file .. " " .. line .. "\n")
elseif ev == events.WATCH then
server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
elseif ev == events.RESTART then
-- nothing to do
else
server:send("401 Error in Execution " .. #file .. "\n")
server:send(file)
end
elseif command == "OVER" or command == "OUT" then
server:send("200 OK\n")
step_over = true
-- OVER and OUT are very similar except for
-- the stack level value at which to stop
if command == "OUT" then step_level = stack_level - 1
else step_level = stack_level end
local ev, vars, file, line, idx_watch = coroyield()
eval_env = vars
if ev == events.BREAK then
server:send("202 Paused " .. file .. " " .. line .. "\n")
elseif ev == events.WATCH then
server:send("203 Paused " .. file .. " " .. line .. " " .. idx_watch .. "\n")
elseif ev == events.RESTART then
-- nothing to do
else
server:send("401 Error in Execution " .. #file .. "\n")
server:send(file)
end
elseif command == "BASEDIR" then
local _, _, dir = string.find(line, "^[A-Z]+%s+(.+)%s*$")
if dir then
basedir = iscasepreserving and string.lower(dir) or dir
-- reset cached source as it may change with basedir
lastsource = nil
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "SUSPEND" then
-- do nothing; it already fulfilled its role
elseif command == "DONE" then
server:send("200 OK\n")
done()
return -- done with all the debugging
elseif command == "STACK" then
-- first check if we can execute the stack command
-- as it requires yielding back to debug_hook it cannot be executed
-- if we have not seen the hook yet as happens after start().
-- in this case we simply return an empty result
local vars, ev = {}
if seen_hook then
ev, vars = coroyield("stack")
end
if ev and ev ~= events.STACK then
server:send("401 Error in Execution " .. #vars .. "\n")
server:send(vars)
else
local ok, res = pcall(mobdebug.dump, vars, {nocode = true, sparse = false})
if ok then
server:send("200 OK " .. res .. "\n")
else
server:send("401 Error in Execution " .. #res .. "\n")
server:send(res)
end
end
elseif command == "OUTPUT" then
local _, _, stream, mode = string.find(line, "^[A-Z]+%s+(%w+)%s+([dcr])%s*$")
if stream and mode and stream == "stdout" then
-- assign "print" in the global environment
local default = mode == 'd'
genv.print = default and iobase.print or coroutine.wrap(function()
-- wrapping into coroutine.wrap protects this function from
-- being stepped through in the debugger.
-- don't use vararg (...) as it adds a reference for its values,
-- which may affect how they are garbage collected
while true do
local tbl = {coroutine.yield()}
if mode == 'c' then iobase.print(unpack(tbl)) end
for n = 1, #tbl do
tbl[n] = select(2, pcall(mobdebug.line, tbl[n], {nocode = true, comment = false})) end
local file = table.concat(tbl, "\t").."\n"
server:send("204 Output " .. stream .. " " .. #file .. "\n" .. file)
end
end)
if not default then genv.print() end -- "fake" print to start printing loop
server:send("200 OK\n")
else
server:send("400 Bad Request\n")
end
elseif command == "EXIT" then
server:send("200 OK\n")
coroyield("exit")
else
server:send("400 Bad Request\n")
end
end
end
local function connect(controller_host, controller_port)
local sock, err = socket.tcp()
if not sock then return nil, err end
if sock.settimeout then sock:settimeout(mobdebug.connecttimeout) end
local res, err = sock:connect(controller_host, controller_port)
if sock.settimeout then sock:settimeout() end
if not res then return nil, err end
return sock
end
local lasthost, lastport
-- Starts a debug session by connecting to a controller
local function start(controller_host, controller_port)
-- only one debugging session can be run (as there is only one debug hook)
if isrunning() then return end
lasthost = controller_host or lasthost
lastport = controller_port or lastport
controller_host = lasthost or "localhost"
controller_port = lastport or mobdebug.port
local err
server, err = mobdebug.connect(controller_host, controller_port)
if server then
-- correct stack depth which already has some calls on it
-- so it doesn't go into negative when those calls return
-- as this breaks subsequence checks in stack_depth().
-- start from 16th frame, which is sufficiently large for this check.
stack_level = stack_depth(16)
-- provide our own traceback function to report the error remotely
do
local dtraceback = debug.traceback
debug.traceback = function (...)
if select('#', ...) >= 1 then
local err, lvl = ...
if err and type(err) ~= 'thread' then
local trace = dtraceback(err, (lvl or 2)+1)
if genv.print == iobase.print then -- no remote redirect
return trace
else
genv.print(trace) -- report the error remotely
return -- don't report locally to avoid double reporting
end
end
end
-- direct call to debug.traceback: return the original.
-- debug.traceback(nil, level) doesn't work in Lua 5.1
-- (http://lua-users.org/lists/lua-l/2011-06/msg00574.html), so
-- simply remove first frame from the stack trace
return (dtraceback(...):gsub("(stack traceback:\n)[^\n]*\n", "%1"))
end
end
coro_debugger = corocreate(debugger_loop)
debug.sethook(debug_hook, "lcr")
seen_hook = nil -- reset in case the last start() call was refused
step_into = true -- start with step command
return true
else
print(("Could not connect to %s:%s: %s")
:format(controller_host, controller_port, err or "unknown error"))
end
end
local function controller(controller_host, controller_port, scratchpad)
-- only one debugging session can be run (as there is only one debug hook)
if isrunning() then return end
lasthost = controller_host or lasthost
lastport = controller_port or lastport
controller_host = lasthost or "localhost"
controller_port = lastport or mobdebug.port
local exitonerror = not scratchpad
local err
server, err = mobdebug.connect(controller_host, controller_port)
if server then
local function report(trace, err)
local msg = err .. "\n" .. trace
server:send("401 Error in Execution " .. #msg .. "\n")
server:send(msg)
return err
end
seen_hook = true -- allow to accept all commands
coro_debugger = corocreate(debugger_loop)
while true do
step_into = true -- start with step command
abort = false -- reset abort flag from the previous loop
if scratchpad then checkcount = mobdebug.checkcount end -- force suspend right away
coro_debugee = corocreate(debugee)
debug.sethook(coro_debugee, debug_hook, "lcr")
local status, err = cororesume(coro_debugee)
-- was there an error or is the script done?
-- 'abort' state is allowed here; ignore it
if abort then
if tostring(abort) == 'exit' then break end
else
if status then -- normal execution is done
break
elseif err and not tostring(err):find(deferror) then
-- report the error back
-- err is not necessarily a string, so convert to string to report
report(debug.traceback(coro_debugee), tostring(err))
if exitonerror then break end
-- check if the debugging is done (coro_debugger is nil)
if not coro_debugger then break end
-- resume once more to clear the response the debugger wants to send
-- need to use capture_vars(2) as three would be the level of
-- the caller for controller(), but because of the tail call,
-- the caller may not exist;
-- This is not entirely safe as the user may see the local
-- variable from console, but they will be reset anyway.
-- This functionality is used when scratchpad is paused to
-- gain access to remote console to modify global variables.
local status, err = cororesume(coro_debugger, events.RESTART, capture_vars(2))
if not status or status and err == "exit" then break end
end
end
end
else
print(("Could not connect to %s:%s: %s")
:format(controller_host, controller_port, err or "unknown error"))
return false
end
return true
end
local function scratchpad(controller_host, controller_port)
return controller(controller_host, controller_port, true)
end
local function loop(controller_host, controller_port)
return controller(controller_host, controller_port, false)
end
local function on()
if not (isrunning() and server) then return end
-- main is set to true under Lua5.2 for the "main" chunk.
-- Lua5.1 returns co as `nil` in that case.
local co, main = coroutine.running()
if main then co = nil end
if co then
coroutines[co] = true
debug.sethook(co, debug_hook, "lcr")
else
if jit then coroutines.main = true end
debug.sethook(debug_hook, "lcr")
end
end
local function off()
if not (isrunning() and server) then return end
-- main is set to true under Lua5.2 for the "main" chunk.
-- Lua5.1 returns co as `nil` in that case.
local co, main = coroutine.running()
if main then co = nil end
-- don't remove coroutine hook under LuaJIT as there is only one (global) hook
if co then
coroutines[co] = false
if not jit then debug.sethook(co) end
else
if jit then coroutines.main = false end
if not jit then debug.sethook() end
end
-- check if there is any thread that is still being debugged under LuaJIT;
-- if not, turn the debugging off
if jit then
local remove = true
for _, debugged in pairs(coroutines) do
if debugged then remove = false; break end
end
if remove then debug.sethook() end
end
end
-- Handles server debugging commands
local function handle(params, client, options)
local _, _, command = string.find(params, "^([a-z]+)")
local file, line, watch_idx
if command == "run" or command == "step" or command == "out"
or command == "over" or command == "exit" then
client:send(string.upper(command) .. "\n")
client:receive() -- this should consume the first '200 OK' response
while true do
local done = true
local breakpoint = client:receive()
if not breakpoint then
print("Program finished")
os.exit(0, true)
return -- use return here for those cases where os.exit() is not wanted
end
local _, _, status = string.find(breakpoint, "^(%d+)")
if status == "200" then
-- don't need to do anything
elseif status == "202" then
_, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$")
if file and line then
print("Paused at file " .. file .. " line " .. line)
end
elseif status == "203" then
_, _, file, line, watch_idx = string.find(breakpoint, "^203 Paused%s+(.-)%s+(%d+)%s+(%d+)%s*$")
if file and line and watch_idx then
print("Paused at file " .. file .. " line " .. line .. " (watch expression " .. watch_idx .. ": [" .. watches[watch_idx] .. "])")
end
elseif status == "204" then
local _, _, stream, size = string.find(breakpoint, "^204 Output (%w+) (%d+)$")
if stream and size then
local msg = client:receive(tonumber(size))
print(msg)
if outputs[stream] then outputs[stream](msg) end
-- this was just the output, so go back reading the response
done = false
end
elseif status == "401" then
local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)$")
if size then
local msg = client:receive(tonumber(size))
print("Error in remote application: " .. msg)
os.exit(1, true)
return nil, nil, msg -- use return here for those cases where os.exit() is not wanted
end
else
print("Unknown error")
os.exit(1, true)
-- use return here for those cases where os.exit() is not wanted
return nil, nil, "Debugger error: unexpected response '" .. breakpoint .. "'"
end
if done then break end
end
elseif command == "done" then
client:send(string.upper(command) .. "\n")
if client:receive() ~= "200 OK" then
print("Unknown error")
os.exit(1, true)
return nil, nil, "Debugger error: unexpected response after DONE"
end
elseif command == "setb" or command == "asetb" then
_, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$")
if file and line then
-- if this is a file name, and not a file source
if not file:find('^".*"$') then
file = string.gsub(file, "\\", "/") -- convert slash
file = removebasedir(file, basedir)
end
client:send("SETB " .. file .. " " .. line .. "\n")
if command == "asetb" or client:receive() == "200 OK" then
set_breakpoint(file, line)
else
print("Error: breakpoint not inserted")
end
else
print("Invalid command")
end
elseif command == "setw" then
local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$")
if exp then
client:send("SETW " .. exp .. "\n")
local answer = client:receive()
local _, _, watch_idx = string.find(answer, "^200 OK (%d+)%s*$")
if watch_idx then
watches[watch_idx] = exp
print("Inserted watch exp no. " .. watch_idx)
else
local _, _, size = string.find(answer, "^401 Error in Expression (%d+)$")
if size then
local err = client:receive(tonumber(size)):gsub(".-:%d+:%s*","")
print("Error: watch expression not set: " .. err)
else
print("Error: watch expression not set")
end
end
else
print("Invalid command")
end
elseif command == "delb" or command == "adelb" then
_, _, _, file, line = string.find(params, "^([a-z]+)%s+(.-)%s+(%d+)%s*$")
if file and line then
-- if this is a file name, and not a file source
if not file:find('^".*"$') then
file = string.gsub(file, "\\", "/") -- convert slash
file = removebasedir(file, basedir)
end
client:send("DELB " .. file .. " " .. line .. "\n")
if command == "adelb" or client:receive() == "200 OK" then
remove_breakpoint(file, line)
else
print("Error: breakpoint not removed")
end
else
print("Invalid command")
end
elseif command == "delallb" then
for line, breaks in pairs(breakpoints) do
for file, _ in pairs(breaks) do
client:send("DELB " .. file .. " " .. line .. "\n")
if client:receive() == "200 OK" then
remove_breakpoint(file, line)
else
print("Error: breakpoint at file " .. file .. " line " .. line .. " not removed")
end
end
end
elseif command == "delw" then
local _, _, index = string.find(params, "^[a-z]+%s+(%d+)%s*$")
if index then
client:send("DELW " .. index .. "\n")
if client:receive() == "200 OK" then
watches[index] = nil
else
print("Error: watch expression not removed")
end
else
print("Invalid command")
end
elseif command == "delallw" then
for index, exp in pairs(watches) do
client:send("DELW " .. index .. "\n")
if client:receive() == "200 OK" then
watches[index] = nil
else
print("Error: watch expression at index " .. index .. " [" .. exp .. "] not removed")
end
end
elseif command == "eval" or command == "exec"
or command == "load" or command == "loadstring"
or command == "reload" then
local _, _, exp = string.find(params, "^[a-z]+%s+(.+)$")
if exp or (command == "reload") then
if command == "eval" or command == "exec" then
exp = (exp:gsub("%-%-%[(=*)%[.-%]%1%]", "") -- remove comments
:gsub("%-%-.-\n", " ") -- remove line comments
:gsub("\n", " ")) -- convert new lines
if command == "eval" then exp = "return " .. exp end
client:send("EXEC " .. exp .. "\n")
elseif command == "reload" then
client:send("LOAD 0 -\n")
elseif command == "loadstring" then
local _, _, _, file, lines = string.find(exp, "^([\"'])(.-)%1%s+(.+)")
if not file then
_, _, file, lines = string.find(exp, "^(%S+)%s+(.+)")
end
client:send("LOAD " .. #lines .. " " .. file .. "\n")
client:send(lines)
else
local file = io.open(exp, "r")
if not file and pcall(require, "winapi") then
-- if file is not open and winapi is there, try with a short path;
-- this may be needed for unicode paths on windows
winapi.set_encoding(winapi.CP_UTF8)
local shortp = winapi.short_path(exp)
file = shortp and io.open(shortp, "r")
end
if not file then return nil, nil, "Cannot open file " .. exp end
-- read the file and remove the shebang line as it causes a compilation error
local lines = file:read("*all"):gsub("^#!.-\n", "\n")
file:close()
local file = string.gsub(exp, "\\", "/") -- convert slash
file = removebasedir(file, basedir)
client:send("LOAD " .. #lines .. " " .. file .. "\n")
if #lines > 0 then client:send(lines) end
end
while true do
local params, err = client:receive()
if not params then
return nil, nil, "Debugger connection " .. (err or "error")
end
local done = true
local _, _, status, len = string.find(params, "^(%d+).-%s+(%d+)%s*$")
if status == "200" then
len = tonumber(len)
if len > 0 then
local status, res
local str = client:receive(len)
-- handle serialized table with results
local func, err = loadstring(str)
if func then
status, res = pcall(func)
if not status then err = res
elseif type(res) ~= "table" then
err = "received "..type(res).." instead of expected 'table'"
end
end
if err then
print("Error in processing results: " .. err)
return nil, nil, "Error in processing results: " .. err
end
print(unpack(res))
return res[1], res
end
elseif status == "201" then
_, _, file, line = string.find(params, "^201 Started%s+(.-)%s+(%d+)%s*$")
elseif status == "202" or params == "200 OK" then
-- do nothing; this only happens when RE/LOAD command gets the response
-- that was for the original command that was aborted
elseif status == "204" then
local _, _, stream, size = string.find(params, "^204 Output (%w+) (%d+)$")
if stream and size then
local msg = client:receive(tonumber(size))
print(msg)
if outputs[stream] then outputs[stream](msg) end
-- this was just the output, so go back reading the response
done = false
end
elseif status == "401" then
len = tonumber(len)
local res = client:receive(len)
print("Error in expression: " .. res)
return nil, nil, res
else
print("Unknown error")
return nil, nil, "Debugger error: unexpected response after EXEC/LOAD '" .. params .. "'"
end
if done then break end
end
else
print("Invalid command")
end
elseif command == "listb" then
for l, v in pairs(breakpoints) do
for f in pairs(v) do
print(f .. ": " .. l)
end
end
elseif command == "listw" then
for i, v in pairs(watches) do
print("Watch exp. " .. i .. ": " .. v)
end
elseif command == "suspend" then
client:send("SUSPEND\n")
elseif command == "stack" then
client:send("STACK\n")
local resp = client:receive()
local _, _, status, res = string.find(resp, "^(%d+)%s+%w+%s+(.+)%s*$")
if status == "200" then
local func, err = loadstring(res)
if func == nil then
print("Error in stack information: " .. err)
return nil, nil, err
end
local ok, stack = pcall(func)
if not ok then
print("Error in stack information: " .. stack)
return nil, nil, stack
end
for _,frame in ipairs(stack) do
print(mobdebug.line(frame[1], {comment = false}))
end
return stack
elseif status == "401" then
local _, _, len = string.find(resp, "%s+(%d+)%s*$")
len = tonumber(len)
local res = len > 0 and client:receive(len) or "Invalid stack information."
print("Error in expression: " .. res)
return nil, nil, res
else
print("Unknown error")
return nil, nil, "Debugger error: unexpected response after STACK"
end
elseif command == "output" then
local _, _, stream, mode = string.find(params, "^[a-z]+%s+(%w+)%s+([dcr])%s*$")
if stream and mode then
client:send("OUTPUT "..stream.." "..mode.."\n")
local resp = client:receive()
local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$")
if status == "200" then
print("Stream "..stream.." redirected")
outputs[stream] = type(options) == 'table' and options.handler or nil
else
print("Unknown error")
return nil, nil, "Debugger error: can't redirect "..stream
end
else
print("Invalid command")
end
elseif command == "basedir" then
local _, _, dir = string.find(params, "^[a-z]+%s+(.+)$")
if dir then
dir = string.gsub(dir, "\\", "/") -- convert slash
if not string.find(dir, "/$") then dir = dir .. "/" end
local remdir = dir:match("\t(.+)")
if remdir then dir = dir:gsub("/?\t.+", "/") end
basedir = dir
client:send("BASEDIR "..(remdir or dir).."\n")
local resp, err = client:receive()
if not resp then
print("Unknown error: "..err)
return nil, nil, "Debugger connection closed"
end
local _, _, status = string.find(resp, "^(%d+)%s+%w+%s*$")
if status == "200" then
print("New base directory is " .. basedir)
else
print("Unknown error")
return nil, nil, "Debugger error: unexpected response after BASEDIR"
end
else
print(basedir)
end
elseif command == "help" then
print("setb <file> <line> -- sets a breakpoint")
print("delb <file> <line> -- removes a breakpoint")
print("delallb -- removes all breakpoints")
print("setw <exp> -- adds a new watch expression")
print("delw <index> -- removes the watch expression at index")
print("delallw -- removes all watch expressions")
print("run -- runs until next breakpoint")
print("step -- runs until next line, stepping into function calls")
print("over -- runs until next line, stepping over function calls")
print("out -- runs until line after returning from current function")
print("listb -- lists breakpoints")
print("listw -- lists watch expressions")
print("eval <exp> -- evaluates expression on the current context and returns its value")
print("exec <stmt> -- executes statement on the current context")
print("load <file> -- loads a local file for debugging")
print("reload -- restarts the current debugging session")
print("stack -- reports stack trace")
print("output stdout <d|c|r> -- capture and redirect io stream (default|copy|redirect)")
print("basedir [<path>] -- sets the base path of the remote application, or shows the current one")
print("done -- stops the debugger and continues application execution")
print("exit -- exits debugger and the application")
else
local _, _, spaces = string.find(params, "^(%s*)$")
if not spaces then
print("Invalid command")
return nil, nil, "Invalid command"
end
end
return file, line
end
-- Starts debugging server
local function listen(host, port)
host = host or "*"
port = port or mobdebug.port
local socket = require "socket"
print("Lua Remote Debugger")
print("Run the program you wish to debug")
local server = socket.bind(host, port)
local client = server:accept()
client:send("STEP\n")
client:receive()
local breakpoint = client:receive()
local _, _, file, line = string.find(breakpoint, "^202 Paused%s+(.-)%s+(%d+)%s*$")
if file and line then
print("Paused at file " .. file )
print("Type 'help' for commands")
else
local _, _, size = string.find(breakpoint, "^401 Error in Execution (%d+)%s*$")
if size then
print("Error in remote application: ")
print(client:receive(size))
end
end
while true do
io.write("> ")
local line = io.read("*line")
handle(line, client)
end
end
local cocreate
local function coro()
if cocreate then return end -- only set once
cocreate = cocreate or coroutine.create
coroutine.create = function(f, ...)
return cocreate(function(...)
mobdebug.on()
return f(...)
end, ...)
end
end
local moconew
local function moai()
if moconew then return end -- only set once
moconew = moconew or (MOAICoroutine and MOAICoroutine.new)
if not moconew then return end
MOAICoroutine.new = function(...)
local thread = moconew(...)
-- need to support both thread.run and getmetatable(thread).run, which
-- was used in earlier MOAI versions
local mt = thread.run and thread or getmetatable(thread)
local patched = mt.run
mt.run = function(self, f, ...)
return patched(self, function(...)
mobdebug.on()
return f(...)
end, ...)
end
return thread
end
end
-- make public functions available
mobdebug.setbreakpoint = set_breakpoint
mobdebug.removebreakpoint = remove_breakpoint
mobdebug.listen = listen
mobdebug.loop = loop
mobdebug.scratchpad = scratchpad
mobdebug.handle = handle
mobdebug.connect = connect
mobdebug.start = start
mobdebug.on = on
mobdebug.off = off
mobdebug.moai = moai
mobdebug.coro = coro
mobdebug.done = done
mobdebug.pause = function() step_into = true end
mobdebug.yield = nil -- callback
-- this is needed to make "require 'modebug'" to work when mobdebug
-- module is loaded manually
package.loaded.mobdebug = mobdebug
return mobdebug
| mit |
nyczducky/darkstar | scripts/globals/spells/hojo_ichi.lua | 27 | 1249 | -----------------------------------------
-- Spell: Hojo:Ichi
-- Description: Inflicts Slow on target.
-- Edited from slow.lua
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Power for Hojo is a flat 14.6% reduction
local power = 150;
--Duration and Resistance calculation
local duration = 180 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
--Calculates the resist chance from Resist Blind trait
if (math.random(0,100) >= target:getMod(MOD_SLOWRES)) then
-- Spell succeeds if a 1 or 1/2 resist check is achieved
if (duration >= 150) then
if (target:addStatusEffect(EFFECT_SLOW,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return EFFECT_SLOW;
end; | gpl-3.0 |
ruleless/skynet | lualib/skynet/manager.lua | 72 | 1923 | local skynet = require "skynet"
local c = require "skynet.core"
function skynet.launch(...)
local addr = c.command("LAUNCH", table.concat({...}," "))
if addr then
return tonumber("0x" .. string.sub(addr , 2))
end
end
function skynet.kill(name)
if type(name) == "number" then
skynet.send(".launcher","lua","REMOVE",name, true)
name = skynet.address(name)
end
c.command("KILL",name)
end
function skynet.abort()
c.command("ABORT")
end
local function globalname(name, handle)
local c = string.sub(name,1,1)
assert(c ~= ':')
if c == '.' then
return false
end
assert(#name <= 16) -- GLOBALNAME_LENGTH is 16, defined in skynet_harbor.h
assert(tonumber(name) == nil) -- global name can't be number
local harbor = require "skynet.harbor"
harbor.globalname(name, handle)
return true
end
function skynet.register(name)
if not globalname(name) then
c.command("REG", name)
end
end
function skynet.name(name, handle)
if not globalname(name, handle) then
c.command("NAME", name .. " " .. skynet.address(handle))
end
end
local dispatch_message = skynet.dispatch_message
function skynet.forward_type(map, start_func)
c.callback(function(ptype, msg, sz, ...)
local prototype = map[ptype]
if prototype then
dispatch_message(prototype, msg, sz, ...)
else
dispatch_message(ptype, msg, sz, ...)
c.trash(msg, sz)
end
end, true)
skynet.timeout(0, function()
skynet.init_service(start_func)
end)
end
function skynet.filter(f ,start_func)
c.callback(function(...)
dispatch_message(f(...))
end)
skynet.timeout(0, function()
skynet.init_service(start_func)
end)
end
function skynet.monitor(service, query)
local monitor
if query then
monitor = skynet.queryservice(true, service)
else
monitor = skynet.uniqueservice(true, service)
end
assert(monitor, "Monitor launch failed")
c.command("MONITOR", string.format(":%08x", monitor))
return monitor
end
return skynet
| mit |
nyczducky/darkstar | scripts/zones/Windurst_Woods/npcs/Harara_WW.lua | 13 | 5527 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Harara, W.W.
-- 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/Windurst_Woods/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Windurst_Woods/TextIDs");
local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = #WindInv;
local inventory = WindInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
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
Menu1 = getArg1(guardnation,player);
Menu2 = getExForceAvailable(guardnation,player);
Menu3 = conquestRanking();
Menu4 = getSupplyAvailable(guardnation,player);
Menu5 = player:getNationTeleport(guardnation);
Menu6 = getArg6(player);
Menu7 = player:getCP();
Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Arrapago_Reef/mobs/Medusa.lua | 20 | 1467 | -----------------------------------
-- Area: Arrapago Reef
-- MOB: Medusa
-- @pos -458 -20 458
-- TODO: resists, attack/def boosts
-----------------------------------
require("scripts/globals/titles");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("eeshpp", math.random(5,99)); -- Uses EES randomly during the fight
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob, target)
local mobID = mob:getID();
target:showText(mob, MEDUSA_ENGAGE);
SpawnMob(mobID+1, 180):updateEnmity(target);
SpawnMob(mobID+2, 180):updateEnmity(target);
SpawnMob(mobID+3, 180):updateEnmity(target);
SpawnMob(mobID+4, 180):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local HPP = mob:getHPP();
if (mob:getLocalVar("usedees") == 0) then
if (HPP <= mob:getLocalVar("eeshpp")) then
mob:useMobAbility(1931); -- Eagle Eye Shot
mob:setLocalVar("usedees", 1);
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob, MEDUSA_DEATH);
player:addTitle(GORGONSTONE_SUNDERER);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Apollyon/bcnms/SE_Apollyon.lua | 22 | 1456 | -----------------------------------
-- Area: Appolyon
-- Name: SE_Apollyon
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[SE_Apollyon]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1293),APPOLLYON_SE_NE);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[SE_Apollyon]UniqueID"));
player:setVar("LimbusID",1293);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(BLACK_CARD);
end;
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 4) then
player:setPos(643,0.1,-600);
ResetPlayerLimbusVariable(player)
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/globals/mobskills/Stormwind.lua | 30 | 2237 | ---------------------------------------------
-- Stormwind
--
-- Description: Creates a whirlwind that deals Wind damage to targets in an area of effect.
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Unknown radial
-- 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 dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS);
if (mob:getName() == "Kreutzet") then
if (mob:actionQueueAbility() == true) then
if (mob:getLocalVar("Stormwind") == 0) then
mob:setLocalVar("Stormwind", 1);
dmgmod = 1.25;
info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT);
dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS);
elseif (mob:getLocalVar("Stormwind") == 1) then
mob:setLocalVar("Stormwind", 0);
dmgmod = 1.6;
info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,ELE_WIND,dmgmod,TP_NO_EFFECT);
dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WIND,MOBPARAM_WIPE_SHADOWS);
end
elseif (mob:actionQueueAbility() == false) then
for i = 0, 1 do -- Stormwind 3 times per use. Gets stronger each use.
-- TODO: Should be some sort of delay here between ws's..
mob:useMobAbility(926);
mob:setLocalVar("Stormwind", 0);
end
end
end
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
dtrip/awesome | tests/examples/wibox/layout/template.lua | 5 | 3075 | local file_path, image_path = ...
require("_common_template")(...)
local wibox = require( "wibox" )
local color = require( "gears.color" )
local beautiful = require( "beautiful" )
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
-- Create a generic rectangle widget to show layout disposition
local function generic_widget(text, col, margins)
return wibox.widget {
{
{
draw = function(_, _, cr, width, height)
cr:set_source(color(col or beautiful.bg_normal))
cr:set_line_width(3)
cr:rectangle(0, 0, width, height)
cr:fill_preserve()
cr:set_source(color(beautiful.border_color))
cr:stroke()
end,
widget = wibox.widget.base.make_widget
},
{
id = "text",
align = "center",
valign = "center",
text = text or "foobar",
widget = wibox.widget.textbox
} or nil,
widget = wibox.layout.stack
},
margins = margins or 5,
set_text = function(self, text2)
self:get_children_by_id("text")[1]:set_text(text2)
end,
is_widget = true,
widget = wibox.container.margin,
}
end
local names = {
"first" ,
"second" ,
"third" ,
"fourth" ,
"fifth" ,
"sixth" ,
"seventh",
"eighth" ,
"ninth" ,
}
-- Generic template to create "before and after" for layout mutators
local function generic_before_after(layout, layout_args, count, method, method_args)
local ls = {}
-- Create the layouts
for i=1, 2 do
local args = {layout = layout}
-- In case the layout change the array (it is technically not forbidden)
for k,v in pairs(layout_args) do
args[k] = v
end
local l = wibox.layout(args)
for j=1, count or 3 do
l:add(generic_widget(names[j] or "N/A"))
end
ls[i] = l
end
-- Mutate
if type(method) == "function" then
method(ls[2], unpack(method_args or {}))
else
ls[2][method](ls[2], unpack(method_args or {}))
end
return wibox.layout {
{
markup = "<b>Before:</b>",
widget = wibox.widget.textbox,
},
ls[1],
{
markup = "<b>After:</b>",
widget = wibox.widget.textbox,
},
ls[2],
layout = wibox.layout.fixed.vertical
}
end
-- Let the test request a size and file format
local widget, w, h = loadfile(file_path)(generic_widget, generic_before_after)
-- Emulate the event loop for 10 iterations
for _ = 1, 10 do
require("gears.timer").run_delayed_calls_now()
end
-- Save to the output file
wibox.widget.draw_to_svg_file(widget, image_path..".svg", w or 200, h or 30)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
weissj3/milkywayathome_client | separation/tests/stripe_22.lua | 4 | 1488 |
wedge = 22
background = {
q = 0.31434394882494787193,
r0 = 2.87911089665332431409
}
streams = {
{
epsilon = -1.65881577218413367447,
mu = 135.91388126472116937293,
r = 18.13833616641942469982,
theta = 0.71972082401347736713,
phi = -1.23577346797868070638,
sigma = 1.66692320391639148269
},
{
epsilon = 0.54945309871835834592,
mu = 183.92390878500503959003,
r = -2.93711875183102399944,
theta = 1.14705726103115135395,
phi = 2.10297973493284606761,
sigma = 24.42323755019587849802
},
{
epsilon = 0.83581763242964690619,
mu = 131.51971478884220800865,
r = -26.22006937000678306049,
theta = 0.85148326301075494271,
phi = -2.17473757732651362673,
sigma = 7.07295318456947086361
}
}
area = {
{
r_min = 16.0,
r_max = 22.5,
r_steps = 140,
mu_min = 131,
mu_max = 225,
mu_steps = 160,
nu_min = -1.25,
nu_max = 1.25,
nu_steps = 64
},
{
r_min = 16.0,
r_max = 22.5,
r_steps = 140,
mu_min = 207.0,
mu_max = 209.0,
mu_steps = 40,
nu_min = 0.8,
nu_max = 1.25,
nu_steps = 32
},
{
r_min = 16.0,
r_max = 22.5,
r_steps = 140,
mu_min = 202.0,
mu_max = 204.0,
mu_steps = 40,
nu_min = -0.5,
nu_max = 0.4,
nu_steps = 32
}
}
| gpl-3.0 |
SamOatesPlugins/cuberite | Server/Plugins/APIDump/Hooks/OnPluginsLoaded.lua | 44 | 2702 | return
{
HOOK_PLUGINS_LOADED =
{
CalledWhen = "All the enabled plugins have been loaded",
DefaultFnName = "OnPluginsLoaded", -- also used as pagename
Desc = [[
This callback gets called when the server finishes loading and initializing plugins. This is the
perfect occasion for a plugin to query other plugins through {{cPluginManager}}:GetPlugin() and
possibly start communicating with them using the {{cPlugin}}:Call() function.
]],
Params = {},
Returns = [[
The return value is ignored, all registered callbacks are called.
]],
CodeExamples =
{
{
Title = "CoreMessaging",
Desc = [[
This example shows how to implement the CoreMessaging functionality - messages to players will be
sent through the Core plugin, formatted by that plugin. As a fallback for when the Core plugin is
not present, the messages are sent directly by this code, unformatted.
]],
Code = [[
-- These are the fallback functions used when the Core is not present:
local function SendMessageFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
local function SendMessageSuccessFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
local function SendMessageFailureFallback(a_Player, a_Message)
a_Player:SendMessage(a_Message);
end
-- These three "variables" will hold the actual functions to call.
-- By default they are initialized to the Fallback variants,
-- but will be redirected to Core when all plugins load
SendMessage = SendMessageFallback;
SendMessageSuccess = SendMessageSuccessFallback;
SendMessageFailure = SendMessageFailureFallback;
-- The callback tries to connect to the Core
-- If successful, overwrites the three functions with Core ones
local function OnPluginsLoaded()
local CorePlugin = cPluginManager:Get():GetPlugin("Core");
if (CorePlugin == nil) then
-- The Core is not loaded, keep the Fallback functions
return;
end
-- Overwrite the three functions with Core functionality:
SendMessage = function(a_Player, a_Message)
CorePlugin:Call("SendMessage", a_Player, a_Message);
end
SendMessageSuccess = function(a_Player, a_Message)
CorePlugin:Call("SendMessageSuccess", a_Player, a_Message);
end
SendMessageFailure = function(a_Player, a_Message)
CorePlugin:Call("SendMessageFailure", a_Player, a_Message);
end
end
-- Global scope, register the callback:
cPluginManager.AddHook(cPluginManager.HOOK_PLUGINS_LOADED, CoreMessagingPluginsLoaded);
-- Usage, anywhere else in the plugin:
SendMessageFailure(
a_Player,
"Cannot teleport to player, the destination player " .. PlayerName .. " was not found"
);
]],
},
} , -- CodeExamples
}, -- HOOK_PLUGINS_LOADED
}
| apache-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/wisker.lua | 6 | 3979 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- WISKER
-- ================================================================================================
-- L O C A L V A R I A B L E S
-- ================================================================================================
v.fireDelay = 2
v.moveTimer = 0
v.charge = 0
local STATE_CHARGE = 1000
local STATE_DELAY = 1001
v.inited = false
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init(me)
setupBasicEntity(
me,
"", -- texture
6, -- health
2, -- manaballamount
2, -- exp
1, -- money
64, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
256, -- sprite width
256, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
1, -- 0/1 hit other entities off/on (uses collideRadius)
3000 -- updateCull -1: disabled, default: 4000
)
entity_scale(me, 0.75, 0.75)
entity_setDropChance(me, 25)
entity_clampToSurface(me)
entity_setDeathParticleEffect(me, "TinyGreenExplode")
entity_initSkeletal(me, "Wisker")
entity_setState(me, STATE_IDLE)
esetv(me, EV_WALLOUT, 10)
entity_setEatType(me, EAT_FILE, "Wisker")
end
function update(me, dt)
if entity_isState(me, STATE_IDLE) then
entity_moveAlongSurface(me, dt, 140, 6, 30)
entity_rotateToSurfaceNormal(me, 0.1)
-- entity_rotateToSurfaceNormal(0.1)
v.moveTimer = v.moveTimer + dt
if v.moveTimer > 4 then
entity_switchSurfaceDirection(me)
v.moveTimer = 0
end
if not(entity_hasTarget(me)) then
entity_findTarget(me, 1200)
else
if v.fireDelay > 0 then
v.fireDelay = v.fireDelay - dt
if v.fireDelay < 0 then
v.fireDelay = 3
entity_setState(me, STATE_CHARGE)
end
end
end
end
if entity_isState(me, STATE_DELAY) then
entity_moveAlongSurface(me, dt, 60, 6, 10)
entity_rotateToSurfaceNormal(me, 0.1)
end
entity_handleShotCollisions(me)
if entity_touchAvatarDamage(me, entity_getCollideRadius(me), 1, 500) then
setPoison(1, 12)
end
end
function enterState(me)
if entity_getState(me)==STATE_IDLE then
entity_animate(me, "waddle", -1)
elseif entity_isState(me, STATE_CHARGE) then
entity_setStateTime(me, entity_animate(me, "charge"))
elseif entity_isState(me, STATE_DELAY) then
entity_animate(me, "idle", -1)
entity_setStateTime(me, 1)
end
end
local function fireShot(me, a)
local s = createShot("WiskerShot", me, entity_getTarget(me))
shot_setAimVector(s, entity_getAimVector(me, a, 1))
shot_setOut(s, 32)
end
function exitState(me)
if entity_isState(me, STATE_CHARGE) then
--entity_doGlint(me, "Particles/PurpleFlare")
entity_sound(me, "SpineFire")
fireShot(me, -45)
fireShot(me, 0)
fireShot(me, 45)
entity_setState(me, STATE_DELAY)
elseif entity_isState(me, STATE_DELAY) then
entity_setState(me, STATE_IDLE)
end
end
function damage(me)
return true
end
function hitSurface(me)
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/pistolshrimp.lua | 6 | 4121 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
v.n = 0
v.dir = 0
local STATE_FLYBACK = 1000
function init(me)
v.fireDelay = 2 + math.random(2)
setupEntity(me)
entity_setEntityType(me, ET_ENEMY)
entity_initSkeletal(me, "pistolshrimp")
entity_setAllDamageTargets(me, true)
entity_setCollideRadius(me, 32)
entity_setState(me, STATE_IDLE)
entity_setHealth(me, 9)
entity_setUpdateCull(me, 3000)
entity_setDeathParticleEffect(me, "tinyyellowexplode")
v.dir = math.random(2)-1
--[[
if v.dir == 0 then
entity_rotateOffset(me, 90)
--entity_rotateOffset(me, 80)
--entity_rotateOffset(me, 110, 1, -1)
else
entity_rotateOffset(me, -90)
--entity_rotateOffset(me, -80)
--entity_rotateOffset(me, -110, 1, -1)
end
]]--
--entity_scale(me, 0.8, 0.8)
entity_setEatType(me, EAT_FILE, "PistolShrimp")
entity_setEntityLayer(me, 1)
esetv(me, EV_TYPEID, EVT_PISTOLSHRIMP)
loadSound("pistolshrimp-fire")
end
function postInit(me)
v.n = getNaija()
end
function update(me, dt)
if entity_hasTarget(me) then
if not entity_isState(me, STATE_FLYBACK) then
if entity_isTargetInRange(me, 400) then
entity_moveTowardsTarget(me, dt, 2000)
if entity_isTargetInRange(me, 256) then
entity_moveTowardsTarget(me, dt, -2000)
end
entity_setMaxSpeedLerp(me, 2, 0.5)
entity_moveAroundTarget(me, dt, 3000, v.dir)
v.fireDelay = v.fireDelay - dt*1.5
entity_doEntityAvoidance(me, dt, 8, 0.5)
else
v.fireDelay = v.fireDelay - dt
entity_doEntityAvoidance(me, dt, 16, 1)
entity_doEntityAvoidance(me, dt, 32, 0.6)
entity_setMaxSpeedLerp(me, 1, 0.5)
entity_moveTowardsTarget(me, dt, 1000)
--entity_rotate(me, 90, 0.5)
end
entity_rotate(me, 0, 0.5)
elseif entity_isState(me, STATE_FLYBACK) then
end
if v.fireDelay < 0 then
if entity_isEntityInRange(me, v.n, 900) then
v.fireDelay = 1 + math.random(2)
local s = createShot("pistolshrimp", me, v.n)
shot_setOut(s, 32)
entity_setMaxSpeedLerp(me, 4)
entity_setMaxSpeedLerp(me, 1, 3)
entity_moveTowards(me, entity_x(v.n), entity_y(v.n), 1, -4000)
entity_rotateToVel(me, 0.1, -90)--, 80)
entity_setState(me, STATE_FLYBACK, 1)
end
end
entity_doCollisionAvoidance(me, dt, 4, 0.1)
entity_findTarget(me, 1800)
else
entity_findTarget(me, 900)
entity_setMaxSpeedLerp(me, 0.01, 1)
end
entity_updateMovement(me, dt)
entity_handleShotCollisions(me)
entity_touchAvatarDamage(me, entity_getCollideRadius(me), 0.5, 400)
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
entity_animate(me, "idle", -1)
end
end
function exitState(me)
if entity_isState(me, STATE_FLYBACK) then
entity_setState(me, STATE_IDLE, -1)
end
end
function damage(me, attacker, bone, damageType, dmg)
if attacker == me or eisv(attacker, EV_TYPEID, EVT_PISTOLSHRIMP) then
return false
end
if damageType == DT_AVATAR_BITE then
entity_changeHealth(me, -100)
end
return true
end
function animationKey(me, key)
end
function hitSurface(me)
end
function songNote(me, note)
end
function songNoteDone(me, note)
end
function song(me, song)
end
function activate(me)
end
function dieNormal(me)
if chance(50) then
spawnIngredient("SpicyMeat", entity_x(me), entity_y(me))
end
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Kazham/npcs/Roropp.lua | 15 | 8491 | -----------------------------------
-- Area: Kazham
-- NPC: Roropp
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
require("scripts/globals/pathfind");
local path = {
16.031977, -8.000000, -106.132980,
16.257568, -8.000000, -105.056381,
16.488544, -8.000000, -103.993233,
16.736769, -8.000000, -102.925789,
16.683693, -8.000000, -103.979767,
16.548674, -8.000000, -105.063362,
16.395681, -8.000000, -106.140511,
16.232897, -8.000000, -107.264717,
15.467215, -8.000000, -111.498398,
14.589552, -8.000000, -110.994324,
15.159187, -8.000000, -111.843941,
14.467873, -8.000000, -110.962730,
15.174071, -8.000000, -111.862633,
14.541949, -8.000000, -111.057007,
14.902087, -8.000000, -110.084839,
16.047390, -8.000000, -109.979256,
15.778022, -8.000000, -111.043304,
14.890110, -8.000000, -111.671753,
14.021555, -8.000000, -112.251015,
14.686207, -8.000000, -111.499725,
14.093862, -8.000000, -110.499420,
13.680259, -8.000000, -109.391823,
13.557489, -8.000000, -108.379669,
13.505498, -8.000000, -107.381012,
13.459559, -8.000000, -106.253922,
13.316416, -8.000000, -103.526192,
13.187886, -8.000000, -104.739197,
13.107801, -8.000000, -105.800117,
12.796517, -8.000000, -112.526253,
13.832601, -8.000000, -112.296143,
14.750398, -8.000000, -111.783379,
15.670343, -8.000000, -111.165863,
16.603874, -8.000000, -110.633209,
16.092684, -8.000000, -111.518547,
14.989306, -8.000000, -111.488846,
14.200422, -8.000000, -110.700859,
13.893030, -8.000000, -109.573753,
14.125311, -8.000000, -108.444000,
14.459513, -8.000000, -107.450630,
14.801712, -8.000000, -106.489639,
17.003086, -8.000000, -99.881256,
16.131863, -8.000000, -100.382454,
15.278582, -8.000000, -101.082420,
14.444073, -8.000000, -101.823395,
13.716499, -8.000000, -102.551468,
13.602413, -8.000000, -103.671387,
13.773719, -8.000000, -104.753410,
14.019071, -8.000000, -105.842079,
14.275101, -8.000000, -106.944748,
15.256051, -8.000000, -111.604820,
14.447664, -8.000000, -110.851128,
15.032362, -8.000000, -111.679832,
14.342421, -8.000000, -110.802597,
13.347830, -8.000000, -111.075569,
12.911378, -8.000000, -112.149437,
13.853123, -8.000000, -112.719269,
14.862821, -8.000000, -112.491272,
14.661202, -8.000000, -111.423317,
14.026034, -8.000000, -110.421486,
13.683197, -8.000000, -109.474442,
13.565609, -8.000000, -108.425598,
13.508922, -8.000000, -107.411247,
13.463074, -8.000000, -106.340248,
13.314778, -8.000000, -103.679779,
13.196125, -8.000000, -104.712784,
13.107168, -8.000000, -105.817261,
12.642462, -8.000000, -112.284569,
12.722448, -8.000000, -111.167519,
12.800394, -8.000000, -110.082321,
13.358773, -8.000000, -103.535522,
13.700077, -8.000000, -104.534401,
13.968060, -8.000000, -105.588699,
14.196942, -8.000000, -106.594994,
14.446990, -8.000000, -107.686691,
14.850841, -8.000000, -109.436707,
15.239276, -8.000000, -111.548279,
14.406080, -8.000000, -110.805321,
15.076430, -8.000000, -111.739746,
14.353576, -8.000000, -110.817177,
13.903994, -8.000000, -109.854828,
14.002557, -8.000000, -108.838097,
14.350549, -8.000000, -107.686317,
14.707720, -8.000000, -106.730751,
15.101375, -8.000000, -105.648056,
16.961918, -8.000000, -99.919090,
15.985752, -8.000000, -100.501892,
15.192271, -8.000000, -101.161407,
14.369474, -8.000000, -101.891479,
13.749530, -8.000000, -102.797821,
13.968772, -8.000000, -103.829323,
14.469959, -8.000000, -104.888268,
14.964800, -8.000000, -105.802879,
16.955986, -8.000000, -109.414169,
16.776617, -8.000000, -110.478836,
16.263479, -8.000000, -111.339577,
15.200941, -8.000000, -111.526329,
14.352178, -8.000000, -110.754326,
15.190737, -8.000000, -110.001801,
16.302240, -8.000000, -110.005722,
15.815475, -8.000000, -111.014900,
14.911292, -8.000000, -111.661888,
14.005045, -8.000000, -112.263855,
14.883535, -8.000000, -111.781982,
14.404255, -8.000000, -110.876640,
15.071056, -8.000000, -111.731522,
14.335340, -8.000000, -110.793587,
13.342915, -8.000000, -111.184967,
12.869198, -8.000000, -112.210732,
13.971279, -8.000000, -112.223083,
14.902745, -8.000000, -111.661880,
15.813969, -8.000000, -111.060051,
16.728361, -8.000000, -110.402679,
16.754343, -8.000000, -109.357780,
16.393435, -8.000000, -108.410202,
15.880263, -8.000000, -107.455299,
15.362660, -8.000000, -106.521095,
13.593607, -8.000000, -103.312202,
14.028812, -8.000000, -102.335686,
14.836555, -8.000000, -101.487602,
15.656289, -8.000000, -100.748199,
16.544455, -8.000000, -99.965248,
15.712431, -8.000000, -100.702980,
14.859239, -8.000000, -101.459091,
13.961225, -8.000000, -102.255051,
14.754376, -8.000000, -101.551842,
15.574628, -8.000000, -100.824944,
16.913191, -8.000000, -99.639374,
16.158613, -8.000000, -100.307716,
15.371163, -8.000000, -101.005310,
13.802610, -8.000000, -102.395645,
13.852294, -8.000000, -103.601982,
14.296268, -8.000000, -104.610878,
14.826925, -8.000000, -105.560638,
15.320851, -8.000000, -106.448463,
15.858366, -8.000000, -107.421883,
17.018456, -8.000000, -109.527451,
16.734596, -8.000000, -110.580498,
16.095715, -8.000000, -111.542282
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
-- item IDs
-- 483 Broken Mithran Fishing Rod
-- 22 Workbench
-- 1008 Ten of Coins
-- 1157 Sands of Silence
-- 1158 Wandering Bulb
-- 904 Giant Fish Bones
-- 4599 Blackened Toad
-- 905 Wyvern Skull
-- 1147 Ancient Salt
-- 4600 Lucky Egg
function onTrade(player,npc,trade)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local goodtrade = trade:hasItemQty(1157,1);
local badtrade = (trade:hasItemQty(483,1) or trade:hasItemQty(22,1) or trade:hasItemQty(1008,1) or trade:hasItemQty(1158,1) or trade:hasItemQty(904,1) or trade:hasItemQty(4599,1) or trade:hasItemQty(905,1) or trade:hasItemQty(1147,1) or trade:hasItemQty(4600,1));
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if progress == 3 or failed == 4 then
if goodtrade then
player:startEvent(0x00DE);
elseif badtrade then
player:startEvent(0x00E8);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OpoOpoAndIStatus = player:getQuestStatus(OUTLANDS, THE_OPO_OPO_AND_I);
local progress = player:getVar("OPO_OPO_PROGRESS");
local failed = player:getVar("OPO_OPO_FAILED");
local retry = player:getVar("OPO_OPO_RETRY");
if (OpoOpoAndIStatus == QUEST_ACCEPTED) then
if retry >= 1 then -- has failed on future npc so disregard previous successful trade
player:startEvent(0x00C8);
npc:wait(-1);
elseif (progress == 3 or failed == 4) then
player:startEvent(0x00D2); -- asking for sands of silence
elseif (progress >= 4 or failed >= 5) then
player:startEvent(0x00F5); -- happy with sands of silence
end
else
player:startEvent(0x00C8);
npc:wait(-1);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x00DE) then -- correct trade, onto next opo
if player:getVar("OPO_OPO_PROGRESS") == 3 then
player:tradeComplete();
player:setVar("OPO_OPO_PROGRESS",4);
player:setVar("OPO_OPO_FAILED",0);
else
player:setVar("OPO_OPO_FAILED",5);
end
elseif (csid == 0x00E8) then -- wrong trade, restart at first opo
player:setVar("OPO_OPO_FAILED",1);
player:setVar("OPO_OPO_RETRY",4);
else
npc:wait(0);
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Mhaura/npcs/Tya_Padolih.lua | 14 | 1479 | -----------------------------------
-- Area: Mhaura
-- NPC: Tya Padolih
-- Standard Merchant NPC
-- @pos -48 -4 30 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TYAPADOLIH_SHOP_DIALOG);
stock = {0x126c,4147, --Scroll of Regen
0x126e,7516, --Scroll of Regen II
0x1311,10752, --Scroll of Sleepga
0x1252,29030, --Scroll of Baramnesia
0x1253,29030, --Scroll of Baramnesra
0x1288,5523, --Scroll of Invisible
0x1289,2400, --Scroll of Sneak
0x128a,1243, --Scroll of Deodorize
0x1330,18032} --Scroll of Distract
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5f8.lua | 12 | 1096 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Titan's Gate
-- @pos 260 -34 88 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
return 0;
end;
--
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Castle_Oztroja/npcs/_47z.lua | 14 | 1429 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _47z (Torch Stand)
-- Notes: Opens door _474
-- @pos -62.464 24.218 -67.313 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
DoorID = npc:getID() - 4;
local DoorA = GetNPCByID(DoorID):getAnimation();
local TorchStandA = npc:getAnimation();
Torch1 = npc:getID();
Torch2 = npc:getID() - 1;
if (DoorA == 9 and TorchStandA == 9) then
player:startEvent(0x000a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
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 |
MOSAVI17/Generalbot | plugins/gImages.lua | 8 | 2110 | -- You need a Google API key and a Google Custom Search Engine set up to use this, in config.google_api_key and config.google_cse_key, respectively.
-- You must also sign up for the CSE in the Google Developer Concsole, and enable image results.
if not config.google_api_key then
print('Missing config value: google_api_key.')
print('gImages.lua will not be enabled.')
return
elseif not config.google_cse_key then
print('Missing config value: google_cse_key.')
print('gImages.lua will not be enabled.')
return
end
local command = 'image <query>'
local doc = [[```
/image <query>
Returns a randomized top result from Google Images. Safe search is enabled by default; use "/insfw" to disable it. NSFW results will not display an image preview.
Alias: /i
```]]
local triggers = {
'^/image[@'..bot.username..']*',
'^/i[@'..bot.username..']* ',
'^/i[@'..bot.username..']*$',
'^/insfw[@'..bot.username..']*'
}
local action = function(msg)
local input = msg.text:input()
if not input then
if msg.reply_to_message and msg.reply_to_message.text then
input = msg.reply_to_message.text
else
sendMessage(msg.chat.id, doc, true, msg.message_id, true)
return
end
end
local url = 'https://www.googleapis.com/customsearch/v1?&searchType=image&imgSize=xlarge&alt=json&num=8&start=1&key=' .. config.google_api_key .. '&cx=' .. config.google_cse_key
if not string.match(msg.text, '^/i[mage]*nsfw') then
url = url .. '&safe=high'
end
url = url .. '&q=' .. URL.escape(input)
local jstr, res = HTTPS.request(url)
if res ~= 200 then
sendReply(msg, config.errors.connection)
return
end
local jdat = JSON.decode(jstr)
if jdat.searchInformation.totalResults == '0' then
sendReply(msg, config.errors.results)
return
end
local i = math.random(jdat.queries.request[1].count)
local result = jdat.items[i].link
local output = '[]('..result..')'
if string.match(msg.text, '^/i[mage]*nsfw') then
sendReply(msg, result)
else
sendMessage(msg.chat.id, output, false, nil, true)
end
end
return {
action = action,
triggers = triggers,
doc = doc,
command = command
}
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Nullifying_Dropkick.lua | 58 | 1046 | ---------------------------------------------
-- Nullifying Dropkick
--
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/zones/Empyreal_Paradox/TextIDs");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (target:hasStatusEffect(EFFECT_PHYSICAL_SHIELD) or target:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then
mob:showText(mob, PRISHE_TEXT + 5);
return 0;
end
return 1;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 2.0;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
target:delStatusEffect(EFFECT_PHYSICAL_SHIELD);
target:delStatusEffect(EFFECT_MAGIC_SHIELD);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
lgeek/koreader | plugins/kobolight.koplugin/main.lua | 1 | 9548 | local Device = require("device")
local with_frontlight = (Device:isKindle() or Device:isKobo()) and Device:hasFrontlight()
local with_natural_light = Device:isKobo() and Device:hasNaturalLight()
if not (with_frontlight or Device:isSDL()) then
return { disabled = true, }
end
local ConfirmBox = require("ui/widget/confirmbox")
local ImageWidget = require("ui/widget/imagewidget")
local InfoMessage = require("ui/widget/infomessage")
local Notification = require("ui/widget/notification")
local Screen = require("device").screen
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local T = require("ffi/util").template
local _ = require("gettext")
local tap_touch_zone_ratio = { x = 0, y = 15/16, w = 1/10, h = 1/16, }
local swipe_touch_zone_ratio = { x = 0, y = 1/8, w = 1/10, h = 7/8, }
local swipe_touch_zone_ratio_warmth = { x = 7/8, y = 1/8, w = 1/8, h = 7/8, }
local KoboLight = WidgetContainer:new{
name = 'kobolight',
gestureScale = nil, -- initialized in self:resetLayout()
}
function KoboLight:init()
local powerd = Device:getPowerDevice()
local scale = (powerd.fl_max - powerd.fl_min) / 2 / 10.6
self.steps = { 0.1, 0.1, 0.2, 0.4, 0.7, 1.1, 1.6, 2.2, 2.9, 3.7, 4.6, 5.6, 6.7, 7.9, 9.2, 10.6, }
for i = 1, #self.steps, 1
do
self.steps[i] = math.ceil(self.steps[i] * scale)
end
self.ui.menu:registerToMainMenu(self)
end
function KoboLight:onReaderReady()
self:setupTouchZones()
self:resetLayout()
end
function KoboLight:disabled()
return G_reader_settings:isTrue("disable_kobolight")
end
function KoboLight:setupTouchZones()
if not Device:isTouchDevice() then return end
if self:disabled() then return end
local swipe_zone = {
ratio_x = swipe_touch_zone_ratio.x, ratio_y = swipe_touch_zone_ratio.y,
ratio_w = swipe_touch_zone_ratio.w, ratio_h = swipe_touch_zone_ratio.h,
}
local swipe_zone_warmth = {
ratio_x = swipe_touch_zone_ratio_warmth.x,
ratio_y = swipe_touch_zone_ratio_warmth.y,
ratio_w = swipe_touch_zone_ratio_warmth.w,
ratio_h = swipe_touch_zone_ratio_warmth.h,
}
self.ui:registerTouchZones({
{
id = "plugin_kobolight_tap",
ges = "tap",
screen_zone = {
ratio_x = tap_touch_zone_ratio.x, ratio_y = tap_touch_zone_ratio.y,
ratio_w = tap_touch_zone_ratio.w, ratio_h = tap_touch_zone_ratio.h,
},
handler = function() return self:onTap() end,
overrides = { 'readerfooter_tap' },
},
{
id = "plugin_kobolight_swipe",
ges = "swipe",
screen_zone = swipe_zone,
handler = function(ges) return self:onSwipe(nil, ges) end,
overrides = { 'paging_swipe', 'rolling_swipe', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan",
ges = "pan",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan', 'rolling_pan', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_release",
ges = "pan_release",
screen_zone = swipe_zone,
handler = function(ges) return true end,
overrides = { 'paging_pan_release', },
},
})
if with_natural_light then
self.ui:registerTouchZones({
{
id = "plugin_kobolight_swipe_warmth",
ges = "swipe",
screen_zone = swipe_zone_warmth,
handler = function(ges) return self:onSwipeWarmth(nil, ges) end,
overrides = { 'paging_swipe', 'rolling_swipe', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_warmth",
ges = "pan",
screen_zone = swipe_zone_warmth,
handler = function(ges) return true end,
overrides = { 'paging_pan', 'rolling_pan', },
},
{
-- dummy zone to disable reader panning
id = "plugin_kobolight_pan_release_warmth",
ges = "pan_release",
screen_zone = swipe_zone_warmth,
handler = function(ges) return true end,
overrides = { 'paging_pan_release', },
},
})
end
end
function KoboLight:resetLayout()
local new_screen_height = Screen:getHeight()
self.gestureScale = new_screen_height * swipe_touch_zone_ratio.h * 0.8
end
function KoboLight:onShowIntensity()
local powerd = Device:getPowerDevice()
if powerd.fl_intensity ~= nil then
UIManager:show(Notification:new{
text = T(_("Frontlight intensity is set to %1."), powerd.fl_intensity),
timeout = 1.0,
})
end
return true
end
function KoboLight:onShowWarmth(value)
local powerd = Device:getPowerDevice()
if powerd.fl_warmth ~= nil then
UIManager:show(Notification:new{
text = T(_("Warmth is set to %1."), powerd.fl_warmth),
timeout = 1.0,
})
end
return true
end
function KoboLight:onShowOnOff()
local powerd = Device:getPowerDevice()
local new_text
if powerd.is_fl_on then
new_text = _("Frontlight is on.")
else
new_text = _("Frontlight is off.")
end
UIManager:show(Notification:new{
text = new_text,
timeout = 1.0,
})
return true
end
function KoboLight:onTap()
Device:getPowerDevice():toggleFrontlight()
self:onShowOnOff()
return true
end
function KoboLight:onSwipe(_, ges)
local powerd = Device:getPowerDevice()
if powerd.fl_intensity == nil then return false end
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
local delta_int = self.steps[step] or self.steps[#self.steps]
local new_intensity
if ges.direction == "north" then
new_intensity = powerd.fl_intensity + delta_int
elseif ges.direction == "south" then
new_intensity = powerd.fl_intensity - delta_int
else
return false -- don't consume swipe event if it's not matched
end
-- when new_intensity <=0, toggle light off
if new_intensity <=0 then
if powerd.is_fl_on then
powerd:toggleFrontlight()
end
self:onShowOnOff()
else -- general case
powerd:setIntensity(new_intensity)
self:onShowIntensity()
end
return true
end
function KoboLight:onSwipeWarmth(ignored, ges)
local powerd = Device:getPowerDevice()
if powerd.fl_warmth == nil then return false end
if powerd.auto_warmth then
UIManager:show(Notification:new{
text = _("Warmth is handled automatically."),
timeout = 1.0,
})
return true
end
local step = math.ceil(#self.steps * ges.distance / self.gestureScale)
local delta_int = self.steps[step] or self.steps[#self.steps]
local warmth
if ges.direction == "north" then
warmth = math.min(powerd.fl_warmth + delta_int, 100)
elseif ges.direction == "south" then
warmth = math.max(powerd.fl_warmth - delta_int, 0)
else
return false -- don't consume swipe event if it's not matched
end
powerd:setWarmth(warmth)
self:onShowWarmth()
return true
end
function KoboLight:addToMainMenu(menu_items)
menu_items.frontlight_gesture_controller = {
text = _("Frontlight gesture controller"),
callback = function()
local image_name
local nl_text = ""
if with_natural_light then
image_name = "/demo_ka1.png"
nl_text = _("\n- Change frontlight warmth by swiping up or down on the right of the screen.")
else
image_name = "/demo.png"
end
local image = ImageWidget:new{
file = self.path .. image_name,
height = Screen:getHeight(),
width = Screen:getWidth(),
scale_factor = 0,
}
UIManager:show(image)
UIManager:show(ConfirmBox:new{
text = _("Frontlight gesture controller can:\n- Turn on or off frontlight by tapping bottom left of the screen.\n- Change frontlight intensity by swiping up or down on the left of the screen.") .. nl_text .. "\n\n" ..
(self:disabled() and _("Do you want to enable the frontlight gesture controller?") or _("Do you want to disable the frontlight gesture controller?")),
ok_text = self:disabled() and _("Enable") or _("Disable"),
ok_callback = function()
UIManager:close(image)
UIManager:setDirty("all", "full")
UIManager:show(InfoMessage:new{
text = T(_("You have %1 the frontlight gesture controller. It will take effect on next restart."),
self:disabled() and _("enabled") or _("disabled"))
})
G_reader_settings:flipTrue("disable_kobolight")
end,
cancel_text = _("Close"),
cancel_callback = function()
UIManager:close(image)
UIManager:setDirty("all", "full")
end,
})
UIManager:setDirty("all", "full")
end,
}
end
return KoboLight
| agpl-3.0 |
nyczducky/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua | 14 | 2081 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Wyatt
-- @zone 80
-- @pos 124 0 84
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then
player:startEvent(0x0004);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS);
if (seeingSpots == QUEST_AVAILABLE) then
player:startEvent(0x0002);
elseif (seeingSpots == QUEST_ACCEPTED) then
player:startEvent(0x0003);
else
player:showText(npc, WYATT_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
player:addQuest(CRYSTAL_WAR,SEEING_SPOTS);
elseif (csid == 0x0004) then
player:tradeComplete();
if (player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS);
else
player:addTitle(LADY_KILLER);
player:addGil(GIL_RATE*3000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000);
end
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Port_Windurst/npcs/Erabu-Fumulubu.lua | 53 | 1835 | -----------------------------------
-- Area: Port Windurst
-- NPC: Erabu-Fumulubu
-- Type: Fishing Synthesis Image Support
-- @pos -178.900 -2.789 76.200 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,5);
local SkillCap = getCraftSkillCap(player,SKILL_FISHING);
local SkillLevel = player:getSkillLevel(SKILL_FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),0,0,0); -- p1 = skill level
else
player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),19194,4031,0);
end
else
player:startEvent(0x271C); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x271C and option == 1) then
player:messageSpecial(FISHING_SUPPORT,0,0,1);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600);
end
end; | gpl-3.0 |
cliffano/swaggy-jenkins | clients/lua/generated/spec/generic_resource_spec.lua | 1 | 1812 | --[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.5.1-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
--[[
Unit tests for openapiclient.model.generic_resource
Automatically generated by openapi-generator (https://openapi-generator.tech)
Please update as you see appropriate
]]
describe("generic_resource", function()
local openapiclient_generic_resource = require "openapiclient.model.generic_resource"
-- unit tests for the property '_class'
describe("property _class test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'display_name'
describe("property display_name test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'duration_in_millis'
describe("property duration_in_millis test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'id'
describe("property id test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'result'
describe("property result test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'start_time'
describe("property start_time test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
end)
| mit |
nyczducky/darkstar | scripts/globals/items/serving_of_salmon_meuniere_+1.lua | 12 | 1400 | -----------------------------------------
-- 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");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4347);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
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;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
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 |
micdah/LrControl | Source/LrControl.Plugin/ModulesLrDevelopController.lua | 1 | 8510 | --[[----------------------------------------------------------------------------
Copyright ? 2016 Michael Dahl
This file is part of LrControl.
LrControl 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 3 of the License, or
(at your option) any later version.
LrControl 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 LrControl. If not, see <http://www.gnu.org/licenses/>.
------------------------------------------------------------------------------]]
local LrDevelopController = import 'LrDevelopController'
local ModuleTools = require 'ModuleTools'
return {
decrement =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.decrement",
ModuleTools.AfterFunction("LrDevelopController.decrement",
function(param)
LrDevelopController.decrement(param)
end))),
getProcessVersion =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.getProcessVersion",
ModuleTools.AfterFunction("LrDevelopController.getProcessVersion",
function()
return LrDevelopController.getProcessVersion()
end))),
getRange =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.getRange",
ModuleTools.AfterFunction("LrDevelopController.getRange",
function(param)
return LrDevelopController.getRange(param)
end))),
getSelectedTool =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.getSelectedTool",
ModuleTools.AfterFunction("LrDevelopController.getSelectedTool",
function()
return LrDevelopController.getSelectedTool()
end))),
getValue =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.getValue",
ModuleTools.AfterFunction("LrDevelopController.getValue",
function(param)
return LrDevelopController.getValue(param)
end))),
increment =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.increment",
ModuleTools.AfterFunction("LrDevelopController.increment",
function(param)
LrDevelopController.increment(param)
end))),
resetAllDevelopAdjustments =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetAllDevelopAdjustments",
ModuleTools.AfterFunction("LrDevelopController.resetAllDevelopAdjustments",
function()
LrDevelopController.resetAllDevelopAdjustments()
end))),
resetBrushing =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetBrushing",
ModuleTools.AfterFunction("LrDevelopController.resetBrushing",
function()
LrDevelopController.resetBrushing()
end))),
resetCircularGradient =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetCircularGradient",
ModuleTools.AfterFunction("LrDevelopController.resetCircularGradient",
function()
LrDevelopController.resetCircularGradient()
end))),
resetCrop =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetCrop",
ModuleTools.AfterFunction("LrDevelopController.resetCrop",
function()
LrDevelopController.resetCrop()
end))),
resetGradient =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetGradient",
ModuleTools.AfterFunction("LrDevelopController.resetGradient",
function()
LrDevelopController.resetGradient()
end))),
resetRedEye =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetRedEye",
ModuleTools.AfterFunction("LrDevelopController.resetRedEye",
function()
LrDevelopController.resetRedEye()
end))),
resetSpotRemoval =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetSpotRemoval",
ModuleTools.AfterFunction("LrDevelopController.resetSpotRemoval",
function()
LrDevelopController.resetSpotRemoval()
end))),
resetToDefault =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.resetToDefault",
ModuleTools.AfterFunction("LrDevelopController.resetToDefault",
function(param)
LrDevelopController.resetToDefault(param)
end))),
revealAdjustedControls =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.revealAdjustedControls",
ModuleTools.AfterFunction("LrDevelopController.revealAdjustedControls",
function(reveal)
LrDevelopController.revealAdjustedControls(reveal)
end))),
revealPanel =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.revealPanel",
ModuleTools.AfterFunction("LrDevelopController.revealPanel",
function(param)
LrDevelopController.revealPanel(param)
end))),
selectTool =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.selectTool",
ModuleTools.AfterFunction("LrDevelopController.selectTool",
function(tool)
LrDevelopController.selectTool(tool)
end))),
setMultipleAdjustmentThreshold =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.setMultipleAdjustmentThreshold",
ModuleTools.AfterFunction("LrDevelopController.setMultipleAdjustmentThreshold",
function(seconds)
LrDevelopController.setMultipleAdjustmentThreshold(seconds)
end))),
setProcessVersion =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.setProcessVersion",
ModuleTools.AfterFunction("LrDevelopController.setProcessVersion",
function(version)
LrDevelopController.setProcessVersion(version)
end))),
setTrackingDelay =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.setTrackingDelay",
ModuleTools.AfterFunction("LrDevelopController.setTrackingDelay",
function(seconds)
LrDevelopController.setTrackingDelay(seconds)
end))),
setValue =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.setValue",
ModuleTools.AfterFunction("LrDevelopController.setValue",
function(param,value)
LrDevelopController.setValue(param,value)
end))),
startTracking =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.startTracking",
ModuleTools.AfterFunction("LrDevelopController.startTracking",
function(param)
LrDevelopController.startTracking(param)
end))),
stopTracking =
ModuleTools.RequireModule("develop",
ModuleTools.BeforeFunction("LrDevelopController.stopTracking",
ModuleTools.AfterFunction("LrDevelopController.stopTracking",
function()
LrDevelopController.stopTracking()
end))),
} | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Lower_Jeuno/npcs/_l08.lua | 7 | 2719 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @pos -44 0 -47 245
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/NPCIDs");
require("scripts/zones/Lower_Jeuno/TextIDs");
-- lamp id vary from 17780881 to 17780892
-- lamp cs vary from 0x0078 to 0x0083 (120 to 131)
local lampNum = 8;
local lampId = lampIdOffset + lampNum;
local cs = lampCsOffset + lampNum;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local playerOnQuest = GetServerVariable("[JEUNO]CommService");
-- player is on the quest
if playerOnQuest == player:getID() then
if hour >= 20 and hour < 21 then
player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock.
elseif hour >= 21 or hour < 1 then
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,2); -- The lamp is already lit.
else
player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No
end
else
player:startEvent(cs,3); -- You have failed to light the lamps in time.
end
-- player is not on the quest
else
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,5); -- The lamp is lit.
else
player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually.
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if csid == cs and option == 1 then
-- lamp is now lit
GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR);
-- tell player how many remain
local lampsRemaining = 12;
for i=0,11 do
local lamp = GetNPCByID(lampIdOffset + i);
if lamp:getAnimation() == ANIMATION_OPEN_DOOR then
lampsRemaining = lampsRemaining - 1;
end
end
player:messageSpecial(7241,lampsRemaining);
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Nyzul_Isle/mobs/Imperial_Gear.lua | 10 | 1851 | -----------------------------------
-- Area: Nyzul Isle (Path of Darkness)
-- MOB: Imperial Gear
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Nyzul_Isle/IDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
local instance = mob:getInstance();
local progress = instance:getProgress();
if (progress >= 24) then
local mobs = instance:getMobs();
for i,v in pairs(mobs) do
if (v:getID() == NyzulIsle.mobs[58].AMNAF_BLU) then
local pos = v:getPos();
if (mob:getID() == NyzulIsle.mobs[58].IMPERIAL_GEAR1) then
mob:setPos(pos.x+2,pos.y,pos.z,pos.rot);
elseif (mob:getID() == NyzulIsle.mobs[58].IMPERIAL_GEAR2) then
mob:setPos(pos.x,pos.y,pos.z+2,pos.rot);
elseif (mob:getID() == NyzulIsle.mobs[58].IMPERIAL_GEAR3) then
mob:setPos(pos.x-2,pos.y,pos.z,pos.rot);
elseif (mob:getID() == NyzulIsle.mobs[58].IMPERIAL_GEAR4) then
mob:setPos(pos.x,pos.y,pos.z-2,pos.rot);
end
end
end
end
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob,target)
local naja = mob:getInstance():getEntity(bit.band(NyzulIsle.mobs[58].NAJA, 0xFFF))
naja:setLocalVar("ready",1)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local instance = mob:getInstance();
instance:setProgress(instance:getProgress() + 1);
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
end;
| gpl-3.0 |
jbeich/Aquaria | files/scripts/entities/_unused/lumitebreeder.lua | 6 | 3488 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- L U M I T E
-- ================================================================================================
-- entity specific
local STATE_STUNNED = 1000
local STATE_GRABBED = 1001
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
function init()
setupBasicEntity(
"Lumite", -- texture
3, -- health
0, -- manaballamount
1, -- exp
0, -- money
16, -- collideRadius (only used if hit entities is on)
STATE_IDLE, -- initState
32, -- sprite width
32, -- sprite height
1, -- particle "explosion" type, maps to particleEffects.txt -1 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
5000, -- updateCull -1: disabled, default: 4000
2 -- layer 0: below avatar, 1: above avatar, 2: dark layer
)
entity_initPart("Glow", "lumite-glow", 0, 0, 1)
entity_partWidthHeight("Glow", 900, 900)
entity_partBlendType("Glow", 1)
end
function update(dt)
if entity_getState()==STATE_IDLE then
if not entity_hasTarget() then
entity_findTarget(800)
--entity_partAlpha("Glow", -1, 0, 0.1)
else
if not entity_isTargetInRange(300) then
entity_moveTowardsTarget(dt, 1000)
else
entity_moveTowardsTarget(dt, -1500)
end
--[[
dist = entity_getDistanceToTarget()
totalDist = 600
if dist > totalDist then
entity_partAlpha("Glow", -1, 0.1)
else
entity_partAlpha("Glow", -1, ((totalDist-dist)/totalDist)*0.5+0.1)
end
]]--
end
entity_doSpellAvoidance(dt, 200, 0.5)
entity_doCollisionAvoidance(dt, 5, 1)
entity_doEntityAvoidance(dt, 64, 0.5)
entity_updateMovement(dt)
if entity_getHealth() == 1 then
entity_setState(STATE_STUNNED)
end
entity_rotateToVel(0.1)
elseif entity_getState()==STATE_STUNNED then
entity_doFriction(dt, 400)
if entity_isTargetInRange(64) then
entity_setState(STATE_GRABBED)
end
end
end
function enterState()
if entity_getState()==STATE_IDLE then
entity_setMaxSpeed(500)
elseif entity_getState()==STATE_DEAD then
entity_partAlpha("Glow", -1, 0, 0.1)
elseif entity_getState()==STATE_GRABBED then
pickupItem("Lumite", 1)
--msg1("Naija: Got one!")
entity_partAlpha("Glow", -1, 0, 0.1)
entity_delete()
if getItem("Lumite")>=2 and getFlag("Q2")==0 and getFlag("Q2-intro")>0 then
setFlag("Q2", 1)
conversation("Q2-collectedLumites")
end
end
end
function exitState()
end
function hitSurface()
end | gpl-2.0 |
nyczducky/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Ragyaya.lua | 14 | 1056 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Ragyaya
-- Type: Standard NPC
-- @zone 94
-- @pos -95.376 -3 60.795
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0196);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/items/dish_of_spaghetti_pescatora_+1.lua | 12 | 1664 | -----------------------------------------
-- ID: 5200
-- Item: dish_of_spaghetti_pescatora_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health % 15
-- Health Cap 160
-- Vitality 3
-- Mind -1
-- Defense % 22
-- Defense Cap 70
-- Store TP 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5200);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 15);
target:addMod(MOD_FOOD_HP_CAP, 160);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_DEFP, 22);
target:addMod(MOD_FOOD_DEF_CAP, 70);
target:addMod(MOD_STORETP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 15);
target:delMod(MOD_FOOD_HP_CAP, 160);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_DEFP, 22);
target:delMod(MOD_FOOD_DEF_CAP, 70);
target:delMod(MOD_STORETP, 6);
end;
| gpl-3.0 |
wenhulove333/ScutServer | Sample/Koudai/Client/lua/datapool/Image.lua | 1 | 4398 |
------------------------------------------------------------------
-- Image.lua
-- Author :
-- Version : 1.15
-- Date :
-- Description: ͼƬ,
------------------------------------------------------------------
module("Image", package.seeall)--ͼƬ×ÊԴ·¾¶
------------------
image_toumingPath="common/ground_2018.9.png"--°ë͸Ã÷
image_npc_talk_toumingPath="common/list_5001.9.png"--npc¶Ô»°°ë͸Ã÷¿ò
image_close="button/list_1046.png"--¹Ø±Õ°´Å¥
image_background_sm="common/list_1002_1.9.png"--±³¾°Í¼
image_list_txt_2="common/list_1004.9.png"--Îı¾ÊäÈë¿òµ×ͼ
image_title_3="common/list_1007.9.png"--2¼¶½çÃæ±³¾°Í¼
image_taskBg = "common/List_2009_3.9.png"
image_button_jiantou="button/list_1081.png"--Ë«¼ýÍ·°´Å¥
image_top_button_0="common/list_1042.png"--¶¥²¿²Ëµ¥
image_top_button_1="common/list_1041.png"--¶¥²¿²Ëµ¥
image_LeftButtonNorPath="button/list_1069.png"--×ó°´Å¥
image_rightButtonNorPath="button/list_1068.png"--ÓÒ°´Å¥
image_button_password="button/main_3001_15.png"--ÃÜÂ벹ȫ°´Å¥
image_button_VIP="mainUI/bottom_1009.png"--VIP°´Å¥
image_down_button_="mainUI/menu_bottom_%d.png"--Ö÷½çÃæÓÒϽDz˵¥°´Å¥Í¼
----------------
image_main_1015_1="mainUI/main_1015_1.png"--ÐÞÁ¶Í¼
----------
image_hand_="mainUI/list_1029_%d.png"--³öÊÖ˳Ðòͼ
image_good_="smallitem/%s.png"--×°±¸
image_map_="map/%s.jpg"--³ÇÕòͼ
image_npc_="npc_talk/%s.png"--npc°ëÉíͼ
image_npc_head_title_="mainUI/%s.png"-- NPCÍ·¶¥Í¼±ê
image_man_stop="role/role_%d_stop.png"--Ö÷½Ç
image_man_run="role/role_%d_run.png"--Ö÷½Ç
image_man_head="headImg/%s.png"--Ó¶±øÍ·Ïñ
image_man_title_head_="headImg/%s.png"--Ö÷½ÇԲͷÏñ
-----------ÁÙʱͼƬ
image_man_title_head_0="headImg/man_000%s.png"--Ö÷½ÇԲͷÏñÄÐ
image_man_title_head_1="headImg/man_100%s.png"--Ö÷½ÇԲͷÏñÅ®
image_man_head_0="headImg/Figure_100%d_1.png"--ÄÐÖ÷½ÇÍ·Ïñ
image_man_head_1="headImg/Figure_200%d_1.png"--Å®Ö÷½ÇÍ·Ïñ Image.Figure_2003_1
image_head_00000000000="headImg/Figure_1001_1.png"--ÁÙʱͷÏñ Image.image_head_00000000000
image_map_00000000000="map/map_1002.jpg"--ÁÙʱ³¡¾°Í¼
image_mainscene = "common/list_1015.png"
---------------------¼ÙÊý¾Ý
imageToday = "mainUI/list_1024.png"
--------------------ÿÈÕ̽ÏÕ½çÃæ
---------------------±³¾°Í¼
---- ÊýÁ¿ÊäÈë¿òͼƬ
ImageBBackground = "Image/list_1002.png"
--¿Ú´üÌì½ç
image_exp_bar="mainUI/list_1003.png"
image_touxiang_beijing="common/list_1012.png"--Í·Ïñ±³¾°¿ò
image_top_line="mainUI/list_1022_1.png"--ÉϺáÏß
image_under_Line="mainUI/list_1022_2.png"--ϺáÏß
image_bg="imageupdate/default.png"--"Image/default.jpg"--·âÃæ±³¾°
-----------------------------------
image_tudi = "zhuanyuan/bottom_1015_6.png"
Huang_tudi = "zhuanyuan/bottom_1015_7.png"
image_zhuangyuan ="zhuanyuan/list_3001.jpg"
image_input_beijing="common/list_1049.9.png"
image_background="common/list_1076.png"--±³¾°Í¼
image_frontground="common/list_1074.png"--±³¾°Í¼
image_halfbackground="common/list_1024.png"--С±³¾°
image_close="button/list_1046.png"--¹Ø±Õ°´Å¥
image_button="button/list_1039.png"--ÂÌÉ«°´Å¥
image_list_txt="common/list_2004.9.png"--Îı¾ÊäÈë¿òµ×ͼ
image_blood="mainUI/list_1034.png"
image_power="mainUI/list_1034.png"
image_soul="mainUI/list_1034.png"
image_intellect="mainUI/list_1034.png"
image_good_beijing="common/list_1012.png"--ÎïÆ·À¸±³¾°Í¼
image_zhenfa_beijing="common/list_1012.png"--Õ󷨱³¾°
image_TodayToScene_buttonRed = "button/list_1083_1.png" ----- ºìÉ«µÄͼƬ
image_TodayToScene_buttonGray = "button/list_1083_2.png" ----»ÒÉ«µÄͼƬ
image_transparent="common/tou_ming.9.png"--ȫ͸Ã÷
image_button_hook_0="button/list_1044.png"--´ò¹³±ê¼ÇÎÞ
image_button_hook_1="button/list_1045.png"--´ò¹³±ê¼Ç
image_logo="mainUI/list_1169.png"--"Image/logo.png"--logo
-----Ë;«Á¦µÄ±³¾°
image_bgSendImg = "activeBg/list_1087.png"
image_loveHert = "common/list_1086.png"
image_BIG = "common/list_1076.png"
image_BIGBorder = "common/list_1074.png"
ImageBackground = "common/list_1024.png"
image_lock = "common/list_1016.png"
Image_choicebox="common/list_1173.png"--Ñ¡Ôñ¿ò
Image_moreChoiceButton = "button/list_1166.png"--¶àÕ˺ÅÑ¡Ôñ°´Å¥
Image_normalItemBg="common/icon_8015_3.png"
image_button_red_c_0="button/bottom_1002_2.9.png"--ºìÉ«³¤°´Å¥
image_button_red_c_1="button/bottom_1002_1.9.png"--ºìÉ«³¤°´Å¥
image_button_hui_c="button/bottom_1002_3.9.png"--»ÒÉ«³¤°´Å¥
| mit |
nyczducky/darkstar | scripts/zones/Southern_San_dOria/npcs/Kueh_Igunahmori.lua | 14 | 1252 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Kueh Igunahmori
-- Guild Merchant NPC: Leathercrafting Guild
-- @pos -194.791 -8.800 13.130 230
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(529,3,18,4)) then
player:showText(npc,KUEH_IGUNAHMORI_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jakianroy/NGUI_To_Be_Best | Assets/LuaFramework/Lua/3rd/cjson/util.lua | 170 | 6837 | local json = require "cjson"
-- Various common routines used by the Lua CJSON package
--
-- Mark Pulford <mark@kyne.com.au>
-- Determine with a Lua table can be treated as an array.
-- Explicitly returns "not an array" for very sparse arrays.
-- Returns:
-- -1 Not an array
-- 0 Empty table
-- >0 Highest index in the array
local function is_array(table)
local max = 0
local count = 0
for k, v in pairs(table) do
if type(k) == "number" then
if k > max then max = k end
count = count + 1
else
return -1
end
end
if max > count * 2 then
return -1
end
return max
end
local serialise_value
local function serialise_table(value, indent, depth)
local spacing, spacing2, indent2
if indent then
spacing = "\n" .. indent
spacing2 = spacing .. " "
indent2 = indent .. " "
else
spacing, spacing2, indent2 = " ", " ", false
end
depth = depth + 1
if depth > 50 then
return "Cannot serialise any further: too many nested tables"
end
local max = is_array(value)
local comma = false
local fragment = { "{" .. spacing2 }
if max > 0 then
-- Serialise array
for i = 1, max do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment, serialise_value(value[i], indent2, depth))
comma = true
end
elseif max < 0 then
-- Serialise table
for k, v in pairs(value) do
if comma then
table.insert(fragment, "," .. spacing2)
end
table.insert(fragment,
("[%s] = %s"):format(serialise_value(k, indent2, depth),
serialise_value(v, indent2, depth)))
comma = true
end
end
table.insert(fragment, spacing .. "}")
return table.concat(fragment)
end
function serialise_value(value, indent, depth)
if indent == nil then indent = "" end
if depth == nil then depth = 0 end
if value == json.null then
return "json.null"
elseif type(value) == "string" then
return ("%q"):format(value)
elseif type(value) == "nil" or type(value) == "number" or
type(value) == "boolean" then
return tostring(value)
elseif type(value) == "table" then
return serialise_table(value, indent, depth)
else
return "\"<" .. type(value) .. ">\""
end
end
local function file_load(filename)
local file
if filename == nil then
file = io.stdin
else
local err
file, err = io.open(filename, "rb")
if file == nil then
error(("Unable to read '%s': %s"):format(filename, err))
end
end
local data = file:read("*a")
if filename ~= nil then
file:close()
end
if data == nil then
error("Failed to read " .. filename)
end
return data
end
local function file_save(filename, data)
local file
if filename == nil then
file = io.stdout
else
local err
file, err = io.open(filename, "wb")
if file == nil then
error(("Unable to write '%s': %s"):format(filename, err))
end
end
file:write(data)
if filename ~= nil then
file:close()
end
end
local function compare_values(val1, val2)
local type1 = type(val1)
local type2 = type(val2)
if type1 ~= type2 then
return false
end
-- Check for NaN
if type1 == "number" and val1 ~= val1 and val2 ~= val2 then
return true
end
if type1 ~= "table" then
return val1 == val2
end
-- check_keys stores all the keys that must be checked in val2
local check_keys = {}
for k, _ in pairs(val1) do
check_keys[k] = true
end
for k, v in pairs(val2) do
if not check_keys[k] then
return false
end
if not compare_values(val1[k], val2[k]) then
return false
end
check_keys[k] = nil
end
for k, _ in pairs(check_keys) do
-- Not the same if any keys from val1 were not found in val2
return false
end
return true
end
local test_count_pass = 0
local test_count_total = 0
local function run_test_summary()
return test_count_pass, test_count_total
end
local function run_test(testname, func, input, should_work, output)
local function status_line(name, status, value)
local statusmap = { [true] = ":success", [false] = ":error" }
if status ~= nil then
name = name .. statusmap[status]
end
print(("[%s] %s"):format(name, serialise_value(value, false)))
end
local result = { pcall(func, unpack(input)) }
local success = table.remove(result, 1)
local correct = false
if success == should_work and compare_values(result, output) then
correct = true
test_count_pass = test_count_pass + 1
end
test_count_total = test_count_total + 1
local teststatus = { [true] = "PASS", [false] = "FAIL" }
print(("==> Test [%d] %s: %s"):format(test_count_total, testname,
teststatus[correct]))
status_line("Input", nil, input)
if not correct then
status_line("Expected", should_work, output)
end
status_line("Received", success, result)
print()
return correct, result
end
local function run_test_group(tests)
local function run_helper(name, func, input)
if type(name) == "string" and #name > 0 then
print("==> " .. name)
end
-- Not a protected call, these functions should never generate errors.
func(unpack(input or {}))
print()
end
for _, v in ipairs(tests) do
-- Run the helper if "should_work" is missing
if v[4] == nil then
run_helper(unpack(v))
else
run_test(unpack(v))
end
end
end
-- Run a Lua script in a separate environment
local function run_script(script, env)
local env = env or {}
local func
-- Use setfenv() if it exists, otherwise assume Lua 5.2 load() exists
if _G.setfenv then
func = loadstring(script)
if func then
setfenv(func, env)
end
else
func = load(script, nil, nil, env)
end
if func == nil then
error("Invalid syntax.")
end
func()
return env
end
-- Export functions
return {
serialise_value = serialise_value,
file_load = file_load,
file_save = file_save,
compare_values = compare_values,
run_test_summary = run_test_summary,
run_test = run_test,
run_test_group = run_test_group,
run_script = run_script
}
-- vi:ai et sw=4 ts=4:
| gpl-3.0 |
zeuosagenti/zeuosagenti | plugins/help.lua | 1 | 4710 | do
function run(msg, matches)
local mods = [[
راهنما فارسی مدیران :
@telemanager_ch
!kick [Username | ID | Reply]
!ban [username | ID | Reply]
!unban [Username | ID | Reply]
!banlist
!id [Username | Id | Reply]
!res @username
!res [Reply]
!lock [ads | name | tag | leave | badw | member | chat | farsi | bots]
!unlock [ads | name | tag | leave | badw | member | chat | farsi | bots]
!all
!addsudo
!set[photo | name]
!set [rules | about]
!tagall [MSG]
!who
!filter [+-?] [word]
!set [value] [MSG]
!info [Username | ID | Reply]
!plugins [-+] (Plug Name) chat
==========================
به علاوه تمامی دستورات رنک :
member
==========================
جهت دریافت راهنمای رنک های دیگر میتوانید از دستورات زیر استفاده کنید :
!help owner
راهنمای صاحبان
!help mod
راهنمای مدیران
!help member
راهنمای اعضای معمولی
]]
local admin = [[
راهنمای فارسی ادمین ها :
@telemanager_ch
!banall [Reply | ID | Username]
!unbanall [ID]
!add
!rem
!leave
!setowner [ID | Reply]
!kill chat [ID]
!bc [GP-ID] [MSG]
!all [GP-ID]
==========================
به علاوه تمامی دستورات رنک های :
owner
و
mod
و
member
==========================
جهت دریافت راهنمای رنک های دیگر میتوانید از دستورات زیر استفاده کنید :
!help owner
راهنمای صاحبان
!help mod
راهنمای مدیران
!help member
راهنمای اعضای معمولی
]]
local owner = [[
راهنمای فارسی صاحبان گروه :
@telemanager_ch
!promote [Reply | ID | Username]
!demote [Reply | ID | Username]
!setowner [ID | Reply]
!addsudo
!setrank [Reply | ID | Username]
==========================
به علاوه تمامی دستورات رنک های :
mod
و
member
==========================
جهت دریافت راهنمای رنک های دیگر میتوانید از دستورات زیر استفاده کنید :
!help owner
راهنمای صاحبان
!help mod
راهنمای مدیران
!help member
راهنمای اعضای معمولی
]]
local member = [[
راهنمای فارسی عضو ها :
@telemanager_ch
!calc [formula]
!get [Value]
!filterlist
!info
!id
!me
!voice [MSG]
!time
!time [Area]
!tex [Msg]
!feedback [msg]
!share
!telemanagerplus
!sticker [TXT]
==========================
جهت دریافت راهنمای رنک های دیگر میتوانید از دستورات زیر استفاده کنید :
!help owner
راهنمای صاحبان
!help mod
راهنمای مدیران
!help member
راهنمای اعضای معمولی
]]
local sudo = [[
راهنما فارسی سودو ها :
@telemanager_ch
!addadmin [ID | Username]
!removeadmin [ID | Username]
!creategroup [Name]
!up [Name.format] [Text]
!dl [name.format]
!echo> [name.format] [Text]
!invite [Username | ID | Reply]
!stats bot
!plugins
!plugins [+-] [Plugname]
!reload
==========================
به علاوه دسترسی به تمامی دستورات رنک های دیگر
==========================
جهت دریافت راهنمای رنک های دیگر میتوانید از دستورات زیر استفاده کنید :
!help owner
راهنمای صاحبان
!help mod
راهنمای مدیران
!help member
راهنمای اعضای معمولی
]]
if msg.to.type == 'chat' and matches[1]:lower() == 'help' and matches[2] == nil then
if is_sudo(msg) then
return sudo
elseif is_admin(msg) then
return admin
elseif is_owner(msg) then
return owner
elseif is_momod(msg) then
return mods
else
return member
end
end
if msg.to.type == 'chat' and matches[1]:lower() == 'help' and matches[2]:lower() == 'owner' then
if is_owner(msg) then
return owner
else return 'Only Admins or higher can See this !'
end
end
if msg.to.type == 'chat' and matches[1]:lower() == 'help' and matches[2]:lower() == 'mod' then
if is_momod(msg) then
return mods
else return 'only Owners Or higher Can See this !'
end
end
if msg.to.type == 'chat' and matches[1]:lower() == 'help' and matches[2]:lower() == 'member' then
return member
end
end
return {
patterns = {
"^!(help)$",
"^([Hh]elp)$",
"^/(help)$",
"^!(help) (mod)$",
"^!(help) (owner)$",
"^!(help) (member)$",
},
run = run
}
end
| gpl-2.0 |
weissj3/milkywayathome_client | separation/tests/SeparationTests.lua | 4 | 6702 | --
-- Copyright (C) 2011 Matthew Arsenault
--
-- This file is part of Milkway@Home.
--
-- Milkyway@Home 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 3 of the License, or
-- (at your option) any later version.
--
-- Milkyway@Home 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 Milkyway@Home. If not, see <http://www.gnu.org/licenses/>.
--
require "ResultSets"
argv = {...}
binName = argv[1]
testDir = argv[2]
extraFlags = argv[3] -- Extra flags to pass, such as choosing which SSE path to use
testName = argv[4]
assert(binName, "Binary name not set")
function os.readProcess(bin, ...)
local args, cmd
args = table.concat({...}, " ")
-- Redirect stderr to stdout, since popen only gets stdout
cmd = table.concat({ bin, args, "2>&1" }, " ")
local f = assert(io.popen(cmd, "r"))
local s = assert(f:read('*a'))
f:close()
return s
end
-- Find numbers in between xml tags called tagName
function findResults(str, tagName)
assert(str, "Expected string to search for results")
assert(tagName, "Expected tagName")
local _, innerTag = str:match("<" .. tagName .. "%s*(.-)>(.-)</" .. tagName .. ">")
local i, results = 1, { }
assert(innerTag ~= nil, "Expected to find tag " .. innerTag)
for num in innerTag:gmatch("[+-]?%d+[.]?%d+e?[+-]?%d+%s+") do
results[i] = tonumber(num)
i = i + 1
end
return results
end
-- Find the expected results from the printed output
function findSeparationResults(str)
local bgInt, stInt, bgLike, stLike, searchLike
local results = { }
bgInt = findResults(str, "background_integral")
stInt = findResults(str, "stream_integral")
bgLike = findResults(str, "background_likelihood")
stLike = findResults(str, "stream_only_likelihood")
searchLike = findResults(str, "search_likelihood")
assert(#bgInt == 1, "Expected to find one background_integral")
assert(#bgLike == 1, "Expected to find one background_only_likelihood")
assert(#searchLike == 1, "Expected to find one search_likelihood")
results.background_integral = bgInt[1]
results.stream_integral = stInt
results.background_likelihood = bgLike[1]
results.stream_only_likelihood = stLike
results.search_likelihood = searchLike[1]
return results
end
function resultCloseEnough(a, b)
return math.abs(a - b) < 1.0e-12
end
local errFmtStr = [[
Result '%s' differs from expected:
Actual = %20.15f Expected = %20.15f |Difference| = %20.15f
]]
function checkSeparationResults(results, reference)
local function compareField(name)
local closeEnough
assert(results[name] ~= nil, string.format("Field '%s' not set for results", name))
assert(reference[name] ~= nil, string.format("Field '%s' not set for reference", name))
local resultField, refField = results[name], reference[name]
assert(type(resultField) == type(refField), "Expected results and reference to be the same type")
if type(refField) == "table" then
closeEnough = true
local closeTmp
assert(#resultField == #refField and #resultField > 0, "Expected reference result table to have same > 0 size")
-- Report all of the items which don't match rather than stopping on the first
for i = 1, #refField do
closeTmp = resultCloseEnough(resultField[i], refField[i])
if not closeTmp then
io.stderr:write(string.format(errFmtStr,
string.format("%s\[%d\]", name, i - 1),
resultField[i],
refField[i],
math.abs(resultField[i] - refField[i])
)
)
end
closeEnough = closeEnough and closeTmp
end
elseif type(refField) == "number" then
closeEnough = resultCloseEnough(results[name], reference[name])
if not closeEnough then
io.stderr:write(
string.format(errFmtStr,
name,
results[name],
reference[name],
math.abs(reference[name] - results[name]))
)
end
else
error("Result must be a number or table of numbers")
end
return closeEnough
end
-- and with correct second to avoid short circuiting
local correct = true
correct = compareField("background_integral") and correct
correct = compareField("stream_integral") and correct
correct = compareField("background_likelihood") and correct
correct = compareField("stream_only_likelihood") and correct
correct = compareField("search_likelihood") and correct
return correct
end
function runTest(test, checkResults)
assert(test, "No test found!")
local output
local path = testDir .. "/" .. test.file
local starsPath = testDir .. "/" .. test.stars
if test.parameters ~= nil then
output = os.readProcess(binName,
extraFlags,
"-i", -- FIXME: Avoid stale checkpoints a better way?
"-g",
"-a", path,
"-s", starsPath,
"-np", #test.parameters,
"-p", table.concat(test.parameters, " ")
)
else
output = os.readProcess(binName, extraFlags, "-i", "-g", "-a", path, "-s", starsPath)
end
print(output)
-- If we aren't checking the reference results, then just print the
-- output of the process.
if not checkResults then
return false
end
local results = findSeparationResults(output)
assert(results ~= nil, "Results missing from output?")
local check = checkSeparationResults(results, test.results)
return check
end
rc = 0
for name, test in pairs(testSet) do
io.stdout:write(string.rep("-", 80) .. "\n")
io.stdout:write(string.format("Beginning test %s:\n\n", name))
if runTest(test, false) then
rc = 1
end
io.stdout:write(string.format("Test %s completed:\n", name))
io.stdout:write(string.rep("-", 80) .. "\n")
end
os.exit(rc)
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle.lua | 28 | 1049 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle1.lua | 28 | 1049 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
abeschneider/nn | View.lua | 41 | 2232 | local View, parent = torch.class('nn.View', 'nn.Module')
function View:__init(...)
parent.__init(self)
if select('#', ...) == 1 and torch.typename(select(1, ...)) == 'torch.LongStorage' then
self.size = select(1, ...)
else
self.size = torch.LongStorage({...})
end
self.numElements = 1
local inferdim = false
for i = 1,#self.size do
local szi = self.size[i]
if szi >= 0 then
self.numElements = self.numElements * self.size[i]
else
assert(szi == -1, 'size should be positive or -1')
assert(not inferdim, 'only one dimension can be at -1')
inferdim = true
end
end
self.output = nil
self.gradInput = nil
self.numInputDims = nil
end
function View:setNumInputDims(numInputDims)
self.numInputDims = numInputDims
return self
end
local function batchsize(input, size, numInputDims, numElements)
local ind = input:nDimension()
local isz = input:size()
local maxdim = numInputDims and numInputDims or ind
local ine = 1
for i=ind,ind-maxdim+1,-1 do
ine = ine * isz[i]
end
if ine % numElements ~= 0 then
error(string.format(
'input view (%s) and desired view (%s) do not match',
table.concat(input:size():totable(), 'x'),
table.concat(size:totable(), 'x')))
end
-- the remainder is either the batch...
local bsz = ine / numElements
-- ... or the missing size dim
for i=1,size:size() do
if size[i] == -1 then
bsz = 1
break
end
end
-- for dim over maxdim, it is definitively the batch
for i=ind-maxdim,1,-1 do
bsz = bsz * isz[i]
end
-- special card
if bsz == 1 and (not numInputDims or input:nDimension() <= numInputDims) then
return
end
return bsz
end
function View:updateOutput(input)
local bsz = batchsize(input, self.size, self.numInputDims, self.numElements)
if bsz then
self.output = input:view(bsz, table.unpack(self.size:totable()))
else
self.output = input:view(self.size)
end
return self.output
end
function View:updateGradInput(input, gradOutput)
self.gradInput = gradOutput:view(input:size())
return self.gradInput
end
| bsd-3-clause |
wenhulove333/ScutServer | Sample/Koudai/Client/lua/scenes/ActiveTopUpScene.lua | 1 | 6744 | ------------------------------------------------------------------
-- ActiveTopUpScene.lua.lua
-- Author : yeyq
-- Version : 1.0
-- Date :
-- Description: Ê׳佱Àø½çÃæ
------------------------------------------------------------------
module("ActiveTopUpScene", package.seeall)
-- ³¡¾°ÖÐÓõ½µÄ³ÉÔ±±äÁ¿ÒªÔÚÎļþÍ·²¿ÏÈÉêÃ÷£¬²¢¸½¼Ó±ØÒªµÄ˵Ã÷
-- ³ÉÔ±±äÁ¿Í³Ò»ÒÔÏ»®Ïß¿ªÊ¼£¬½ô½ÓµÄÊ××ÖĸҪСд
local g_scene = nil -- ³¡¾°
local g_imgTabel = {}
local g_mListColWidth = nil
local choiceLayer = nil
local g_LayerBG = nil
--
---------------¹«ÓнӿÚ(ÒÔÏÂÁ½¸öº¯Êý¹Ì¶¨²»Óøıä)--------
function setData(info)
g_DataInfo = info
end;
--
-- º¯ÊýÃûÒÔСд×Öĸ¿ªÊ¼£¬Ã¿¸öº¯Êý¶¼Ó¦×¢ÊÍ
-- ³¡¾°Èë¿Ú
function pushScene()
initResource()
createScene()
--- CCDirector:sharedDirector():pushScene(_scene)
end
-- Í˳ö³¡¾°
function popScene()
releaseResource()
-- CCDirector:sharedDirector():popScene()
end
--
-------------------------˽ÓнӿÚ------------------------
--
-- ³õʼ»¯×ÊÔ´¡¢³ÉÔ±±äÁ¿
function initResource()
g_scene = nil -- ³¡¾°
g_imgTabel = {}
g_mListColWidth = nil
choiceLayer = nil
end
-- ÊÍ·Å×ÊÔ´
function releaseResource()
closeAction()
g_scene = nil -- ³¡¾°
g_imgTabel = {}
g_mListColWidth = nil
choiceLayer = nil
g_gainButton=nil
g_DataInfo=nil
end
-- ´´½¨³¡¾°
function init(mScene,mLayer)
g_scene = mScene
-- ×¢²áÍøÂç»Øµ÷
-- Ìí¼Ó±³¾°
g_LayerBG = CCLayer:create()
mLayer:addChild(g_LayerBG,1)
-- ×¢²á´¥ÆÁʼþ
-- g_LayerBG.__CCTouchDelegate__:registerScriptTouchHandler(CCTOUCHBEGAN, "ActiveTopUpScene.touchBegan")
-- g_LayerBG.__CCTouchDelegate__:registerScriptTouchHandler(CCTOUCHMOVED, "ActiveTopUpScene.touchMove")
-- g_LayerBG.__CCTouchDelegate__:registerScriptTouchHandler(CCTOUCHENDED, "ActiveTopUpScene.touchEnd")
local tBgImg = CCSprite:create(P("common/list_1038.9.png"))
tBgImg:setScaleX(pWinSize.width*0.92/tBgImg:getContentSize().width)
tBgImg:setScaleY(pWinSize.height*0.6/tBgImg:getContentSize().height)
tBgImg:setAnchorPoint(PT(0.5,0))
tBgImg:setPosition(PT(pWinSize.width*0.5,pWinSize.height-pWinSize.height*0.6-SY(32)))
g_LayerBG:addChild(tBgImg,0)
local titleImg = CCSprite:create(P("title/list_1149.png"))
titleImg:setAnchorPoint(PT(0.5,0))
titleImg:setPosition(PT(pWinSize.width*0.5,pWinSize.height*0.75))
g_LayerBG:addChild(titleImg,0)
local contentWidth = pWinSize.width*0.8
local contentSize = SZ(pWinSize.width*0.8,pWinSize.height*0.3)
local topUpStr = ZyMultiLabel:new(Language.ACTIVE_TOPUPSTR,contentWidth,FONT_NAME,FONT_SM_SIZE,nil,nil)
topUpStr:setAnchorPoint(PT(0,0))
topUpStr:setPosition(PT((pWinSize.width-contentWidth)/2,titleImg:getPosition().y-SY(30)))
topUpStr:addto(g_LayerBG,0)
local m_showChoice_Height = pWinSize.height* 0.2
local m_showChoice_StartY = (topUpStr:getPosition().y-tBgImg:getPosition().y-m_showChoice_Height)/2+tBgImg:getPosition().y
local brImg = CCSprite:create(P("common/list_1052.9.png"))
brImg:setScaleY(m_showChoice_Height/brImg:getContentSize().height)
brImg:setAnchorPoint(PT(0.5,0))
brImg:setPosition(PT(pWinSize.width*0.5,m_showChoice_StartY))
g_LayerBG:addChild(brImg,0)
local col=4
local listSize=SZ(brImg:getContentSize().width*0.96,pWinSize.height*0.2)
g_mListColWidth= listSize.width/col
local list = ScutCxList:node(g_mListColWidth, ccc4(24, 24, 24, 0), listSize)
list:setAnchorPoint(PT(0,0))
list:setHorizontal(true)
list:setTouchEnabled(true)
list:setPosition(PT(brImg:getPosition().x-listSize.width/2+SX(1),brImg:getPosition().y))
g_LayerBG:addChild(list,1)
mList=list
--ÁìÈ¡°´Å¥
local gainButton=ZyButton:new(Image.image_button_red_c_0, Image.image_button_red_c_1, Image.image_button_hui_c, Language.ACTIVE_BUTTONSTR2)
gainButton:setAnchorPoint(PT(0.5,0.5))
gainButton:setPosition(PT(pWinSize.width*0.5,m_showChoice_StartY-SY(37)))
gainButton:addto(g_LayerBG,0)
gainButton:registerScriptHandler(gotoAction)
gainButton:setEnabled(false)
--
g_gainButton = gainButton
actionLayer.Action9006(g_scene, false)
end
function gotoAction()
actionLayer.Action3014(g_scene, nil, g_DataInfo.FestivalID )
end
function closeAction()
if choiceLayer ~= nil then
choiceLayer:getParent():removeChild(choiceLayer,true)
choiceLayer = nil
end
if g_LayerBG ~= nil then
g_LayerBG:getParent():removeChild(g_LayerBG,true)
g_LayerBG = nil
end
end
---
function showListImg(table)
local layout = CxLayout()
layout.val_x.t = ABS_WITH_PIXEL
layout.val_y.t = ABS_WITH_PIXEL
layout.val_x.val.pixel_val = 0
layout.val_y.val.pixel_val = 0
for k, v in pairs(table) do
v.HeadID=v.HeadID or "icon_4109"
local picPath=string.format("smallitem/%s.png",v.HeadID)
local name =v.ItemName or Language.DAILY_REWARDTYPE_[v.Type]
--1 ½ð±Ò 2 ÉùÍû 3 ÔÄÀú 4 ¾«Á¦ 5 ¾Ñé 6 ¾§Ê¯ 7 ÎïÆ·
local picPathTable={
[1]="smallitem/icon_8012.png",
[3]="smallitem/icon_8011.png",
[4]="smallitem/icon_4094.png",
[6]="smallitem/icon_8010.png",
}
picPath=picPathTable[v.Type] or picPath
local listItem = ScutCxListItem:itemWithColor(ccc3(24,24,24))
listItem:setOpacity(0)
local itemLayer = createImg(picPath,name,v.Num,k)
listItem:addChildItem(itemLayer, layout)
mList:addListItem(listItem, false)
end
if g_DataInfo and g_DataInfo.IsReceive == 1 then
g_gainButton:setEnabled(true)
end
end
--
function createImg(img,str,num,k)
local layer = CCLayer:create()
local itemColW=mList:getRowWidth()
local itemHeight=mList:getContentSize().height
local bgSmallImg = CCSprite:create(P(Image.Image_normalItemBg))
bgSmallImg:setAnchorPoint(PT(0.5,0))
bgSmallImg:setPosition(PT(g_mListColWidth/2,
(itemHeight-bgSmallImg:getContentSize().height)/2))
layer:addChild(bgSmallImg,0)
local smallImg = CCSprite:create(P(img))
smallImg:setAnchorPoint(PT(0.5, 0.5))
smallImg:setPosition(PT(bgSmallImg:getContentSize().width/2,
bgSmallImg:getContentSize().height/2))
bgSmallImg:addChild(smallImg,0)
local imgStr=CCLabelTTF:create(str.. "*" .. num,FONT_NAME,FONT_FM_SIZE)
imgStr:setAnchorPoint(PT(0.5,0))
imgStr:setPosition(PT(bgSmallImg:getContentSize().width/2,-imgStr:getContentSize().height))
bgSmallImg:addChild(imgStr,0)
return layer
end
-- ÍøÂç»Øµ÷
function networkCallback(pScutScene, lpExternalData)
local actionID = ZyReader:getActionID()
if actionID == 9006 then
local serverInfo = actionLayer._9006Callback(pScutScene, lpExternalData)
if serverInfo ~= nil and serverInfo ~= "" then
local info = serverInfo
showListImg(info)
end
end
end
| mit |
nyczducky/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/HomePoint#1.lua | 27 | 1295 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: HomePoint#1
-- @pos -21.129 0.001 -20.944 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 65);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
masterfeizz/EDuke3D | source/lunatic/engine_maptext.lua | 1 | 14564 | -- MAPTEXT
-- Lunatic: routines for reading and writing map-text.
local ffi = require("ffi")
local ffiC = ffi.C
local assert = assert
local loadstring = loadstring
local pairs = pairs
local pcall = pcall
local print = print
local setfenv = setfenv
local tonumber = tonumber
local type = type
local readintostr = assert(string.readintostr)
local io = require("io")
local string = require("string")
ffi.cdef[[
int32_t (*saveboard_maptext)(const char *filename, const vec3_t *dapos, int16_t daang, int16_t dacursectnum);
int32_t (*loadboard_maptext)(int32_t fil, vec3_t *dapos, int16_t *daang, int16_t *dacursectnum);
]]
--== COMMON ==--
local sector_members = {
-- Mandatory positional members first, [pos]=<name>.
"ceilingz", "floorz",
"ceilingpicnum", "floorpicnum",
"ceilingshade", "floorshade";
-- If other positional members are to be added, they must be optional
-- for backwards compatibility.
-- Optional key/value members next.
B = { "ceilingbunch", -1 }, b = { "floorbunch", -1 }, -- default: -1
F = "ceilingstat", f = "floorstat", -- default: 0
H = "ceilingheinum", h = "floorheinum",
P = "ceilingpal", p = "floorpal",
X = "ceilingxpanning", x = "floorxpanning",
Y = "ceilingypanning", y = "floorypanning",
v = "visibility",
_ = "fogpal",
o = "lotag", i = "hitag", e = { "extra", -1 }
}
-- Defines the order in which the members are written out. A space denotes that
-- a newline should appear in the output. KEEPINSYNC with sector_members.
local sector_ord = { mand="12 34 56 ", opt="Bb Ff Hh Pp Xx Yy v _ oie" }
-- KEEPINSYNC with sector_members.
local sector_default = ffi.new("const sectortype", { ceilingbunch=-1, floorbunch=-1, extra=-1 })
local wall_members = {
-- mandatory
"point2", -- special: 0, 1 or 2 in map-text
"x", "y",
"nextwall",
"picnum",
"shade",
"xrepeat", "yrepeat",
"xpanning", "ypanning";
-- optional
f = "cstat",
m = "overpicnum", b = "blend",
p = "pal",
w = { "upwall", -1 }, W = { "dnwall", -1 },
o = "lotag", i = "hitag", e = { "extra", -1 }
}
local wall_ord = { mand="1 23 4 5 6 78 90 ", opt="f mb p wW oie" }
local wall_default = ffi.new("const walltype", { extra = -1, upwall=-1, dnwall=-1 })
local sprite_members = {
-- mandatory
"x", "y", "z",
"ang",
"sectnum",
"picnum",
"cstat",
"shade",
"xrepeat", "yrepeat",
-- optional
p = "pal",
c = { "clipdist", 32 },
b = "blend",
x = "xoffset", y = "yoffset",
s = "statnum",
w = { "owner", -1 },
X = "xvel", Y = "yvel", Z = "zvel",
o = "lotag", i = "hitag", e = { "extra", -1 }
}
local sprite_ord = { mand="123 4 5 6 7 8 90 ", opt="p c b xy s w XYZ oie" }
local sprite_default = ffi.new("const spritetype", { clipdist=32, owner=-1, extra=-1 })
--== SAVING ==--
local function write_struct(f, struct, members, ord)
-- Write mandatory members first.
local str = ord.mand:gsub(".",
function(s)
local num = (s=="0") and 10 or tonumber(s)
return (s==" ") and "\n" or (struct[members[num]]..",")
end)
f:write("{"..str)
local havesth = false
-- Write optional members next.
str = ord.opt:gsub(".",
function(s)
if (s==" ") then
local ohavesth = havesth
havesth = false
return ohavesth and "\n" or ""
end
local memb = members[s]
local mname = (type(memb)=="table") and memb[1] or memb
local mdefault = (type(memb)=="table") and memb[2] or 0
local val = struct[mname]
if (val~=mdefault) then
havesth = true
return s.."="..val..","
else
return ""
end
end)
local neednl = (#str>0 and str:sub(-1)~="\n")
f:write(str..(neednl and "\n" or "").."},\n")
end
-- common
local function check_bad_point2()
local lastloopstart = 0
for i=0,ffiC.numwalls-1 do
local p2 = ffiC.wall[i].point2
if (not (p2 == i+1 or (p2 ~= i and p2 == lastloopstart))) then
-- If we hit this, the map is seriously corrupted!
print(string.format("INTERNAL ERROR: wall[%d].point2=%d invalid", i, p2))
return true
end
if (p2 ~= i+1) then
lastloopstart = i+1
end
end
end
local function lastwallofsect(s)
return ffiC.sector[s].wallptr + ffiC.sector[s].wallnum - 1
end
-- In map-text, instead of saving wall[].point2, we store whether a particular
-- wall is the last one in its loop instead: the on-disk wall[i].point2 is
-- * 2 if wall i is last of its sector (no need to save sector's .wallnum),
-- * 1 if wall i is last of its loop,
-- * 0 otherwise.
-- This function prepares saving to map-text by tweaking the wall[].point2
-- members in-place.
local function save_tweak_point2()
-- Check first.
if (check_bad_point2()) then
return true
end
-- Do it for real.
local lastloopstart = 0
local cursect, curlastwall = 0, lastwallofsect(0)
for i=0,ffiC.numwalls-1 do
local wal = ffiC.wall[i]
if (wal.point2 == i+1) then
wal.point2 = 0
else
-- Wall i is last point in loop.
if (i==curlastwall) then
-- ... and also last wall of sector.
cursect = cursect+1
curlastwall = lastwallofsect(cursect)
wal.point2 = 2
else
wal.point2 = 1
end
lastloopstart = i+1
end
end
end
-- Common: restore tweaked point2 members to actual wall indices.
-- If <alsosectorp> is true, also set sector's .wallptr and .wallnum members.
local function restore_point2(alsosectorp)
local lastloopstart = 0
local cursect, curfirstwall = 0, 0
for i=0,ffiC.numwalls-1 do
local wal = ffiC.wall[i]
local islast = (wal.point2~=0)
if (not islast) then
wal.point2 = i+1
else
-- Wall i is last point in loop.
if (alsosectorp and wal.point2 == 2) then
-- ... and also last wall of sector.
if (cursect==ffiC.MAXSECTORS) then
return true -- Too many sectors.
end
ffiC.sector[cursect].wallptr = curfirstwall
ffiC.sector[cursect].wallnum = i-curfirstwall+1
cursect = cursect+1
curfirstwall = i+1
end
wal.point2 = lastloopstart
lastloopstart = i+1
end
end
end
local function saveboard_maptext(filename, pos, ang, cursectnum)
assert(ffiC.numsectors > 0)
-- First, temporarily tweak wall[].point2.
if (save_tweak_point2()) then
return -1
end
-- We open in binary mode so that newlines get written out as one byte even
-- on Windows.
local f, msg = io.open(ffi.string(filename), "wb")
if (f == nil) then
print(string.format("Couldn't open \"%s\" for writing: %s\n", filename, msg))
restore_point2(false)
return -1
end
-- Write header.
f:write(string.format("--EDuke32 map\n"..
"return {\n"..
"version=10,\n\n"..
"pos={%d,%d,%d},\n"..
"sectnum=%d,\n"..
"ang=%d,\n\n",
pos.x, pos.y, pos.z,
cursectnum,
ang))
-- Sectors.
f:write("sector={\n")
for i=0,ffiC.numsectors-1 do
write_struct(f, ffiC.sector[i], sector_members, sector_ord)
end
f:write("},\n\n")
-- Walls.
f:write("wall={\n")
for i=0,ffiC.numwalls-1 do
write_struct(f, ffiC.wall[i], wall_members, wall_ord)
end
f:write("},\n\n")
-- Sprites.
f:write("sprite={\n")
for i=0,ffiC.MAXSPRITES-1 do
if (ffiC.sprite[i].statnum ~= ffiC.MAXSTATUS) then
write_struct(f, ffiC.sprite[i], sprite_members, sprite_ord)
end
end
f:write("},\n\n")
f:write("}\n");
-- Done.
f:close()
restore_point2(false)
return 0
end
--== LOADING ==--
local function isnum(v)
return (type(v)=="number")
end
local function istab(v)
return (type(v)=="table")
end
-- Checks whether <tab> is a table all values of <tab> are of type <extype>.
local function allxtab(tab, extype)
if (not istab(tab)) then
return false
end
for _,val in pairs(tab) do
if (type(val) ~= extype) then
return false
end
end
return true
end
-- Is table of all numbers?
local function allnumtab(tab) return allxtab(tab, "number") end
-- Is table of all tables?
local function alltabtab(tab) return allxtab(tab, "table") end
-- Is table of tables of all numbers? Additionally, each must contain exactly
-- as many mandatory positional entries as given by the <members> table.
local function tabofnumtabs(tab, members)
for i=1,#tab do
if (not allnumtab(tab[i])) then
return false
end
local nummand = #members -- number of mandatory entries
if (#tab[i] ~= nummand) then
return false
end
end
return true
end
-- Read data from Lua table <stab> into C struct <cs>, using the struct
-- description <members>.
-- Returns true on error.
local function read_struct(cs, stab, members, defaults)
-- Clear struct to default values.
ffi.copy(cs, defaults, ffi.sizeof(defaults))
-- Read mandatory positional members.
for i=1,#members do
cs[members[i]] = stab[i]
end
-- Read optional key/value members.
for k,val in pairs(stab) do
if (members[k]==nil) then
-- No such member abbreviation for the given struct.
return true
end
local memb = istab(members[k]) and members[k][1] or members[k]
cs[memb] = val
end
end
local RETERR = -4
local function loadboard_maptext(fil, posptr, angptr, cursectnumptr)
-- Read the whole map-text as string.
local str = readintostr(fil)
if (str == nil) then
return RETERR
end
-- Strip all one-line comments (currently, only the header).
str = str:gsub("%-%-.-\n", "")
--- Preliminary (pseudo-syntactical) validation ---
-- Whitelist approach: map-text may only contain certain characters. This
-- excludes various potentially 'bad' operations (such as calling a
-- function) in one blow. Also, this assures (by exclusion) that the Lua
-- code contains no long comments, strings, or function calls.
if (not str:find("^[ A-Za-z_0-9{},%-\n=]+$")) then
return RETERR-1
end
-- The map-text code must return a single table.
if (not str:find("^return %b{}\n$")) then
return RETERR-2
end
local func, errmsg = loadstring(str, "maptext")
if (func == nil) then
print("Error preloading map-text Lua code: "..errmsg)
return RETERR-3
end
-- Completely empty the function's environment as an additional safety
-- measure, then run the chunk protected! (XXX: currently a bit pointless
-- because of the asserts below.)
local ok, map = pcall(setfenv(func, {}))
if (not ok) then
print("Error executing map-text Lua code: "..map)
return RETERR-4
end
assert(istab(map))
-- OK, now 'map' contains the map data.
--- Structural validation ---
-- Check types.
if (not isnum(map.version) or not allnumtab(map.pos) or #map.pos~=3 or
not isnum(map.sectnum) or not isnum(map.ang))
then
return RETERR-5
end
if (not (map.version <= 10)) then
return RETERR-6
end
local msector, mwall, msprite = map.sector, map.wall, map.sprite
if (not alltabtab(msector) or not alltabtab(mwall) or not alltabtab(msprite)) then
return RETERR-7
end
if (not tabofnumtabs(msector, sector_members) or
not tabofnumtabs(mwall, wall_members) or
not tabofnumtabs(msprite, sprite_members))
then
return RETERR-8
end
local numsectors, numwalls, numsprites = #msector, #mwall, #msprite
local sector, wall, sprite = ffiC.sector, ffiC.wall, ffiC.sprite
if (numsectors == 0 or numsectors > ffiC.MAXSECTORS or
numwalls > ffiC.MAXWALLS or numsprites > ffiC.MAXSPRITES)
then
return RETERR-9
end
--- From here on, start filling out C structures. ---
ffiC.numsectors = numsectors
ffiC.numwalls = numwalls
-- Header.
posptr.x = map.pos[1]
posptr.y = map.pos[2]
posptr.z = map.pos[3]
angptr[0] = map.ang
cursectnumptr[0] = map.sectnum
-- Sectors.
for i=0,numsectors-1 do
if (read_struct(sector[i], msector[i+1], sector_members, sector_default)) then
return RETERR-10
end
end
-- Walls.
for i=0,numwalls-1 do
if (read_struct(wall[i], mwall[i+1], wall_members, wall_default)) then
return RETERR-11
end
end
-- Sprites.
for i=0,numsprites-1 do
if (read_struct(sprite[i], msprite[i+1], sprite_members, sprite_default)) then
return RETERR-12
end
end
-- XXX: need to consistency-check much more here! Basically, all of
-- astub.c's CheckMapCorruption() for corruption level >=4?
-- See NOTNICE below.
--- Tweakery: mostly setting dependent members. ---
-- sector[]: .wallptr calculated from .wallnum.
local numw = 0
for i=0,numsectors-1 do
assert(numw >= 0 and numw < numwalls) -- NOTNICE, cheap check instead of real one.
sector[i].wallptr = numw
numw = numw + sector[i].wallnum
end
-- .point2 in {0, 1} --> wall index, sector[].wallptr/.wallnum
if (restore_point2(true)) then
return RETERR-13
end
-- Check .point2 at least.
if (check_bad_point2()) then
return RETERR-14
end
-- wall[]: .nextsector calculated by using engine's sectorofwall_noquick()
for i=0,numwalls-1 do
local nw = wall[i].nextwall
if (nw >= 0) then
assert(nw >= 0 and nw < numwalls) -- NOTNICE
wall[i].nextsector = ffiC.sectorofwall_noquick(nw)
else
wall[i].nextsector = -1
end
end
-- All OK, return the number of sprites for further engine loading code.
return numsprites
end
-- Register our Lua functions as callbacks from C.
ffiC.saveboard_maptext = saveboard_maptext
ffiC.loadboard_maptext = loadboard_maptext
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Trembling.lua | 37 | 1114 | ---------------------------------------------
-- Trembling
--
-- Description: Deals physical damage to enemies within an area of effect. Additional effect: Dispel
-- Type: Physical
-- Wipes Shadows
-- Range: 10' radial
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 4;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,MOBPARAM_WIPE_SHADOWS);
local dispelled = math.random(2,3);
if (info.hitslanded ~= 0) then
for i=1,dispelled do
target:dispelStatusEffect();
end
end
-- TODO: Dispelled messages. No examples of damage+dispel working to crib notes from.
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
dtrip/awesome | tests/test-selection-transfer.lua | 2 | 7427 | -- Test the selection ownership and transfer API
local runner = require("_runner")
local spawn = require("awful.spawn")
-- Assemble data for the large transfer that will be done later
local large_transfer_piece = "a"
for _ = 1, 25 do
large_transfer_piece = large_transfer_piece .. large_transfer_piece
end
large_transfer_piece = large_transfer_piece .. large_transfer_piece .. large_transfer_piece
local large_transfer_piece_count = 3
local large_transfer_size = #large_transfer_piece * large_transfer_piece_count
local header = [[
local lgi = require("lgi")
local Gdk = lgi.Gdk
local Gtk = lgi.Gtk
local GLib = lgi.GLib
local function assert_equal(a, b)
assert(a == b,
string.format("%s == %s", a or "nil/false", b or "nil/false"))
end
local clipboard = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)
]]
local acquire_and_clear_clipboard = header .. [[
clipboard:set_text("This is an experiment", -1)
GLib.idle_add(GLib.PRIORITY_DEFAULT, Gtk.main_quit)
Gtk.main()
]]
local done_footer = [[
io.stdout:write("done")
io.stdout:flush()
]]
local check_targets_and_text = header .. [[
local targets = clipboard:wait_for_targets()
assert_equal(targets[1]:name(), "TARGETS")
assert_equal(targets[2]:name(), "UTF8_STRING")
assert_equal(#targets, 2)
assert_equal(clipboard:wait_for_text(), "Hello World!")
]] .. done_footer
local check_large_transfer = header
.. string.format("\nassert_equal(#clipboard:wait_for_text(), %d)\n", large_transfer_size)
.. done_footer
local check_empty_selection = header .. [[
assert_equal(clipboard:wait_for_targets(), nil)
assert_equal(clipboard:wait_for_text(), nil)
]] .. done_footer
local selection_object
local selection_released
local continue
runner.run_steps({
function()
-- Get the selection
local s = assert(selection.acquire{ selection = "CLIPBOARD" },
"Failed to acquire the clipboard selection")
-- Steal selection ownership from ourselves and test that it works
local s_released
s:connect_signal("release", function() s_released = true end)
selection_object = assert(selection.acquire{ selection = "CLIPBOARD" },
"Failed to acquire the clipboard selection")
assert(s_released)
-- Now test selection transfers
selection_object = assert(selection.acquire{ selection = "CLIPBOARD" },
"Failed to acquire the clipboard selection")
selection_object:connect_signal("request", function(_, target, transfer)
if target == "TARGETS" then
transfer:send{
format = "atom",
data = { "TARGETS", "UTF8_STRING" },
}
elseif target == "UTF8_STRING" then
transfer:send{ data = "Hello World!" }
end
end)
awesome.sync()
spawn.with_line_callback({ "lua", "-e", check_targets_and_text },
{ stdout = function(line)
assert(line == "done", "Unexpected line: " .. line)
continue = true
end })
return true
end,
function()
-- Wait for the previous test to succeed
if not continue then return end
continue = false
-- Now test piece-wise selection transfers
selection_object = assert(selection.acquire{ selection = "CLIPBOARD" },
"Failed to acquire the clipboard selection")
selection_object:connect_signal("request", function(_, target, transfer)
if target == "TARGETS" then
transfer:send{
format = "atom",
data = { "TARGETS", "UTF8_STRING" },
}
elseif target == "UTF8_STRING" then
local offset = 1
local data = "Hello World!"
local function send_piece()
local piece = data:sub(offset, offset)
transfer:send{
data = piece,
continue = piece ~= ""
}
offset = offset + 1
end
transfer:connect_signal("continue", send_piece)
send_piece()
end
end)
awesome.sync()
spawn.with_line_callback({ "lua", "-e", check_targets_and_text },
{ stdout = function(line)
assert(line == "done", "Unexpected line: " .. line)
continue = true
end })
return true
end,
function()
-- Wait for the previous test to succeed
if not continue then return end
continue = false
-- Now test a huge transfer
selection_object = assert(selection.acquire{ selection = "CLIPBOARD" },
"Failed to acquire the clipboard selection")
selection_object:connect_signal("request", function(_, target, transfer)
if target == "TARGETS" then
transfer:send{
format = "atom",
data = { "TARGETS", "UTF8_STRING" },
}
elseif target == "UTF8_STRING" then
local count = 0
local function send_piece()
count = count + 1
local done = count == large_transfer_piece_count
transfer:send{
data = large_transfer_piece,
continue = not done,
}
end
transfer:connect_signal("continue", send_piece)
send_piece()
end
end)
awesome.sync()
spawn.with_line_callback({ "lua", "-e", check_large_transfer },
{ stdout = function(line)
assert(line == "done", "Unexpected line: " .. line)
continue = true
end })
return true
end,
function()
-- Wait for the previous test to succeed
if not continue then return end
continue = false
-- Now test that :release() works
selection_object:release()
awesome.sync()
spawn.with_line_callback({ "lua", "-e", check_empty_selection },
{ stdout = function(line)
assert(line == "done", "Unexpected line: " .. line)
continue = true
end })
return true
end,
function()
-- Wait for the previous test to succeed
if not continue then return end
continue = false
-- Test for "release" signal when we lose selection
selection_object = assert(selection.acquire{ selection = "CLIPBOARD" },
"Failed to acquire the clipboard selection")
selection_object:connect_signal("release", function() selection_released = true end)
awesome.sync()
spawn.with_line_callback({ "lua", "-e", acquire_and_clear_clipboard },
{ exit = function() continue = true end })
return true
end,
function()
-- Wait for the previous test to succeed
if not continue then return end
continue = false
assert(selection_released)
return true
end,
}, {
-- Use a larger step timeout for the large data transfer, which
-- transfers 3 * 2^25 bytes of data (96 MiB), and takes a while.
wait_per_step = 10,
})
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Flat_Blade.lua | 9 | 1360 | ---------------------------------------------
-- Flat Blade
--
-- Description: Stuns enemy. Chance of stunning varies with TP.
-- Type: Physical
-- Utsusemi/Blink absorb: Shadow per hit
-- Range: Melee
---------------------------------------------
require("scripts/globals/monstertpmoves");
require("scripts/globals/settings");
require("scripts/globals/status");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:getPool() ~= 4006) then
mob:messageBasic(43, 0, 35);
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
if (mob:getPool() == 4006) then -- Trion@Qubia_Arena only
require("scripts/zones/Qubia_Arena/TextIDs");
target:showText(mob,FLAT_LAND);
end
local numhits = 1;
local accmod = 1;
local dmgmod = 1.25;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_CRIT_VARIES,1.1,1.2,1.3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
skill:setSkillchain(35);
if (math.random(1,100) < skill:getTP()/3) then
MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_STUN, 1, 0, 4);
end
-- AA EV: Approx 900 damage to 75 DRG/35 THF. 400 to a NIN/WAR in Arhat, but took shadows.
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
kurzalead/yalon | yalon/yalon.lua | 2 | 23881 | --[[
Copyright (c) 2016 kurzyx https://github.com/kurzyx
Licensed under MIT (https://github.com/kurzalead/yalon/blob/master/LICENSE.md)
----------------------------------------------------------------------------
YALON 1.00.00
Yet Another Lua Object Notation
]]
yalon = {}
local error = function(message)
error(debug.traceback("YALON: "..message, 2))
end
local pairs = pairs
local ipairs = ipairs
local type = type
local string_find = string.find
local string_sub = string.sub
local table_concat = table.concat
-- Serialize
do
local
valueSerializers,
typeSerializers
valueSerializers = {
["string"] = function()
local escapedChars = {
["\""] = "\\\"",
["\\"] = "\\\\",
["\b"] = "\\b",
["\f"] = "\\f",
["\n"] = "\\n",
["\r"] = "\\r",
["\t"] = "\\t"
}
local escapedCharsNum = {}
for k, v in pairs(escapedChars) do
escapedCharsNum[#escapedCharsNum + 1] = k
end
local pattern = "["
for k, v in pairs(escapedChars) do
pattern = pattern..k
end
pattern = pattern.."]"
--[[
- @arg table t The table we store all strings in
- @arg number i The table's current index
- @arg string v The value we need to serialize
- @retur number
]]
return function(t, i, v)
local b, e, bt = 1, 1, nil
i = i + 1
t[i] = "\""
while true do
-- TODO: Try to optimize this better
e = #v + 1
for x=1, #escapedCharsNum do
bt = string_find(v, escapedCharsNum[x], b, true)
if bt ~= nil and bt < e then
e = bt
end
end
if e == #v + 1 then
i = i + 1
t[i] = string_sub(v, b, #v)
break
end
t[i + 1] = string_sub(v, b, e - 1)
i = i + 2
t[i] = escapedChars[string_sub(v, e, e)]
b = e + 1
end
i = i + 1
t[i] = "\""
return i
end
end,
["number"] = function()
--[[
- @arg table t The table we store all strings in
- @arg number i The table's current index
- @arg number v The value we need to serialize
- @retur number
]]
return function(t, i, v)
i = i + 1
-- As simple as that
t[i] = v
return i
end
end,
["boolean"] = function()
--[[
- @arg table t The table we store all strings in
- @arg number i The table's current index
- @arg bool v The value we need to serialize
- @retur number
]]
return function(t, i, v)
i = i + 1
if v == true then
t[i] = "true"
else
t[i] = "false"
end
return i
end
end,
["table"] = function()
local function isSequential(t)
local i = 0
for _ in pairs(t) do
i = i + 1
if t[i] == nil then return false end
end
return true
end
local getIdentifier
do
local chars, len = {}, nil
for c in ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"):gmatch(".") do
chars[#chars + 1] = c
end
len = #chars
getIdentifier = function(n)
n = n - 1
local s = ""
while true do
s = chars[n % len + 1]..s
n = math.floor(n / len)
if n == 0 then
break
end
end
return s
end
end
--[[
- @arg table t The table we store all strings in
- @arg number i The table's current index
- @arg table v The value we need to serialize
- @arg table tc The table cache for reference
- @retur number
]]
return function(t, i, v, tc)
if tc[v] == nil then
-- Reserve an index for reference
i = i + 1
t[i] = ""
-- Table refers to the reserved index
tc[v] = i
else
local ti = tc[v]
-- Set the declaring reference if not set (This is always if the table is used for the second time)
if t[ti] == "" then
tc[1] = tc[1] + 1
t[ti] = "&"..getIdentifier(tc[1]).."="
end
i = i + 1
t[i] = string_sub(t[ti], 1, #t[ti] - 1)
return i -- And return because we don't have to declare the table again
end
-- Numeric
if isSequential(v) then
i = i + 1
t[i] = "["
local l = i
-- Iterrate through each value
for _, _v in ipairs(v) do
i = typeSerializers[type(_v)](t, i, _v, tc)
i = i + 1
t[i] = ","
end
-- Remove last comma if there is at least one value in the table
if l == i then
i = i + 1
t[i] = "]"
else
t[i] = "]"
end
-- Generic
else
i = i + 1
t[i] = "{"
local l = i
-- Iterrate through each value
for _k, _v in pairs(v) do
i = typeSerializers[type(_k)](t, i, _k, tc) -- Key
i = i + 1
t[i] = ":"
i = typeSerializers[type(_v)](t, i, _v, tc) -- Value
i = i + 1
t[i] = ","
end
-- Remove last comma if there is at least one value in the table
if l == i then
i = i + 1
t[i] = "}"
else
t[i] = "}"
end
end
return i
end
end
}
typeSerializers = {
["string"] = valueSerializers["string"](),
["boolean"] = valueSerializers["boolean"](),
["table"] = valueSerializers["table"](),
["number"] = valueSerializers["number"](),
-- On unsupported type
__index = function(self, t)
return function(s, i, v)
error(("Unsupported type '%s' can not be serialized."):format(t))
end
end
}
setmetatable(typeSerializers, typeSerializers)
--[[
- @arg any v The value to serialize
- @return string
]]
function yalon.serialize(v)
-- The table all strings will be put in to be concatenated
local t = {}
-- Any supported value is allowed
typeSerializers[type(v)](t, 0, v, {[1] = 0})
-- Return the concatenated table
return table_concat(t)
end
end
-- Deserialize
do
local whitespacing = {
[' '] = true,
[' '] = true,
['\n'] = true,
['\r'] = true
}
local
valueDeserializers,
characterDeserializers
valueDeserializers = {
["string"] = function()
local escapedChars = {
["\""] = "\"",
["\\"] = "\\",
["b"] = "\b",
["f"] = "\f",
["n"] = "\n",
["r"] = "\r",
["t"] = "\t"
}
--[[
- @arg string s The string we are parsing
- @arg number i The index of the string we are currently at
- @return number, string
]]
return function(s, i)
local c, v = nil, ""
local p1, p2
i = i + 1
while true do
-- Faster than patterns
p1 = string_find(s, "\"", i, true)
p2 = string_find(s, "\\", i, true)
if p1 == nil then
error("Unexpected end of string while parsing string.")
end
if p2 ~= nil and p2 < p1 then
p2 = p2 + 1
c = string_sub(s, p2, p2)
if escapedChars[c] ~= nil then
v = v..string_sub(s, i, p2 - 2)..escapedChars[c]
i = p2 + 1
else
error(("Invalid escaped character '%s' at index %d."):format(c, p2))
end
else
return p1, v..string_sub(s, i, p1 - 1)
end
end
end
end,
["number"] = function()
--[[
- @arg string s The string we are parsing
- @arg number i The index of the string we are currently at
- @return number, number
]]
return function(s, i)
local b, e = string_find(s, "^%-?%d*%.?%d+", i)
if e == nil then
error(("Unexpected end of number at index %d."):format(i - 1))
end
return e, tonumber(string_sub(s, b, e))
end
end,
["boolean"] = function(bool)
--[[
- @arg string s The string we are parsing
- @arg number i The index of the string we are currently at
- @return number, bool
]]
if bool == true then
return function(s, i)
-- Cache the next character
local c = string_sub(s, i, i + 3)
if c == "true" then
return i + 3, true
end
if c == "" then -- End of string
error("Unexpected end of string while parsing boolean.")
else
error(("Unexpected end of boolean for character '%s' at index %d."):format(c, i))
end
end
else
return function(s, i)
-- Cache the next character
local c = string_sub(s, i, i + 4)
if c == "false" then
return i + 4, false
end
if c == "" then -- End of string
error("Unexpected end of string while parsing boolean.")
else
error(("Unexpected end of boolean for character '%s' at index %d."):format(c, i))
end
end
end
end,
["table-numeric"] = function()
local EXPECT_VALUE = 1
local EXPECT_END = 2
--[[
- @arg string s The string we are parsing
- @arg number i The index of the string we are currently at
- @arg table tc The table cache for reference
- @arg table|nil t The new table to use (may be nil)
- @return number, table
]]
return function(s, i, tc, t)
local c = nil
if t == nil then
t = {}
end
-- What to expect next
local expect = EXPECT_VALUE
-- Loop through characters
while true do
-- Cache the next character
i = i + 1
c = string_sub(s, i, i)
-- Whitespacing
if whitespacing[c] then
-- Continue to the next character
-- Expect value or end of table
elseif expect == EXPECT_VALUE then
-- End of table is also possible
if c == "]" then
return i, t
end
i, t[#t + 1] = characterDeserializers[c](s, i, tc)
expect = EXPECT_END
-- Expect end of table or value seperator
elseif c == "," then
expect = EXPECT_VALUE
elseif c == "]" then
return i, t
-- Error on unexpected end of table
else
if c == "" then -- End of string
error("Expected end of numeric table instead of end of string.")
else
error(("Expected end of numeric table instead of character '%s' at index %d."):format(c, i))
end
end
end
end
end,
["table-generic"] = function()
local EXPECT_KEY = 1
local EXPECT_KEY_VALUE_SEPERATOR = 2
local EXPECT_VALUE = 3
local EXPECT_END = 4
--[[
- @arg string s The string we are parsing
- @arg number i The index of the string we are currently at
- @arg table tc The table cache for reference
- @arg table|nil t The new table to use (may be nil)
- @return number, table
]]
return function(s, i, tc, t)
local c = nil
if t == nil then
t = {}
end
-- The last parsed key
local key
-- What to expect next
local expect = EXPECT_KEY
-- Loop through characters
while true do
-- Cache the next character
i = i + 1
c = string_sub(s, i, i)
-- Whitespacing
if whitespacing[c] then
-- Continue to the next character
-- Expect key or end of table
elseif expect == EXPECT_KEY then
-- End of table is also possible
if c == "}" then
return i, t
end
i, key = characterDeserializers[c](s, i, tc)
expect = EXPECT_KEY_VALUE_SEPERATOR
-- Expect value
elseif expect == EXPECT_VALUE then
i, t[key] = characterDeserializers[c](s, i, tc)
expect = EXPECT_END
-- Expect key value seperator
elseif expect == EXPECT_KEY_VALUE_SEPERATOR then
-- Expect key value seperator
if c == ":" then
expect = EXPECT_VALUE
else
if c == "" then -- End of string
error("Expected key value seperator ':' instead of end of string while parsing generic table.")
else
error(("Expected key value seperator ':' instead of character '%s' at index %d while parsing generic table."):format(c, i))
end
end
-- Expect end of table or value seperator
elseif c == "," then
expect = EXPECT_KEY
elseif c == "}" then
return i, t
-- Error on unexpected end of table
else
if c == "" then -- End of string
error("Expected end of generic table instead of end of string.")
else
error(("Expected end of generic table instead of character '%s' at index %d."):format(c, i))
end
end
end
end
end,
["table-reference"] = function()
--[[
- @arg string s The string we are parsing
- @arg number i The index of the string we are currently at
- @arg table tc The table cache for reference
- @return number, table
]]
return function(s, i, tc)
-- Get the reference id
local b, i, ri = string_find(s, "^&(%w+)", i)
if i == nil then
error("Unexpected end of string while parsing reference.")
end
local declaring = false
-- Loop through characters
while true do
-- Cache the next character
i = i + 1
c = string_sub(s, i, i)
-- Whitespacing
if whitespacing[c] then
-- Continue to the next character
-- Reference declaration
elseif declaring == false and c == "=" then
declaring = true
elseif c == "" then
-- End of string?
error("Unexpected end of string while parsing reference.")
else
if declaring == true then
local v = {}
-- Cache the reference before parsing the table
-- This means we don't have to declare the reference
-- In the most inner table if needed
tc[ri] = v
i, v = characterDeserializers[c](s, i, tc, v)
tc[ri] = v -- References may not be tables
return i, v
else
if tc[ri] == nil then
error(("Undeclared reference '%s' at index %d."):format(ri, i))
end
return i - 1, tc[ri]
end
end
end
end
end,
}
characterDeserializers = {
-- String
["\""] = valueDeserializers["string"](),
-- Table
["["] = valueDeserializers["table-numeric"](),
["{"] = valueDeserializers["table-generic"](),
-- Reference
["&"] = valueDeserializers["table-reference"](),
-- Boolean
["t"] = valueDeserializers["boolean"](true),
["f"] = valueDeserializers["boolean"](false),
-- Numbers
["0"] = valueDeserializers["number"](),
["1"] = valueDeserializers["number"](),
["2"] = valueDeserializers["number"](),
["3"] = valueDeserializers["number"](),
["4"] = valueDeserializers["number"](),
["5"] = valueDeserializers["number"](),
["6"] = valueDeserializers["number"](),
["7"] = valueDeserializers["number"](),
["8"] = valueDeserializers["number"](),
["9"] = valueDeserializers["number"](),
["-"] = valueDeserializers["number"](),
-- On undefined character
__index = function(self, c)
return function(s, i)
if c == "" then
error(("Unexpected end of string while trying to parse a value."):format(c, i))
else
error(("Can't find use for character '%s' at index %d."):format(c, i))
end
end
end
}
setmetatable(characterDeserializers, characterDeserializers)
--[[
- @arg string s The string to deserialize
- @return any
]]
function yalon.deserialize(s)
local i, v = 0, nil
-- Loop through characters
while true do
-- Cache the next character
i = i + 1
c = string_sub(s, i, i)
-- Whitespacing
if whitespacing[c] then
-- Continue to the next character
elseif c == "" then
-- Empty string?
error("Can not parse an empty string.")
else
-- We can parse any value that is supported
i, v = characterDeserializers[c](s, i, {})
return v
end
end
end
end
-- Version of YALON
yalon.version = "1.00.00"
yalon.version_nr = 10000
return yalon
| mit |
jbeich/Aquaria | files/scripts/maps/node_openenergydoor.lua | 12 | 1262 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
node_setCursorActivation(me, false)
end
function activate(me)
local energyOrb = node_getNearestEntity(me, "EnergyOrb")
if energyOrb ~= 0 and entity_isState(energyOrb, STATE_CHARGED) then
local door = node_getNearestEntity(me, "EnergyDoor")
if door ~= 0 then
entity_setState(door, STATE_OPEN)
end
end
end
function update(me, dt)
end
| gpl-2.0 |
jbeich/Aquaria | files/scripts/entities/wisp.lua | 6 | 3458 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
v.n = 0
v.mld = 0.2
v.ld = v.mld
v.note = -1
v.excited = 0
v.glow = 0
function init(me)
setupEntity(me)
entity_setEntityType(me, ET_ENEMY)
entity_setTexture(me, "Wisp")
entity_setAllDamageTargets(me, true)
entity_setDamageTarget(me, DT_AVATAR_LIZAP, false)
entity_setCollideRadius(me, 20)
entity_setState(me, STATE_IDLE)
entity_addRandomVel(me, 500)
v.glow = createQuad("Naija/LightFormGlow", 13)
quad_scale(v.glow, 2, 2)
entity_setHealth(me, 6)
entity_setDeathParticleEffect(me, "TinyRedExplode")
entity_setUpdateCull(me, 3000)
entity_setDamageTarget(me, DT_AVATAR_PET, false)
end
function dieNormal(me)
if chance(5) then
spawnIngredient("GlowingEgg", entity_x(me), entity_y(me))
end
end
function postInit(me)
v.n = getNaija()
entity_setTarget(me, v.n)
end
function update(me, dt)
v.ld = v.ld - dt
if v.ld < 0 then
v.ld = v.mld
local l = createQuad("Naija/LightFormGlow", 13)
local r = 1
local g = 1
local b = 1
if v.note ~= -1 then
r, g, b = getNoteColor(v.note)
r = r*0.5 + 0.5
g = g*0.5 + 0.5
b = b*0.5 + 0.5
end
quad_setPosition(l, entity_getPosition(me))
quad_scale(l, 1.5, 1.5)
quad_alpha(l, 0)
quad_alpha(l, 1, 0.5)
quad_color(l, r, g, b)
quad_delete(l, 4)
quad_color(v.glow, r, g, b, 0.5)
end
--entity_doCollisionAvoidance(me, dt, 8, 0.2)
entity_doCollisionAvoidance(me, dt, 4, 0.8)
entity_updateMovement(me, dt)
entity_handleShotCollisions(me)
--entity_touchAvatarDamage(me, entity_getCollideRadius(me), 1, 500)
if v.excited > 0 then
v.excited = v.excited - dt
if v.excited < 0 then
entity_addRandomVel(me, 500)
end
if entity_isTargetInRange(me, 256) then
entity_moveAroundTarget(me, dt, 1000)
else
entity_moveTowardsTarget(me, dt, 400)
end
end
if not entity_isRotating(me) then
entity_rotateToVel(me, 0.2)
end
quad_setPosition(v.glow, entity_getPosition(me))
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
elseif entity_isState(me, STATE_DEAD) then
quad_delete(v.glow, 1)
end
end
function exitState(me)
end
function damage(me, attacker, bone, damageType, dmg)
return true
end
function animationKey(me, key)
end
function hitSurface(me)
end
function songNote(me, n)
v.note = n
v.excited = 10
--entity_rotate(me, entity_getRotation(me)+360, 0.5, 0, 0, 1)
quad_scale(v.glow, 2, 2)
quad_scale(v.glow, 4, 4, 0.5, 1, 1, 1)
entity_setMaxSpeedLerp(me, 1.25)
entity_setMaxSpeedLerp(me, 1, 3)
end
function songNoteDone(me, note)
v.excited = 3
end
function song(me, song)
end
function activate(me)
end
| gpl-2.0 |
jbeich/Aquaria | files/scripts/entities/darkjelly.lua | 6 | 4156 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- DARK JELLY
v.blupTimer = 0
v.dirTimer = 0
v.blupTime = 3.0
v.sz = 1.0
v.dir = 0
local MOVE_STATE_UP = 0
local MOVE_STATE_DOWN = 1
v.moveState = 0
v.moveTimer = 0
v.velx = 0
v.waveDir = 1
v.waveTimer = 0
v.soundDelay = 0
v.glows = nil
local function doIdleScale(me)
entity_scale(me, 0.9*v.sz, 1.1*v.sz)
entity_scale(me, 1.1*v.sz, 0.9*v.sz, v.blupTime, -1, 1, 1)
end
function init(me)
v.glows = {}
setupBasicEntity(
me,
"", -- texture
6, -- health
2, -- manaballamount
2, -- exp
10, -- money
0, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
1, -- particle "explosion" type, 0 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
4000, -- updateCull -1: disabled, default: 4000
1
)
entity_initSkeletal(me, "DarkJelly")
entity_setEntityType(me, ET_NEUTRAL)
entity_setAllDamageTargets(me, false)
entity_setEntityLayer(me, -4)
--entity_initHair(me, 64, 16, 128, "DarkJelly/Tentacles")
doIdleScale(me)
entity_exertHairForce(me, 0, 400, 1)
entity_setState(me, STATE_IDLE)
--entity_setCullRadius(me, -3)
entity_setCull(me, false)
bone_setSegs(entity_getBoneByName(me, "Tentacles"), 4, 32, 0.6, 0.6, -0.028, 0, 0.75, 0)
--[[
for i=1,4 do
v.glows[i] = entity_getBoneByName(me, string.format("Glow%d", i))
bone_alpha(v.glows[i], 0.5)
bone_alpha(v.glows[i], 1, 1, -1, 1, 1)
bone_update(v.glows[i], i*0.25)
end
]]--
end
function postInit(me)
entity_update(me, math.random(100)/100.0)
end
function update(me, dt)
--dt = dt * 1.5
local sx,sy = entity_getScale(me)
v.moveTimer = v.moveTimer - dt
if v.moveTimer < 0 then
if v.moveState == MOVE_STATE_DOWN then
v.moveState = MOVE_STATE_UP
entity_setMaxSpeedLerp(me, 1.5, 0.2)
--entity_scale(me, 0.75, 1, 1, 1, 1)
v.moveTimer = 3 + math.random(200)/100.0
--entity_sound(me, "JellyBlup")
elseif v.moveState == MOVE_STATE_UP then
v.velx = math.random(400)+100
if math.random(2) == 1 then
v.velx = -v.velx
end
v.moveState = MOVE_STATE_DOWN
entity_setMaxSpeedLerp(me, 1, 1)
v.moveTimer = 5 + math.random(200)/100.0 + math.random(3)
end
end
v.waveTimer = v.waveTimer + dt
if v.waveTimer > 2 then
v.waveTimer = 0
if v.waveDir == 1 then
v.waveDir = -1
else
v.waveDir = 1
end
end
if v.moveState == MOVE_STATE_UP then
entity_addVel(me, v.velx*dt, -600*dt)
entity_rotateToVel(me, 8)
elseif v.moveState == MOVE_STATE_DOWN then
entity_addVel(me, 0, 50*dt)
entity_rotateTo(me, 0, 8)
entity_exertHairForce(me, 0, 200, dt*0.6, -1)
end
--[[
entity_doEntityAvoidance(me, dt, 32, 1.0)
entity_doCollisionAvoidance(me, 1.0, 8, 1.0)
entity_updateCurrents(me, dt)
]]--
entity_updateMovement(me, dt)
--[[
local bx, by = bone_getWorldPosition(entity_getBoneByIdx(me, 0))
entity_setHairHeadPosition(me, bx, by)
entity_updateHair(me, dt*5)
]]--
end
function hitSurface(me)
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
entity_setMaxSpeed(me, 40)
entity_animate(me, "idle", LOOP_INF)
end
end
function damage(me, attacker, bone, damageType, dmg)
return true
end
function exitState(me)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Ekki-Mokki.lua | 14 | 1061 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Ekki-Mokki
-- Type: Standard NPC
-- @zone 94
-- @pos -26.558 -4.5 62.930
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0199);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
guangbin79/Lua_5.1.5-iOS | luasocket-3.0-rc1/test/ftptest.lua | 26 | 3156 | local socket = require("socket")
local ftp = require("socket.ftp")
local url = require("socket.url")
local ltn12 = require("ltn12")
-- override protection to make sure we see all errors
--socket.protect = function(s) return s end
dofile("testsupport.lua")
local host, port, index_file, index, back, err, ret
local t = socket.gettime()
host = host or "localhost"
index_file = "index.html"
-- a function that returns a directory listing
local function nlst(u)
local t = {}
local p = url.parse(u)
p.command = "nlst"
p.sink = ltn12.sink.table(t)
local r, e = ftp.get(p)
return r and table.concat(t), e
end
-- function that removes a remote file
local function dele(u)
local p = url.parse(u)
p.command = "dele"
p.argument = string.gsub(p.path, "^/", "")
if p.argumet == "" then p.argument = nil end
p.check = 250
return ftp.command(p)
end
-- read index with CRLF convention
index = readfile(index_file)
io.write("testing wrong scheme: ")
back, err = ftp.get("wrong://banana.com/lixo")
assert(not back and err == "wrong scheme 'wrong'", err)
print("ok")
io.write("testing invalid url: ")
back, err = ftp.get("localhost/dir1/index.html;type=i")
assert(not back and err)
print("ok")
io.write("testing anonymous file download: ")
back, err = socket.ftp.get("ftp://" .. host .. "/pub/index.html;type=i")
assert(not err and back == index, err)
print("ok")
io.write("erasing before upload: ")
ret, err = dele("ftp://luasocket:pedrovian@" .. host .. "/index.up.html")
if not ret then print(err)
else print("ok") end
io.write("testing upload: ")
ret, err = ftp.put("ftp://luasocket:pedrovian@" .. host .. "/index.up.html;type=i", index)
assert(ret and not err, err)
print("ok")
io.write("downloading uploaded file: ")
back, err = ftp.get("ftp://luasocket:pedrovian@" .. host .. "/index.up.html;type=i")
assert(ret and not err and index == back, err)
print("ok")
io.write("erasing after upload/download: ")
ret, err = dele("ftp://luasocket:pedrovian@" .. host .. "/index.up.html")
assert(ret and not err, err)
print("ok")
io.write("testing weird-character translation: ")
back, err = ftp.get("ftp://luasocket:pedrovian@" .. host .. "/%23%3f;type=i")
assert(not err and back == index, err)
print("ok")
io.write("testing parameter overriding: ")
local back = {}
ret, err = ftp.get{
url = "//stupid:mistake@" .. host .. "/index.html",
user = "luasocket",
password = "pedrovian",
type = "i",
sink = ltn12.sink.table(back)
}
assert(ret and not err and table.concat(back) == index, err)
print("ok")
io.write("testing upload denial: ")
ret, err = ftp.put("ftp://" .. host .. "/index.up.html;type=a", index)
assert(not ret and err, "should have failed")
print(err)
io.write("testing authentication failure: ")
ret, err = ftp.get("ftp://luasocket:wrong@".. host .. "/index.html;type=a")
assert(not ret and err, "should have failed")
print(err)
io.write("testing wrong file: ")
back, err = ftp.get("ftp://".. host .. "/index.wrong.html;type=a")
assert(not back and err, "should have failed")
print(err)
print("passed all tests")
print(string.format("done in %.2fs", socket.gettime() - t))
| mit |
nyczducky/darkstar | scripts/zones/Selbina/npcs/Yaya.lua | 14 | 1465 | -----------------------------------
-- Area: Selbina
-- NPC: Yaya
-- Starts Quest: Under the sea
-- @pos -19 -2 -16 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getFameLevel(SELBINA) >= 2 and player:getQuestStatus(OTHER_AREAS,UNDER_THE_SEA) == QUEST_AVAILABLE) then
player:startEvent(0x001f); -- Start quest "Under the sea"
else
player:startEvent(0x0099); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x001f) then
player:addQuest(OTHER_AREAS,UNDER_THE_SEA);
player:setVar("underTheSeaVar",1);
end
end;
| gpl-3.0 |
wenhulove333/ScutServer | Sample/ClientSource/samples/Lua/TestLua/Resources/luaScript/DrawPrimitivesTest/DrawPrimitivesTest.lua | 1 | 4050 |
local SceneIdx = -1
local MAX_LAYER = 2
local background = nil
local labelAtlas = nil
local baseLayer_entry = nil
local s = CCDirector:sharedDirector():getWinSize()
local function getBaseLayer()
local layer = CCLayer:create()
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
local item4 = CCMenuItemToggle:create(CCMenuItemFont:create("Free Movement"))
item4:addSubItem(CCMenuItemFont:create("Relative Movement"))
item4:addSubItem(CCMenuItemFont:create("Grouped Movement"))
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
labelAtlas = CCLabelAtlas:create("0000", "fps_images.png", 12, 32, string.byte('.'))
layer:addChild(labelAtlas, 100)
labelAtlas:setPosition(ccp(s.width - 66, 50))
layer:setTouchEnabled(false)
Helper.initWithLayer(layer)
return layer
end
local function drawPrimitivesTest()
local layer = getBaseLayer()
ccDrawLine( ccp(0, s.height), ccp(s.width, 0) );
glLineWidth( 5.0);
ccDrawColor4B(255,0,0,255);
ccDrawLine(ccp(0, 0), ccp(s.width, s.height) );
-- ccPointSize(64);
-- ccDrawColor4B(0,0,255,128);
-- ccDrawPoint( VisibleRect::center() );
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw 4 small points
-- CCPoint points[] = { ccp(60,60), ccp(70,70), ccp(60,70), ccp(70,60) };
-- ccPointSize(4);
-- ccDrawColor4B(0,255,255,255);
-- ccDrawPoints( points, 4);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw a green circle with 10 segments
-- glLineWidth(16);
-- ccDrawColor4B(0, 255, 0, 255);
-- ccDrawCircle( VisibleRect::center(), 100, 0, 10, false);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw a green circle with 50 segments with line to center
-- glLineWidth(2);
-- ccDrawColor4B(0, 255, 255, 255);
-- ccDrawCircle( VisibleRect::center(), 50, CC_DEGREES_TO_RADIANS(90), 50, true);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // open yellow poly
-- ccDrawColor4B(255, 255, 0, 255);
-- glLineWidth(10);
-- CCPoint vertices[] = { ccp(0,0), ccp(50,50), ccp(100,50), ccp(100,100), ccp(50,100) };
-- ccDrawPoly( vertices, 5, false);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // filled poly
-- glLineWidth(1);
-- CCPoint filledVertices[] = { ccp(0,120), ccp(50,120), ccp(50,170), ccp(25,200), ccp(0,170) };
-- ccDrawSolidPoly(filledVertices, 5, ccc4f(0.5f, 0.5f, 1, 1 ) );
--
--
-- // closed purble poly
-- ccDrawColor4B(255, 0, 255, 255);
-- glLineWidth(2);
-- CCPoint vertices2[] = { ccp(30,130), ccp(30,230), ccp(50,200) };
-- ccDrawPoly( vertices2, 3, true);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw quad bezier path
-- ccDrawQuadBezier(VisibleRect::leftTop(), VisibleRect::center(), VisibleRect::rightTop(), 50);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- // draw cubic bezier path
-- ccDrawCubicBezier(VisibleRect::center(), ccp(VisibleRect::center().x+30,VisibleRect::center().y+50), ccp(VisibleRect::center().x+60,VisibleRect::center().y-50),VisibleRect::right(),100);
--
-- CHECK_GL_ERROR_DEBUG();
--
-- //draw a solid polygon
-- CCPoint vertices3[] = {ccp(60,160), ccp(70,190), ccp(100,190), ccp(90,160)};
-- ccDrawSolidPoly( vertices3, 4, ccc4f(1,1,0,1) );
--
-- // restore original values
-- glLineWidth(1);
-- ccDrawColor4B(255,255,255,255);
-- ccPointSize(1);
--
-- CHECK_GL_ERROR_DEBUG();
return layer
end
---------------------------------
-- DrawPrimitives Test
---------------------------------
function CreateDrawPrimitivesTestLayer()
if SceneIdx == 0 then return drawPrimitivesTest()
end
end
function DrawPrimitivesTest()
cclog("DrawPrimitivesTest")
local scene = CCScene:create()
Helper.createFunctionTable = {
drawPrimitivesTest
}
scene:addChild(drawPrimitivesTest())
scene:addChild(CreateBackMenuItem())
return scene
end
| mit |
nyczducky/darkstar | scripts/zones/Northern_San_dOria/npcs/Abioleget.lua | 13 | 2388 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Abioleget
-- Type: Quest Giver (Her Memories: The Faux Pas and The Vicasque's Sermon) / Merchant
-- @zone 231
-- @pos 128.771 0.000 118.538
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (sermonQuest == QUEST_ACCEPTED) then
gil = trade:getGil();
count = trade:getItemCount();
if (gil == 70 and count == 1) then
player:tradeComplete();
player:startEvent(0x024F);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
sermonQuest = player:getQuestStatus(SANDORIA,THE_VICASQUE_S_SERMON);
if (sermonQuest == QUEST_AVAILABLE) then
player:startEvent(0x024d);
elseif (sermonQuest == QUEST_ACCEPTED) then
if (player:getVar("sermonQuestVar") == 1) then
player:tradeComplete();
player:startEvent(0x0258);
else
player:showText(npc,11103,618,70);
end
else
player:showText(npc,ABIOLEGET_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0258) then
player:addItem(13465);
player:messageSpecial(6567, 13465);
player:addFame(SANDORIA,30);
player:addTitle(THE_BENEVOLENT_ONE);
player:setVar("sermonQuestVar",0);
player:completeQuest(SANDORIA,THE_VICASQUE_S_SERMON );
elseif (csid == 0x024D) then
player:addQuest(SANDORIA,THE_VICASQUE_S_SERMON );
elseif (csid == 0x024F) then
player:addItem(618);
player:messageSpecial(6567, 618);
end
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Southern_San_dOria/npcs/Ashene.lua | 14 | 2287 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Ashene
-- Standard Merchant NPC
-- @zone 230
-- @pos 70 0 61
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
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;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ASH_THADI_ENE_SHOP_DIALOG);
local stock = {0x4047,4309,1, --Baselard
0x4094,16934,1, --Gladius
0x40a1,21067,1, --Broadsword
0x40c0,35769,1, --Hunting Sword
0x408c,13406,1, --Fleuret
0x4001,129,2, --Cesti
0x4042,1827,2, --Dagger
0x4098,7128,2, --Iron Sword
0x40b6,8294,2, --Longsword
0x4040,140,3, --Bronze Dagger
0x4041,837,3, --Brass Dagger
0x4093,3523,3, --Brass Xiphos
0x4097,241,3, --Bronze Sword
0x40b5,1674,3} --Spatha
showNationShop(player, NATION_SANDORIA, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Mhaura/npcs/Explorer_Moogle.lua | 17 | 1876 | -----------------------------------
-- Area: Mhaura
-- NPC: Explorer Moogle
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/teleports");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local accept = 0;
local event = 0x014e;
if (player:getGil() < 300) then
accept = 1;
end
if (player:getMainLvl() < EXPLORER_MOOGLE_LEVELCAP) then
event = event + 1;
end
player:startEvent(event,player:getZoneID(),0,accept);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local price = 300;
if (csid == 0x014e) then
if (option == 1 and player:delGil(price)) then
toExplorerMoogle(player,231);
elseif (option == 2 and player:delGil(price)) then
toExplorerMoogle(player,234);
elseif (option == 3 and player:delGil(price)) then
toExplorerMoogle(player,240);
elseif (option == 4 and player:delGil(price)) then
toExplorerMoogle(player,248);
elseif (option == 5 and player:delGil(price)) then
toExplorerMoogle(player,249);
end
end
end; | gpl-3.0 |
nyczducky/darkstar | scripts/zones/Port_Bastok/npcs/Blabbivix.lua | 14 | 1200 | -----------------------------------
-- Area: Port Bastok
-- NPC: Blabbivix
-- Standard merchant, though he acts like a guild merchant
-- @pos -110.209 4.898 22.957 236
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(60418,11,22,3)) then
player:showText(npc,BLABBIVIX_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Ordelles_Caves/npcs/qm5.lua | 14 | 1434 | -----------------------------------
-- Area: Ordelles Caves
-- NPC: ??? (qm5)
-- Involved In Quest: Dark Puppet
-- @pos -92 -28 -70 193
-----------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("darkPuppetCS") >= 3 and player:hasItem(16940) == false) then
if (trade:hasItemQty(16681,1) and trade:getItemCount() == 1) then -- Trade Gerwitz's Axe
player:tradeComplete();
player:messageSpecial(GERWITZS_SWORD_DIALOG);
SpawnMob(17568136):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
cliffano/swaggy-jenkins | clients/lua/generated/spec/pipeline_step_impllinks_spec.lua | 1 | 1181 | --[[
Swaggy Jenkins
Jenkins API clients generated from Swagger / Open API specification
The version of the OpenAPI document: 1.5.1-pre.0
Contact: blah@cliffano.com
Generated by: https://openapi-generator.tech
]]
--[[
Unit tests for openapiclient.model.pipeline_step_impllinks
Automatically generated by openapi-generator (https://openapi-generator.tech)
Please update as you see appropriate
]]
describe("pipeline_step_impllinks", function()
local openapiclient_pipeline_step_impllinks = require "openapiclient.model.pipeline_step_impllinks"
-- unit tests for the property 'self'
describe("property self test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property 'actions'
describe("property actions test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
-- unit tests for the property '_class'
describe("property _class test", function()
it("should work", function()
-- TODO assertion here: http://olivinelabs.com/busted/#asserts
end)
end)
end)
| mit |
jbeich/Aquaria | files/scripts/maps/node_spawnli.lua | 6 | 1102 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
if (isFlag(FLAG_LI, 0) and isMapName("VEIL01"))
or (isFlag(FLAG_LI, 1) and isMapName("LICAVE")) then
createEntity("Li", "", node_x(me), node_y(me))
end
end
function update(me, dt)
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/maps/node_spawnli.lua | 6 | 1102 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
function init(me)
if (isFlag(FLAG_LI, 0) and isMapName("VEIL01"))
or (isFlag(FLAG_LI, 1) and isMapName("LICAVE")) then
createEntity("Li", "", node_x(me), node_y(me))
end
end
function update(me, dt)
end
| gpl-2.0 |
AquariaOSE/Aquaria | files/scripts/entities/splitter1.lua | 6 | 4379 | -- Copyright (C) 2007, 2010 - Bit-Blot
--
-- This file is part of Aquaria.
--
-- Aquaria is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
--
-- See the GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
if not v then v = {} end
if not AQUARIA_VERSION then dofile("scripts/entities/entityinclude.lua") end
-- ================================================================================================
-- JELLY
-- ================================================================================================
-- ================================================================================================
-- L O C A L V A R I A B L E S
-- ================================================================================================
-- ================================================================================================
-- FUNCTIONS
-- ================================================================================================
local MOVE_STATE_UP = 0
local MOVE_STATE_DOWN = 1
v.moveState = 0
v.moveTimer = 0
v.velx = 0
v.waveDir = 1
v.waveTimer = 0
v.soundDelay = 0
function init(me)
setupBasicEntity(
me,
"", -- texture
3, -- health
2, -- manaballamount
2, -- exp
10, -- money
32, -- collideRadius (for hitting entities + spells)
STATE_IDLE, -- initState
128, -- sprite width
128, -- sprite height
1, -- particle "explosion" type, 0 = none
0, -- 0/1 hit other entities off/on (uses collideRadius)
2000, -- updateCull -1: disabled, default: 4000
1
)
--entity_setDeathParticleEffect(me, "PurpleExplode")
entity_initSkeletal(me, "Splitter1")
entity_scale(me, 1.1, 1.1)
entity_setDropChance(me, 40, 1)
--entity_setWeight(me, 300)
entity_setState(me, STATE_IDLE)
entity_setTarget(me, getNaija())
--entity_setDropChance(me, 100)
end
function update(me, dt)
dt = dt * 3
if entity_touchAvatarDamage(me, 32, 1, 1000) then
entity_sound(me, "JellyBlup", 800)
end
entity_handleShotCollisions(me)
v.moveTimer = v.moveTimer - dt
if v.moveTimer < 0 then
if v.moveState == MOVE_STATE_DOWN then
v.moveState = MOVE_STATE_UP
entity_setMaxSpeedLerp(me, 1.5, 0.2)
entity_scale(me, 0.75, 1, 1, 1, 1)
v.moveTimer = 3 + math.random(200)/100.0
entity_sound(me, "JellyBlup")
elseif v.moveState == MOVE_STATE_UP then
v.velx = math.random(400)+100
if math.random(2) == 1 then
v.velx = -v.velx
end
v.moveState = MOVE_STATE_DOWN
--doIdleScale(me)
entity_setMaxSpeedLerp(me, 1, 1)
v.moveTimer = 5 + math.random(200)/100.0 + math.random(3)
end
end
v.waveTimer = v.waveTimer + dt
if v.waveTimer > 2 then
v.waveTimer = 0
if v.waveDir == 1 then
v.waveDir = -1
else
v.waveDir = 1
end
end
if v.moveState == MOVE_STATE_UP then
--entity_addVel(me, v.velx*dt, -600*dt)
--entity_rotateToVel(me, 1)
entity_rotateTo(me, 0, 1)
if not entity_isNearObstruction(getNaija(), 3) then
entity_moveTowardsTarget(me, dt, 500)
end
elseif v.moveState == MOVE_STATE_DOWN then
entity_addVel(me, 0, 300*dt)
--entity_moveTowardsTarget(me, dt, 50)
entity_rotateTo(me, 0, 3)
entity_exertHairForce(me, 0, 200, dt*0.6, -1)
end
entity_doEntityAvoidance(me, dt, 32, 1.0)
entity_doCollisionAvoidance(me, 1.0, 8, 1.0)
entity_updateMovement(me, dt)
end
function hitSurface(me)
end
function enterState(me)
if entity_isState(me, STATE_IDLE) then
entity_animate(me, "idle", -1)
entity_setMaxSpeed(me, 50)
elseif entity_isState(me, STATE_DEAD) then
createEntity("Splitter2", "", entity_x(me)-16, entity_y(me))
createEntity("Splitter2", "", entity_x(me)+16, entity_y(me))
end
end
function damage(me, attacker, bone, damageType, dmg)
return true
end
function exitState(me)
end
| gpl-2.0 |
nyczducky/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Pelsey-Holsey.lua | 14 | 1065 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Pelsey-Holsey
-- Type: Standard NPC
-- @zone 94
-- @pos 119.755 -4.5 209.754
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01a3);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
moltafet35/senatorv2 | plugins/bugzilla.lua | 611 | 3983 | do
local BASE_URL = "https://bugzilla.mozilla.org/rest/"
local function bugzilla_login()
local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password
print("accessing " .. url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_check(id)
-- data = bugzilla_login()
local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey
-- print(url)
local res,code = https.request( url )
local data = json:decode(res)
return data
end
local function bugzilla_listopened(email)
local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey
local res,code = https.request( url )
print(res)
local data = json:decode(res)
return data
end
local function run(msg, matches)
local response = ""
if matches[1] == "status" then
local data = bugzilla_check(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
response = response .. "\n Last update: "..data.bugs[1].last_change_time
response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
print(response)
end
elseif matches[1] == "list" then
local data = bugzilla_listopened(matches[2])
vardump(data)
if data.error == true then
return "Sorry, API failed with message: " .. data.message
else
-- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator
-- response = response .. "\n Last update: "..data.bugs[1].last_change_time
-- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution
-- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard
-- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1]
local total = table.map_length(data.bugs)
print("total bugs: " .. total)
local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2]
if total > 0 then
response = response .. ": "
for tableKey, bug in pairs(data.bugs) do
response = response .. "\n #" .. bug.id
response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution
response = response .. "\n Whiteboard: " .. bug.whiteboard
response = response .. "\n Summary: " .. bug.summary
end
end
end
end
return response
end
-- (table)
-- [bugs] = (table)
-- [1] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 927704
-- [whiteboard] = (string) [approved][full processed]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/
-- [2] = (table)
-- [status] = (string) ASSIGNED
-- [id] = (number) 1049337
-- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos]
-- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/
-- total bugs: 2
return {
description = "Lookup bugzilla status update",
usage = "/bot bugzilla [bug number]",
patterns = {
"^/bugzilla (status) (.*)$",
"^/bugzilla (list) (.*)$"
},
run = run
}
end | gpl-2.0 |
nyczducky/darkstar | scripts/globals/mobskills/Typhoon.lua | 34 | 1116 | ---------------------------------------------
-- Typhoon
--
-- Description: Spins around dealing damage to targets in an area of effect.
-- Type: Physical
-- Utsusemi/Blink absorb: 2-4 shadows
-- Range: 10' radial
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 4;
local accmod = 1;
local dmgmod = 0.5;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
target:delHP(dmg);
if (mob:getName() == "Faust") then
if (mob:getLocalVar("Typhoon") == 0) then
mob:useMobAbility(539);
mob:setLocalVar("Typhoon", 1);
else
mob:setLocalVar("Typhoon", 0);
end
end
return dmg;
end;
| gpl-3.0 |
wenhulove333/ScutServer | Sample/ClientSource/samples/Lua/TestLua/Resources/luaScript/PerformanceTest/PerformanceSpriteTest.lua | 1 | 16575 | local kMaxNodes = 50000
local kBasicZOrder = 10
local kNodesIncrease = 250
local TEST_COUNT = 7
local s = CCDirector:sharedDirector():getWinSize()
-----------------------------------
-- For test functions
-----------------------------------
local function performanceActions(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
local period = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local rot = CCRotateBy:create(period, 360.0 * math.random())
local rot = CCRotateBy:create(period, 360.0 * math.random())
local permanentRotation = CCRepeatForever:create(CCSequence:createWithTwoActions(rot, rot:reverse()))
sprite:runAction(permanentRotation)
local growDuration = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local grow = CCScaleBy:create(growDuration, 0.5, 0.5)
local permanentScaleLoop = CCRepeatForever:create(CCSequence:createWithTwoActions(grow, grow:reverse()))
sprite:runAction(permanentScaleLoop)
end
local function performanceActions20(sprite)
if math.random() < 0.2 then
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
else
sprite:setPosition(CCPointMake(-1000, -1000))
end
local period = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local rot = CCRotateBy:create(period, 360.0 * math.random())
local permanentRotation = CCRepeatForever:create(CCSequence:createWithTwoActions(rot, rot:reverse()))
sprite:runAction(permanentRotation)
local growDuration = 0.5 + math.mod(math.random(1, 99999999), 1000) / 500.0
local grow = CCScaleBy:create(growDuration, 0.5, 0.5)
local permanentScaleLoop = CCRepeatForever:create(CCSequence:createWithTwoActions(grow, grow:reverse()))
sprite:runAction(permanentScaleLoop)
end
local function performanceRotationScale(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
sprite:setRotation(math.random() * 360)
sprite:setScale(math.random() * 2)
end
local function performancePosition(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
end
local function performanceout20(sprite)
if math.random() < 0.2 then
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
else
sprite:setPosition(CCPointMake(-1000, -1000))
end
end
local function performanceOut100(sprite)
sprite:setPosition(CCPointMake( -1000, -1000))
end
local function performanceScale(sprite)
sprite:setPosition(CCPointMake(math.mod(math.random(1, 99999999), s.width), math.mod(math.random(1, 99999999), s.height)))
sprite:setScale(math.random() * 100 / 50)
end
-----------------------------------
-- Subtest
-----------------------------------
local subtestNumber = 1
local batchNode = nil -- CCSpriteBatchNode
local parent = nil -- CCNode
local function initWithSubTest(nSubTest, p)
subtestNumber = nSubTest
parent = p
batchNode = nil
local mgr = CCTextureCache:sharedTextureCache()
-- remove all texture
mgr:removeTexture(mgr:addImage("Images/grossinis_sister1.png"))
mgr:removeTexture(mgr:addImage("Images/grossini_dance_atlas.png"))
mgr:removeTexture(mgr:addImage("Images/spritesheet1.png"))
if subtestNumber == 2 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
batchNode = CCSpriteBatchNode:create("Images/grossinis_sister1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 3 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444)
batchNode = CCSpriteBatchNode:create("Images/grossinis_sister1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 5 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
batchNode = CCSpriteBatchNode:create("Images/grossini_dance_atlas.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 6 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444)
batchNode = CCSpriteBatchNode:create("Images/grossini_dance_atlas.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 8 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
batchNode = CCSpriteBatchNode:create("Images/spritesheet1.png", 100)
p:addChild(batchNode, 0)
elseif subtestNumber == 9 then
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA4444)
batchNode = CCSpriteBatchNode:create("Images/spritesheet1.png", 100)
p:addChild(batchNode, 0)
end
-- todo
if batchNode ~= nil then
batchNode:retain()
end
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default)
end
local function createSpriteWithTag(tag)
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_RGBA8888)
local sprite = nil
if subtestNumber == 1 then
sprite = CCSprite:create("Images/grossinis_sister1.png")
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 2 then
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(0, 0, 52, 139))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 3 then
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(0, 0, 52, 139))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 4 then
local idx = math.floor((math.random() * 1400 / 100)) + 1
local num
if idx < 10 then
num = "0" .. idx
else
num = idx
end
local str = "Images/grossini_dance_" .. num .. ".png"
sprite = CCSprite:create(str)
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 5 then
local y, x
local r = math.floor(math.random() * 1400 / 100)
y = math.floor(r / 5)
x = math.mod(r, 5)
x = x * 85
y = y * 121
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 85, 121))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 6 then
local y, x
local r = math.floor(math.random() * 1400 / 100)
y = math.floor(r / 5)
x = math.mod(r, 5)
x = x * 85
y = y * 121
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 85, 121))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 7 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
local str = "Images/sprites_test/sprite-"..x.."-"..y..".png"
sprite = CCSprite:create(str)
parent:addChild(sprite, -1, tag + 100)
elseif subtestNumber == 8 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
x = x * 32
y = y * 32
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 32, 32))
batchNode:addChild(sprite, 0, tag + 100)
elseif subtestNumber == 9 then
local y, x
local r = math.floor(math.random() * 6400 / 100)
y = math.floor(r / 8)
x = math.mod(r, 8)
x = x * 32
y = y * 32
sprite = CCSprite:createWithTexture(batchNode:getTexture(), CCRectMake(x, y, 32, 32))
batchNode:addChild(sprite, 0, tag + 100)
end
CCTexture2D:setDefaultAlphaPixelFormat(kCCTexture2DPixelFormat_Default)
return sprite
end
local function removeByTag(tag)
if subtestNumber == 1 then
parent:removeChildByTag(tag + 100, true)
elseif subtestNumber == 4 then
parent:removeChildByTag(tag + 100, true)
elseif subtestNumber == 7 then
parent:removeChildByTag(tag + 100, true)
else
batchNode:removeChildAtIndex(tag, true)
end
end
-----------------------------------
-- PerformBasicLayer
-----------------------------------
local curCase = 0
local maxCases = 7
local function showThisTest()
local scene = CreateSpriteTestScene()
CCDirector:sharedDirector():replaceScene(scene)
end
local function backCallback(sender)
subtestNumber = 1
curCase = curCase - 1
if curCase < 0 then
curCase = curCase + maxCases
end
showThisTest()
end
local function restartCallback(sender)
subtestNumber = 1
showThisTest()
end
local function nextCallback(sender)
subtestNumber = 1
curCase = curCase + 1
curCase = math.mod(curCase, maxCases)
showThisTest()
end
local function toPerformanceMainLayer(sender)
CCDirector:sharedDirector():replaceScene(PerformanceTest())
end
local function initWithLayer(layer, controlMenuVisible)
CCMenuItemFont:setFontName("Arial")
CCMenuItemFont:setFontSize(24)
local mainItem = CCMenuItemFont:create("Back")
mainItem:registerScriptTapHandler(toPerformanceMainLayer)
mainItem:setPosition(s.width - 50, 25)
local menu = CCMenu:create()
menu:addChild(mainItem)
menu:setPosition(CCPointMake(0, 0))
if controlMenuVisible == true then
local item1 = CCMenuItemImage:create(s_pPathB1, s_pPathB2)
local item2 = CCMenuItemImage:create(s_pPathR1, s_pPathR2)
local item3 = CCMenuItemImage:create(s_pPathF1, s_pPathF2)
item1:registerScriptTapHandler(backCallback)
item2:registerScriptTapHandler(restartCallback)
item3:registerScriptTapHandler(nextCallback)
item1:setPosition(s.width / 2 - 100, 30)
item2:setPosition(s.width / 2, 30)
item3:setPosition(s.width / 2 + 100, 30)
menu:addChild(item1, kItemTagBasic)
menu:addChild(item2, kItemTagBasic)
menu:addChild(item3, kItemTagBasic)
end
layer:addChild(menu)
end
-----------------------------------
-- SpriteMainScene
-----------------------------------
local lastRenderedCount = nil
local quantityNodes = nil
local infoLabel = nil
local titleLabel = nil
local function testNCallback(tag)
subtestNumber = tag - kBasicZOrder
showThisTest()
end
local function updateNodes()
if quantityNodes ~= lastRenderedCount then
local str = quantityNodes .. " nodes"
infoLabel:setString(str)
lastRenderedCount = quantityNodes
end
end
local function onDecrease(sender)
if quantityNodes <= 0 then
return
end
for i = 0, kNodesIncrease - 1 do
quantityNodes = quantityNodes - 1
removeByTag(quantityNodes)
end
updateNodes()
end
local function onIncrease(sender)
if quantityNodes >= kMaxNodes then
return
end
for i = 0, kNodesIncrease - 1 do
local sprite = createSpriteWithTag(quantityNodes)
if curCase == 0 then
doPerformSpriteTest1(sprite)
elseif curCase == 1 then
doPerformSpriteTest2(sprite)
elseif curCase == 2 then
doPerformSpriteTest3(sprite)
elseif curCase == 3 then
doPerformSpriteTest4(sprite)
elseif curCase == 4 then
doPerformSpriteTest5(sprite)
elseif curCase == 5 then
doPerformSpriteTest6(sprite)
elseif curCase == 6 then
doPerformSpriteTest7(sprite)
end
quantityNodes = quantityNodes + 1
end
updateNodes()
end
local function initWithMainTest(scene, asubtest, nNodes)
subtestNumber = asubtest
initWithSubTest(asubtest, scene)
lastRenderedCount = 0
quantityNodes = 0
CCMenuItemFont:setFontSize(65)
local decrease = CCMenuItemFont:create(" - ")
decrease:registerScriptTapHandler(onDecrease)
decrease:setColor(ccc3(0, 200, 20))
local increase = CCMenuItemFont:create(" + ")
increase:registerScriptTapHandler(onIncrease)
increase:setColor(ccc3(0, 200, 20))
local menu = CCMenu:create()
menu:addChild(decrease)
menu:addChild(increase)
menu:alignItemsHorizontally()
menu:setPosition(s.width / 2, s.height - 65)
scene:addChild(menu, 1)
infoLabel = CCLabelTTF:create("0 nodes", "Marker Felt", 30)
infoLabel:setColor(ccc3(0, 200, 20))
infoLabel:setPosition(s.width / 2, s.height - 90)
scene:addChild(infoLabel, 1)
maxCases = TEST_COUNT
-- Sub Tests
CCMenuItemFont:setFontSize(32)
subMenu = CCMenu:create()
for i = 1, 9 do
local str = i .. " "
local itemFont = CCMenuItemFont:create(str)
itemFont:registerScriptTapHandler(testNCallback)
--itemFont:setTag(i)
subMenu:addChild(itemFont, kBasicZOrder + i, kBasicZOrder + i)
if i <= 3 then
itemFont:setColor(ccc3(200, 20, 20))
elseif i <= 6 then
itemFont:setColor(ccc3(0, 200, 20))
else
itemFont:setColor(ccc3(0, 20, 200))
end
end
subMenu:alignItemsHorizontally()
subMenu:setPosition(CCPointMake(s.width / 2, 80))
scene:addChild(subMenu, 1)
-- add title label
titleLabel = CCLabelTTF:create("No title", "Arial", 40)
scene:addChild(titleLabel, 1)
titleLabel:setPosition(s.width / 2, s.height - 32)
titleLabel:setColor(ccc3(255, 255, 40))
while quantityNodes < nNodes do
onIncrease()
end
end
-----------------------------------
-- SpritePerformTest1
-----------------------------------
function doPerformSpriteTest1(sprite)
performancePosition(sprite)
end
local function SpriteTestLayer1()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "A (" .. subtestNumber .. ") position"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest2
-----------------------------------
function doPerformSpriteTest2(sprite)
performanceScale(sprite)
end
local function SpriteTestLayer2()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "B (" .. subtestNumber .. ") scale"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest3
-----------------------------------
function doPerformSpriteTest3(sprite)
performanceRotationScale(sprite)
end
local function SpriteTestLayer3()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "C (" .. subtestNumber .. ") scale + rot"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest4
-----------------------------------
function doPerformSpriteTest4(sprite)
performanceOut100(sprite)
end
local function SpriteTestLayer4()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "D (" .. subtestNumber .. ") 100% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest5
-----------------------------------
function doPerformSpriteTest5(sprite)
performanceout20(sprite)
end
local function SpriteTestLayer5()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "E (" .. subtestNumber .. ") 80% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest6
-----------------------------------
function doPerformSpriteTest6(sprite)
performanceActions(sprite)
end
local function SpriteTestLayer6()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "F (" .. subtestNumber .. ") actions"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- SpritePerformTest7
-----------------------------------
function doPerformSpriteTest7(sprite)
performanceActions20(sprite)
end
local function SpriteTestLayer7()
local layer = CCLayer:create()
initWithLayer(layer, true)
local str = "G (" .. subtestNumber .. ") actions 80% out"
titleLabel:setString(str)
return layer
end
-----------------------------------
-- PerformanceSpriteTest
-----------------------------------
function CreateSpriteTestScene()
local scene = CCScene:create()
initWithMainTest(scene, subtestNumber, kNodesIncrease)
if curCase == 0 then
scene:addChild(SpriteTestLayer1())
elseif curCase == 1 then
scene:addChild(SpriteTestLayer2())
elseif curCase == 2 then
scene:addChild(SpriteTestLayer3())
elseif curCase == 3 then
scene:addChild(SpriteTestLayer4())
elseif curCase == 4 then
scene:addChild(SpriteTestLayer5())
elseif curCase == 5 then
scene:addChild(SpriteTestLayer6())
elseif curCase == 6 then
scene:addChild(SpriteTestLayer7())
end
return scene
end
function PerformanceSpriteTest()
curCase = 0
return CreateSpriteTestScene()
end
| mit |
nyczducky/darkstar | scripts/zones/Southern_San_dOria/npcs/Blendare.lua | 14 | 1949 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Blendare
-- Type: Standard NPC
-- @zone 230
-- @pos 33.033 0.999 -30.119
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeBlendare") == 0) then
player:messageSpecial(BLENDARE_DIALOG);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradeBlendare",1);
player:messageSpecial(FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getVar("tradeBlendare") ==1) then
player:messageSpecial(FLYER_ALREADY);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x025e) -- my brother always takes my sweets
-- player:startEvent(0x0256) --did nothing no speech or text
-- player:startEvent(0x03b1) --black screen and hang
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x025e) then
player:setVar("BrothersCS", 1)
end
end;
| gpl-3.0 |
jakianroy/NGUI_To_Be_Best | Assets/LuaFramework/ToLua/Lua/misc/utf8.lua | 15 | 8353 | local utf8 = {}
--byte index of the next char after the char at byte index i, followed by a valid flag for the char at byte index i.
--nil if not found. invalid characters are iterated as 1-byte chars.
function utf8.next_raw(s, i)
if not i then
if #s == 0 then return nil end
return 1, true --fake flag (doesn't matter since this flag is not to be taken as full validation)
end
if i > #s then return end
local c = s:byte(i)
if c >= 0x00 and c <= 0x7F then
i = i + 1
elseif c >= 0xC2 and c <= 0xDF then
i = i + 2
elseif c >= 0xE0 and c <= 0xEF then
i = i + 3
elseif c >= 0xF0 and c <= 0xF4 then
i = i + 4
else --invalid
return i + 1, false
end
if i > #s then return end
return i, true
end
--next() is the generic iterator and can be replaced for different semantics. next_raw() must preserve its semantics.
utf8.next = utf8.next_raw
--iterate chars, returning the byte index where each char starts
function utf8.byte_indices(s, previ)
return utf8.next, s, previ
end
--number of chars in string
function utf8.len(s)
assert(s, "bad argument #1 to 'len' (string expected, got nil)")
local len = 0
for _ in utf8.byte_indices(s) do
len = len + 1
end
return len
end
--byte index given char index. nil if the index is outside the string.
function utf8.byte_index(s, target_ci)
if target_ci < 1 then return end
local ci = 0
for i in utf8.byte_indices(s) do
ci = ci + 1
if ci == target_ci then
return i
end
end
assert(target_ci > ci, "invalid index")
end
--char index given byte index. nil if the index is outside the string.
function utf8.char_index(s, target_i)
if target_i < 1 or target_i > #s then return end
local ci = 0
for i in utf8.byte_indices(s) do
ci = ci + 1
if i == target_i then
return ci
end
end
error("invalid index")
end
--byte index of the prev. char before the char at byte index i, which defaults to #s + 1.
--nil if the index is outside the 2..#s+1 range.
--NOTE: unlike next(), this is a O(N) operation!
function utf8.prev(s, nexti)
nexti = nexti or #s + 1
if nexti <= 1 or nexti > #s + 1 then return end
local lasti, lastvalid = utf8.next(s)
for i, valid in utf8.byte_indices(s) do
if i == nexti then
return lasti, lastvalid
end
lasti, lastvalid = i, valid
end
if nexti == #s + 1 then
return lasti, lastvalid
end
error("invalid index")
end
--iterate chars in reverse order, returning the byte index where each char starts.
function utf8.byte_indices_reverse(s, nexti)
if #s < 200 then
--using prev() is a O(N^2/2) operation, ok for small strings (200 chars need 40,000 iterations)
return utf8.prev, s, nexti
else
--store byte indices in a table and iterate them in reverse.
--this is 40x slower than byte_indices() but still fast at 2mil chars/second (but eats RAM and makes garbage).
local t = {}
for i in utf8.byte_indices(s) do
if nexti and i >= nexti then break end
table.insert(t, i)
end
local i = #t + 1
return function()
i = i - 1
return t[i]
end
end
end
--sub based on char indices, which, unlike with standard string.sub(), can't be negative.
--start_ci can be 1..inf and end_ci can be 0..inf. end_ci can be nil meaning last char.
--if start_ci is out of range or end_ci < start_ci, the empty string is returned.
--if end_ci is out of range, it is considered to be the last position in the string.
function utf8.sub(s, start_ci, end_ci)
--assert for positive indices because we might implement negative indices in the future.
assert(start_ci >= 1)
assert(not end_ci or end_ci >= 0)
local ci = 0
local start_i, end_i
for i in utf8.byte_indices(s) do
ci = ci + 1
if ci == start_ci then
start_i = i
end
if ci == end_ci then
end_i = i
end
end
if not start_i then
assert(start_ci > ci, 'invalid index')
return ''
end
if end_ci and not end_i then
if end_ci < start_ci then
return ''
end
assert(end_ci > ci, 'invalid index')
end
return s:sub(start_i, end_i and end_i - 1)
end
--check if a string contains a substring at byte index i without making garbage.
--nil if the index is out of range. true if searching for the empty string.
function utf8.contains(s, i, sub)
if i < 1 or i > #s then return nil end
for si = 1, #sub do
if s:byte(i + si - 1) ~= sub:byte(si) then
return false
end
end
return true
end
--count the number of occurences of a substring in a string. the substring cannot be the empty string.
function utf8.count(s, sub)
assert(#sub > 0)
local count = 0
local i = 1
while i do
if utf8.contains(s, i, sub) then
count = count + 1
i = i + #sub
if i > #s then break end
else
i = utf8.next(s, i)
end
end
return count
end
--utf8 validation and sanitization
--check if there's a valid utf8 codepoint at byte index i. valid ranges for each utf8 byte are:
-- byte 1 2 3 4
--------------------------------------------
-- 00 - 7F
-- C2 - DF 80 - BF
-- E0 A0 - BF 80 - BF
-- E1 - EC 80 - BF 80 - BF
-- ED 80 - 9F 80 - BF
-- EE - EF 80 - BF 80 - BF
-- F0 90 - BF 80 - BF 80 - BF
-- F1 - F3 80 - BF 80 - BF 80 - BF
-- F4 80 - 8F 80 - BF 80 - BF
function utf8.isvalid(s, i)
local c = s:byte(i)
if not c then
return false
elseif c >= 0x00 and c <= 0x7F then
return true
elseif c >= 0xC2 and c <= 0xDF then
local c2 = s:byte(i + 1)
return c2 and c2 >= 0x80 and c2 <= 0xBF
elseif c >= 0xE0 and c <= 0xEF then
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
if c == 0xE0 then
return c2 and c3 and
c2 >= 0xA0 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF
elseif c >= 0xE1 and c <= 0xEC then
return c2 and c3 and
c2 >= 0x80 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF
elseif c == 0xED then
return c2 and c3 and
c2 >= 0x80 and c2 <= 0x9F and
c3 >= 0x80 and c3 <= 0xBF
elseif c >= 0xEE and c <= 0xEF then
if c == 0xEF and c2 == 0xBF and (c3 == 0xBE or c3 == 0xBF) then
return false --uFFFE and uFFFF non-characters
end
return c2 and c3 and
c2 >= 0x80 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF
end
elseif c >= 0xF0 and c <= 0xF4 then
local c2 = s:byte(i + 1)
local c3 = s:byte(i + 2)
local c4 = s:byte(i + 3)
if c == 0xF0 then
return c2 and c3 and c4 and
c2 >= 0x90 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
elseif c >= 0xF1 and c <= 0xF3 then
return c2 and c3 and c4 and
c2 >= 0x80 and c2 <= 0xBF and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
elseif c == 0xF4 then
return c2 and c3 and c4 and
c2 >= 0x80 and c2 <= 0x8F and
c3 >= 0x80 and c3 <= 0xBF and
c4 >= 0x80 and c4 <= 0xBF
end
end
return false
end
--byte index of the next valid utf8 char after the char at byte index i.
--nil if indices go out of range. invalid characters are skipped.
function utf8.next_valid(s, i)
local valid
i, valid = utf8.next_raw(s, i)
while i and (not valid or not utf8.isvalid(s, i)) do
i, valid = utf8.next(s, i)
end
return i
end
--iterate valid chars, returning the byte index where each char starts
function utf8.valid_byte_indices(s)
return utf8.next_valid, s
end
--assert that a string only contains valid utf8 characters
function utf8.validate(s)
for i, valid in utf8.byte_indices(s) do
if not valid or not utf8.isvalid(s, i) then
error(string.format('invalid utf8 char at #%d', i))
end
end
end
local function table_lookup(s, i, j, t)
return t[s:sub(i, j)]
end
--replace characters in string based on a function f(s, i, j, ...) -> replacement_string | nil
function utf8.replace(s, f, ...)
if type(f) == 'table' then
return utf8.replace(s, table_lookup, f)
end
if s == '' then
return s
end
local t = {}
local lasti = 1
for i in utf8.byte_indices(s) do
local nexti = utf8.next(s, i) or #s + 1
local repl = f(s, i, nexti - 1, ...)
if repl then
table.insert(t, s:sub(lasti, i - 1))
table.insert(t, repl)
lasti = nexti
end
end
table.insert(t, s:sub(lasti))
return table.concat(t)
end
local function replace_invalid(s, i, j, repl_char)
if not utf8.isvalid(s, i) then
return repl_char
end
end
--replace invalid utf8 chars with a replacement char
function utf8.sanitize(s, repl_char)
repl_char = repl_char or '�' --\uFFFD
return utf8.replace(s, replace_invalid, repl_char)
end
return utf8
| gpl-3.0 |
nyczducky/darkstar | scripts/zones/Port_Jeuno/npcs/Leyla.lua | 17 | 1514 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Leyla
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,LEYLA_SHOP_DIALOG);
stock = {0x439c,55, -- Hawkeye
0x43a8,7, -- Iron Arrow
0x43b8,5, -- Crossbow Bolt
0x119d,10, -- Distilled Water
0x13ae,1000, -- Enchanting Etude
0x13ad,1265, -- Spirited Etude
0x13ac,1567, -- Learned Etude
0x13ab,1913, -- Quick Etude
0x13aa,2208, -- Vivacious Etude
0x13a9,2815, -- Dextrous Etude
0x13a8,3146} -- Sinewy Etude
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
nyczducky/darkstar | scripts/globals/abilities/aspir_samba.lua | 25 | 1430 | -----------------------------------
-- Ability: Aspir Samba
-- Inflicts the next target you strike with Aspir daze, allowing all those engaged in battle with it to drain its MP.
-- Obtained: Dancer Level 25
-- TP Required: 10%
-- Recast Time: 1:00
-- Duration: 2:00
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then
return MSGBASIC_UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 100) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
return 0,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(100);
end;
local duration = 120 + player:getMod(MOD_SAMBA_DURATION);
duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100;
player:delStatusEffect(EFFECT_HASTE_SAMBA);
player:delStatusEffect(EFFECT_DRAIN_SAMBA);
player:addStatusEffect(EFFECT_ASPIR_SAMBA,1,0,duration);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.