repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
kidaa/Awakening-Core3 | bin/scripts/mobile/tutorial/tutorial_commoner.lua | 1 | 4906 | tutorial_commoner = Creature:new {
objectName = "@mob/creature_names:commoner",
socialGroup = "",
pvpFaction = "",
faction = "",
level = 30,
chanceHit = 0.390000,
damageMin = 290,
damageMax = 300,
baseXp = 2914,
baseHAM = 8400,
baseHAMmax = 10200,
armor = 0,
resists = {-1,-1,-1,-1,-1,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
diet = HERBIVORE,
templates = {"object/mobile/dressed_commoner_fat_zabrak_male_02.iff",
"object/mobile/dressed_commoner_naboo_human_female_04.iff",
"object/mobile/dressed_commoner_naboo_human_male_01.iff",
"object/mobile/dressed_commoner_naboo_bothan_male_02.iff",
"object/mobile/dressed_commoner_naboo_moncal_male_02.iff",
"object/mobile/dressed_commoner_old_human_female_02.iff",
"object/mobile/dressed_commoner_old_zabrak_male_02.iff",
"object/mobile/dressed_commoner_tatooine_nikto_male_05.iff",
},
lootGroups = {},
weapons = {},
attacks = {},
conversationTemplate = "",
optionsBitmask = 0
}
CreatureTemplates:addCreatureTemplate(tutorial_commoner, "tutorial_commoner")
tutorial_commoner_1 = Creature:new {
objectName = "@mob/creature_names:commoner",
socialGroup = "",
pvpFaction = "",
faction = "",
level = 30,
chanceHit = 0.390000,
damageMin = 290,
damageMax = 300,
baseXp = 2914,
baseHAM = 8400,
baseHAMmax = 10200,
armor = 0,
resists = {-1,-1,-1,-1,-1,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_commoner_old_human_female_02.iff",
},
lootGroups = {},
weapons = {},
attacks = {},
conversationTemplate = "",
optionsBitmask = 0
}
CreatureTemplates:addCreatureTemplate(tutorial_commoner_1, "tutorial_commoner_1")
tutorial_commoner_2 = Creature:new {
objectName = "@mob/creature_names:commoner",
socialGroup = "",
pvpFaction = "",
faction = "",
level = 30,
chanceHit = 0.390000,
damageMin = 290,
damageMax = 300,
baseXp = 2914,
baseHAM = 8400,
baseHAMmax = 10200,
armor = 0,
resists = {-1,-1,-1,-1,-1,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_commoner_old_zabrak_male_02.iff",
},
lootGroups = {},
weapons = {},
attacks = {},
conversationTemplate = "",
optionsBitmask = 0
}
CreatureTemplates:addCreatureTemplate(tutorial_commoner_2, "tutorial_commoner_2")
tutorial_commoner_3 = Creature:new {
objectName = "@mob/creature_names:commoner",
socialGroup = "",
pvpFaction = "",
faction = "",
level = 30,
chanceHit = 0.390000,
damageMin = 290,
damageMax = 300,
baseXp = 2914,
baseHAM = 8400,
baseHAMmax = 10200,
armor = 0,
resists = {-1,-1,-1,-1,-1,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_commoner_naboo_moncal_male_02.iff",
},
lootGroups = {},
weapons = {},
attacks = {},
conversationTemplate = "",
optionsBitmask = 0
}
CreatureTemplates:addCreatureTemplate(tutorial_commoner_3, "tutorial_commoner_3")
tutorial_commoner_talking = Creature:new {
objectName = "@mob/creature_names:commoner",
socialGroup = "",
pvpFaction = "",
faction = "",
level = 30,
chanceHit = 0.390000,
damageMin = 290,
damageMax = 300,
baseXp = 2914,
baseHAM = 8400,
baseHAMmax = 10200,
armor = 0,
resists = {-1,-1,-1,-1,-1,-1,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0.000000,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
diet = HERBIVORE,
templates = {"object/mobile/dressed_commoner_fat_zabrak_male_02.iff",
"object/mobile/dressed_commoner_naboo_human_female_04.iff",
"object/mobile/dressed_commoner_naboo_human_male_01.iff",
"object/mobile/dressed_commoner_naboo_bothan_male_02.iff",
"object/mobile/dressed_commoner_naboo_moncal_male_02.iff",
"object/mobile/dressed_commoner_old_human_female_02.iff",
"object/mobile/dressed_commoner_old_zabrak_male_02.iff",
"object/mobile/dressed_commoner_tatooine_nikto_male_05.iff",
},
lootGroups = {},
weapons = {},
attacks = {},
conversationTemplate = "commoner_convotemplate",--dont change this
optionsBitmask = 264
}
CreatureTemplates:addCreatureTemplate(tutorial_commoner_talking, "tutorial_commoner_talking") | lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/wearables/wookiee/wke_gloves_s03.lua | 3 | 2875 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_wearables_wookiee_wke_gloves_s03 = object_tangible_wearables_wookiee_shared_wke_gloves_s03:new {
playerRaces = { "object/creature/player/wookiee_male.iff",
"object/creature/player/wookiee_female.iff",
"object/mobile/vendor/wookiee_female.iff",
"object/mobile/vendor/wookiee_male.iff" },
numberExperimentalProperties = {1, 1, 1, 1},
experimentalProperties = {"XX", "XX", "XX", "XX"},
experimentalWeights = {1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "null", "null"},
experimentalSubGroupTitles = {"null", "null", "sockets", "hitpoints"},
experimentalMin = {0, 0, 0, 1000},
experimentalMax = {0, 0, 0, 1000},
experimentalPrecision = {0, 0, 0, 0},
experimentalCombineType = {0, 0, 4, 4},
}
ObjectTemplates:addTemplate(object_tangible_wearables_wookiee_wke_gloves_s03, "object/tangible/wearables/wookiee/wke_gloves_s03.iff")
| lgpl-3.0 |
airstruck/luigi | luigi/backend/ffisdl.lua | 3 | 14995 | local ROOT = (...):gsub('[^.]*.[^.]*$', '')
local Hooker = require(ROOT .. 'hooker')
local ffi = require 'ffi'
local sdl = require((...) .. '.sdl')
local Image = require((...) .. '.image')
local Font = require((...) .. '.font')
local Keyboard = require((...) .. '.keyboard')
local Text = require((...) .. '.text')
local IntOut = ffi.typeof 'int[1]'
local stack = {}
-- create window and renderer
sdl.enableScreenSaver()
local window = sdl.createWindow('',
sdl.WINDOWPOS_CENTERED, sdl.WINDOWPOS_CENTERED, 800, 600,
sdl.WINDOW_SHOWN + sdl.WINDOW_RESIZABLE)
if window == nil then
error(ffi.string(sdl.getError()))
end
ffi.gc(window, sdl.destroyWindow)
local renderer = sdl.createRenderer(window, -1,
sdl.RENDERER_ACCELERATED + sdl.RENDERER_PRESENTVSYNC)
if renderer == nil then
error(ffi.string(sdl.getError()))
end
ffi.gc(renderer, sdl.destroyRenderer)
sdl.setRenderDrawBlendMode(renderer, sdl.BLENDMODE_BLEND)
local Backend = {}
Backend.sdl = sdl
Backend.isMac = function ()
return sdl.getPlatform() == 'Mac OS X'
end
local callback = {
draw = function () end,
resize = function () end,
mousepressed = function () end,
mousereleased = function () end,
mousemoved = function () end,
keypressed = function () end,
keyreleased = function () end,
textinput = function () end,
wheelmoved = function () end,
}
Backend.run = function ()
local event = sdl.Event()
local tickInterval = 16 -- ~60 fps (with room)
local nextTick = 0
local sdl = sdl
while true do
sdl.pumpEvents()
while sdl.pollEvent(event) ~= 0 do
if event.type == sdl.QUIT then
return
elseif event.type == sdl.WINDOWEVENT
and event.window.event == sdl.WINDOWEVENT_RESIZED then
local window = event.window
callback.resize(window.data1, window.data2)
elseif event.type == sdl.MOUSEBUTTONDOWN then
local button = event.button
callback.mousepressed(button.x, button.y, button.button)
elseif event.type == sdl.MOUSEBUTTONUP then
local button = event.button
callback.mousereleased(button.x, button.y, button.button)
elseif event.type == sdl.MOUSEMOTION then
local motion = event.motion
callback.mousemoved(motion.x, motion.y)
elseif event.type == sdl.KEYDOWN then
local key = Keyboard.stringByKeycode[event.key.keysym.sym] or 'unknown'
local scanCode = Keyboard.stringByScancode[event.key.keysym.scancode] or 'unknown'
callback.keypressed(key, scanCode, event.key['repeat'])
elseif event.type == sdl.KEYUP then
local key = Keyboard.stringByKeycode[event.key.keysym.sym] or 'unknown'
local scanCode = Keyboard.stringByScancode[event.key.keysym.scancode] or 'unknown'
callback.keyreleased(key, scanCode, event.key['repeat'])
elseif event.type == sdl.TEXTINPUT then
callback.textinput(ffi.string(event.text.text))
elseif event.type == sdl.MOUSEWHEEL then
local wheel = event.wheel
callback.wheelmoved(wheel.x, wheel.y)
end
end
sdl.renderSetClipRect(renderer, nil)
sdl.setRenderDrawColor(renderer, 0, 0, 0, 255)
sdl.renderClear(renderer)
callback.draw()
local now = sdl.getTicks()
if nextTick > now then
sdl.delay(nextTick - now)
end
nextTick = now + tickInterval
sdl.renderPresent(renderer)
end
end
Backend.Cursor = function (image, x, y)
return sdl.createColorCursor(image.sdlSurface, x, y)
end
Backend.Font = Font
Backend.Image = function (path)
return Image(renderer, path)
end
Backend.Text = function (...)
return Text(renderer, ...)
end
Backend.Quad = function (x, y, w, h)
return { x, y, w, h }
end
Backend.SpriteBatch = require((...) .. '.spritebatch')
Backend.draw = function (drawable, x, y, sx, sy)
if drawable.draw then
return drawable:draw(x, y, sx, sy)
end
if drawable.sdlTexture == nil
or drawable.sdlRenderer == nil
or drawable.getWidth == nil
or drawable.getHeight == nil
then return
end
local w = drawable:getWidth() * (sx or 1)
local h = drawable:getHeight() * (sy or 1)
-- HACK. Somehow drawing something first prevents renderCopy from
-- incorrectly scaling up in some cases (after rendering slices).
-- For example http://stackoverflow.com/questions/28218906
sdl.renderDrawPoint(drawable.sdlRenderer, -1, -1)
-- Draw the image.
sdl.renderCopy(drawable.sdlRenderer, drawable.sdlTexture,
nil, sdl.Rect(x, y, w, h))
end
Backend.drawRectangle = function (mode, x, y, w, h)
if mode == 'fill' then
sdl.renderFillRect(renderer, sdl.Rect(x, y, w, h))
else
sdl.renderDrawRect(renderer, sdl.Rect(x, y, w, h))
end
end
local currentFont = Font()
local lastColor
-- print( text, x, y, r, sx, sy, ox, oy, kx, ky )
Backend.print = function (text, x, y)
if not text or text == '' then return end
local font = currentFont.sdlFont
local color = sdl.Color(lastColor or { 0, 0, 0, 255 })
local write = Font.SDL2_ttf.TTF_RenderUTF8_Blended
local surface = write(font, text, color)
ffi.gc(surface, sdl.freeSurface)
local texture = sdl.createTextureFromSurface(renderer, surface)
ffi.gc(texture, sdl.destroyTexture)
sdl.renderCopy(renderer, texture, nil, sdl.Rect(x, y, surface.w, surface.h))
end
Backend.getClipboardText = function ()
return ffi.string(sdl.getClipboardText())
end
Backend.setClipboardText = sdl.setClipboardText
Backend.getMousePosition = function ()
local x, y = IntOut(), IntOut()
sdl.getMouseState(x, y)
return x[0], y[0]
end
local function SystemCursor (id)
return ffi.gc(sdl.createSystemCursor(id), sdl.freeCursor)
end
local systemCursors = {
arrow = SystemCursor(sdl.SYSTEM_CURSOR_ARROW),
ibeam = SystemCursor(sdl.SYSTEM_CURSOR_IBEAM),
wait = SystemCursor(sdl.SYSTEM_CURSOR_WAIT),
crosshair = SystemCursor(sdl.SYSTEM_CURSOR_CROSSHAIR),
waitarrow = SystemCursor(sdl.SYSTEM_CURSOR_WAITARROW),
sizenwse = SystemCursor(sdl.SYSTEM_CURSOR_SIZENWSE),
sizenesw = SystemCursor(sdl.SYSTEM_CURSOR_SIZENESW),
sizewe = SystemCursor(sdl.SYSTEM_CURSOR_SIZEWE),
sizens = SystemCursor(sdl.SYSTEM_CURSOR_SIZENS),
sizeall = SystemCursor(sdl.SYSTEM_CURSOR_SIZEALL),
no = SystemCursor(sdl.SYSTEM_CURSOR_NO),
hand = SystemCursor(sdl.SYSTEM_CURSOR_HAND),
}
Backend.getSystemCursor = function (name)
return systemCursors[name] or systemCursors.arrow
end
Backend.getWindowSize = function ()
local x, y = IntOut(), IntOut()
sdl.getWindowSize(window, x, y)
return x[0], y[0]
end
Backend.getTime = function ()
return sdl.getTicks() * 0.001
end
Backend.isKeyDown = function (...)
local state = sdl.getKeyboardState(nil)
for i = 1, select('#', ...) do
local name = select(i, ...)
local scan = Keyboard.scancodeByString[name]
if scan and state[scan] ~= 0 then
return true
end
end
return false
end
Backend.isMouseDown = function ()
end
Backend.quit = function ()
sdl.quit()
os.exit()
end
Backend.setColor = function (color)
lastColor = color
sdl.setRenderDrawColor(renderer,
color[1], color[2], color[3], color[4] or 255)
end
Backend.setCursor = function (cursor)
sdl.setCursor(cursor or Backend.getSystemCursor('arrow'))
end
Backend.setFont = function (font)
currentFont = font
end
local lastScissor
Backend.setScissor = function (x, y, w, h)
-- y = y and Backend.getWindowHeight() - (y + h)
lastScissor = x and sdl.Rect(x, y, w, h)
sdl.renderSetClipRect(renderer, lastScissor)
end
Backend.getScissor = function ()
if lastScissor ~= nil then
local x, y = lastScissor.x, lastScissor.y
local w, h = lastScissor.w, lastScissor.h
-- y = y and Backend.getWindowHeight() - (y + h)
return x, y, w, h
end
end
function Backend.hide (layout)
for _, item in ipairs(layout.hooks) do
Hooker.unhook(item)
end
layout.hooks = {}
end
local function hook (layout, key, method, hookLast)
layout.hooks[#layout.hooks + 1] = Hooker.hook(
callback, key, method, hookLast)
end
Backend.pop = function ()
local history = stack[#stack]
lastColor = history.color or { 0, 0, 0, 255 }
lastScissor = history.scissor
sdl.setRenderDrawColor(renderer,
lastColor[1], lastColor[2], lastColor[3], lastColor[4] or 255)
sdl.renderSetClipRect(renderer, lastScissor) -- Backend.setScissor(history.scissor)
stack[#stack] = nil
end
Backend.push = function ()
stack[#stack + 1] = {
color = lastColor,
scissor = lastScissor,
}
end
local isMouseDown = function ()
return sdl.getMouseState(nil, nil) > 0
end
local buttonIds = {
[sdl.BUTTON_LEFT] = 'left',
[sdl.BUTTON_MIDDLE] = 'middle',
[sdl.BUTTON_RIGHT] = 'right',
-- [sdl.BUTTON_X1] = 'x1',
-- [sdl.BUTTON_X2] = 'x2',
}
local function getMouseButtonId (value)
return value and buttonIds[value] or value
end
function Backend.show (layout)
local input = layout.input
hook(layout, 'draw', function ()
input:handleDisplay(layout)
end, true)
hook(layout, 'resize', function (width, height)
return input:handleReshape(layout, width, height)
end)
hook(layout, 'mousepressed', function (x, y, button)
return input:handlePressStart(layout, getMouseButtonId(button), x, y)
end)
hook(layout, 'mousereleased', function (x, y, button)
return input:handlePressEnd(layout, getMouseButtonId(button), x, y)
end)
hook(layout, 'mousemoved', function (x, y, dx, dy)
if isMouseDown() then
return input:handlePressedMove(layout, x, y)
else
return input:handleMove(layout, x, y)
end
end)
hook(layout, 'keypressed', function (key, scanCode, isRepeat)
return input:handleKeyPress(layout, key, scanCode, Backend.getMousePosition())
end)
hook(layout, 'keyreleased', function (key, scanCode)
return input:handleKeyRelease(layout, key, scanCode, Backend.getMousePosition())
end)
hook(layout, 'textinput', function (text)
return input:handleTextInput(layout, text, Backend.getMousePosition())
end)
hook(layout, 'wheelmoved', function (x, y)
return input:handleWheelMove(layout, x, y)
end)
end
function Backend.getWindowMaximized ()
local flags = sdl.getWindowFlags(window)
return bit.band(flags, sdl.WINDOW_MAXIMIZED) ~= 0
end
function Backend.setWindowMaximized (maximized)
if maximized then
sdl.maximizeWindow(window)
else
sdl.restoreWindow(window)
end
end
function Backend.getWindowMinimized ()
local flags = sdl.getWindowFlags(window)
return bit.band(flags, sdl.WINDOW_MINIMIZED) ~= 0
end
function Backend.setWindowMinimized (minimized)
if minimized then
sdl.minimizeWindow(window)
else
sdl.restoreWindow(window)
end
end
function Backend.getWindowBorderless ()
local flags = sdl.getWindowFlags(window)
return bit.band(flags, sdl.WINDOW_BORDERLESS) ~= 0
end
function Backend.setWindowBorderless (borderless)
return sdl.setWindowBordered(window, not borderless)
end
function Backend.getWindowFullscreen ()
local flags = sdl.getWindowFlags(window)
return bit.band(flags, sdl.WINDOW_FULLSCREEN) ~= 0
end
function Backend.setWindowFullscreen (fullscreen)
return sdl.setWindowFullscreen(window, not not fullscreen)
end
function Backend.getWindowGrab ()
return sdl.getWindowGrab(window)
end
function Backend.setWindowGrab (grab)
return sdl.setWindowGrab(window, not not grab)
end
local SDL2_image = ffi.load 'SDL2_image'
function Backend.setWindowIcon (icon)
-- XXX: is it safe to free this?
local surface = ffi.gc(SDL2_image.IMG_Load(icon), sdl.freeSurface)
if surface == nil then
error(ffi.string(sdl.getError()))
end
sdl.setWindowIcon(window, surface)
end
function Backend.getWindowMaxwidth ()
local w, h = IntOut(), IntOut()
sdl.getWindowMaximumSize(window, w, h)
return w[0]
end
function Backend.setWindowMaxwidth (maxwidth)
local w, h = IntOut(), IntOut()
sdl.getWindowMaximumSize(window, w, h)
sdl.setWindowMaximumSize(window, maxwidth, h[0] or 16384)
end
function Backend.getWindowMaxheight ()
local w, h = IntOut(), IntOut()
sdl.getWindowMaximumSize(window, w, h)
return h[0]
end
function Backend.setWindowMaxheight (maxheight)
local w, h = IntOut(), IntOut()
sdl.getWindowMaximumSize(window, w, h)
sdl.setWindowMaximumSize(window, w[0] or 16384, maxheight)
end
function Backend.getWindowMinwidth ()
local w, h = IntOut(), IntOut()
sdl.getWindowMinimumSize(window, w, h)
return w[0]
end
function Backend.setWindowMinwidth (minwidth)
local w, h = IntOut(), IntOut()
sdl.getWindowMinimumSize(window, w, h)
sdl.setWindowMinimumSize(window, minwidth, h[0] or 0)
end
function Backend.getWindowMinheight ()
local w, h = IntOut(), IntOut()
sdl.getWindowMinimumSize(window, w, h)
return h[0]
end
function Backend.setWindowMinheight (minheight)
local w, h = IntOut(), IntOut()
sdl.getWindowMinimumSize(window, w, h)
sdl.setWindowMinimumSize(window, w[0] or 0, minheight)
end
function Backend.getWindowTop ()
local x, y = IntOut(), IntOut()
sdl.getWindowPosition(window, x, y)
return y[0]
end
function Backend.setWindowTop (top)
local x, y = IntOut(), IntOut()
sdl.getWindowPosition(window, x, y)
sdl.setWindowPosition(window, x[0] or 0, top)
end
function Backend.getWindowLeft ()
local x, y = IntOut(), IntOut()
sdl.getWindowPosition(window, x, y)
return x[0]
end
function Backend.setWindowLeft (left)
local x, y = IntOut(), IntOut()
sdl.getWindowPosition(window, x, y)
sdl.setWindowPosition(window, left, y[0] or 0)
end
function Backend.getWindowWidth ()
local w, h = IntOut(), IntOut()
sdl.getWindowSize(window, w, h)
return w[0]
end
function Backend.setWindowWidth (width)
local w, h = IntOut(), IntOut()
sdl.getWindowSize(window, w, h)
sdl.setWindowSize(window, width, h[0] or 600)
end
function Backend.getWindowHeight ()
local w, h = IntOut(), IntOut()
sdl.getWindowSize(window, w, h)
return h[0]
end
function Backend.setWindowHeight (height)
local w, h = IntOut(), IntOut()
sdl.getWindowSize(window, w, h)
sdl.setWindowSize(window, w[0] or 800, height)
end
function Backend.getWindowTitle (title)
return sdl.getWindowTitle(window)
end
function Backend.setWindowTitle (title)
sdl.setWindowTitle(window, title)
end
return Backend
| mit |
kidaa/Awakening-Core3 | bin/scripts/object/static/flora/flora_plant_tato_falotil_bare.lua | 3 | 2256 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_static_flora_flora_plant_tato_falotil_bare = object_static_flora_shared_flora_plant_tato_falotil_bare:new {
}
ObjectTemplates:addTemplate(object_static_flora_flora_plant_tato_falotil_bare, "object/static/flora/flora_plant_tato_falotil_bare.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/wearables/necklace/necklace_ornamental_ratchet.lua | 3 | 4267 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_wearables_necklace_necklace_ornamental_ratchet = object_tangible_wearables_necklace_shared_necklace_ornamental_ratchet:new {
playerRaces = { "object/creature/player/bothan_male.iff",
"object/creature/player/bothan_female.iff",
"object/creature/player/human_male.iff",
"object/creature/player/human_female.iff",
"object/creature/player/moncal_male.iff",
"object/creature/player/moncal_female.iff",
"object/creature/player/rodian_male.iff",
"object/creature/player/rodian_female.iff",
"object/creature/player/sullustan_male.iff",
"object/creature/player/sullustan_female.iff",
"object/creature/player/trandoshan_male.iff",
"object/creature/player/trandoshan_female.iff",
"object/creature/player/twilek_male.iff",
"object/creature/player/twilek_female.iff",
"object/creature/player/zabrak_male.iff",
"object/creature/player/zabrak_female.iff",
"object/mobile/vendor/aqualish_female.iff",
"object/mobile/vendor/aqualish_male.iff",
"object/mobile/vendor/bith_female.iff",
"object/mobile/vendor/bith_male.iff",
"object/mobile/vendor/bothan_female.iff",
"object/mobile/vendor/bothan_male.iff",
"object/mobile/vendor/devaronian_male.iff",
"object/mobile/vendor/gran_male.iff",
"object/mobile/vendor/human_female.iff",
"object/mobile/vendor/human_male.iff",
"object/mobile/vendor/ishi_tib_male.iff",
"object/mobile/vendor/moncal_female.iff",
"object/mobile/vendor/moncal_male.iff",
"object/mobile/vendor/nikto_male.iff",
"object/mobile/vendor/quarren_male.iff",
"object/mobile/vendor/rodian_female.iff",
"object/mobile/vendor/rodian_male.iff",
"object/mobile/vendor/sullustan_female.iff",
"object/mobile/vendor/sullustan_male.iff",
"object/mobile/vendor/trandoshan_female.iff",
"object/mobile/vendor/trandoshan_male.iff",
"object/mobile/vendor/twilek_female.iff",
"object/mobile/vendor/twilek_male.iff",
"object/mobile/vendor/weequay_male.iff",
"object/mobile/vendor/zabrak_female.iff",
"object/mobile/vendor/zabrak_male.iff" },
}
ObjectTemplates:addTemplate(object_tangible_wearables_necklace_necklace_ornamental_ratchet, "object/tangible/wearables/necklace/necklace_ornamental_ratchet.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/creature/npc/base/weequay_base_male.lua | 3 | 2228 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_creature_npc_base_weequay_base_male = object_creature_npc_base_shared_weequay_base_male:new {
}
ObjectTemplates:addTemplate(object_creature_npc_base_weequay_base_male, "object/creature/npc/base/weequay_base_male.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/mobile/dressed_binayre_ruffian_trandoshan_female_01.lua | 3 | 2292 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_mobile_dressed_binayre_ruffian_trandoshan_female_01 = object_mobile_shared_dressed_binayre_ruffian_trandoshan_female_01:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_binayre_ruffian_trandoshan_female_01, "object/mobile/dressed_binayre_ruffian_trandoshan_female_01.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/furniture/cheap/objects.lua | 3 | 18219 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_tangible_furniture_cheap_shared_armoire_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_armoire_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_armoire_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8197,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 2,
containerVolumeLimit = 50,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_armoire",
gameObjectType = 8197,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_armoire",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 814787995,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_armoire_s01, "object/tangible/furniture/cheap/shared_armoire_s01.iff")
object_tangible_furniture_cheap_shared_bookcase_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_bookcase_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_bookcase_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8197,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 2,
containerVolumeLimit = 50,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_bookcase",
gameObjectType = 8197,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_bookcase",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 536193644,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_bookcase_s01, "object/tangible/furniture/cheap/shared_bookcase_s01.iff")
object_tangible_furniture_cheap_shared_cabinet_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_cabinet_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_cabinet_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8197,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 2,
containerVolumeLimit = 50,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_cabinet",
gameObjectType = 8197,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_cabinet",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1571830128,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_cabinet_s01, "object/tangible/furniture/cheap/shared_cabinet_s01.iff")
object_tangible_furniture_cheap_shared_chair_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_chair_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_chair_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8203,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_chair",
gameObjectType = 8203,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_chair",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 390371593,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_chair_s01, "object/tangible/furniture/cheap/shared_chair_s01.iff")
object_tangible_furniture_cheap_shared_chest_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_chest_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_chest_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8197,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 2,
containerVolumeLimit = 50,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_chest",
gameObjectType = 8197,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_chest",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3830949127,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_chest_s01, "object/tangible/furniture/cheap/shared_chest_s01.iff")
object_tangible_furniture_cheap_shared_coffee_table_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_coffee_table_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_coffee_table_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8203,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_coffee_table",
gameObjectType = 8203,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_coffee_table_s01",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 3533156957,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_coffee_table_s01, "object/tangible/furniture/cheap/shared_coffee_table_s01.iff")
object_tangible_furniture_cheap_shared_couch_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_couch_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_couch_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8203,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_couch",
gameObjectType = 8203,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_couch",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 760525609,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_couch_s01, "object/tangible/furniture/cheap/shared_couch_s01.iff")
object_tangible_furniture_cheap_shared_end_table_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_end_table_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_end_table_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8203,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_end_table",
gameObjectType = 8203,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_end_table",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 506885495,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_end_table_s01, "object/tangible/furniture/cheap/shared_end_table_s01.iff")
object_tangible_furniture_cheap_shared_love_seat_s01 = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/furniture/cheap/shared_love_seat_s01.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/frn_all_chep_love_seat_s01.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 0,
clientDataFile = "",
clientGameObjectType = 8203,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 0,
collisionMaterialBlockFlags = 1,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@frn_d:frn_love_seat",
gameObjectType = 8203,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 0,
objectName = "@frn_n:frn_love_seat",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "abstract/slot/descriptor/tangible.iff",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 649092668,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/base/shared_tangible_craftable.iff", "object/tangible/furniture/base/shared_furniture_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_furniture_cheap_shared_love_seat_s01, "object/tangible/furniture/cheap/shared_love_seat_s01.iff")
| lgpl-3.0 |
eraffxi/darkstar | scripts/globals/items/bowl_of_shark_fin_soup.lua | 2 | 1666 | -----------------------------------------
-- ID: 4452
-- Item: bowl_of_shark_fin_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- HP % 5 (cap 150)
-- MP 5
-- Dexterity 4
-- HP Recovered While Healing 9
-- Attack % 14 (cap 85)
-- Ranged Attack % 14 (cap 85)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(dsp.effect.FOOD) == true or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4452);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(dsp.mod.FOOD_HPP, 5);
target:addMod(dsp.mod.FOOD_HP_CAP, 150);
target:addMod(dsp.mod.DEX, 4);
target:addMod(dsp.mod.MP, 5);
target:addMod(dsp.mod.HPHEAL, 9);
target:addMod(dsp.mod.FOOD_ATTP, 14);
target:addMod(dsp.mod.FOOD_ATT_CAP, 85);
target:addMod(dsp.mod.FOOD_RATTP, 14);
target:addMod(dsp.mod.FOOD_RATT_CAP, 85);
end;
function onEffectLose(target, effect)
target:delMod(dsp.mod.FOOD_HPP, 5);
target:delMod(dsp.mod.FOOD_HP_CAP, 150);
target:delMod(dsp.mod.DEX, 4);
target:delMod(dsp.mod.MP, 5);
target:delMod(dsp.mod.HPHEAL, 9);
target:delMod(dsp.mod.FOOD_ATTP, 14);
target:delMod(dsp.mod.FOOD_ATT_CAP, 85);
target:delMod(dsp.mod.FOOD_RATTP, 14);
target:delMod(dsp.mod.FOOD_RATT_CAP, 85);
end;
| gpl-3.0 |
eraffxi/darkstar | scripts/zones/Apollyon/mobs/Carnagechief_Jackbodokk.lua | 2 | 2127 | -----------------------------------
-- Area: Apollyon CS
-- MOB: Carnagechief_Jackbodokk
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Apollyon/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
end;
function onMobEngaged(mob,target)
local mobID = mob:getID();
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
SpawnMob(16933130):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
SpawnMob(16933131):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
SpawnMob(16933132):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
end;
function onMobFight(mob,target)
local mobID = mob:getID();
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100);
local instancetime = target:getSpecialBattlefieldLeftTime(5);
if (lifepourcent < 50 and GetNPCByID(16933245):getAnimation() == 8) then
SpawnMob(16933134):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
SpawnMob(16933135):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
SpawnMob(16933133):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
SpawnMob(16933136):setMobMod(dsp.mobMod.SUPERLINK, mob:getShortID());
GetNPCByID(16933245):setAnimation(9);
end
if (instancetime < 13) then
if (IsMobDead(16933144) == false) then --link dee wapa
GetMobByID(16933144):updateEnmity(target);
elseif (IsMobDead(16933137) == false) then --link na qba
GetMobByID(16933137):updateEnmity(target);
end
end
end;
function onMobDeath(mob, player, isKiller)
if ((IsMobDead(16933144) == false or IsMobDead(16933137) == false) and alreadyReceived(player,1,GetInstanceRegion(1294)) == false) then
player:addTimeToSpecialBattlefield(5,5);
addLimbusList(player,1,GetInstanceRegion(1294));
end
end;
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/hair/human/hair_human_male_s03.lua | 3 | 2244 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_hair_human_hair_human_male_s03 = object_tangible_hair_human_shared_hair_human_male_s03:new {
}
ObjectTemplates:addTemplate(object_tangible_hair_human_hair_human_male_s03, "object/tangible/hair/human/hair_human_male_s03.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/weapon/ranged/rifle/serverobjects.lua | 3 | 3196 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--Children folder includes
includeFile("weapon/ranged/rifle/base/serverobjects.lua")
-- Server Objects
includeFile("weapon/ranged/rifle/rifle_acid_beam.lua")
includeFile("weapon/ranged/rifle/rifle_beam.lua")
includeFile("weapon/ranged/rifle/rifle_berserker.lua")
includeFile("weapon/ranged/rifle/rifle_bowcaster.lua")
includeFile("weapon/ranged/rifle/rifle_cdef.lua")
includeFile("weapon/ranged/rifle/rifle_dlt20.lua")
includeFile("weapon/ranged/rifle/rifle_dlt20a.lua")
includeFile("weapon/ranged/rifle/rifle_e11.lua")
includeFile("weapon/ranged/rifle/rifle_ewok_crossbow.lua")
includeFile("weapon/ranged/rifle/rifle_flame_thrower.lua")
includeFile("weapon/ranged/rifle/rifle_jawa_ion.lua")
includeFile("weapon/ranged/rifle/rifle_laser.lua")
includeFile("weapon/ranged/rifle/rifle_laser_noob.lua")
includeFile("weapon/ranged/rifle/rifle_lightning.lua")
includeFile("weapon/ranged/rifle/rifle_sg82.lua")
includeFile("weapon/ranged/rifle/rifle_spraystick.lua")
includeFile("weapon/ranged/rifle/rifle_t21.lua")
includeFile("weapon/ranged/rifle/rifle_tenloss_dxr6_disruptor_loot.lua")
includeFile("weapon/ranged/rifle/rifle_tusken.lua")
includeFile("weapon/ranged/rifle/rifle_victor_tusken.lua")
| lgpl-3.0 |
sohrab96/tabchi | fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
EhsanFox/Self-Bot-V3 | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
Richard857/BadRotations | Rotations/Paladin/Retribution/RetributionCuteOne.lua | 1 | 51534 | local rotationName = "CuteOne"
---------------
--- Toggles ---
---------------
local function createToggles()
-- Rotation Button
RotationModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Automatic Rotation", tip = "基于范围内的目标数,在单目标和多目标自动切换输出方式.", highlight = 1, icon = br.player.spell.divineStorm },
[2] = { mode = "Mult", value = 2 , overlay = "Multiple Target Rotation", tip = "使用多目标方式输出.", highlight = 0, icon = br.player.spell.divineStorm },
[3] = { mode = "Sing", value = 3 , overlay = "Single Target Rotation", tip = "使用单目标方式输出.", highlight = 0, icon = br.player.spell.crusaderStrike },
[4] = { mode = "Off", value = 4 , overlay = "DPS Rotation Disabled", tip = "禁用DPS输出", highlight = 0, icon = br.player.spell.flashOfLight }
}
CreateButton("Rotation",1,0)
-- Cooldown Button
CooldownModes = {
[1] = { mode = "Auto", value = 1 , overlay = "Cooldowns Automated", tip = "自动使用大技能 - 只在BOSS.", highlight = 1, icon = br.player.spell.avengingWrath },
[2] = { mode = "On", value = 1 , overlay = "Cooldowns Enabled", tip = "不管任何目标都使用大技能.", highlight = 0, icon = br.player.spell.avengingWrath },
[3] = { mode = "Off", value = 3 , overlay = "Cooldowns Disabled", tip = "不使用大技能.", highlight = 0, icon = br.player.spell.avengingWrath }
};
CreateButton("Cooldown",2,0)
-- Defensive Button
DefensiveModes = {
[1] = { mode = "On", value = 1 , overlay = "Defensive Enabled", tip = "使用保命技能.", highlight = 1, icon = br.player.spell.flashOfLight },
[2] = { mode = "Off", value = 2 , overlay = "Defensive Disabled", tip = "不使用保命技能.", highlight = 0, icon = br.player.spell.flashOfLight }
};
CreateButton("Defensive",3,0)
-- Interrupt Button
InterruptModes = {
[1] = { mode = "On", value = 1 , overlay = "Interrupts Enabled", tip = "使用打断.", highlight = 1, icon = br.player.spell.hammerOfJustice },
[2] = { mode = "Off", value = 2 , overlay = "Interrupts Disabled", tip = "不使用打断.", highlight = 0, icon = br.player.spell.hammerOfJustice }
};
CreateButton("Interrupt",4,0)
end
---------------
--- OPTIONS ---
---------------
local function createOptions()
local optionTable
local function rotationOptions()
-----------------------
--- GENERAL OPTIONS ---
-----------------------
section = br.ui:createSection(br.ui.window.profile, "一般")
-- APL
br.ui:createDropdownWithout(section, "APL模式", {"|cffFFFFFFSimC","|cffFFFFFFAMR"}, 1, "|cffFFFFFF选择输出循环.")
-- Dummy DPS Test
br.ui:createSpinner(section, "DPS测试", 5, 5, 60, 5, "|cffFFFFFF设置为所需的测试的时间(分钟). 最小: 5 / 最大: 60 / 间隔: 5")
-- Opener
br.ui:createCheckbox(section, "Opener")
-- Greater Blessing of Might
-- br.ui:createCheckbox(section, "Greater Blessing of Might")
-- Hand of Freedom
br.ui:createCheckbox(section, "自由祝福")
-- Hand of Hindeance
br.ui:createCheckbox(section, "妨害之手")
-- Divine Storm Units
br.ui:createSpinner(section, "神圣风暴 数量", 2, 2, 3, 1, "|cffFFBB00使用神风暴的单位.如果你有神恩风暴和正义之刃神的神器特质请设置为2,如果你没有这些特质设置为3.")
-- Artifact
br.ui:createDropdownWithout(section,"神器技能", {"|cff00FF00任何时候","|cffFFFF00冷却技能","|cffFF0000决不"}, 1, "|cffFFFFFF何时使用神器技能.")
br.ui:checkSectionState(section)
------------------------
--- COOLDOWN OPTIONS ---
------------------------
section = br.ui:createSection(br.ui.window.profile, "冷却技能")
-- Racial
br.ui:createCheckbox(section,"种族技能")
-- Trinkets
br.ui:createCheckbox(section,"饰品")
-- Holy Wrath
br.ui:createCheckbox(section,"神圣愤怒")
-- Avenging Wrath
br.ui:createCheckbox(section,"复仇之怒")
-- Shield of Vengeance
br.ui:createCheckbox(section,"复仇之盾")
-- Cruusade
br.ui:createCheckbox(section,"征伐")
br.ui:checkSectionState(section)
-------------------------
--- DEFENSIVE OPTIONS ---
-------------------------
section = br.ui:createSection(br.ui.window.profile, "保命")
-- Healthstone
br.ui:createSpinner(section, "药水/治疗石", 60, 0, 100, 5, "|cffFFFFFF多少血量百分比使用")
-- Heirloom Neck
br.ui:createSpinner(section, "传家宝项链", 60, 0, 100, 5, "|cffFFBB00多少血量百分比使用");
-- Gift of The Naaru
if br.player.race == "Draenei" then
br.ui:createSpinner(section, "纳鲁的赐福", 50, 0, 100, 5, "|cffFFFFFF多少血量百分比使用")
end
-- Blessing of Protection
br.ui:createSpinner(section, "保护祝福", 20, 0, 100, 5, "多少血量百分比使用")
br.ui:createDropdownWithout(section, "保护祝福 目标", {"|cffFFFFFF所有","|cffFFFFFF坦克", "|cffFFFFFF自己"}, 1, "|cffFFFFFF使用保护祝福的目标")
-- Blinding Light
br.ui:createSpinner(section, "盲目之光 - HP", 50, 0, 100, 5, "|cffFFFFFF多少血量百分比使用")
br.ui:createSpinner(section, "盲目之光 - AoE", 3, 0, 10, 1, "|cffFFFFFF投5码的单位数量")
-- Cleanse Toxin
br.ui:createDropdown(section, "清毒术", {"|cff00FF00自己","|cffFFFF00所选的目标","|cffFF0000鼠标位置目标"}, 1, "|ccfFFFFFF选择目标")
-- Divine Shield
br.ui:createSpinner(section, "圣盾术", 50, 0, 100, 5, "|cffFFBB00多少血量百分比使用")
-- Eye for an Eye
br.ui:createSpinner(section, "以眼还眼", 50, 0 , 100, 5, "|cffFFBB00多少血量百分比使用")
-- Flash of Light
br.ui:createSpinner(section, "圣光闪现", 50, 0, 100, 5, "|cffFFBB00多少血量百分比使用")
-- Hammer of Justice
br.ui:createSpinner(section, "制裁之锤 - HP", 50, 0, 100, 5, "|cffFFBB00多少血量百分比使用")
-- Justicar's Vengeance
br.ui:createSpinner(section, "审判官复仇", 50, 0, 100, 5, "|cffFFBB00多少血量百分比使用")
-- Lay On Hands
br.ui:createSpinner(section, "圣疗术", 50, 0, 100, 5, "|cffFFBB00多少血量百分比使用")
br.ui:createDropdownWithout(section, "圣疗术 目标", {"|cffFFFFFF所有","|cffFFFFFF坦克", "|cffFFFFFF自己"}, 1, "|cffFFFFFF选择目标")
-- Redemption
br.ui:createDropdown(section, "救赎", {"|cffFFFF00所选的目标","|cffFF0000鼠标位置目标"}, 1, "|ccfFFFFFF选择目标")
br.ui:checkSectionState(section)
-------------------------
--- INTERRUPT OPTIONS ---
-------------------------
section = br.ui:createSection(br.ui.window.profile, "打断")
-- Blinding Light
br.ui:createCheckbox(section, "盲目之光")
-- Hammer of Justice
br.ui:createCheckbox(section, "制裁之锤")
-- Rebuke
br.ui:createCheckbox(section, "责难")
-- Interrupt Percentage
br.ui:createSpinner(section, "打断", 0, 0, 95, 5, "|cffFFBB00读条百分几打断")
br.ui:checkSectionState(section)
----------------------
--- TOGGLE OPTIONS ---
----------------------
section = br.ui:createSection(br.ui.window.profile, "切换快捷键")
-- Single/Multi Toggle
br.ui:createDropdown(section, "运行模式", br.dropOptions.Toggle, 4)
--Cooldown Key Toggle
br.ui:createDropdown(section, "冷却技能模式", br.dropOptions.Toggle, 3)
--Defensive Key Toggle
br.ui:createDropdown(section, "保命模式", br.dropOptions.Toggle, 6)
-- Interrupts Key Toggle
br.ui:createDropdown(section, "打断模式", br.dropOptions.Toggle, 6)
-- Pause Toggle
br.ui:createDropdown(section, "暂停模式", br.dropOptions.Toggle, 6)
br.ui:checkSectionState(section)
end
optionTable = {{
[1] = "脚本选项",
[2] = rotationOptions,
}}
return optionTable
end
----------------
--- ROTATION ---
----------------
local function runRotation()
if br.timer:useTimer("debugRetribution", math.random(0.15,0.3)) then -- Change debugSpec tp name of Spec IE: debugFeral or debugWindwalker
--Print("Running: "..rotationName)
---------------
--- Toggles ---
---------------
UpdateToggle("Rotation",0.25)
UpdateToggle("Cooldown",0.25)
UpdateToggle("Defensive",0.25)
UpdateToggle("Interrupt",0.25)
--------------
--- Locals ---
--------------
local artifact = br.player.artifact
local buff = br.player.buff
local cast = br.player.cast
local cd = br.player.cd
local charges = br.player.charges
local combatTime = getCombatTime()
local debuff = br.player.debuff
local enemies = enemies or {}
local gcd = br.player.gcd
local hastar = GetObjectExists("target")
local healPot = getHealthPot()
local holyPower = br.player.power.amount.holyPower
local holyPowerMax = br.player.power.holyPower.max
local inCombat = br.player.inCombat
local level = br.player.level
local mode = br.player.mode
local php = br.player.health
local race = br.player.race
local racial = br.player.getRacial()
local resable = UnitIsPlayer("target") and UnitIsDeadOrGhost("target") and UnitIsFriend("target","player")
local solo = GetNumGroupMembers() == 0
local spell = br.player.spell
local talent = br.player.talent
local ttd = getTTD(br.player.units(5))
local units = units or {}
units.dyn5 = br.player.units(5)
enemies.yards5 = br.player.enemies(5)
enemies.yards8 = br.player.enemies(8)
enemies.yards10 = br.player.enemies(10)
if profileStop == nil then profileStop = false end
if opener == nil then opener = false end
if not inCombat and not GetObjectExists("target") then
opener = false
JUD1 = false
BOJ1 = false
CRU1 = false
EXE1 = false
TMV1 = false
WOA1 = false
TMV2 = false
ARC1 = false
TMV3 = false
CRS1 = false
TMV4 = false
end
judgmentExists = debuff.judgment.exists(units.dyn5)
judgmentRemain = debuff.judgment.remain(units.dyn5)
if debuff.judgment.exists(units.dyn5) or level < 42 or (cd.judgment > 2 and not debuff.judgment.exists(units.dyn5)) then
judgmentVar = true
else
judgmentVar = false
end
local greaterBuff
greaterBuff = 0
local lowestUnit
lowestUnit = "player"
for i = 1, #br.friend do
local thisUnit = br.friend[i].unit
local thisHP = getHP(thisUnit)
local lowestHP = getHP(lowestUnit)
if thisHP < lowestHP then
lowestUnit = thisUnit
end
-- if UnitBuffID(thisUnit,spell.buffs.greaterBlessingOfMight) ~= nil then
-- greaterBuff = greaterBuff + 1
-- end
end
--------------------
--- Action Lists ---
--------------------
-- Action List - Extras
local function actionList_Extras()
-- Hand of Freedom
if isChecked("自由祝福") and hasNoControl("player") then
if cast.blessingOfFreedom("player") then return end
end
-- Hand of Hinderance
if isChecked("妨害之手") and isMoving("target") and not getFacing("target","player") and getDistance("target") > 8 then
if cast.handOfHinderance("target") then return end
end
-- Greater Blessing of Might
-- if isChecked("Greater Blessing of Might") and greaterBuff < 3 then
-- for i = 1, #br.friend do
-- local thisUnit = br.friend[i].unit
-- local unitRole = UnitGroupRolesAssigned(thisUnit)
-- if UnitBuffID(thisUnit,spell.buffs.greaterBlessingOfMight) == nil and (unitRole == "DAMAGER" or solo) then
-- if cast.greaterBlessingOfMight(thisUnit) then return end
-- end
-- end
-- end
end -- End Action List - Extras
-- Action List - Defensives
local function actionList_Defensive()
if useDefensive() then
-- Pot/Stoned
if isChecked("药水/治疗石") and php <= getOptionValue("药水/治疗石")
and inCombat and (hasHealthPot() or hasItem(5512))
then
if canUse(5512) then
useItem(5512)
elseif canUse(healPot) then
useItem(healPot)
end
end
-- Heirloom Neck
if isChecked("传家宝项链") and php <= getOptionValue("传家宝项链") then
if hasEquiped(122667) then
if GetItemCooldown(122667)==0 then
useItem(122667)
end
end
end
-- Gift of the Naaru
if isChecked("纳鲁的赐福") and php <= getOptionValue("纳鲁的赐福") and php > 0 and race == "Draenei" then
if castSpell("player",racial,false,false,false) then return end
end
-- Blessing of Protection
if isChecked("保护祝福") and GetSpellCooldown(1022) == 0 then
if getOptionValue("保护祝福 目标") == 1 then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue ("保护祝福") and not debuff.forbearance.exists(br.friend[i].unit) then
if isCastingSpell(spell.holyLight) then
SpellStopCasting()
end
if cast.blessingOfProtection(br.friend[i].unit) then return end
end
end
elseif getOptionValue("保护祝福 目标") == 2 then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue ("保护祝福") and not debuff.forbearance.exists(br.friend[i].unit) and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then
if cast.blessingOfProtection(br.friend[i].unit) then return end
end
end
elseif getOptionValue("保护祝福 目标") == 3 then
if php <= getValue("保护祝福") and not debuff.forbearance.exists("player") then
if cast.blessingOfProtection("player") then return end
end
end
end
-- Blinding Light
if isChecked("盲目之光 - HP") and php <= getOptionValue("盲目之光 - HP") and inCombat and #enemies.yards10 > 0 then
if cast.blindingLight() then return end
end
if isChecked("盲目之光 - AoE") and #enemies.yards5 >= getOptionValue("盲目之光 - AoE") and inCombat then
if cast.blindingLight() then return end
end
-- Cleanse Toxins
if isChecked("清毒术") then
if getOptionValue("清毒术")==1 and canDispel("player",spell.cleanseToxins) then
if cast.cleanseToxins("player") then return end
end
if getOptionValue("清毒术")==2 and canDispel("target",spell.cleanseToxins) then
if cast.cleanseToxins("target") then return end
end
if getOptionValue("清毒术")==3 and canDispel("mouseover",spell.cleanseToxins) then
if cast.cleanseToxins("mouseover") then return end
end
end
-- Divine Shield
if isChecked("圣盾术") then
if php <= getOptionValue("圣盾术") and inCombat then
if cast.divineShield() then return end
end
end
-- Eye for an Eye
if isChecked("以眼还眼") then
if php <= getOptionValue("以眼还眼") and inCombat then
if cast.eyeForAnEye() then return end
end
end
-- Flash of Light
if isChecked("圣光闪现") then
if (forceHeal or (inCombat and php <= getOptionValue("圣光闪现") / 2) or (not inCombat and php <= getOptionValue("圣光闪现"))) and not isMoving("player") then
if cast.flashOfLight() then return end
end
end
-- Hammer of Justice
if isChecked("制裁之锤 - HP") and php <= getOptionValue("制裁之锤 - HP") and inCombat then
if cast.hammerOfJustice() then return end
end
-- Lay On Hands
if isChecked("圣疗术") then
-- if getHP(lowestUnit) < getOptionValue("圣疗术") and inCombat then
-- if cast.layOnHands(lowestUnit) then return end
-- end
if getOptionValue("圣疗术 目标") == 1 then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue ("圣疗术") then
if cast.layOnHands(br.friend[i].unit) then return end
end
end
elseif getOptionValue("圣疗术 目标") == 2 then
for i = 1, #br.friend do
if br.friend[i].hp <= getValue ("圣疗术") and UnitGroupRolesAssigned(br.friend[i].unit) == "TANK" then
if cast.layOnHands(br.friend[i].unit) then return end
end
end
elseif getOptionValue("圣疗术 目标") == 3 then
if php <= getValue("圣疗术") then
if cast.layOnHands("player") then return end
end
end
end
-- Redemption
if isChecked("救赎") then
if getOptionValue("救赎")==1 and not isMoving("player") and resable then
if cast.redemption("target","dead") then return end
end
if getOptionValue("救赎")==2 and not isMoving("player") and resable then
if cast.redemption("mouseover","dead") then return end
end
end
end
end -- End Action List - Defensive
-- Action List - Interrupts
local function actionList_Interrupts()
if useInterrupts() then
for i = 1, #enemies.yards10 do
local thisUnit = enemies.yards10[i]
local distance = getDistance(thisUnit)
if canInterrupt(thisUnit,getOptionValue("打断")) then
-- Hammer of Justice
if isChecked("制裁之锤") and distance < 10 then
if cast.hammerOfJustice(thisUnit) then return end
end
-- Rebuke
if isChecked("责难") and distance < 5 then
if cast.rebuke(thisUnit) then return end
end
-- Blinding Light
if isChecked("盲目之光") and distance < 10 then
if cast.blindingLight() then return end
end
end
end
end
end -- End Action List - Interrupts
-- Action List - Cooldowns
local function actionList_Cooldowns()
if useCDs() or burst then
-- Trinkets
if isChecked("饰品") and getDistance(units.dyn5) < 5 then
if canUse(13) then
useItem(13)
end
if canUse(14) then
useItem(14)
end
end
if getOptionValue("APL模式") == 1 then
end
if getOptionValue("APL模式") == 2 then
-- Crusade
if isChecked("征伐") and talent.crusade then
if cast.avengingWrath() then return end
end
-- Avenging Wrath
if isChecked("复仇之怒") and not talent.crusade then
if cast.avengingWrath() then return end
end
end
end -- End Cooldown Usage Check
end -- End Action List - Cooldowns
-- Action List - PreCombat
local function actionList_PreCombat()
if isValidUnit("target") and (not isBoss("target") or not isChecked("Opener")) then
-- Divine Hammer
if cast.divineHammer() then return end
-- Judgment
if cast.judgment("target") then return end
-- Start Attack
if getDistance("target") < 5 then StartAttack() end
end
end -- End Action List - PreCombat
-- Action List - Opener
local function actionList_Opener()
if isValidUnit("target") and getDistance("target") < 5 then
if isChecked("Opener") and isBoss("target") and opener == false then
if not JUD1 then
Print("Starting Opener")
-- Divine Hammer
cast.divineHammer()
-- Judgment
if castOpener("judgment","JUD1",1) then return end
elseif JUD1 and not BOJ1 then
-- Blade of Justice
if talent.bladeOfWrath then
if castOpener("bladeOfJustice","BOJ1",2) then return end
else
if castOpener("divineHammer","BOJ1",2) then return end
end
elseif BOJ1 and not CRU1 then
-- Crusade
if castOpener("avengingWrath","CRU1",3) then return end
elseif CRU1 and not EXE1 then
-- Execution Sentence / Templar's Verdict
if talent.executionSentence then
if castOpener("executionSentence","EXE1",4) then return end
else
if castOpener("templarsVerdict","EXE1",4) then return end
end
elseif EXE1 and not WOA1 then
-- Wake of Ashes
if castOpener("wakeOfAshes","WOA1",5) then return end
elseif WOA1 and not TMV1 then
-- Templar's Verdict
if castOpener("templarsVerdict","TMV1",6) then return end
elseif TMV1 and not ARC1 then
if br.player.race == "BloodElf" then
-- Arcane Torrent
castSpell("player",racial,false,false,false)
if castOpener("templarsVerdict","ARC1",7) then return end
else
if castOpener("crusaderStrike","ARC1",7) then return end
end
elseif ARC1 and not TMV2 then
if castOpener("templarsVerdict","TMV2",8) then return end
elseif TMV2 then
opener = true;
Print("Opener Complete")
return
end
else
opener = true
end
end
end -- End Action List - Opener
---------------------
--- Begin Profile ---
---------------------
--Profile Stop | Pause
if not inCombat and not hastar and profileStop == true then
profileStop = false
elseif (inCombat and profileStop == true) or ((IsMounted() or IsFlying()) and not UnitBuffID("player",220507) and not buff.divineSteed.exists()) or pause() or mode.rotation == 4 then
return true
else
-----------------------
--- Extras Rotation ---
-----------------------
if actionList_Extras() then return end
--------------------------
--- Defensive Rotation ---
--------------------------
if actionList_Defensive() then return end
------------------------------
--- Out of Combat Rotation ---
------------------------------
if actionList_PreCombat() then return end
----------------------------
--- Out of Combat Opener ---
----------------------------
if actionList_Opener() then return end
--------------------------
--- In Combat Rotation ---
--------------------------
if inCombat and profileStop==false then
------------------------------
--- In Combat - Interrupts ---
------------------------------
if actionList_Interrupts() then return end
-----------------------------
--- In Combat - Cooldowns ---
-----------------------------
if actionList_Cooldowns() then return end
----------------------------------
--- In Combat - Begin Rotation ---
----------------------------------
--------------------------------
--- In Combat - SimCraft APL ---
--------------------------------
if getOptionValue("APL模式") == 1 then
-- Opener
if actionList_Opener() then return end
-- Start Attack
if getDistance(units.dyn5) < 5 then
if not IsCurrentSpell(6603) then
StartAttack(units.dyn5)
end
end
-- Racials
-- blood_fury
-- berserking
-- arcane_torrent,if=holy_power<5
if isChecked("种族技能") and useCDs() then
if race == "Orc" or race == "Troll" or (race == "BloodElf" and holyPower < 5 and (buff.crusade.exists() or buff.avengingWrath.exists() or combatTime < 2)) and getSpellCD(racial) == 0 then
if castSpell("player",racial,false,false,false) then return end
end
end
-- Combat Time less than 2 secs
if combatTime < 2 then
-- Judgement
-- judgment,if=time<2
if cast.judgment() then return end
-- Blade of Justice
-- blade_of_justice,if=time<2&(equipped.137048|race.blood_elf)
if not talent.divineHammer and (hasEquiped(137048) or race == "BloodElf") then
if cast.bladeOfJustice() then return end
end
-- Divine Hammer
-- divine_hammer,if=time<2&(equipped.137048|race.blood_elf)
if talent.divineHammer and (hasEquiped(137048) or race == "BloodElf") then
if cast.divineHammer() then return end
end
-- Wake of Ashes
-- wake_of_ashes,if=holy_power<=1&time<2
if getOptionValue("神器技能") == 1 or (getOptionValue("神器技能") == 2 and useCDs()) then
if getDistance(units.dyn5) < 5 and holyPower <= 1 then
if cast.wakeOfAshes() then return end
end
end
end
if useCDs() then
-- Holy Wrath
-- holy_wrath
if isChecked("神圣愤怒") then
if cast.holyWrath() then return end
end
-- Avenging Wrath
-- avenging_wrath
if isChecked("复仇之怒") and not talent.crusade and getDistance(units.dyn5) < 5 then
if cast.avengingWrath() then return end
end
-- Shield of Vengeance
-- shield_of_vengeance
if isChecked("复仇之盾") then
if cast.shieldOfVengeance() then return end
end
-- Crusade
-- crusade,if=holy_power>=5&!equipped.137048|((equipped.137048|race.blood_elf)&time<2|time>2&holy_power>=4)
if isChecked("征伐") and talent.crusade and getDistance(units.dyn5) < 5 then
if (holyPower >= 5 and not hasEquiped(137048)) or ((hasEquiped(137048) or race == "BloodElf") and combatTime < 2 or combatTime > 2 and holyPower >= 4) then
if cast.avengingWrath() then return end
end
end
end
-- Execution Sentence
-- execution_sentence,if=spell_targets.divine_storm<=3&(cooldown.judgment.remain()s<gcd*4.5|debuff.judgment.remain()s>gcd*4.67)&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*2)
if #enemies.yards8 <= 3 and (cd.judgment < gcd * 4.5 or judgmentRemain > gcd * 4.67) and (not talent.crusade or cd.crusade > gcd *2 or not isChecked("征伐") or not useCDs()) and ttd > 6 then
if cast.executionSentence() then return end
end
-- Divine Storm
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&buff.divine_purpose.up&buff.divine_purpose.remain()s<gcd*2
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=5&buff.divine_purpose.react
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=3&buff.crusade.up&(buff.crusade.stack()<15|buff.bloodlust.up)
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&holy_power>=5&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*3)
if not isChecked("审判官复仇") or (isChecked("审判官复仇") and php >= getOptionValue("审判官复仇")) then
if judgmentVar and ((mode.rotation == 1 and #enemies.yards8 >= getOptionValue("神圣风暴 数量")) or mode.rotation == 2)
and ((buff.divinePurpose.exists() and buff.divinePurpose.remain() < gcd * 2)
or (holyPower >= 5 and buff.divinePurpose.exists())
or (holyPower >= 3 and buff.crusade.exists() and (buff.crusade.stack() < 15 or hasBloodLust()))
or (holyPower >= 5 and (not talent.crusade or cd.crusade > gcd * 3 or not isChecked("征伐") or not useCDs())))
then
if cast.divineStorm() then return end
end
end
-- Justicar's Vengeance
-- justicars_vengeance,if=debuff.judgment.up&buff.divine_purpose.up&buff.divine_purpose.remain()s<gcd*2&!equipped.whisper_of_the_nathrezim
-- justicars_vengeance,if=debuff.judgment.up&holy_power>=5&buff.divine_purpose.react&!equipped.whisper_of_the_nathrezim
if isChecked("审判官复仇") and php < getOptionValue("审判官复仇") then
if judgmentVar and ((buff.divinePurpose.exists() and buff.divinePurpose.remain() < gcd * 2 and not hasEquiped(137020))
or holyPower >= 5 )
then
if cast.justicarsVengeance() then return end
end
end
-- Templar's Verdict
-- templars_verdict,if=debuff.judgment.up&buff.divine_purpose.up&buff.divine_purpose.remain()s<gcd*2
-- templars_verdict,if=debuff.judgment.up&holy_power>=5&buff.divine_purpose.react
-- templars_verdict,if=debuff.judgment.up&holy_power>=3&buff.crusade.up&(buff.crusade.stack()<15|buff.bloodlust.up)
-- templars_verdict,if=debuff.judgment.up&holy_power>=5&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*3)
if not isChecked("审判官复仇") or (isChecked("审判官复仇") and php >= getOptionValue("审判官复仇")) then
if judgmentVar and ((mode.rotation == 1 and #enemies.yards8 < getOptionValue("神圣风暴 数量")) or mode.rotation == 3)
and ((buff.divinePurpose.exists() and buff.divinePurpose.remain() < gcd * 2)
or (holyPower >= 5 and buff.divinePurpose.exists())
or (holyPower >= 3 and buff.crusade.exists() and (buff.crusade.stack() < 15 or hasBloodLust()))
or (holyPower >= 5 and (not talent.crusade or cd.crusade > gcd * 3 or not isChecked("征伐") or not useCDs())))
then
if cast.templarsVerdict() then return end
end
end
-- Divine Storm
-- divine_storm,if=debuff.judgment.up&holy_power>=3&spell_targets.divine_storm>=2&(cooldown.wake_of_ashes.remain()s<gcd*2&artifact.wake_of_ashes.enabled|buff.whisper_of_the_nathrezim.up&buff.whisper_of_the_nathrezim.remain()s<gcd)&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*4)
if not isChecked("审判官复仇") or (isChecked("审判官复仇") and php >= getOptionValue("审判官复仇")) then
if judgmentVar and holyPower >= 3 and ((mode.rotation == 1 and #enemies.yards8 >= getOptionValue("神圣风暴 数量")) or mode.rotation == 2)
and ((cd.wakeOfAshes < gcd * 2 and artifact.wakeOfAshes) or (buff.whisperOfTheNathrezim.exists() and buff.whisperOfTheNathrezim.remain() < gcd) or not artifact.wakeOfAshes)
and (not talent.crusade or cd.crusade > gcd * 4 or not isChecked("征伐") or not useCDs())
then
if cast.divineStorm() then return end
end
end
-- Justicar's Vengeance
-- justicars_vengeance,if=debuff.judgment.up&holy_power>=3&buff.divine_purpose.up&cooldown.wake_of_ashes.remain()s<gcd*2&artifact.wake_of_ashes.enabled&!equipped.whisper_of_the_nathrezim
if isChecked("审判官复仇") and php < getOptionValue("审判官复仇") then
if judgmentVar and holyPower >= 3 and buff.divinePurpose.exists() and ((cd.wakeOfAshes < gcd * 2 and artifact.wakeOfAshes) or not artifact.wakeOfAshes) and not hasEquiped(137020) then
if cast.justicarsVengeance() then return end
end
end
-- Templar's Verdict
-- templars_verdict,if=debuff.judgment.up&holy_power>=3&(cooldown.wake_of_ashes.remain()s<gcd*2&artifact.wake_of_ashes.enabled|buff.whisper_of_the_nathrezim.up&buff.whisper_of_the_nathrezim.remain()s<gcd)&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*4)
if not isChecked("审判官复仇") or (isChecked("审判官复仇") and php >= getOptionValue("审判官复仇")) then
if judgmentVar and holyPower >= 3 and ((mode.rotation == 1 and #enemies.yards8 < getOptionValue("神圣风暴 数量")) or mode.rotation == 3)
and ((cd.wakeOfAshes < gcd * 2 and artifact.wakeOfAshes) or (buff.whisperOfTheNathrezim.exists() and buff.whisperOfTheNathrezim.remain() < gcd) or not artifact.wakeOfAshes)
and (not talent.crusade or cd.crusade < gcd * 4 or not isChecked("征伐") or not useCDs())
then
if cast.templarsVerdict() then return end
end
end
-- Wake of Ashes
-- wake_of_ashes,if=holy_power=0|holy_power=1&(cooldown.blade_of_justice.remain()s>gcd|cooldown.divine_hammer.remain()s>gcd)|holy_power=2&(cooldown.zeal.charges_fractional<=0.65|cooldown.crusader_strike.charges_fractional<=0.65)
if getOptionValue("神器技能") == 1 or (getOptionValue("神器技能") == 2 and useCDs()) then
if holyPower == 0 or (holyPower == 1 and (cd.bladeOfJustice > gcd or cd.divineHammer > gcd)) or (holyPower == 2 and (charges.frac.zeal <= 0.65 or charges.frac.crusaderStrike <= 0.65)) and getDistance(units.dyn5) < 5 then
if cast.wakeOfAshes() then return end
end
end
-- Blade of Justice
-- blade_of_justice,if=holy_power<=3&buff.whisper_of_the_nathrezim.up&buff.whisper_of_the_nathrezim.remain()s>gcd&buff.whisper_of_the_nathrezim.remain()s<gcd*3&debuff.judgment.up&debuff.judgment.remain()s>gcd*2
if not talent.divineHammer and holyPower <= 3 and buff.whisperOfTheNathrezim.exists() and buff.whisperOfTheNathrezim.remain() > gcd and buff.whisperOfTheNathrezim.remain() < gcd * 3 and judgmentVar and debuff.judgment.remain(units.dyn5) > gcd * 2 then
if cast.bladeOfJustice() then return end
end
-- Divine Hammer
-- divine_hammer,if=holy_power<=3&buff.whisper_of_the_nathrezim.up&buff.whisper_of_the_nathrezim.remain()s>gcd&buff.whisper_of_the_nathrezim.remain()s<gcd*3&debuff.judgment.up&debuff.judgment.remain()s>gcd*2
-- if ((mode.rotation == 1 and #enemies.yards8 >= getOptionValue("神圣风暴 数量")) or mode.rotation == 2) then
if talent.divineHammer and holyPower <= 3 and buff.whisperOfTheNathrezim.exists() and buff.whisperOfTheNathrezim.remain() > gcd and buff.whisperOfTheNathrezim.remain() < gcd * 3 and judgmentVar and debuff.judgment.remain(units.dyn5) > gcd * 2 then
if cast.divineHammer() then return end
end
-- end
-- Blade of Justice
-- blade_of_justice,if=talent.blade_of_wrath.enabled&holy_power<=3
if talent.bladeOfWrath and holyPower <= 3 then
if cast.bladeOfJustice() then return end
end
-- Zeal
-- zeal,if=charges=2&holy_power<=4
if talent.zeal and charges.zeal == 2 and holyPower <= 4 then
if cast.zeal() then return end
end
-- Crusader Strike
-- crusader_strike,if=charges=2&holy_power<=4
if not talent.zeal and charges.crusaderStrike == 2 and holyPower <= 4 then
if cast.crusaderStrike() then return end
end
-- Blade of Justice
-- blade_of_justice,if=holy_power<=2|(holy_power<=3&(cooldown.zeal.charges_fractional<=1.34|cooldown.crusader_strike.charges_fractional<=1.34))
if not talent.divineHammer and (holyPower <= 2 or (holyPower <= 3 and (charges.frac.zeal <= 1.34 or charges.frac.crusaderStrike <= 1.34))) then
if cast.bladeOfJustice() then return end
end
-- Divine Hammer
-- divine_hammer,if=holy_power<=2|(holy_power<=3&(cooldown.zeal.charges_fractional<=1.34|cooldown.crusader_strike.charges_fractional<=1.34))
-- if ((mode.rotation == 1 and #enemies.yards8 >= getOptionValue("神圣风暴 数量")) or mode.rotation == 2) then
if talent.divineHammer and holyPower <= 2 or (holyPower <= 3 and (charges.frac.zeal <= 1.34 or charges.frac.crusaderStrike <= 1.34)) then
if cast.divineHammer() then return end
end
-- end
-- Judgement
-- judgment,if=holy_power>=3|((cooldown.zeal.charges_fractional<=1.67|cooldown.crusader_strike.charges_fractional<=1.67)&(cooldown.divine_hammer.remain()s>gcd|cooldown.blade_of_justice.remain()s>gcd))|(talent.greater_judgment.enabled&target.health.pct>50)
if holyPower >= 3 or ((charges.frac.zeal <= 1.67 or charges.frac.crusaderStrike <= 1.67) and (cd.divineHammer > gcd or cd.bladeOfJustice > gcd))
or (talent.greaterJudgement and thp > 50)
then
if cast.judgment() then return end
end
-- Consecration
-- consecration
if #enemies.yards8 >= 1 then
if cast.consecration() then return end
end
-- Divine Storm
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&buff.divine_purpose.react
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&buff.the_fires_of_justice.react&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*3)
-- divine_storm,if=debuff.judgment.up&spell_targets.divine_storm>=2&(holy_power>=4|((cooldown.zeal.charges_fractional<=1.34|cooldown.crusader_strike.charges_fractional<=1.34)&(cooldown.divine_hammer.remain()s>gcd|cooldown.blade_of_justice.remain()s>gcd)))&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*4)
if not isChecked("审判官复仇") or (isChecked("审判官复仇") and php >= getOptionValue("审判官复仇")) then
if judgmentVar and ((mode.rotation == 1 and #enemies.yards8 >= getOptionValue("神圣风暴 数量")) or mode.rotation == 2)
and (buff.divinePurpose.exists()
or (buff.theFiresOfJustice.exists() and (not talent.crusade or cd.crusade > gcd * 3 or not isChecked("征伐") or not useCDs()))
or (holyPower >= 4 or ((charges.frac.zeal <= 1.34 or charges.frac.crusaderStrike <= 1.34) and (cd.divineHammer > gcd or cd.bladeOfJustice > gcd)) and (not talent.crusade or cd.crusade > gcd * 4 or not isChecked("征伐") or not useCDs())))
then
if cast.divineStorm() then return end
end
end
-- Justicar's Vengeance
-- justicars_vengeance,if=debuff.judgment.up&buff.divine_purpose.react&!equipped.whisper_of_the_nathrezim
if isChecked("审判官复仇") and php < getOptionValue("审判官复仇") then
if judgmentVar and buff.divinePurpose.exists() and not hasEquiped(137020) then
if cast.justicarsVengeance() then return end
end
end
-- Templar's Verdict
-- templars_verdict,if=debuff.judgment.up&buff.divine_purpose.react
-- templars_verdict,if=debuff.judgment.up&buff.the_fires_of_justice.react&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*3)
-- templars_verdict,if=debuff.judgment.up&(holy_power>=4|((cooldown.zeal.charges_fractional<=1.34|cooldown.crusader_strike.charges_fractional<=1.34)&(cooldown.divine_hammer.remain()s>gcd|cooldown.blade_of_justice.remain()s>gcd)))&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*4)
if not isChecked("审判官复仇") or (isChecked("审判官复仇") and php >= getOptionValue("审判官复仇")) then
if judgmentVar
and ((mode.rotation == 1 and #enemies.yards8 < getOptionValue("神圣风暴 数量")) or mode.rotation == 3)
and (buff.divinePurpose.exists()
or (buff.theFiresOfJustice.exists() and (not talent.crusade or cd.crusade > gcd * 3 or not isChecked("征伐") or not useCDs()))
or (holyPower >= 4 or ((charges.frac.zeal <= 1.34 or charges.frac.crusaderStrike <= 1.34) and (cd.divineHammer > gcd or cd.bladeOfJustice > gcd)) and (not talent.crusade or cd.crusade > gcd * 4 or not isChecked("征伐") or not useCDs())))
then
if cast.templarsVerdict() then return end
end
end
-- Zeal
-- zeal,if=holy_power<=4
if talent.zeal and holyPower <= 4 then
if cast.zeal() then return end
end
-- Crusader Strike
-- crusader_strike,if=holy_power<=4
if not talent.zeal and holyPower <= 4 then
if cast.crusaderStrike() then return end
end
-- Divine Storm
-- divine_storm,if=debuff.judgment.up&holy_power>=3&spell_targets.divine_storm>=2&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*5)
if judgmentVar and holyPower >= 3 and ((mode.rotation == 1 and #enemies.yards8 >= getOptionValue("神圣风暴 数量")) or mode.rotation == 2) and (not talent.crusade or cd.crusade > gcd * 5 or not isChecked("征伐") or not useCDs()) then
if cast.divineStorm() then return end
end
-- Templar's Verdict
-- templars_verdict,if=debuff.judgment.up&holy_power>=3&(!talent.crusade.enabled|cooldown.crusade.remain()s>gcd*5)
if judgmentVar and holyPower >= 3 and ((mode.rotation == 1 and #enemies.yards8 < getOptionValue("神圣风暴 数量")) or mode.rotation == 3) and (not talent.crusade or cd.crusade > gcd * 5 or not isChecked("征伐") or not useCDs()) then
if cast.templarsVerdict() then return end
end
end -- End SimC APL
----------------------------------
--- In Combat - AskMrRobot APL ---
----------------------------------
if getOptionValue("APL模式") == 2 then
-- Execution Sentence
-- if CooldownSecRemaining(Judgment) <= GlobalCooldownSec * 3
if cd.judgment <= gcd * 3 then
if cast.executionSentence(units.dyn5) then return end
end
-- Judgment
if cast.judgment("target") then return end
-- Consecration
-- if not HasBuff(Judgment)
if not judgmentExists and #enemies.yards8 >= 3 then
if cast.consecration() then return end
end
-- Justicar's Vengeance
-- if HasBuff(DivinePurpose) and TargetsInRadius(DivineStorm) <= 3
if isChecked("审判官复仇") and php < getOptionValue("审判官复仇") then
if buff.divinePurpose.exists() and #enemies.yards8 <= 3 then
if cast.justicarsVengeance(units.dyn5) then return end
end
end
-- Divine Storm
-- if (AlternatePower >= 4 or HasBuff(DivinePurpose) or HasBuff(Judgment)) and TargetsInRadius(DivineStorm) > 2
if not isChecked("审判官复仇") or php >= getOptionValue("审判官复仇") then
if (holyPower >= 3 or buff.divinePurpose.exists() or judgmentExists) and #enemies.yards8 > 2 then
if cast.divineStorm() then return end
end
end
-- Templar's Verdict
-- if (AlternatePower >= 4 or HasBuff(DivinePurpose) or HasBuff(Judgment))
if not isChecked("审判官复仇") or php >= getOptionValue("审判官复仇") then
if (holyPower >= 3 or buff.divinePurpose.exists() or judgmentExists) then
if cast.templarsVerdict(units.dyn5) then return end
end
end
-- Wake of Ashes
-- if AlternatePowerToMax >= 4
if getOptionValue("神器技能") == 1 or (getOptionValue("神器技能") == 2 and useCDs()) then
if holyPowerMax - holyPower >= 4 and getDistance(units.dyn5) < 5 then
if cast.wakeOfAshes(units.dyn5) then return end
end
end
-- Blade of Justice
-- if AlternatePowerToMax >= 2
if holyPowerMax - holyPower >= 2 then
if cast.bladeOfJustice(units.dyn5) then return end
end
-- Blade of Wrath
-- if AlternatePowerToMax >= 2
if holyPowerMax - holyPower >= 2 then
if cast.bladeOfWrath(units.dyn5) then return end
end
-- Divine Hammer
-- if AlternatePowerToMax >= 2
if holyPowerMax - holyPower >= 2 then
if cast.divineHammer(units.dyn5) then return end
end
-- Hammer of Justice
-- if HasItem(JusticeGaze) and TargetHealthPercent > 0.75 and not HasBuff(Judgment)
-- TODO
-- Crusader Strike
if cast.crusaderStrike(units.dyn5) then return end
-- Zeal
if cast.zeal(units.dyn5) then return end
end -- End AMR APL
end -- End In Combat
end -- End Profile
end -- Timer
end -- runRotation
local id = 70
if br.rotations[id] == nil then br.rotations[id] = {} end
tinsert(br.rotations[id],{
name = rotationName,
toggles = createToggles,
options = createOptions,
run = runRotation,
})
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/mobile/rori/first_brigade_gunner.lua | 1 | 1257 | first_brigade_gunner = Creature:new {
objectName = "@mob/creature_names:brigade_gunner",
socialGroup = "restuss",
pvpFaction = "restuss",
faction = "restuss",
level = 9,
chanceHit = 0.27,
damageMin = 80,
damageMax = 90,
baseXp = 292,
baseHAM = 675,
baseHAMmax = 825,
armor = 0,
resists = {0,0,0,0,0,0,0,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + HERD,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_brigade_gunner_bith_male_01.iff",
"object/mobile/dressed_brigade_gunner_bith_female_01.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 5000000},
{group = "wearables_common", chance = 2000000},
{group = "color_crystals", chance = 500000},
{group = "rifles", chance = 1000000},
{group = "pistols", chance = 1000000},
{group = "loot_kit_parts", chance = 500000}
},
lootChance = 3200000
}
},
weapons = {"rebel_weapons_medium"},
conversationTemplate = "",
attacks = merge(brawlernovice,marksmannovice)
}
CreatureTemplates:addCreatureTemplate(first_brigade_gunner, "first_brigade_gunner") | lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/draft_schematic/space/weapon/shield_effectiveness_intensifier_mk1.lua | 2 | 3284 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_draft_schematic_space_weapon_shield_effectiveness_intensifier_mk1 = object_draft_schematic_space_weapon_shared_shield_effectiveness_intensifier_mk1:new {
templateType = DRAFTSCHEMATIC,
customObjectName = "Shield Effectiveness Intensifier - Mark I",
craftingToolTab = 131072, -- (See DraftSchemticImplementation.h)
complexity = 19,
size = 1,
xpType = "shipwright",
xp = 25,
assemblySkill = "shields_assembly",
experimentingSkill = "shields_experimentation",
customizationSkill = "medicine_customization",
customizationOptions = {},
customizationStringNames = {},
customizationDefaults = {},
ingredientTemplateNames = {"craft_item_ingredients_n", "craft_item_ingredients_n"},
ingredientTitleNames = {"casing", "effectiveness_enhancer"},
ingredientSlotType = {0, 0},
resourceTypes = {"steel", "radioactive_polymetric"},
resourceQuantities = {75, 25},
contribution = {100, 100},
targetTemplate = "object/tangible/ship/crafted/weapon/shield_effectiveness_intensifier_mk1.iff",
additionalTemplates = {
}
}
ObjectTemplates:addTemplate(object_draft_schematic_space_weapon_shield_effectiveness_intensifier_mk1, "object/draft_schematic/space/weapon/shield_effectiveness_intensifier_mk1.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/component/droid/armor_module_2.lua | 1 | 2912 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_component_droid_armor_module_2 = object_tangible_component_droid_shared_armor_module_2:new {
numberExperimentalProperties = {1, 1, 2, 1, 2, 2, 2},
experimentalProperties = {"XX", "XX", "CD", "OQ", "XX", "CD", "OQ", "CD", "OQ", "CD", "OQ"},
experimentalWeights = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
experimentalGroupTitles = {"null", "null", "exp_durability", "null", "exp_effectiveness", "exp_effectiveness", "exp_effectiveness"},
experimentalSubGroupTitles = {"null", "null", "decayrate", "hitpoints", "mechanism_quality", "armor_toughness", "armor_module"},
experimentalMin = {0, 0, 5, 1000, -10, 200, 3},
experimentalMax = {0, 0, 15, 1000, 15, 500, 5},
experimentalPrecision = {0, 0, 0, 0, 0, 0, 0},
experimentalCombineType = {0, 0, 1, 4, 1, 1, 1},
}
ObjectTemplates:addTemplate(object_tangible_component_droid_armor_module_2, "object/tangible/component/droid/armor_module_2.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/commands/fireLightningCone2.lua | 1 | 2411 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
FireLightningCone2Command = {
name = "firelightningcone2",
damageMultiplier = 4.0,
speedMultiplier = 2.0,
healthCostMultiplier = 1,
actionCostMultiplier = 1,
mindCostMultiplier = 1,
animationCRC = hashCode("fire_area_medium"),
combatSpam = "firelightningcone2",
coneAngle = 60,
coneAction = true,
range = 16
}
AddCommand(FireLightningCone2Command)
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/mobile/spawn/naboo_world_creatures.lua | 1 | 7693 | naboo_world_creatures = {
wanderRadius = 10,
commandLevel = 0,
type = LAIR,
maxSpawnLimit = 2048,
lairSpawns = {
{
lairTemplateName = "naboo_gnort_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 4,
maxDifficulty = 4,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_mott_lair_neutral_medium",
spawnLimit = -1,
minDifficulty = 4,
maxDifficulty = 4,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_chuba_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 5,
maxDifficulty = 5,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_flesh_eating_chuba_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 6,
maxDifficulty = 6,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_capper_spineflap_nest_neutral_large",
spawnLimit = -1,
minDifficulty = 6,
maxDifficulty = 6,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_diseased_nuna_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 6,
maxDifficulty = 6,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_flewt_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 7,
maxDifficulty = 7,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_hermit_spider_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 7,
maxDifficulty = 7,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_nightspider_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 7,
maxDifficulty = 7,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_ikopi_lair_neutral_medium",
spawnLimit = -1,
minDifficulty = 7,
maxDifficulty = 7,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_sharupat_family_neutral_medium",
spawnLimit = -1,
minDifficulty = 7,
maxDifficulty = 7,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_mott_herd_neutral_none",
spawnLimit = -1,
minDifficulty = 11,
maxDifficulty = 11,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_bark_mite_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 10,
maxDifficulty = 10,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_flewt_lair_neutral_small_01",
spawnLimit = -1,
minDifficulty = 9,
maxDifficulty = 9,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_krevol_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 10,
maxDifficulty = 10,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_fanned_rawl_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 10,
maxDifficulty = 10,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_kaadu_lair_neutral_medium",
spawnLimit = -1,
minDifficulty = 10,
maxDifficulty = 10,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_nuna_lair_neutral_medium",
spawnLimit = -1,
minDifficulty = 10,
maxDifficulty = 10,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "veermok_forest",
spawnLimit = -1,
minDifficulty = 13,
maxDifficulty = 13,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_peko_peko_solitary_neutral_none",
spawnLimit = -1,
minDifficulty = 14,
maxDifficulty = 14,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_krevol_click_neutral_none",
spawnLimit = -1,
minDifficulty = 15,
maxDifficulty = 15,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_gualama_herd_neutral_none",
spawnLimit = -1,
minDifficulty = 14,
maxDifficulty = 14,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_veermok_rangers_neutral_none",
spawnLimit = -1,
minDifficulty = 17,
maxDifficulty = 17,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_plains_tusk_cat_pride_neutral_medium",
spawnLimit = -1,
minDifficulty = 16,
maxDifficulty = 16,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_swamp_tusk_cat_pride_neutral_medium",
spawnLimit = -1,
minDifficulty = 17,
maxDifficulty = 17,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "tusk_cat_grassland",
spawnLimit = -1,
minDifficulty = 16,
maxDifficulty = 16,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_falumpaset_lair_neutral_large",
spawnLimit = -1,
minDifficulty = 19,
maxDifficulty = 19,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_narglatch_male_neutral_none",
spawnLimit = -1,
minDifficulty = 22,
maxDifficulty = 22,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_veermok_camp_neutral_medium",
spawnLimit = -1,
minDifficulty = 22,
maxDifficulty = 22,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_sharupat_pack_diseased_neutral_none",
spawnLimit = -1,
minDifficulty = 22,
maxDifficulty = 22,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_peko_peko_giant_pair_neutral_none",
spawnLimit = -1,
minDifficulty = 23,
maxDifficulty = 23,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_fanned_rawl_hunter_neutral_none",
spawnLimit = -1,
minDifficulty = 24,
maxDifficulty = 24,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_bolle_bol_lair_neutral_large",
spawnLimit = -1,
minDifficulty = 27,
maxDifficulty = 27,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_bolle_bol_herd_neutral_none",
spawnLimit = -1,
minDifficulty = 27,
maxDifficulty = 27,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_fambaa_lair_neutral_large",
spawnLimit = -1,
minDifficulty = 34,
maxDifficulty = 34,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_fambaa_lair_neutral_large_boss_01",
spawnLimit = -1,
minDifficulty = 34,
maxDifficulty = 34,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_gualama_small_lair_neutral_medium",
spawnLimit = -1,
minDifficulty = 13,
maxDifficulty = 13,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "tusk_cat",
spawnLimit = -1,
minDifficulty = 16,
maxDifficulty = 16,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_nightspider_lair_neutral_small",
spawnLimit = -1,
minDifficulty = 7,
maxDifficulty = 7,
numberToSpawn = 0,
weighting = 15,
size = 25
},
{
lairTemplateName = "naboo_mountain_ikopi_lair_neutral_medium",
spawnLimit = -1,
minDifficulty = 17,
maxDifficulty = 17,
numberToSpawn = 0,
weighting = 15,
size = 25
}
}
}
addLairGroup("naboo_world_creatures", naboo_world_creatures);
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/remmer/serverobjects.lua | 3 | 2221 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--Children folder includes
-- Server Objects
includeFile("tangible/lair/remmer/lair_remmer.lua")
includeFile("tangible/lair/remmer/lair_remmer_grassland.lua")
includeFile("tangible/lair/remmer/lair_remmer_jungle.lua")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/base/poi_all_lair_mound_small_evil_fire_red.lua | 2 | 2368 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_base_poi_all_lair_mound_small_evil_fire_red = object_tangible_lair_base_shared_poi_all_lair_mound_small_evil_fire_red:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
}
ObjectTemplates:addTemplate(object_tangible_lair_base_poi_all_lair_mound_small_evil_fire_red, "object/tangible/lair/base/poi_all_lair_mound_small_evil_fire_red.iff")
| lgpl-3.0 |
suppayami/alex-gets-oppai | data/class/layermanager.lua | 1 | 2063 | -- singleton
LayerManager = class(Object)
LayerManager.layer = {}
LayerManager.sort = {}
function LayerManager:clearAll()
for k,v in pairs(self.layer) do
for i,s in pairs(v) do
s:unsetImage()
v[i] = nil
end
self.layer[k] = nil
end
end
function LayerManager:clearLayer(layer)
if self.layer[layer] == nil then return 0 end
local l = self.layer[layer]
for k,v in pairs(l) do
v:unsetImage()
l[k] = nil
end
self.layer[layer] = nil
end
function LayerManager:removeSprite(layer, spriteName)
if self.layer[layer] == nil then return 0 end
local l = self.layer[layer]
if l[spriteName] == nil then return 0 end
l[spriteName]:unsetImage()
l[spriteName] = nil
end
function LayerManager:addSprite(layer, spriteName, spriteClass, ...)
if self.layer[layer] == nil then self.layer[layer] = {} end
--
local l = self.layer[layer]
if l[spriteName] then l[spriteName]:unsetImage() end
l[spriteName] = spriteClass:new(...)
self.sort[layer] = sortFunc.sortTable(l, function (a,b) return a.z < b.z end)
return l[spriteName]
end
function LayerManager:sortSprite(layer)
local l = self.layer[layer]
self.sort[layer] = sortFunc.sortTable(l, function (a,b) return a.z < b.z end)
end
function LayerManager:draw(layer)
if self.sort[layer] == nil then self.sort[layer] = {} end
--
local l = self.sort[layer]
for i,s in pairs(l) do s:draw() end
end
function LayerManager:drawAll()
for k,v in pairs(self.layer) do
self:draw(k)
end
end
function LayerManager:update(layer, dt)
if self.layer[layer] == nil then self.layer[layer] = {} end
--
local l = self.layer[layer]
for i,s in pairs(l) do s:update(dt) end
end
function LayerManager:updateAll(dt)
for k,v in pairs(self.layer) do
self:update(k, dt)
end
end
function LayerManager:getSprite(layer, spriteName)
return self.layer[layer][spriteName]
end
function LayerManager:getSprites(layer)
return self.layer[layer]
end | mit |
eraffxi/darkstar | scripts/globals/items/cone_of_seraphs_kiss.lua | 2 | 1173 | -----------------------------------------
-- ID: 5556
-- Item: cone_of_seraphs_kiss
-- Food Effect: 1Hr, All Races
-----------------------------------------
-- HP 15
-- MP % 16 (cap 85)
-- MP Recovered While Healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(dsp.effect.FOOD) == true or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,3600,5556);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(dsp.mod.HP, 15);
target:addMod(dsp.mod.FOOD_MPP, 16);
target:addMod(dsp.mod.FOOD_MP_CAP, 85);
target:addMod(dsp.mod.MPHEAL, 2);
end;
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 15);
target:delMod(dsp.mod.FOOD_MPP, 16);
target:delMod(dsp.mod.FOOD_MP_CAP, 85);
target:delMod(dsp.mod.MPHEAL, 2);
end;
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/base/poi_all_lair_nest_small_fog_green.lua | 2 | 2348 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_base_poi_all_lair_nest_small_fog_green = object_tangible_lair_base_shared_poi_all_lair_nest_small_fog_green:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
}
ObjectTemplates:addTemplate(object_tangible_lair_base_poi_all_lair_nest_small_fog_green, "object/tangible/lair/base/poi_all_lair_nest_small_fog_green.iff")
| lgpl-3.0 |
Richard857/BadRotations | System/Libs/DiesalGUI-1.0/Objects/Toggle.lua | 4 | 5897 | -- $Id: Button.lua 43 2014-02-23 18:40:01Z diesal@reece-tech.com $
local DiesalGUI = LibStub("DiesalGUI-1.0")
-- ~~| Libraries |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local DiesalTools = LibStub("DiesalTools-1.0")
local DiesalStyle = LibStub("DiesalStyle-1.0")
-- ~~| Lua Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local type, tonumber, select = type, tonumber, select
local pairs, ipairs, next = pairs, ipairs, next
local min, max = math.min, math.max
-- ~~| WoW Upvalues |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local CreateFrame, UIParent, GetCursorPosition = CreateFrame, UIParent, GetCursorPosition
local GetScreenWidth, GetScreenHeight = GetScreenWidth, GetScreenHeight
local GetSpellInfo, GetBonusBarOffset, GetDodgeChance = GetSpellInfo, GetBonusBarOffset, GetDodgeChance
local GetPrimaryTalentTree, GetCombatRatingBonus = GetPrimaryTalentTree, GetCombatRatingBonus
-- ~~| Button |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local TYPE = "Toggle"
local VERSION = 1
-- ~~| Button StyleSheets |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local styleSheet = {
['frame-shadow'] = {
type = 'outline',
layer = 'BORDER',
color = '000000',
alpha = .17,
offset = 0,
},
['frame-highlight'] = {
type = 'texture',
layer = 'BORDER',
gradient = 'VERTICAL',
color = 'ffffff',
alpha = 0,
alphaEnd = .07,
offset = -1,
},
['frame-innerShadow'] = {
type = 'texture',
layer = 'BORDER',
color = '000000',
offset = -2,
},
['frame-innerColor'] = {
type = 'texture',
layer = 'BORDER',
color = '080808',
offset = -3,
},
}
local checkStyle = {
type = 'texture',
layer = 'ARTWORK',
texFile = 'DiesalGUIcons',
texCoord = {10,5,16,256,128},
texColor = 'ffff00',
offset = {1,nil,2,nil},
width = 16,
height = 16,
}
local checkDisabled = {
type = 'texture',
texColor = 'ffffff',
}
local checkEnabled = {
type = 'texture',
texColor = 'ffff00',
aplha = 1,
}
local wireFrame = {
['frame-white'] = {
type = 'outline',
layer = 'OVERLAY',
color = 'ffffff',
},
}
-- ~~| Button Methods |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local methods = {
['OnAcquire'] = function(self)
self:ApplySettings()
self:AddStyleSheet(styleSheet)
self:Enable()
-- self:AddStyleSheet(wireFrameSheet)
self.fontString:SetFontObject("DiesalFontNormal")
self.fontString:SetText()
self:Show()
end,
['OnRelease'] = function(self)
end,
['ApplySettings'] = function(self)
local settings = self.settings
local frame = self.frame
self:SetWidth(settings.width)
self:SetHeight(settings.height)
end,
["SetChecked"] = function(self,value)
self.settings.checked = value
self.frame:SetChecked(value)
self[self.settings.disabled and "Disable" or "Enable"](self)
end,
["GetChecked"] = function(self)
return self.settings.checked
end,
["Disable"] = function(self)
self.settings.disabled = true
DiesalStyle:StyleTexture(self.check,checkDisabled)
self.frame:Disable()
end,
["Enable"] = function(self)
self.settings.disabled = false
DiesalStyle:StyleTexture(self.check,checkEnabled)
self.frame:Enable()
end,
["RegisterForClicks"] = function(self,...)
self.frame:RegisterForClicks(...)
end,
["SetText"] = function(self, text)
self.fontString:SetText(text)
end,
}
-- ~~| Button Constructor |~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local function Constructor()
local self = DiesalGUI:CreateObjectBase(TYPE)
local frame = CreateFrame('CheckButton', nil, UIParent)
local fontString = frame:CreateFontString()
self.frame = frame
self.fontString = fontString
-- ~~ Default Settings ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
self.defaults = {
height = 12,
width = 12,
}
-- ~~ Events ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-- OnAcquire, OnRelease, OnHeightSet, OnWidthSet
-- OnValueChanged, OnEnter, OnLeave, OnDisable, OnEnable
-- ~~ Construct ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
local check = self:CreateRegion("Texture", 'check', frame)
DiesalStyle:StyleTexture(check,checkStyle)
frame:SetCheckedTexture(check)
frame:SetScript('OnClick', function(this,button,...)
DiesalGUI:OnMouse(this,button)
if not self.settings.disabled then
self:SetChecked(not self.settings.checked)
if self.settings.checked then
PlaySound("igMainMenuOptionCheckBoxOn")
else
PlaySound("igMainMenuOptionCheckBoxOff")
end
self:FireEvent("OnValueChanged", self.settings.checked)
end
end)
frame:SetScript('OnEnter', function(this)
self:FireEvent("OnEnter")
end)
frame:SetScript('OnLeave', function(this)
self:FireEvent("OnLeave")
end)
frame:SetScript("OnDisable", function(this)
self:FireEvent("OnDisable")
end)
frame:SetScript("OnEnable", function(this)
self:FireEvent("OnEnable")
end)
fontString:SetPoint("TOPLEFT", check, "TOPRIGHT", 5, -2)
-- ~~ Methods ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
for method, func in pairs(methods) do self[method] = func end
-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
return self
end
DiesalGUI:RegisterObjectConstructor(TYPE,Constructor,VERSION) | gpl-3.0 |
palmettos/cnLuCI | applications/luci-diag-devinfo/luasrc/model/cbi/luci_diag/netdiscover_devinfo_mini.lua | 141 | 1054 | --[[
netdiscover_devinfo - SIP Device Information
(c) 2009 Daniel Dickinson
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.model.uci")
require("luci.controller.luci_diag.netdiscover_common")
require("luci.controller.luci_diag.devinfo_common")
local debug = false
m = SimpleForm("luci_devinfo", translate("Network Device Scan"), translate("Scan for devices on specified networks."))
m.reset = false
m.submit = false
local outnets = luci.controller.luci_diag.netdiscover_common.get_params()
luci.controller.luci_diag.devinfo_common.run_processes(outnets, luci.controller.luci_diag.netdiscover_common.command_function)
luci.controller.luci_diag.devinfo_common.parse_output(m, outnets, false, "netdiscover", true, debug)
luci.controller.luci_diag.netdiscover_common.action_links(m, true)
return m
| apache-2.0 |
kidaa/Awakening-Core3 | bin/scripts/object/creature/npc/base/twilek_base_male.lua | 3 | 2224 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_creature_npc_base_twilek_base_male = object_creature_npc_base_shared_twilek_base_male:new {
}
ObjectTemplates:addTemplate(object_creature_npc_base_twilek_base_male, "object/creature/npc/base/twilek_base_male.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/static/structure/general/prp_junk_s4.lua | 3 | 2232 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_static_structure_general_prp_junk_s4 = object_static_structure_general_shared_prp_junk_s4:new {
}
ObjectTemplates:addTemplate(object_static_structure_general_prp_junk_s4, "object/static/structure/general/prp_junk_s4.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/static/structure/general/streetlamp_small_red_style_02.lua | 3 | 2304 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_static_structure_general_streetlamp_small_red_style_02 = object_static_structure_general_shared_streetlamp_small_red_style_02:new {
}
ObjectTemplates:addTemplate(object_static_structure_general_streetlamp_small_red_style_02, "object/static/structure/general/streetlamp_small_red_style_02.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/building/endor/endor_lake_hut_s02.lua | 3 | 2220 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_building_endor_endor_lake_hut_s02 = object_building_endor_shared_endor_lake_hut_s02:new {
}
ObjectTemplates:addTemplate(object_building_endor_endor_lake_hut_s02, "object/building/endor/endor_lake_hut_s02.iff")
| lgpl-3.0 |
jmchandonia/narrative | docker/test_docker.lua | 8 | 1638 | -- author: Steve Chan sychan@lbl.gov
--
-- Copyright 2013 The Regents of the University of California,
-- Lawrence Berkeley National Laboratory
-- United States Department of Energy
-- The DOE Systems Biology Knowledgebase (KBase)
-- Made available under the KBase Open Source License
--
PROXY=nil
d = require('docker')
p=require('pl.pretty')
c=d.config()
c.image='kbase/narrative:latest'
c.Cmd={'test_narrative'}
c.PortSpecs= { "8888" }
c.name="test_narrative"
--p.dump(d.client:containers())
res = d.client:create_container{ payload = c, name = "test_narrative"}
--p.dump(res.body)
id = res.body.Id
print("Container id = ", id)
res = d.client:start_container{ id = id, payload = { PublishAllPorts = true }}
if (res.status == 204) then
print("Container started successfully")
else
print("Container failed to start")
p.dump( res.body)
end
res = d.client:containers()
--p.dump(res.body)
print "Listing of ports in containers"
portmap = {}
for index,container in pairs(res.body) do
name = string.sub(container.Names[1],2,-1)
p.dump( name)
portmap[name]={}
for i, v in pairs(container.Ports) do
portmap[name][v.PublicPort] = v.PrivatePort
end
end
p.dump(portmap)
p.dump(d.client:top{id=id,ps_args="auxww"}.body)
res = d.client:stop_container{ id = id}
if (res.status == 204) then
print("Container stopped successfully")
else
print("Container failed to stop")
p.dump( res.body)
end
res = d.client:remove_container{ id = id}
if (res.status == 204) then
print("Container removed successfully")
else
print("Container failed delete")
p.dump( res.body)
end
| mit |
eraffxi/darkstar | scripts/globals/weaponskills/shoulder_tackle.lua | 2 | 1638 | -----------------------------------
-- Shoulder Tackle
-- Hand-to-Hand weapon skill
-- Skill Level: 40
-- Stuns target. Chance of stunning varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Aqua Gorget & Thunder Gorget.
-- Aligned with the Aqua Belt & Thunder Belt.
-- Element: None
-- Modifiers: VIT:100%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.vit_wsc = 1.0;
end
if (damage > 0 and target:hasStatusEffect(dsp.effect.STUN) == false) then
local duration = (tp/500) * applyResistanceAddEffect(player,target,dsp.magic.ele.LIGHTNING,0);
target:addStatusEffect(dsp.effect.STUN, 1, 0, duration);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/swirl_prong/objects.lua | 3 | 5576 | --Copyright (C) 2009 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
object_tangible_lair_swirl_prong_shared_lair_swirl_prong = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/lair/swirl_prong/shared_lair_swirl_prong.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/defaultappearance.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 25,
clientDataFile = "clientdata/client_shared_lair_small.cdf",
clientGameObjectType = 4,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@lair_d:swirl_prong",
gameObjectType = 4,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 64,
objectName = "@lair_n:swirl_prong",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 4003634872,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/lair/base/shared_lair_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_lair_swirl_prong_shared_lair_swirl_prong, "object/tangible/lair/swirl_prong/shared_lair_swirl_prong.iff")
object_tangible_lair_swirl_prong_shared_lair_swirl_prong_grassland = SharedTangibleObjectTemplate:new {
clientTemplateFileName = "object/tangible/lair/swirl_prong/shared_lair_swirl_prong_grassland.iff"
--Data below here is deprecated and loaded from the tres, keeping for easy lookups
--[[
appearanceFilename = "appearance/defaultappearance.apt",
arrangementDescriptorFilename = "",
certificationsRequired = {},
clearFloraRadius = 25,
clientDataFile = "clientdata/client_shared_lair_small.cdf",
clientGameObjectType = 4,
collisionActionBlockFlags = 0,
collisionActionFlags = 51,
collisionActionPassFlags = 1,
collisionMaterialBlockFlags = 0,
collisionMaterialFlags = 1,
collisionMaterialPassFlags = 0,
containerType = 0,
containerVolumeLimit = 1,
customizationVariableMapping = {},
detailedDescription = "@lair_d:swirl_prong_grassland",
gameObjectType = 4,
locationReservationRadius = 0,
lookAtText = "string_id_table",
noBuildRadius = 64,
objectName = "@lair_n:swirl_prong_grassland",
onlyVisibleInTools = 0,
paletteColorCustomizationVariables = {},
portalLayoutFilename = "",
rangedIntCustomizationVariables = {},
scale = 1,
scaleThresholdBeforeExtentTest = 0.5,
sendToClient = 1,
slotDescriptorFilename = "",
snapToTerrain = 1,
socketDestinations = {},
structureFootprintFileName = "",
surfaceType = 0,
targetable = 1,
totalCellNumber = 0,
useStructureFootprintOutline = 0,
clientObjectCRC = 1455751773,
derivedFromTemplates = {"object/object/base/shared_base_object.iff", "object/tangible/base/shared_tangible_base.iff", "object/tangible/lair/base/shared_lair_base.iff"}
]]
}
ObjectTemplates:addClientTemplate(object_tangible_lair_swirl_prong_shared_lair_swirl_prong_grassland, "object/tangible/lair/swirl_prong/shared_lair_swirl_prong_grassland.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/mobile/corellia/hidden_daggers_leader.lua | 1 | 1432 | hidden_daggers_leader = Creature:new {
objectName = "@mob/creature_names:hidden_daggers_leader",
socialGroup = "hidden_daggers",
pvpFaction = "hidden_daggers",
faction = "hidden_daggers",
level = 18,
chanceHit = 0.32,
damageMin = 170,
damageMax = 180,
baseXp = 1426,
baseHAM = 2900,
baseHAMmax = 3500,
armor = 0,
resists = {5,15,5,-1,-1,-1,40,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {
"object/mobile/dressed_mugger.iff",
"object/mobile/dressed_criminal_thug_human_female_01.iff",
"object/mobile/dressed_criminal_thug_human_female_02.iff",
"object/mobile/dressed_criminal_thug_human_male_01.iff",
"object/mobile/dressed_criminal_thug_human_male_02.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 3300000},
{group = "loot_kit_parts", chance = 2000000},
{group = "tailor_components", chance = 1000000},
{group = "hidden_dagger_common", chance = 2700000},
{group = "wearables_all", chance = 1000000},
},
lootChance = 3000000
}
},
weapons = {"ranged_weapons"},
conversationTemplate = "",
attacks = merge(brawlernovice,marksmannovice)
}
CreatureTemplates:addCreatureTemplate(hidden_daggers_leader, "hidden_daggers_leader")
| lgpl-3.0 |
upsoft/avbot | extension/luascript/lpeg-0.11/re.lua | 160 | 6286 | -- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $
-- imported functions and modules
local tonumber, type, print, error = tonumber, type, print, error
local setmetatable = setmetatable
local m = require"lpeg"
-- 'm' will be used to parse expressions, and 'mm' will be used to
-- create expressions; that is, 're' runs on 'm', creating patterns
-- on 'mm'
local mm = m
-- pattern's metatable
local mt = getmetatable(mm.P(0))
-- No more global accesses after this point
local version = _VERSION
if version == "Lua 5.2" then _ENV = nil end
local any = m.P(1)
-- Pre-defined names
local Predef = { nl = m.P"\n" }
local mem
local fmem
local gmem
local function updatelocale ()
mm.locale(Predef)
Predef.a = Predef.alpha
Predef.c = Predef.cntrl
Predef.d = Predef.digit
Predef.g = Predef.graph
Predef.l = Predef.lower
Predef.p = Predef.punct
Predef.s = Predef.space
Predef.u = Predef.upper
Predef.w = Predef.alnum
Predef.x = Predef.xdigit
Predef.A = any - Predef.a
Predef.C = any - Predef.c
Predef.D = any - Predef.d
Predef.G = any - Predef.g
Predef.L = any - Predef.l
Predef.P = any - Predef.p
Predef.S = any - Predef.s
Predef.U = any - Predef.u
Predef.W = any - Predef.w
Predef.X = any - Predef.x
mem = {} -- restart memoization
fmem = {}
gmem = {}
local mt = {__mode = "v"}
setmetatable(mem, mt)
setmetatable(fmem, mt)
setmetatable(gmem, mt)
end
updatelocale()
local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end)
local function getdef (id, defs)
local c = defs and defs[id]
if not c then error("undefined name: " .. id) end
return c
end
local function patt_error (s, i)
local msg = (#s < i + 20) and s:sub(i)
or s:sub(i,i+20) .. "..."
msg = ("pattern error near '%s'"):format(msg)
error(msg, 2)
end
local function mult (p, n)
local np = mm.P(true)
while n >= 1 do
if n%2 >= 1 then np = np * p end
p = p * p
n = n/2
end
return np
end
local function equalcap (s, i, c)
if type(c) ~= "string" then return nil end
local e = #c + i
if s:sub(i, e - 1) == c then return e else return nil end
end
local S = (Predef.space + "--" * (any - Predef.nl)^0)^0
local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0
local arrow = S * "<-"
local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1
name = m.C(name)
-- a defined name only have meaning in a given environment
local Def = name * m.Carg(1)
local num = m.C(m.R"09"^1) * S / tonumber
local String = "'" * m.C((any - "'")^0) * "'" +
'"' * m.C((any - '"')^0) * '"'
local defined = "%" * Def / function (c,Defs)
local cat = Defs and Defs[c] or Predef[c]
if not cat then error ("name '" .. c .. "' undefined") end
return cat
end
local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R
local item = defined + Range + m.C(any)
local Class =
"["
* (m.C(m.P"^"^-1)) -- optional complement symbol
* m.Cf(item * (item - "]")^0, mt.__add) /
function (c, p) return c == "^" and any - p or p end
* "]"
local function adddef (t, k, exp)
if t[k] then
error("'"..k.."' already defined as a rule")
else
t[k] = exp
end
return t
end
local function firstdef (n, r) return adddef({n}, n, r) end
local function NT (n, b)
if not b then
error("rule '"..n.."' used outside a grammar")
else return mm.V(n)
end
end
local exp = m.P{ "Exp",
Exp = S * ( m.V"Grammar"
+ m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) );
Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul)
* (#seq_follow + patt_error);
Prefix = "&" * S * m.V"Prefix" / mt.__len
+ "!" * S * m.V"Prefix" / mt.__unm
+ m.V"Suffix";
Suffix = m.Cf(m.V"Primary" * S *
( ( m.P"+" * m.Cc(1, mt.__pow)
+ m.P"*" * m.Cc(0, mt.__pow)
+ m.P"?" * m.Cc(-1, mt.__pow)
+ "^" * ( m.Cg(num * m.Cc(mult))
+ m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow))
)
+ "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div))
+ m.P"{}" * m.Cc(nil, m.Ct)
+ m.Cg(Def / getdef * m.Cc(mt.__div))
)
+ "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt))
) * S
)^0, function (a,b,f) return f(a,b) end );
Primary = "(" * m.V"Exp" * ")"
+ String / mm.P
+ Class
+ defined
+ "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" /
function (n, p) return mm.Cg(p, n) end
+ "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end
+ m.P"{}" / mm.Cp
+ "{~" * m.V"Exp" * "~}" / mm.Cs
+ "{|" * m.V"Exp" * "|}" / mm.Ct
+ "{" * m.V"Exp" * "}" / mm.C
+ m.P"." * m.Cc(any)
+ (name * -arrow + "<" * name * ">") * m.Cb("G") / NT;
Definition = name * arrow * m.V"Exp";
Grammar = m.Cg(m.Cc(true), "G") *
m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0,
adddef) / mm.P
}
local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error)
local function compile (p, defs)
if mm.type(p) == "pattern" then return p end -- already compiled
local cp = pattern:match(p, 1, defs)
if not cp then error("incorrect pattern", 3) end
return cp
end
local function match (s, p, i)
local cp = mem[p]
if not cp then
cp = compile(p)
mem[p] = cp
end
return cp:match(s, i or 1)
end
local function find (s, p, i)
local cp = fmem[p]
if not cp then
cp = compile(p) / 0
cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) }
fmem[p] = cp
end
local i, e = cp:match(s, i or 1)
if i then return i, e - 1
else return i
end
end
local function gsub (s, p, rep)
local g = gmem[p] or {} -- ensure gmem[p] is not collected while here
gmem[p] = g
local cp = g[rep]
if not cp then
cp = compile(p)
cp = mm.Cs((cp / rep + 1)^0)
g[rep] = cp
end
return cp:match(s)
end
-- exported names
local re = {
compile = compile,
match = match,
find = find,
gsub = gsub,
updatelocale = updatelocale,
}
if version == "Lua 5.1" then _G.re = re end
return re
| agpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/mobile/tatooine/sennex_slavemaster.lua | 1 | 1705 | sennex_slavemaster = Creature:new {
objectName = "@mob/creature_names:sennex_slavemaster",
socialGroup = "sennex",
pvpFaction = "pirate",
faction = "pirate",
level = 37,
chanceHit = 0.43,
damageMin = 340,
damageMax = 390,
baseXp = 3733,
baseHAM = 9200,
baseHAMmax = 11200,
armor = 0,
resists = {0,0,0,30,-1,30,-1,-1,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = AGGRESSIVE + ATTACKABLE,
creatureBitmask = PACK + KILLER,
optionsBitmask = 128,
diet = HERBIVORE,
templates = {"object/mobile/dressed_sennex_pirate_01.iff",
"object/mobile/dressed_sennex_pirate_02.iff",
"object/mobile/dressed_sennex_pirate_03.iff",
"object/mobile/dressed_sennex_pirate_04.iff",
"object/mobile/dressed_sennex_pirate_05.iff",
"object/mobile/dressed_sennex_pirate_06.iff",
"object/mobile/dressed_sennex_pirate_07.iff",
"object/mobile/dressed_sennex_pirate_08.iff",
"object/mobile/dressed_sennex_pirate_09.iff",
"object/mobile/dressed_sennex_pirate_10.iff",
"object/mobile/dressed_sennex_pirate_11.iff",
"object/mobile/dressed_sennex_pirate_12.iff"},
lootGroups = {
{
groups = {
{group = "junk", chance = 3000000},
{group = "wearables_common", chance = 2000000},
{group = "heavy_weapons", chance = 2000000},
{group = "tailor_components", chance = 1500000},
{group = "loot_kit_parts", chance = 1500000}
},
lootChance = 2200000
}
},
weapons = {"pirate_weapons_heavy"},
conversationTemplate = "",
attacks = merge(marksmannovice,brawlernovice)
}
CreatureTemplates:addCreatureTemplate(sennex_slavemaster, "sennex_slavemaster")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/building/player/city/garden_naboo_med_01.lua | 3 | 2756 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_building_player_city_garden_naboo_med_01 = object_building_player_city_shared_garden_naboo_med_01:new {
lotSize = 0,
baseMaintenanceRate = 0,
allowedZones = {"dantooine", "naboo", "rori"},
length = 5,
width = 5,
cityRankRequired = 2,
cityMaintenanceBase = 20000,
abilityRequired = "place_medium_garden",
zoneComponent = "StructureZoneComponent",
dataObjectComponent = "DecorationDataComponent",
childObjects = {
{templateFile = "object/tangible/terminal/terminal_player_structure_nosnap_mini.iff", x = 8.25, z = 1.3, y = -8.25, ox = 0, oy = 1, oz = 0, ow = 0, cellid = -1, containmentType = -1}
}
}
ObjectTemplates:addTemplate(object_building_player_city_garden_naboo_med_01, "object/building/player/city/garden_naboo_med_01.iff")
| lgpl-3.0 |
eraffxi/darkstar | scripts/globals/weaponskills/calamity.lua | 25 | 1516 | -----------------------------------
-- Calamity
-- Axe weapon skill
-- Skill level: 200 (Beastmasters and Warriors only.)
-- Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget & Thunder Gorget.
-- Aligned with the Soil Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:32% ; VIT:32%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 4.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 4;
params.str_wsc = 0.32; params.dex_wsc = 0.0; params.vit_wsc = 0.32; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 2.5; params.ftp200 = 6.5; params.ftp300 = 10.375;
params.str_wsc = 0.5; params.vit_wsc = 0.5;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/ship/components/reactor/rct_sfs_imperial_2.lua | 3 | 2292 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_ship_components_reactor_rct_sfs_imperial_2 = object_tangible_ship_components_reactor_shared_rct_sfs_imperial_2:new {
}
ObjectTemplates:addTemplate(object_tangible_ship_components_reactor_rct_sfs_imperial_2, "object/tangible/ship/components/reactor/rct_sfs_imperial_2.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/commands/healActionWoundOther2.lua | 3 | 2156 | --Copyright (C) 2007 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--which carries forward this exception.
--true = 1, false = 0
HealActionWoundOther2Command = {
name = "healactionwoundother2",
}
AddCommand(HealActionWoundOther2Command)
| lgpl-3.0 |
eraffxi/darkstar | scripts/globals/spells/bluemagic/temporal_shift.lua | 2 | 1501 | -----------------------------------------
-- Spell: Temporal Shift
-- Enemies within range are temporarily prevented from acting
-- Spell cost: 48 MP
-- Monster Type: Luminians
-- Spell Type: Magical (Lightning)
-- Blue Magic Points: 5
-- Stat Bonus: HP+10, MP+15
-- Level: 73
-- Casting Time: 0.5 seconds
-- Recast Time: 120 seconds
-- Magic Bursts on: Impaction, Fragmentation, and Light
-- Combos: Attack Bonus
-----------------------------------------
require("scripts/globals/bluemagic");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local typeEffect = dsp.effect.STUN;
local dINT = caster:getStat(dsp.mod.INT) - target:getStat(dsp.mod.INT);
local params = {};
params.diff = nil;
params.attribute = dsp.mod.INT;
params.skillType = dsp.skill.BLUE_MAGIC;
params.bonus = 0;
params.effect = dsp.effect.STUN;
local resist = applyResistanceEffect(caster, target, spell, params);
local duration = 5 * resist;
if (resist > 0.0625) then -- Do it!
if (target:addStatusEffect(typeEffect,2,0,duration)) then
spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS);
else
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT);
end
else
spell:setMsg(dsp.msg.basic.MAGIC_RESIST);
end;
return typeEffect;
end;
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/womp_rat/serverobjects.lua | 3 | 2167 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
--Children folder includes
-- Server Objects
includeFile("tangible/lair/womp_rat/lair_womp_rat.lua")
includeFile("tangible/lair/womp_rat/lair_womp_rat_desert.lua")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/mobile/dalyrake_matriarch.lua | 3 | 2188 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_mobile_dalyrake_matriarch = object_mobile_shared_dalyrake_matriarch:new {
}
ObjectTemplates:addTemplate(object_mobile_dalyrake_matriarch, "object/mobile/dalyrake_matriarch.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/lair/dune_lizard/lair_dune_lizard_desert.lua | 2 | 2336 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_lair_dune_lizard_lair_dune_lizard_desert = object_tangible_lair_dune_lizard_shared_lair_dune_lizard_desert:new {
objectMenuComponent = {"cpp", "LairMenuComponent"},
}
ObjectTemplates:addTemplate(object_tangible_lair_dune_lizard_lair_dune_lizard_desert, "object/tangible/lair/dune_lizard/lair_dune_lizard_desert.iff")
| lgpl-3.0 |
widelands/widelands | data/campaigns/emp01.wmf/scripting/mission_thread.lua | 1 | 3640 | function mission_thread()
sleep(1000)
-- Initial messages
local sea = wl.Game().map:get_field(50,25)
local ship = p1:place_ship(sea)
p1:hide_fields(sea:region(6), "permanent")
scroll_to_field(sea,0)
campaign_message_box(diary_page_1)
sleep(200)
-- Show the sea
reveal_concentric(p1, sea, 5)
sleep(1000)
campaign_message_box(diary_page_2)
sleep(500)
-- hide a bit more as revealed as the ship might move and discover some fields
hide_concentric(p1, sea, 6)
ship:remove()
-- Back home
include "map:scripting/starting_conditions.lua"
p1:hide_fields(wl.Game().map.player_slots[1].starting_field:region(13),"permanent")
scroll_to_field(wl.Game().map.player_slots[1].starting_field)
campaign_message_box(diary_page_3)
sleep(1000)
reveal_concentric(p1, wl.Game().map.player_slots[1].starting_field, 13)
sleep(400)
-- Check for trees and remove them
local fields = {{12,0}, -- Buildspace
{12,1}, -- Flag of building
{12,2}, {11,2}, -- Roads ...
{10,2}, {9,2},
{8,2}, {7,1},
{7,0},}
remove_trees(fields)
campaign_message_box(saledus_1)
p1:allow_buildings{"empire_blockhouse"}
local o = add_campaign_objective(obj_build_blockhouse)
-- TODO(Nordfriese): Re-add training wheels code after v1.0
-- p1:run_training_wheel("objectives", true)
while #p1:get_buildings("empire_blockhouse") < 1 do sleep(3249) end
set_objective_done(o)
-- Blockhouse is completed now
-- Make sure no tree blocks the building space for Lumberjack
local fields = {{6,3}, -- Buildspace
{7,4}, -- Flag of building
{7,3}, {7,2},} -- Roads
remove_trees(fields)
campaign_message_box(saledus_2)
p1:allow_buildings{"empire_lumberjacks_house"}
o = add_campaign_objective(obj_build_lumberjack)
campaign_message_box(amalea_1)
while #p1:get_buildings("empire_lumberjacks_house") < 1 do sleep(3249) end
set_objective_done(o)
-- TODO(Nordfriese): Re-add training wheels code after v1.0
-- p1:mark_training_wheel_as_solved("logs")
-- Lumberjack is now build
campaign_message_box(amalea_2)
p1:allow_buildings{"empire_sawmill"}
o = add_campaign_objective(obj_build_sawmill_and_lumberjacks)
while not check_for_buildings(p1, { empire_lumberjacks_house = 3, empire_sawmill = 1})
do sleep(2343) end
set_objective_done(o)
-- Now the lady demands a forester after having us cut down the whole forest.
campaign_message_box(amalea_3)
o = add_campaign_objective(obj_build_forester)
p1:allow_buildings{"empire_foresters_house"}
while not check_for_buildings(p1, { empire_foresters_house = 1 }) do sleep(2434) end
set_objective_done(o)
-- Now a quarry
campaign_message_box(saledus_3)
o = add_campaign_objective(obj_build_quarry)
p1:allow_buildings{"empire_quarry"}
while not check_for_buildings(p1, { empire_quarry = 1 }) do sleep(2434) end
set_objective_done(o)
-- TODO(Nordfriese): Re-add training wheels code after v1.0
-- p1:mark_training_wheel_as_solved("rocks")
-- All buildings done. Got home
campaign_message_box(saledus_4)
sleep(25000) -- Sleep a while
campaign_message_box(diary_page_4)
p1:mark_scenario_as_solved("emp01.wmf")
end
-- Show a funny message when the player has build 10 blockhouses
function easter_egg()
while not check_for_buildings(p1, {empire_blockhouse = 10}) do sleep(4253) end
campaign_message_box(safe_peninsula)
end
run(mission_thread)
run(easter_egg)
| gpl-2.0 |
houqp/koreader | spec/unit/nickel_conf_spec.lua | 4 | 4438 | describe("Nickel configuation module", function()
local lfs, NickelConf
setup(function()
require("commonrequire")
lfs = require("libs/libkoreader-lfs")
NickelConf = require("device/kobo/nickel_conf")
end)
describe("Frontlight module", function()
it("should read value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=55
FrontLightState=true
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
assert.Equals(NickelConf.frontLightLevel.get(), 55)
assert.Equals(NickelConf.frontLightState.get(), true)
os.remove(fn)
end)
it("should also read value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=30
FrontLightState=false
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
assert.Equals(NickelConf.frontLightLevel.get(), 30)
assert.Equals(NickelConf.frontLightState.get(), false)
os.remove(fn)
end)
it("should have default value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
assert.Equals(NickelConf.frontLightLevel.get(), 1)
assert.Equals(NickelConf.frontLightState.get(), nil)
os.remove(fn)
end)
it("should create section", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
FrontLightLevel=6
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(100)
NickelConf.frontLightState.set(true)
fd = io.open(fn, "r")
assert.Equals(fd:read("*a"), [[
[OtherThing]
FrontLightLevel=6
[PowerOptions]
FrontLightLevel=100
]])
fd:close()
os.remove(fn)
fd = io.open(fn, "w")
fd:write("")
fd:close()
NickelConf.frontLightLevel.set(20)
NickelConf.frontLightState.set(false)
fd = io.open(fn, "r")
assert.Equals(fd:read("*a"), [[
[PowerOptions]
FrontLightLevel=20
]])
fd:close()
os.remove(fn)
end)
it("should replace value", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=6
FrontLightState=false
[YetAnotherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(100)
NickelConf.frontLightState.set(true)
fd = io.open(fn, "r")
assert.Equals(fd:read("*a"), [[
[OtherThing]
foo=bar
[PowerOptions]
FrontLightLevel=100
FrontLightState=true
[YetAnotherThing]
bar=baz
]])
fd:close()
os.remove(fn)
end)
it("should insert entry", function()
local fn = os.tmpname()
local fd = io.open(fn, "w")
fd:write([[
[PowerOptions]
foo=bar
[OtherThing]
bar=baz
]])
fd:close()
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(1)
NickelConf.frontLightState.set(true)
fd = io.open(fn, "r")
assert.Equals([[
[PowerOptions]
foo=bar
FrontLightLevel=1
[OtherThing]
bar=baz
]], fd:read("*a"))
fd:close()
os.remove(fn)
end)
it("should create config file", function()
local fd
local fn = "/tmp/abcfoobarbaz449"
assert.is_not.Equals(lfs.attributes(fn, "mode"), "file")
finally(function() os.remove(fn) end)
NickelConf._set_kobo_conf_path(fn)
NickelConf.frontLightLevel.set(15)
NickelConf.frontLightState.set(false)
fd = io.open(fn, "r")
assert.Equals([[
[PowerOptions]
FrontLightLevel=15
]],
fd:read("*a"))
fd:close()
end)
end)
end)
| agpl-3.0 |
houqp/koreader | spec/unit/benchmark.lua | 13 | 1556 | require("commonrequire")
local DocumentRegistry = require("document/documentregistry")
local util = require("ffi/util")
local function logDuration(filename, pageno, dur)
local file = io.open(filename, "a+")
if file then
if file:seek("end") == 0 then -- write the header only once
file:write("PAGE\tDUR\n")
end
file:write(string.format("%s\t%s\n", pageno, dur))
file:close()
end
end
describe("PDF rendering benchmark", function()
local sample_pdf = "spec/front/unit/data/sample.pdf"
local doc = DocumentRegistry:openDocument(sample_pdf)
for pageno = 1, math.min(10, doc.info.number_of_pages) do
local secs, usecs = util.gettime()
assert.truthy(doc:renderPage(pageno, nil, 1, 0, 1.0, 0))
local nsecs, nusecs = util.gettime()
local dur = nsecs - secs + (nusecs - usecs) / 1000000
logDuration("pdf_rendering.log", pageno, dur)
end
doc:close()
end)
describe("PDF reflowing benchmark", function()
local sample_pdf = "spec/front/unit/data/sample.pdf"
local doc = DocumentRegistry:openDocument(sample_pdf)
doc.configurable.text_wrap = 1
for pageno = 1, math.min(10, doc.info.number_of_pages) do
local secs, usecs = util.gettime()
assert.truthy(doc:renderPage(pageno, nil, 1, 0, 1.0, 0))
local nsecs, nusecs = util.gettime()
local dur = nsecs - secs + (nusecs - usecs) / 1000000
logDuration("pdf_reflowing.log", pageno, dur)
end
doc:close()
doc.configurable.text_wrap = 0
end)
| agpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/ship/crafted/engine/engine_incom_fusialthrust.lua | 3 | 2304 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_ship_crafted_engine_engine_incom_fusialthrust = object_tangible_ship_crafted_engine_shared_engine_incom_fusialthrust:new {
}
ObjectTemplates:addTemplate(object_tangible_ship_crafted_engine_engine_incom_fusialthrust, "object/tangible/ship/crafted/engine/engine_incom_fusialthrust.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/mobile/dressed_robber_human_female_01.lua | 3 | 2236 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_mobile_dressed_robber_human_female_01 = object_mobile_shared_dressed_robber_human_female_01:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_robber_human_female_01, "object/mobile/dressed_robber_human_female_01.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/mobile/dressed_lost_aqualish_infiltrator_male_01.lua | 3 | 2280 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_mobile_dressed_lost_aqualish_infiltrator_male_01 = object_mobile_shared_dressed_lost_aqualish_infiltrator_male_01:new {
}
ObjectTemplates:addTemplate(object_mobile_dressed_lost_aqualish_infiltrator_male_01, "object/mobile/dressed_lost_aqualish_infiltrator_male_01.iff")
| lgpl-3.0 |
widelands/widelands | data/tribes/buildings/productionsites/frisians/charcoal_kiln/init.lua | 1 | 1685 | push_textdomain("tribes")
dirname = path.dirname (__file__)
wl.Descriptions():new_productionsite_type {
name = "frisians_charcoal_kiln",
-- TRANSLATORS: This is a building name used in lists of buildings
descname = pgettext ("frisians_building", "Charcoal Kiln"),
icon = dirname .. "menu.png",
size = "medium",
buildcost = {
brick = 3,
granite = 1,
log = 1,
reed = 2
},
return_on_dismantle = {
brick = 2,
log = 1,
reed = 1
},
spritesheets = {
idle = {
directory = dirname,
basename = "idle",
hotspot = {50, 82},
frames = 10,
columns = 5,
rows = 2,
fps = 10
},
working = {
directory = dirname,
basename = "working",
hotspot = {50, 82},
frames = 10,
columns = 5,
rows = 2,
fps = 10
}
},
animations = {
unoccupied = {
directory = dirname,
basename = "unoccupied",
hotspot = {50, 64}
}
},
aihints = {
basic_amount = 1
},
working_positions = {
frisians_charcoal_burner = 1
},
inputs = {
{ name = "log", amount = 8 },
{ name = "clay", amount = 4 },
},
programs = {
main = {
-- TRANSLATORS: Completed/Skipped/Did not start producing coal because ...
descname = _("producing coal"),
actions = {
"return=skipped unless economy needs coal",
"consume=log:3 clay",
"sleep=duration:30s",
"animate=working duration:30s",
"produce=coal"
},
},
},
}
pop_textdomain()
| gpl-2.0 |
eraffxi/darkstar | scripts/zones/Al_Zahbi/npcs/Zafif.lua | 2 | 1314 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Zafif
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil
-----------------------------------
require("scripts/zones/Al_Zahbi/TextIDs")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local stock =
{
4612, 23400, -- Scroll of Cure IV
4616, 11200, -- Scroll of Curaga II
4617, 19932, -- Scroll of Curaga III
4653, 32000, -- Scroll of Protect III
4654, 91116, -- Scroll of Protect IV
4736, 85500, -- Scroll of Protectra IV
4629, 35000, -- Scroll of Holy
4647, 20000, -- Scroll of Banishga II
4625, 2330, -- Scroll of Silena
4626, 19200, -- Scroll of Stona
4627, 13300, -- Scroll of Viruna
4628, 8586, -- Scroll of Cursna
4868, 77600, -- Scroll of Dispell
4720, 27000, -- Scroll of Flash
4750, 99375, -- Scroll of Reraise III
4715, 28500 -- Scroll of Reprisal
}
player:showText(npc, ZAFIF_SHOP_DIALOG)
dsp.shop.general(player, stock)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/loot/collectible/collectible_parts/orange_rug_patches.lua | 3 | 2336 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_loot_collectible_collectible_parts_orange_rug_patches = object_tangible_loot_collectible_collectible_parts_shared_orange_rug_patches:new {
}
ObjectTemplates:addTemplate(object_tangible_loot_collectible_collectible_parts_orange_rug_patches, "object/tangible/loot/collectible/collectible_parts/orange_rug_patches.iff")
| lgpl-3.0 |
kidaa/Awakening-Core3 | bin/scripts/object/tangible/component/bio/bio_component_food_light.lua | 3 | 2276 | --Copyright (C) 2010 <SWGEmu>
--This File is part of Core3.
--This program is free software; you can redistribute
--it and/or modify it under the terms of the GNU Lesser
--General Public License as published by the Free Software
--Foundation; either version 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 Lesser General Public License for
--more details.
--You should have received a copy of the GNU Lesser General
--Public License along with this program; if not, write to
--the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
--Linking Engine3 statically or dynamically with other modules
--is making a combined work based on Engine3.
--Thus, the terms and conditions of the GNU Lesser General Public License
--cover the whole combination.
--In addition, as a special exception, the copyright holders of Engine3
--give you permission to combine Engine3 program with free software
--programs or libraries that are released under the GNU LGPL and with
--code included in the standard release of Core3 under the GNU LGPL
--license (or modified versions of such code, with unchanged license).
--You may copy and distribute such a system following the terms of the
--GNU LGPL for Engine3 and the licenses of the other code concerned,
--provided that you include the source code of that other code when
--and as the GNU LGPL requires distribution of source code.
--Note that people who make modified versions of Engine3 are not obligated
--to grant this special exception for their modified versions;
--it is their choice whether to do so. The GNU Lesser General Public License
--gives permission to release a modified version without this exception;
--this exception also makes it possible to release a modified version
object_tangible_component_bio_bio_component_food_light = object_tangible_component_bio_shared_bio_component_food_light:new {
}
ObjectTemplates:addTemplate(object_tangible_component_bio_bio_component_food_light, "object/tangible/component/bio/bio_component_food_light.iff")
| lgpl-3.0 |
LuaDist2/lua-aplicado | lua-aplicado/code/profile.lua | 2 | 1188 | --------------------------------------------------------------------------------
-- profile.lua: lua-aplicado exports profile
-- This file is a part of Lua-Aplicado library
-- Copyright (c) Lua-Aplicado authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local tset = import 'lua-nucleo/table-utils.lua' { 'tset' }
--------------------------------------------------------------------------------
local PROFILE = { }
--------------------------------------------------------------------------------
PROFILE.skip = setmetatable(tset
{
"lua-aplicado/module.lua"; -- Too low-level
-- Excluding both low-level chunk inspector implementations
-- Higher-level implementation would pick proper one.
"lua-aplicado/lj2_chunk_inspector.lua";
"lua-aplicado/bci_chunk_inspector.lua";
}, {
__index = function(t, k)
-- Excluding files outside of lua-aplicado/ and inside lua-aplicado/code
local v = (not k:match("^lua%-aplicado/")) or k:match("^lua%-aplicado/code/")
t[k] = v
return v
end;
})
--------------------------------------------------------------------------------
return PROFILE
| mit |
n0xus/darkstar | scripts/zones/Nashmau/npcs/Yoyoroon.lua | 34 | 1613 | -----------------------------------
-- Area: Nashmau
-- NPC: Yoyoroon
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Nashmau/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,YOYOROON_SHOP_DIALOG);
stock = {0x08BF,4940, -- Tension Spring
0x08C0,9925, -- Inhibitor
0x08C2,9925, -- Mana Booster
0x08C3,4940, -- Loudspeaker
0x08C6,4940, -- Accelerator
0x08C7,9925, -- Scope
0x08CA,9925, -- Shock Absorber
0x08CB,4940, -- Armor Plate
0x08CE,4940, -- Stabilizer
0x08CF,9925, -- Volt Gun
0x08D2,4940, -- Mana Jammer
0x08D4,9925, -- Stealth Screen
0x08D6,4940, -- Auto-Repair Kit
0x08D8,9925, -- Damage Gauge
0x08DA,4940, -- Mana Tank
0x08DC,9925} -- Mana Conserver
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 |
xjdrew/levent | tests/test_socket.lua | 1 | 1210 | local levent = require "levent.levent"
local socket = require "levent.socket"
local timeout = require "levent.timeout"
local test_data = "hello"
function client(host)
local sock, errcode = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
assert(sock, errcode)
print("begin connect:", sock:fileno())
local ok, exception = sock:connect(host, 8859)
if not ok then
error("connect failed:" .. exception)
end
print("connect succeed")
sock:sendall(test_data)
sock:close()
end
function start()
local sock, errcode = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if not sock then
print("create socket failed:", errcode)
return
end
local ok, errcode = sock:bind("0.0.0.0", 8859)
if not ok then
print("bind socket address failed:", errcode)
return
end
sock:listen()
sock:set_timeout(10)
levent.spawn(client, "127.0.0.1")
levent.spawn(client, "localhost")
print("begin accept:", sock:fileno())
local csock, err = sock:accept()
assert(csock, err)
local data = csock:recv(1024)
print("recv:", data)
assert(data == test_data, data)
csock:close()
end
levent.start(start)
| mit |
n0xus/darkstar | scripts/zones/Tahrongi_Canyon/npcs/Excavation_Point.lua | 29 | 1114 | -----------------------------------
-- Area: Tahrongi Canyon
-- NPC: Excavation Point
-----------------------------------
package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/excavation");
require("scripts/zones/Tahrongi_Canyon/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startExcavation(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(MINING_IS_POSSIBLE_HERE,605);
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 |
ppriest/mame | 3rdparty/genie/src/base/bake.lua | 3 | 21785 | --
-- base/bake.lua
--
-- Takes all the configuration information provided by the project scripts
-- and stored in the solution->project->block hierarchy and flattens it all
-- down into one object per configuration. These objects are cached with the
-- project, and can be retrieved by calling the getconfig() or eachconfig().
--
-- Copyright (c) 2008-2011 Jason Perkins and the Premake project
--
premake.bake = { }
local bake = premake.bake
-- do not copy these fields into the configurations
local nocopy =
{
blocks = true,
keywords = true,
projects = true,
__configs = true,
}
-- do not cascade these fields from projects to configurations
local nocascade =
{
makesettings = true,
}
-- leave these paths as absolute, rather than converting to project relative
local keeprelative =
{
basedir = true,
location = true,
}
--
-- Returns a list of all of the active terms from the current environment.
-- See the docs for configuration() for more information about the terms.
--
function premake.getactiveterms()
local terms = { _action = _ACTION:lower(), os = os.get() }
-- add option keys or values
for key, value in pairs(_OPTIONS) do
if value ~= "" then
table.insert(terms, value:lower())
else
table.insert(terms, key:lower())
end
end
return terms
end
--
-- Test a single configuration block keyword against a list of terms.
-- The terms are a mix of key/value pairs. The keyword is tested against
-- the values; on a match, the corresponding key is returned. This
-- enables testing for required values in iskeywordsmatch(), below.
--
function premake.iskeywordmatch(keyword, terms)
-- is it negated?
if keyword:startswith("not ") then
return not premake.iskeywordmatch(keyword:sub(5), terms)
end
for _, pattern in ipairs(keyword:explode(" or ")) do
for termkey, term in pairs(terms) do
if term:match(pattern) == term then
return termkey
end
end
end
end
--
-- Checks a set of configuration block keywords against a list of terms.
-- The required flag is used by the file configurations: only blocks
-- with a term that explictly matches the filename get applied; more
-- general blocks are skipped over (since they were already applied at
-- the config level).
--
function premake.iskeywordsmatch(keywords, terms)
local hasrequired = false
for _, keyword in ipairs(keywords) do
local matched = premake.iskeywordmatch(keyword, terms)
if not matched then
return false
end
if matched == "required" then
hasrequired = true
end
end
if terms.required and not hasrequired then
return false
else
return true
end
end
--
-- Converts path fields from absolute to location-relative paths.
--
-- @param location
-- The base location, paths will be relative to this directory.
-- @param obj
-- The object containing the fields to be adjusted.
--
local function adjustpaths(location, obj)
function adjustpathlist(list)
for i, p in ipairs(list) do
list[i] = path.getrelative(location, p)
end
end
for name, value in pairs(obj) do
local field = premake.fields[name]
if field and value and not keeprelative[name] then
if field.kind == "path" then
obj[name] = path.getrelative(location, value)
elseif field.kind == "dirlist" or field.kind == "filelist" then
adjustpathlist(value)
elseif field.kind == "keypath" then
for k,v in pairs(value) do
adjustpathlist(v)
end
end
end
end
end
--
-- Merge all of the fields from one object into another. String values are overwritten,
-- while list values are merged. Fields listed in premake.nocopy are skipped.
--
-- @param dest
-- The destination object, to contain the merged settings.
-- @param src
-- The source object, containing the settings to added to the destination.
--
local function mergefield(kind, dest, src)
local tbl = dest or { }
if kind == "keyvalue" or kind == "keypath" then
for key, value in pairs(src) do
tbl[key] = mergefield("list", tbl[key], value)
end
else
for _, item in ipairs(src) do
if not tbl[item] then
table.insert(tbl, item)
tbl[item] = item
end
end
end
return tbl
end
local function removevalues(tbl, removes)
for i=#tbl,1,-1 do
for _, pattern in ipairs(removes) do
if pattern == tbl[i] then
table.remove(tbl, i)
break
end
end
end
end
local function mergeobject(dest, src)
-- if there's nothing to add, quick out
if not src then
return
end
for fieldname, value in pairs(src) do
if not nocopy[fieldname] then
-- fields that are included in the API are merged...
local field = premake.fields[fieldname]
if field then
if type(value) == "table" then
dest[fieldname] = mergefield(field.kind, dest[fieldname], value)
if src.removes then
removes = src.removes[fieldname]
if removes then
removevalues(dest[fieldname], removes)
end
end
else
dest[fieldname] = value
end
-- ...everything else is just copied as-is
else
dest[fieldname] = value
end
end
end
end
--
-- Merges the settings from a solution's or project's list of configuration blocks,
-- for all blocks that match the provided set of environment terms.
--
-- @param dest
-- The destination object, to contain the merged settings.
-- @param obj
-- The solution or project object being collapsed.
-- @param basis
-- "Root" level settings, from the solution, which act as a starting point for
-- all of the collapsed settings built during this call.
-- @param terms
-- A list of keywords to filter the configuration blocks; only those that
-- match will be included in the destination.
-- @param cfgname
-- The name of the configuration being collapsed. May be nil.
-- @param pltname
-- The name of the platform being collapsed. May be nil.
--
local function merge(dest, obj, basis, terms, cfgname, pltname)
-- the configuration key is the merged configuration and platform names
local key = cfgname or ""
pltname = pltname or "Native"
if pltname ~= "Native" then
key = key .. pltname
end
-- add the configuration and platform to the block filter terms
terms.config = (cfgname or ""):lower()
terms.platform = pltname:lower()
-- build the configuration base by merging the solution and project level settings
local cfg = {}
mergeobject(cfg, basis[key])
adjustpaths(obj.location, cfg)
mergeobject(cfg, obj)
-- add `kind` to the filter terms
if (cfg.kind) then
terms['kind']=cfg.kind:lower()
end
-- now add in any blocks that match the filter terms
for _, blk in ipairs(obj.blocks) do
if (premake.iskeywordsmatch(blk.keywords, terms))then
mergeobject(cfg, blk)
if (cfg.kind and not cfg.terms.kind) then
cfg.terms['kind'] = cfg.kind:lower()
terms['kind'] = cfg.kind:lower()
end
end
end
-- package it all up and add it to the result set
cfg.name = cfgname
cfg.platform = pltname
for k,v in pairs(terms) do
cfg.terms[k] =v
end
dest[key] = cfg
end
--
-- Collapse a solution or project object down to a canonical set of configuration settings,
-- keyed by configuration block/platform pairs, and taking into account the current
-- environment settings.
--
-- @param obj
-- The solution or project to be collapsed.
-- @param basis
-- "Root" level settings, from the solution, which act as a starting point for
-- all of the collapsed settings built during this call.
-- @returns
-- The collapsed list of settings, keyed by configuration block/platform pair.
--
local function collapse(obj, basis)
local result = {}
basis = basis or {}
-- find the solution, which contains the configuration and platform lists
local sln = obj.solution or obj
-- build a set of configuration filter terms; only those configuration blocks
-- with a matching set of keywords will be included in the merged results
local terms = premake.getactiveterms()
-- build a project-level configuration.
merge(result, obj, basis, terms)--this adjusts terms
-- now build configurations for each build config/platform pair
for _, cfgname in ipairs(sln.configurations) do
local terms_local = {}
for k,v in pairs(terms)do terms_local[k]=v end
merge(result, obj, basis, terms_local, cfgname, "Native")--terms cam also be adjusted here
for _, pltname in ipairs(sln.platforms or {}) do
if pltname ~= "Native" then
merge(result, obj, basis,terms_local, cfgname, pltname)--terms also here
end
end
end
return result
end
--
-- Computes a unique objects directory for every configuration, using the
-- following choices:
-- [1] -> the objects directory as set in the project of config
-- [2] -> [1] + the platform name
-- [3] -> [2] + the configuration name
-- [4] -> [3] + the project name
--
local function builduniquedirs()
local num_variations = 4
-- Start by listing out each possible object directory for each configuration.
-- Keep a count of how many times each path gets used across the session.
local cfg_dirs = {}
local hit_counts = {}
for sln in premake.solution.each() do
for _, prj in ipairs(sln.projects) do
for _, cfg in pairs(prj.__configs) do
local dirs = { }
dirs[1] = path.getabsolute(path.join(cfg.location, cfg.objdir or cfg.project.objdir or "obj"))
dirs[2] = path.join(dirs[1], iif(cfg.platform == "Native", "", cfg.platform))
dirs[3] = path.join(dirs[2], cfg.name)
dirs[4] = path.join(dirs[3], cfg.project.name)
cfg_dirs[cfg] = dirs
-- configurations other than the root should bias toward a more
-- description path, including the platform or config name
local start = iif(cfg.name, 2, 1)
for v = start, num_variations do
local d = dirs[v]
hit_counts[d] = (hit_counts[d] or 0) + 1
end
end
end
end
-- Now assign an object directory to each configuration, skipping those
-- that are in use somewhere else in the session
for sln in premake.solution.each() do
for _, prj in ipairs(sln.projects) do
for _, cfg in pairs(prj.__configs) do
local dir
local start = iif(cfg.name, 2, 1)
for v = start, iif(cfg.flags.SingleOutputDir==true,num_variations-1,num_variations) do
dir = cfg_dirs[cfg][v]
if hit_counts[dir] == 1 then break end
end
cfg.objectsdir = path.getrelative(cfg.location, dir)
end
end
end
end
--
-- Pre-computes the build and link targets for a configuration.
--
local function buildtargets()
for sln in premake.solution.each() do
for _, prj in ipairs(sln.projects) do
for _, cfg in pairs(prj.__configs) do
-- determine which conventions the target should follow for this config
local pathstyle = premake.getpathstyle(cfg)
local namestyle = premake.getnamestyle(cfg)
-- build the targets
cfg.buildtarget = premake.gettarget(cfg, "build", pathstyle, namestyle, cfg.system)
cfg.linktarget = premake.gettarget(cfg, "link", pathstyle, namestyle, cfg.system)
if pathstyle == "windows" then
cfg.objectsdir = path.translate(cfg.objectsdir, "\\")
end
end
end
end
end
local function getCfgKind(cfg)
if(cfg.kind) then
return cfg.kind;
end
if(cfg.project.__configs[""] and cfg.project.__configs[""].kind) then
return cfg.project.__configs[""].kind;
end
return nil
end
local function getprojrec(dstArray, foundList, cfg, cfgname, searchField, bLinkage)
if(not cfg) then return end
local foundUsePrjs = {};
for _, useName in ipairs(cfg[searchField]) do
local testName = useName:lower();
if((not foundList[testName])) then
local theProj = nil;
local theUseProj = nil;
for _, prj in ipairs(cfg.project.solution.projects) do
if (prj.name:lower() == testName) then
if(prj.usage) then
theUseProj = prj;
else
theProj = prj;
end
end
end
--Must connect to a usage project.
if(theUseProj) then
foundList[testName] = true;
local prjEntry = {
name = testName,
proj = theProj,
usageProj = theUseProj,
bLinkageOnly = bLinkage,
};
dstArray[testName] = prjEntry;
table.insert(foundUsePrjs, theUseProj);
end
end
end
for _, usePrj in ipairs(foundUsePrjs) do
--Links can only recurse through static libraries.
if((searchField ~= "links") or
(getCfgKind(usePrj.__configs[cfgname]) == "StaticLib")) then
getprojrec(dstArray, foundList, usePrj.__configs[cfgname],
cfgname, searchField, bLinkage);
end
end
end
--
-- This function will recursively get all projects that the given configuration has in its "uses"
-- field. The return values are a list of tables. Each table in that list contains the following:
-- name = The lowercase name of the project.
-- proj = The project. Can be nil if it is usage-only.
-- usageProj = The usage project. Can't be nil, as using a project that has no
-- usage project is not put into the list.
-- bLinkageOnly = If this is true, then only the linkage information should be copied.
-- The recursion will only look at the "uses" field on *usage* projects.
-- This function will also add projects to the list that are mentioned in the "links"
-- field of usage projects. These will only copy linker information, but they will recurse.
-- through other "links" fields.
--
local function getprojectsconnections(cfg, cfgname)
local dstArray = {};
local foundList = {};
foundList[cfg.project.name:lower()] = true;
--First, follow the uses recursively.
getprojrec(dstArray, foundList, cfg, cfgname, "uses", false);
--Next, go through all of the usage projects and recursively get their links.
--But only if they're not already there. Get the links as linkage-only.
local linkArray = {};
for prjName, prjEntry in pairs(dstArray) do
getprojrec(linkArray, foundList, prjEntry.usageProj.__configs[cfgname], cfgname,
"links", true);
end
--Copy from linkArray into dstArray.
for prjName, prjEntry in pairs(linkArray) do
dstArray[prjName] = prjEntry;
end
return dstArray;
end
local function isnameofproj(cfg, strName)
local sln = cfg.project.solution;
local strTest = strName:lower();
for prjIx, prj in ipairs(sln.projects) do
if (prj.name:lower() == strTest) then
return true;
end
end
return false;
end
--
-- Copies the field from dstCfg to srcCfg.
--
local function copydependentfield(srcCfg, dstCfg, strSrcField)
local srcField = premake.fields[strSrcField];
local strDstField = strSrcField;
if type(srcCfg[strSrcField]) == "table" then
--handle paths.
if (srcField.kind == "dirlist" or srcField.kind == "filelist") and
(not keeprelative[strSrcField]) then
for i,p in ipairs(srcCfg[strSrcField]) do
table.insert(dstCfg[strDstField],
path.rebase(p, srcCfg.project.location, dstCfg.project.location))
end
else
if(strSrcField == "links") then
for i,p in ipairs(srcCfg[strSrcField]) do
if(not isnameofproj(dstCfg, p)) then
table.insert(dstCfg[strDstField], p)
else
printf("Failed to copy '%s' from proj '%s'.",
p, srcCfg.project.name);
end
end
else
for i,p in ipairs(srcCfg[strSrcField]) do
table.insert(dstCfg[strDstField], p)
end
end
end
else
if(srcField.kind == "path" and (not keeprelative[strSrcField])) then
dstCfg[strDstField] = path.rebase(srcCfg[strSrcField],
prj.location, dstCfg.project.location);
else
dstCfg[strDstField] = srcCfg[strSrcField];
end
end
end
--
-- This function will take the list of project entries and apply their usage project data
-- to the given configuration. It will copy compiling information for the projects that are
-- not listed as linkage-only. It will copy the linking information for projects only if
-- the source project is not a static library. It won't copy linking information
-- if the project is in this solution; instead it will add that project to the configuration's
-- links field, expecting that Premake will handle the rest.
--
local function copyusagedata(cfg, cfgname, linkToProjs)
local myPrj = cfg.project;
local bIsStaticLib = (getCfgKind(cfg) == "StaticLib");
for prjName, prjEntry in pairs(linkToProjs) do
local srcPrj = prjEntry.usageProj;
local srcCfg = srcPrj.__configs[cfgname];
for name, field in pairs(premake.fields) do
if(srcCfg[name]) then
if(field.usagecopy) then
if(not prjEntry.bLinkageOnly) then
copydependentfield(srcCfg, cfg, name)
end
elseif(field.linkagecopy) then
--Copy the linkage data if we're building a non-static thing
--and this is a pure usage project. If it's not pure-usage, then
--we will simply put the project's name in the links field later.
if((not bIsStaticLib) and (not prjEntry.proj)) then
copydependentfield(srcCfg, cfg, name)
end
end
end
end
if((not bIsStaticLib) and prjEntry.proj) then
table.insert(cfg.links, prjEntry.proj.name);
end
end
end
--
-- Main function, controls the process of flattening the configurations.
--
function premake.bake.buildconfigs()
-- convert project path fields to be relative to project location
for sln in premake.solution.each() do
for _, prj in ipairs(sln.projects) do
prj.location = prj.location or sln.location or prj.basedir
adjustpaths(prj.location, prj)
for _, blk in ipairs(prj.blocks) do
adjustpaths(prj.location, blk)
end
end
sln.location = sln.location or sln.basedir
end
-- collapse configuration blocks, so that there is only one block per build
-- configuration/platform pair, filtered to the current operating environment
for sln in premake.solution.each() do
local basis = collapse(sln)
for _, prj in ipairs(sln.projects) do
prj.__configs = collapse(prj, basis)
for _, cfg in pairs(prj.__configs) do
bake.postprocess(prj, cfg)
end
end
end
-- This loop finds the projects that a configuration is connected to
-- via its "uses" field. It will then copy any usage project information from that
-- usage project to the configuration in question.
for sln in premake.solution.each() do
for prjIx, prj in ipairs(sln.projects) do
if(not prj.usage) then
for cfgname, cfg in pairs(prj.__configs) do
local usesPrjs = getprojectsconnections(cfg, cfgname);
copyusagedata(cfg, cfgname, usesPrjs)
end
end
end
end
-- Remove all usage projects.
for sln in premake.solution.each() do
local removeList = {};
for index, prj in ipairs(sln.projects) do
if(prj.usage) then
table.insert(removeList, 1, index); --Add in reverse order.
end
end
for _, index in ipairs(removeList) do
table.remove(sln.projects, index);
end
end
-- assign unique object directories to each configuration
builduniquedirs()
-- walk it again and build the targets and unique directories
buildtargets(cfg)
end
--
-- Post-process a project configuration, applying path fix-ups and other adjustments
-- to the "raw" setting data pulled from the project script.
--
-- @param prj
-- The project object which contains the configuration.
-- @param cfg
-- The configuration object to be fixed up.
--
function premake.bake.postprocess(prj, cfg)
cfg.project = prj
cfg.shortname = premake.getconfigname(cfg.name, cfg.platform, true)
cfg.longname = premake.getconfigname(cfg.name, cfg.platform)
-- set the project location, if not already set
cfg.location = cfg.location or cfg.basedir
-- figure out the target system
local platform = premake.platforms[cfg.platform]
if platform.iscrosscompiler then
cfg.system = cfg.platform
else
cfg.system = os.get()
end
-- adjust the kind as required by the target system
if cfg.kind == "SharedLib" and platform.nosharedlibs then
cfg.kind = "StaticLib"
end
-- remove excluded files from the file list
local removefiles = cfg.removefiles
if _ACTION == 'gmake' then
removefiles = table.join(removefiles, cfg.excludes)
end
local files = {}
for _, fname in ipairs(cfg.files) do
if not table.icontains(removefiles, fname) then
table.insert(files, fname)
end
end
cfg.files = files
-- fixup the data
for name, field in pairs(premake.fields) do
-- re-key flag fields for faster lookups
if field.isflags then
local values = cfg[name]
for _, flag in ipairs(values) do values[flag] = true end
end
end
-- build configuration objects for all files
-- TODO: can I build this as a tree instead, and avoid the extra
-- step of building it later?
cfg.__fileconfigs = { }
for _, fname in ipairs(cfg.files) do
local fcfg = {}
-- Only do this if the script has called enablefilelevelconfig()
if premake._filelevelconfig then
cfg.terms.required = fname:lower()
for _, blk in ipairs(cfg.project.blocks) do
-- BK - `iskeywordsmatch` call is super slow for large projects...
if (premake.iskeywordsmatch(blk.keywords, cfg.terms)) then
mergeobject(fcfg, blk)
end
end
end
-- add indexed by name and integer
-- TODO: when everything is converted to trees I won't need
-- to index by name any longer
fcfg.name = fname
cfg.__fileconfigs[fname] = fcfg
table.insert(cfg.__fileconfigs, fcfg)
end
end
| gpl-2.0 |
karai17/Peep | LoveFrames/objects/internal/tooltip.lua | 3 | 9176 | --[[------------------------------------------------
-- Love Frames - A GUI library for LOVE --
-- Copyright (c) 2012-2014 Kenny Shields --
--]]------------------------------------------------
-- tooltip clas
local newobject = loveframes.NewObject("tooltip", "loveframes_object_tooltip", true)
--[[---------------------------------------------------------
- func: initialize()
- desc: initializes the object
--]]---------------------------------------------------------
function newobject:initialize(object, text)
self.type = "tooltip"
self.parent = loveframes.base
self.object = object or nil
self.width = 0
self.height = 0
self.padding = 5
self.xoffset = 10
self.yoffset = -10
self.internal = true
self.show = false
self.followcursor = true
self.followobject = false
self.alwaysupdate = true
self.internals = {}
-- create the object's text
local textobject = loveframes.Create("text")
textobject:Remove()
textobject.parent = self
textobject:SetText(text or "")
textobject:SetPos(0, 0)
table.insert(self.internals, textobject)
-- apply template properties to the object
loveframes.templates.ApplyToObject(self)
table.insert(loveframes.base.internals, self)
end
--[[---------------------------------------------------------
- func: update(deltatime)
- desc: updates the object
--]]---------------------------------------------------------
function newobject:update(dt)
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
local alwaysupdate = self.alwaysupdate
if not visible then
if not alwaysupdate then
return
end
end
local internals = self.internals
local textobject = internals[1]
local padding = self.padding
local object = self.object
local draworder = self.draworder
local update = self.Update
self.width = textobject.width + padding * 2
self.height = textobject.height + padding * 2
if object then
if object == loveframes.base then
self:Remove()
return
end
local ovisible = object.visible
local ohover = object.hover
local ostate = object.state
if ostate ~= state then
self.show = false
self.visible = false
return
end
self.show = ohover
self.visible = ovisible
if ohover and ovisible then
local top = self:IsTopInternal()
local followcursor = self.followcursor
local followobject = self.followobject
local xoffset = self.xoffset
local yoffset = self.yoffset
if followcursor then
local height = self.height
local mx, my = love.mouse.getPosition()
self.x = mx + xoffset
self.y = my - height + yoffset
elseif followobject then
local ox = object.x
local oy = object.y
self.x = ox + xoffset
self.y = oy + yoffset
end
if not top then
self:MoveToTop()
end
textobject:SetPos(padding, padding)
end
end
textobject:SetVisible(self.show)
textobject:SetState(selfstate)
textobject:update(dt)
if update then
update(self, dt)
end
end
--[[---------------------------------------------------------
- func: draw()
- desc: draws the object
--]]---------------------------------------------------------
function newobject:draw()
local state = loveframes.state
local selfstate = self.state
if state ~= selfstate then
return
end
local visible = self.visible
if not visible then
return
end
local internals = self.internals
local textobject = internals[1]
local show = self.show
local skins = loveframes.skins.available
local skinindex = loveframes.config["ACTIVESKIN"]
local defaultskin = loveframes.config["DEFAULTSKIN"]
local selfskin = self.skin
local skin = skins[selfskin] or skins[skinindex]
local drawfunc = skin.DrawToolTip or skins[defaultskin].DrawToolTip
local draw = self.Draw
local drawcount = loveframes.drawcount
-- set the object's draw order
self:SetDrawOrder()
if show then
if draw then
draw(self)
else
drawfunc(self)
end
textobject:draw()
end
end
--[[---------------------------------------------------------
- func: SetFollowCursor(bool)
- desc: sets whether or not the tooltip should follow the
cursor
--]]---------------------------------------------------------
function newobject:SetFollowCursor(bool)
self.followcursor = bool
end
--[[---------------------------------------------------------
- func: GetFollowCursor()
- desc: gets whether or not the tooltip should follow the
cursor
--]]---------------------------------------------------------
function newobject:GetFollowCursor()
return self.followcursor
end
--[[---------------------------------------------------------
- func: SetObject(object)
- desc: sets the tooltip's object
--]]---------------------------------------------------------
function newobject:SetObject(object)
self.object = object
self.x = object.x
self.y = object.y
end
--[[---------------------------------------------------------
- func: GetObject()
- desc: gets the tooltip's object
--]]---------------------------------------------------------
function newobject:GetObject()
return self.object
end
--[[---------------------------------------------------------
- func: SetText(text)
- desc: sets the tooltip's text
--]]---------------------------------------------------------
function newobject:SetText(text)
local internals = self.internals
local textobject = internals[1]
textobject:SetText(text)
end
--[[---------------------------------------------------------
- func: GetText()
- desc: gets the tooltip's text
--]]---------------------------------------------------------
function newobject:GetText()
local internals = self.internals
local textobject = internals[1]
local text = textobject:GetText()
return text
end
--[[---------------------------------------------------------
- func: SetTextMaxWidth(text)
- desc: sets the tooltip's text max width
--]]---------------------------------------------------------
function newobject:SetTextMaxWidth(width)
local internals = self.internals
local textobject = internals[1]
textobject:SetMaxWidth(width)
end
--[[---------------------------------------------------------
- func: SetOffsetX(xoffset)
- desc: sets the tooltip's x offset
--]]---------------------------------------------------------
function newobject:SetOffsetX(xoffset)
self.xoffset = xoffset
end
--[[---------------------------------------------------------
- func: GetOffsetX()
- desc: gets the tooltip's x offset
--]]---------------------------------------------------------
function newobject:GetOffsetX()
return self.xoffset
end
--[[---------------------------------------------------------
- func: SetOffsetY(yoffset)
- desc: sets the tooltip's y offset
--]]---------------------------------------------------------
function newobject:SetOffsetY(yoffset)
self.yoffset = yoffset
end
--[[---------------------------------------------------------
- func: GetOffsetY()
- desc: gets the tooltip's y offset
--]]---------------------------------------------------------
function newobject:GetOffsetY()
return self.yoffset
end
--[[---------------------------------------------------------
- func: SetOffsets(xoffset, yoffset)
- desc: sets the tooltip's x and y offset
--]]---------------------------------------------------------
function newobject:SetOffsets(xoffset, yoffset)
self.xoffset = xoffset
self.yoffset = yoffset
end
--[[---------------------------------------------------------
- func: GetOffsets()
- desc: gets the tooltip's x and y offset
--]]---------------------------------------------------------
function newobject:GetOffsets()
return self.xoffset, self.yoffset
end
--[[---------------------------------------------------------
- func: SetPadding(padding)
- desc: sets the tooltip's padding
--]]---------------------------------------------------------
function newobject:SetPadding(padding)
self.padding = padding
end
--[[---------------------------------------------------------
- func: SetFont(font)
- desc: sets the tooltip's font
--]]---------------------------------------------------------
function newobject:SetFont(font)
local internals = self.internals
local textobject = internals[1]
textobject:SetFont(font)
end
--[[---------------------------------------------------------
- func: GetFont()
- desc: gets the tooltip's font
--]]---------------------------------------------------------
function newobject:GetFont()
local internals = self.internals
local textobject = internals[1]
return textobject:GetFont()
end
--[[---------------------------------------------------------
- func: SetFollowObject(bool)
- desc: sets whether or not the tooltip should follow
its assigned object
--]]---------------------------------------------------------
function newobject:SetFollowObject(bool)
self.followobject = bool
end
--[[---------------------------------------------------------
- func: GetFollowObject()
- desc: gets whether or not the tooltip should follow
its assigned object
--]]---------------------------------------------------------
function newobject:GetFollowObject()
return self.followobject
end | mit |
sixin-zh/mpiT | BiCNN/optim-adadelta.lua | 1 | 1427 | -- Adadelta
-- Author: Minwei Feng (mfeng@us.ibm.com)
require 'optim'
function optim.adadelta(opfunc, w, config, state)
local config = config or {}
local state = state or config
local rho = config.rho or 0.9
local epsilon = config.epsilon or 1e-6
local mode = config.mode or 'global' -- global or local
local pc = config.pclient or nil
local su = config.su or 0 -- sync updates (grad and param)
state.pversion = state.pversion or 0
state.dusync = state.dusync or 0
local fx,dfdx = opfunc(w)
if pc and su>1 then
-- accumulate grad
if not config.accumulated then -- need one copy to accumulate
config.accumulated = torch.Tensor():typeAs(dfdx):resizeAs(dfdx):fill(0)
pc:reset(w,config.accumulated)
end
if mode == 'global' then
config.accumulated:add(dfdx)
if state.pversion%su==0 then
pc:async_send_grad()
pc:async_recv_param()
local synctime = sys.clock()
pc:wait()
state.dusync = state.dusync + sys.clock()-synctime
config.accumulated:fill(0)
else
--do nothing here
end
end
elseif pc and su==1 then
if mode == 'global' then
pc:async_send_grad()
pc:async_recv_param()
local synctime = sys.clock()
pc:wait()
state.dusync = state.dusync + sys.clock()-synctime
end
else
assert(false)
end
state.pversion = state.pversion + 1
return w,{fx}
end
| apache-2.0 |
n0xus/darkstar | scripts/zones/Southern_San_dOria/npcs/Raminel.lua | 19 | 4714 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Raminel
-- Involved in Quests: Riding on the Clouds
-- @zone 230
-- @pos -56 2 -21
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/pathfind");
local path = {
-138.436340, -2.000000, 16.227097,
-137.395432, -2.000000, 15.831898,
-136.317108, -2.000000, 15.728185,
-134.824036, -2.000000, 15.816396,
-108.897049, -2.000000, 16.508110,
-107.823288, -2.000000, 16.354126,
-106.804962, -2.000000, 15.973084,
-105.844963, -2.000000, 15.462379,
-104.922585, -2.000000, 14.885456,
-104.020050, -2.000000, 14.277813,
-103.138374, -2.000000, 13.640303,
-101.501289, -2.000000, 12.422975,
-77.636841, 2.000000, -5.771687,
-59.468536, 2.000000, -19.632719,
-58.541172, 2.000000, -20.197826,
-57.519985, 2.000000, -20.570829,
-56.474659, 2.000000, -20.872238,
-55.417450, 2.000000, -21.129019,
-54.351425, 2.000000, -21.365578,
-53.286743, 2.000000, -21.589529,
-23.770412, 2.000000, -27.508755,
-13.354427, 1.700000, -29.593290,
-14.421194, 1.700000, -29.379389, -- auction house
-43.848141, 2.000000, -23.492155,
-56.516224, 2.000000, -20.955723,
-57.555450, 2.000000, -20.638817,
-58.514832, 2.000000, -20.127840,
-59.426712, 2.000000, -19.534536,
-60.322998, 2.000000, -18.917839,
-61.203823, 2.000000, -18.279247,
-62.510002, 2.000000, -17.300892,
-86.411278, 2.000000, 0.921999,
-105.625214, -2.000000, 15.580724,
-106.582047, -2.000000, 16.089426,
-107.647263, -2.000000, 16.304668,
-108.732132, -2.000000, 16.383970,
-109.819397, -2.000000, 16.423687,
-110.907364, -2.000000, 16.429226,
-111.995232, -2.000000, 16.411282,
-140.205811, -2.000000, 15.668728, -- package Lusiane
-139.296539, -2.000000, 16.786556
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
-- test fromStart
local start = pathfind.fromStart(path, 2);
local startFirst = pathfind.get(path, 3);
if (start[1] ~= startFirst[1] or start[2] ~= startFirst[2] or start[3] ~= startFirst[3]) then
printf("[Error] start path is not right %f %f %f actually = %f %f %f", startFirst[1], startFirst[2], startFirst[3], start[1], start[2], start[3]);
end
-- test fromEnd
-- local endPt = pathfind.fromEnd(path, 2);
-- local endFirst = pathfind.get(path, 37);
-- if (endPt[1] ~= endFirst[1] or endPt[2] ~= endFirst[2] or endPt[3] ~= endFirst[3]) then
-- printf("[Error] endPt path is not right %f %f %f actually = %f %f %f", endFirst[1], endFirst[2], endFirst[3], endPt[1], endPt[2], endPt[3]);
-- end
end;
function onPath(npc)
if (npc:atPoint(pathfind.get(path, 23))) then
local arp = GetNPCByID(17719409);
npc:lookAt(arp:getPos());
npc:wait();
elseif (npc:atPoint(pathfind.get(path, -1))) then
local lus = GetNPCByID(17719350);
-- give package to Lusiane
lus:showText(npc, RAMINEL_DELIVERY);
npc:showText(lus, LUSIANE_THANK);
-- wait default duration 4 seconds
-- then continue path
npc:wait();
elseif (npc:atPoint(pathfind.last(path))) then
local lus = GetNPCByID(17719350);
-- when I walk away stop looking at me
lus:clearTargID();
end
-- go back and forth the set path
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer
player:messageSpecial(FLYER_REFUSED);
end
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 1) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_1",0);
player:tradeComplete();
player:addKeyItem(SCOWLING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0266);
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
npc:wait(0);
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Metalworks/npcs/Lorena.lua | 17 | 2528 | -----------------------------------
-- Area: Metalworks
-- NPC: Lorena
-- Type: Blacksmithing Guildworker's Union Representative
-- @zone: 237
-- @pos -104.990 1 30.995
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
require("scripts/zones/Metalworks/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/crafting");
local keyitems = {
[0] = {
id = METAL_PURIFICATION,
rank = 3,
cost = 40000
},
[1] = {
id = METAL_ENSORCELLMENT,
rank = 3,
cost = 40000
},
[2] = {
id = CHAINWORK,
rank = 3,
cost = 10000
},
[3] = {
id = SHEETING,
rank = 3,
cost = 10000
},
[4] = {
id = WAY_OF_THE_BLACKSMITH,
rank = 9,
cost = 20000
}
};
local items = {
[2] = {
id = 15445,
rank = 3,
cost = 10000
},
[3] = {
id = 14831,
rank = 5,
cost = 70000
},
[4] = {
id = 14393,
rank = 7,
cost = 100000
},
[5] = {
id = 153,
rank = 9,
cost = 150000
},
[6] = {
id = 334,
rank = 9,
cost = 200000
},
[7] = {
id = 15820,
rank = 6,
cost = 80000
},
[8] = {
id = 3661,
rank = 7,
cost = 50000
},
[9] = {
id = 3324,
rank = 9,
cost = 15000
}
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
unionRepresentativeTrade(player, npc, trade, 0x321, 2);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
unionRepresentativeTrigger(player, 2, 0x320, "guild_smithing", keyitems);
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 == 0x320) then
unionRepresentativeTriggerFinish(player, option, target, 2, "guild_smithing", keyitems, items);
elseif (csid == 0x321) then
player:messageSpecial(GP_OBTAINED, option);
end
end;
| gpl-3.0 |
sixin-zh/mpiT | asyncsgd/testreduceall.lua | 1 | 1945 | -- mpirun -n 2 luajit testreduceall.lua
local ssize = 3*4096*4096
local usecuda = false
require 'mpiT'
dofile('init.lua')
mpiT.Init()
local world = mpiT.COMM_WORLD
local rank = mpiT.get_rank(world)
local size = mpiT.get_size(world)
assert((size>0) and (size%2==0))
local conf = {}
conf.rank = rank
conf.world = world
conf.sranks = {}
conf.cranks = {}
for i = 0,size-1 do
if i < size/2 then
table.insert(conf.sranks,i) --as server
else
table.insert(conf.cranks,i) --as client
end
end
if rank < size/2 then
print('rank ' .. rank .. ' is server.')
-- require 'cutorch' -- in case usecuda==true and your mpirun does not stop, try uncomment this out.
torch.setdefaulttensortype('torch.FloatTensor')
print(rank,'use cpu')
-- server
local ps = pServer(conf)
ps:start()
else
print('rank ' .. rank .. ' is client.')
-- use gpu?
if usecuda then
require 'cutorch'
torch.setdefaulttensortype('torch.CudaTensor')
local gpus = cutorch.getDeviceCount()
local gpu =(rank%(size/2)) % gpus + 1
cutorch.setDevice(gpu)
print(rank,'use gpu',gpu)
else
torch.setdefaulttensortype('torch.FloatTensor')
print(rank,'use cpu')
end
-- client
local theta = torch.Tensor(ssize)
local grad = torch.Tensor(ssize)
local pc = pClient(conf)
pc:start(theta,grad)
local begin = os.time()
for t=1,3 do
print('rank' .. rank .. 'pingpong')
pc:async_recv_param()
pc:async_send_grad()
pc:wait()
end
local now = os.time()
print('rank ' .. rank .. ' bandwidth(bi-direction) is ' .. (2*ssize*4/(now-begin)/1024/1024) .. ' MBytes/sec')
pc:stop()
print('pc stopped')
end
torch.manualSeed(123)
a = torch.FloatTensor(3,2):uniform()
b = torch.FloatTensor(3,2)
print('a', a)
mpiT.Allreduce(a:storage(), b:storage(), 6, mpiT.FLOAT, mpiT.SUM, mpiT.COMM_WORLD)
print('b after a', b)
mpiT.Finalize()
| apache-2.0 |
privatesource/Vira_max | plugins/active_user.lua | 6 | 11802 | local function checktodaygr(cb_extra, success, result)
local hash = ''
local thash=''
for k,user in pairs(result.members) do
thash = 'today:'..user.peer_id
if redis:get(thash) then
if redis:get(thash) < os.date("%x",os.time() + 16200) then
hash = 'utmsgst:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgph:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgtex:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgoth:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
redis:set(thash,os.date("%x",os.time() + 16200))
end
else
redis:set(thash,os.date("%x",os.time() + 16200))
end
end
end
local function checktodaych(cb_extra, success, result)
local hash = ''
local thash=''
for k,user in pairs(result) do
thash = 'today:'..user.peer_id
if redis:get(thash) then
if redis:get(thash) < os.date("%x",os.time() + 16200) then
hash = 'utmsgst:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgph:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgtex:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
hash = 'utmsgoth:'..user.peer_id..':'..cb_extra
redis:set(hash,0)
redis:set(thash,os.date("%x",os.time() + 16200))
end
else
redis:set(thash,os.date("%x",os.time() + 16200))
end
end
end
local function cron()
for v,chat in pairs(_chats.chats) do
channel_get_users('channel#id'..chat[1], checktodaych, chat[1])
chat_info('chat#id'..chat[1], checktodaygr, chat[1])
end
end
local function pre_process(msg)
if not msg.service then
if msg.media then
if msg.media.caption == 'sticker.webp' then
local hash = 'utmsgst:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
elseif msg.media.type == 'photo' then
local hash = 'utmsgph:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
end
else
if msg.text then
local hash = 'utmsgtex:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
else
local hash = 'utmsgoth:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
end
end
end
return msg
end
local function getactivegr(cb_extra, success, result)
local maxst = {}
local maxph = {}
local maxtex = {}
local maxoth = {}
local maxname = {}
local maxuser = {}
local maxid = {}
local maxstat = {}
maxstat[1] = 0
maxstat[2] = 0
maxstat[3] = 0
maxname[1] = ''
maxname[2] = ''
maxname[3] = ''
maxuser[1] = ''
maxuser[2] = ''
maxuser[3] = ''
for k,user in pairs(result.members) do
local shash = 'utmsgst:'..user.peer_id..':'..cb_extra
local phash = 'utmsgph:'..user.peer_id..':'..cb_extra
local thash = 'utmsgtex:'..user.peer_id..':'..cb_extra
local ohash = 'utmsgoth:'..user.peer_id..':'..cb_extra
if not redis:get(shash) then
redis:set(shash,0)
end
if not redis:get(phash) then
redis:set(phash,0)
end
if not redis:get(thash) then
redis:set(thash,0)
end
if not redis:get(ohash) then
redis:set(ohash,0)
end
if tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[1] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = maxname[1]
maxuser[2] = maxuser[1]
maxstat[2] = maxstat[1]
maxid[2] = maxid[1]
maxname[1] = user.print_name
maxuser[1] = user.username
maxid[1] = user.peer_id
maxstat[1] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[2] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = user.print_name
maxuser[2] = user.username
maxid[2] = user.peer_id
maxstat[2] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[3] then
maxname[3] = user.print_name
maxuser[3] = user.username
maxid[3] = user.peer_id
maxstat[3] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
end
end
maxst[1] = redis:get('utmsgst:'..maxid[1]..':'..cb_extra)
maxph[1] = redis:get('utmsgph:'..maxid[1]..':'..cb_extra)
maxtex[1] = redis:get('utmsgtex:'..maxid[1]..':'..cb_extra)
maxoth[1] = redis:get('utmsgoth:'..maxid[1]..':'..cb_extra)
if maxid[2] then
maxst[2] = redis:get('utmsgst:'..maxid[2]..':'..cb_extra)
maxph[2] = redis:get('utmsgph:'..maxid[2]..':'..cb_extra)
maxtex[2] = redis:get('utmsgtex:'..maxid[2]..':'..cb_extra)
maxoth[2] = redis:get('utmsgoth:'..maxid[2]..':'..cb_extra)
end
if maxid[3] then
maxst[3] = redis:get('utmsgst:'..maxid[3]..':'..cb_extra)
maxph[3] = redis:get('utmsgph:'..maxid[3]..':'..cb_extra)
maxtex[3] = redis:get('utmsgtex:'..maxid[3]..':'..cb_extra)
maxoth[3] = redis:get('utmsgoth:'..maxid[3]..':'..cb_extra)
end
if not maxuser[1] or maxuser[1] == '' then
maxuser[1] = 'ندارد'
else
maxuser[1] = '@'..maxuser[1]
end
if not maxuser[2] or maxuser[2] == '' then
maxuser[2] = 'ندارد'
else
maxuser[2] = '@'..maxuser[2]
end
if not maxuser[3] or maxuser[3] == '' then
maxuser[3] = 'ندارد'
else
maxuser[3] = '@'..maxuser[3]
end
local text = '♨️فعالان امروز گروه\n\n1⃣ '..maxname[1]..'〖'..maxuser[1]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[1] + maxph[1] + maxst[1] + maxoth[1]..'\n\n👾استیکر: '..maxst[1]..'\n\n📷تصویر: '..maxph[1]..'\n\n📃 متن: '..maxtex[1]..'\n\n📦 سایر: '..maxoth[1]
if maxid[2] then
if not maxid[3] then
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]
else
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]..'\n\n 3⃣ '..maxname[3]..' 〖'..maxuser[3]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[3] + maxph[3] + maxst[3] + maxoth[3]..'\n\n👾استیکر: '..maxst[3]..'\n\n📷تصویر: '..maxph[3]..'\n\n📃 متن: '..maxtex[3]..'\n\n📦 سایر: '..maxoth[3]
end
end
send_msg('chat#id'..cb_extra, text, ok_cb, true)
end
local function getactivech(cb_extra, success, result)
local maxst = {}
local maxph = {}
local maxtex = {}
local maxoth = {}
local maxname = {}
local maxuser = {}
local maxid = {}
local maxstat = {}
maxstat[1] = 0
maxstat[2] = 0
maxstat[3] = 0
maxname[1] = ''
maxname[2] = ''
maxname[3] = ''
maxuser[1] = ''
maxuser[2] = ''
maxuser[3] = ''
for k,user in pairs(result) do
local shash = 'utmsgst:'..user.peer_id..':'..cb_extra
local phash = 'utmsgph:'..user.peer_id..':'..cb_extra
local thash = 'utmsgtex:'..user.peer_id..':'..cb_extra
local ohash = 'utmsgoth:'..user.peer_id..':'..cb_extra
if not redis:get(shash) then
redis:set(shash,0)
end
if not redis:get(phash) then
redis:set(phash,0)
end
if not redis:get(thash) then
redis:set(thash,0)
end
if not redis:get(ohash) then
redis:set(ohash,0)
end
if tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[1] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = maxname[1]
maxuser[2] = maxuser[1]
maxstat[2] = maxstat[1]
maxid[2] = maxid[1]
maxname[1] = user.print_name
maxuser[1] = user.username
maxid[1] = user.peer_id
maxstat[1] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[2] then
maxname[3] = maxname[2]
maxuser[3] = maxuser[2]
maxstat[3] = maxstat[2]
maxid[3] = maxid[2]
maxname[2] = user.print_name
maxuser[2] = user.username
maxid[2] = user.peer_id
maxstat[2] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[3] then
maxname[3] = user.print_name
maxuser[3] = user.username
maxid[3] = user.peer_id
maxstat[3] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash))
end
end
maxst[1] = redis:get('utmsgst:'..maxid[1]..':'..cb_extra)
maxph[1] = redis:get('utmsgph:'..maxid[1]..':'..cb_extra)
maxtex[1] = redis:get('utmsgtex:'..maxid[1]..':'..cb_extra)
maxoth[1] = redis:get('utmsgoth:'..maxid[1]..':'..cb_extra)
if maxid[2] then
maxst[2] = redis:get('utmsgst:'..maxid[2]..':'..cb_extra)
maxph[2] = redis:get('utmsgph:'..maxid[2]..':'..cb_extra)
maxtex[2] = redis:get('utmsgtex:'..maxid[2]..':'..cb_extra)
maxoth[2] = redis:get('utmsgoth:'..maxid[2]..':'..cb_extra)
end
if maxid[3] then
maxst[3] = redis:get('utmsgst:'..maxid[3]..':'..cb_extra)
maxph[3] = redis:get('utmsgph:'..maxid[3]..':'..cb_extra)
maxtex[3] = redis:get('utmsgtex:'..maxid[3]..':'..cb_extra)
maxoth[3] = redis:get('utmsgoth:'..maxid[3]..':'..cb_extra)
end
if not maxuser[1] or maxuser[1] == '' then
maxuser[1] = 'ندارد'
else
maxuser[1] = '@'..maxuser[1]
end
if not maxuser[2] or maxuser[2] == '' then
maxuser[2] = 'ندارد'
else
maxuser[2] = '@'..maxuser[2]
end
if not maxuser[3] or maxuser[3] == '' then
maxuser[3] = 'ندارد'
else
maxuser[3] = '@'..maxuser[3]
end
local text = '♨️فعالان امروز گروه\n1⃣ '..maxname[1]..'〖'..maxuser[1]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[1] + maxph[1] + maxst[1] + maxoth[1]..'\n\n👾استیکر: '..maxst[1]..'\n\n📷تصویر: '..maxph[1]..'\n\n📃 متن: '..maxtex[1]..'\n\n📦 سایر: '..maxoth[1]
if maxid[2] then
if not maxid[3] then
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]
else
text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]..'\n\n 3⃣ '..maxname[3]..' 〖'..maxuser[3]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[3] + maxph[3] + maxst[3] + maxoth[3]..'\n\n👾استیکر: '..maxst[3]..'\n\n📷تصویر: '..maxph[3]..'\n\n📃 متن: '..maxtex[3]..'\n\n📦 سایر: '..maxoth[3]
end
end
send_msg('channel#id'..cb_extra, text, ok_cb, true)
end
local function run(msg,matches)
if msg.to.type == 'channel' then
channel_get_users('channel#id'..msg.to.id, getactivech, msg.to.id)
elseif msg.to.type == 'chat' then
chat_info('chat#id'..msg.to.id, getactivegr, msg.to.id)
end
end
return {
patterns = {
"^[!/#]msguser$",
},
pre_process = pre_process,
cron = cron,
run = run
}
| gpl-2.0 |
rekotc/game-engine-demo | Source/GCC4/3rdParty/luaplus51-all/Src/Modules/LuaMacro/macro/try.lua | 2 | 1238 | --- A try/except block.
-- This generates syntactical sugar around `pcal`l, and correctly
-- distinguishes between the try block finishing naturally and
-- explicitly using 'return' with no value. This is handled by
-- converting any no value `return` to `return nil`.
--
-- Apart from the usual creation of a closure, this uses a table
-- to capture all the results. Not likely to win speed contests,
-- but intended to be correct.
-- @module macro.try
local M = require 'macro'
local function pack (...)
local args = {...}
args.n = select('#',...)
return args
end
function pcall_(fn,...)
return pack(pcall(fn,...))
end
local function check_return_value(get,put)
local t,v = get:next()
put:space()
if t=='keyword' and (v=='end' or v=='else' or v=='until') then
put:keyword 'nil'
end
return put(t,v)
end
M.define('RR_',M.make_scoped_handler('return',check_return_value))
--- A try macro, paired with except.
--
-- try
-- maybe_something_bad()
-- except (e)
-- print(e)
-- end
-- @macro try
M.define 'try do local r_ = pcall_(function() RR_ '
M.define 'except(e) end); if r_[1] then if r_.n > 1 then return unpack(r_,2,r_.n) end else local e = r_[2] _END_END_ '
| lgpl-3.0 |
n0xus/darkstar | scripts/globals/items/bowl_of_mushroom_soup.lua | 35 | 1384 | -----------------------------------------
-- ID: 4419
-- Item: mushroom_soup
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Magic Points 20
-- Strength -1
-- Mind 2
-- MP Recovered While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4419);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 20);
target:addMod(MOD_STR, -1);
target:addMod(MOD_MND, 2);
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 20);
target:delMod(MOD_STR, -1);
target:delMod(MOD_MND, 2);
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
Arashbrsh/lifeiran | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"!qr [text]",
'!qr "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
hamed9898/maxbott | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"!qr [text]",
'!qr "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
ArmanIr/ProFbOt | plugins/qr.lua | 637 | 1730 | --[[
* qr plugin uses:
* - http://goqr.me/api/doc/create-qr-code/
* psykomantis
]]
local function get_hex(str)
local colors = {
red = "f00",
blue = "00f",
green = "0f0",
yellow = "ff0",
purple = "f0f",
white = "fff",
black = "000",
gray = "ccc"
}
for color, value in pairs(colors) do
if color == str then
return value
end
end
return str
end
local function qr(receiver, text, color, bgcolor)
local url = "http://api.qrserver.com/v1/create-qr-code/?"
.."size=600x600" --fixed size otherways it's low detailed
.."&data="..URL.escape(text:trim())
if color then
url = url.."&color="..get_hex(color)
end
if bgcolor then
url = url.."&bgcolor="..get_hex(bgcolor)
end
local response, code, headers = http.request(url)
if code ~= 200 then
return "Oops! Error: " .. code
end
if #response > 0 then
send_photo_from_url(receiver, url)
return
end
return "Oops! Something strange happened :("
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local text = matches[1]
local color
local back
if #matches > 1 then
text = matches[3]
color = matches[2]
back = matches[1]
end
return qr(receiver, text, color, back)
end
return {
description = {"qr code plugin for telegram, given a text it returns the qr code"},
usage = {
"!qr [text]",
'!qr "[background color]" "[data color]" [text]\n'
.."Color through text: red|green|blue|purple|black|white|gray\n"
.."Colors through hex notation: (\"a56729\" is brown)\n"
.."Or colors through decimals: (\"255-192-203\" is pink)"
},
patterns = {
'^!qr "(%w+)" "(%w+)" (.+)$',
"^!qr (.+)$"
},
run = run
} | gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/Qulight_ConfigUI/local/english.lua | 1 | 15650 | QulightL = { }
-- general
QulightL.option_general = "General"
QulightL.option_general_uiscale = "Auto UI Scale"
QulightL.option_general_multisample = "Multisample protection (clean 1px border)"
QulightL.option_general_customuiscale = "UI Scale (if auto-scale is disabled)"
QulightL.option_general_AutoRepair = "Auto Repair items"
QulightL.option_general_AutoGreed = "Auto Greed"
QulightL.option_general_AutoDisenchant = "Auto Disenchant"
QulightL.option_general_AutoAcceptInvite = "Enable Auto-Invite (Friends and Guildmates)"
QulightL.option_general_BlizzardsErrorFrameHiding = "Hide spamming error at the middle of your screen"
QulightL.option_general_topbottompanel = "Top/Bottom panels"
QulightL.option_general_autoinvite = "Autoinvite"
QulightL.option_general_centerpanel = "Left, Right DPS Info Stats"
-- Unitframes
QulightL.option_unitframes = "Unit Frames"
QulightL.option_unitframes_enable = "Enable Unit Frames"
QulightL.option_unitframes_HealFrames = "Raid Frames"
QulightL.option_unitframes_showIndicators = "Buffs Indicator"
QulightL.option_unitframes_showAuraWatch = "Show buffs in corners"
QulightL.option_unitframes_ShowParty = "Show party frames (shown as 5man raid)"
QulightL.option_unitframes_ShowRaid = "Show raid frames"
QulightL.option_unitframes_RaidShowSolo = "Show raid frames even when solo"
QulightL.option_unitframes_RaidShowAllGroups = "Show raid groups 6, 7 and 8 (more than 25man raid)"
QulightL.option_unitframes_enableDebuffHighlight = "Enable *dispelable* debuff highlight for raid frames"
QulightL.option_unitframes_showRaidDebuffs = "Enable important debuff icons to show on raid units"
QulightL.option_unitframes_showtot = "Show target of target frame"
QulightL.option_unitframes_showpet = "Show pet frame"
QulightL.option_unitframes_showfocus = "Show focus frame"
QulightL.option_unitframes_showfocustarget = "Show focus target frame"
QulightL.option_unitframes_showBossFrames = "Show boss frame"
QulightL.option_unitframes_TotemBars = "Show Totem Bars"
QulightL.option_unitframes_MTFrames = "Show main tank frames"
QulightL.option_unitframes_ArenaFrames = "Show arena frame"
QulightL.option_unitframes_Reputationbar = "Show Reputation bar"
QulightL.option_unitframes_Experiencebar = "Show Experience bar"
QulightL.option_unitframes_showPlayerAuras = "use a custom player buffs/debuffs frame instead of Blizzard's default"
QulightL.option_unitframes_ThreatBar = "Show Threat bar"
QulightL.option_unitframes_showPortrait = "Show Portrait on player and target frames"
QulightL.option_unitframes_showRunebar = "Show DK rune bar"
QulightL.option_unitframes_showHolybar = "Show Paladin HolyPower bar"
QulightL.option_unitframes_showEclipsebar = "Show druid Eclipse bar"
QulightL.option_unitframes_showShardbar = "Show Warlock SoulShard bar"
QulightL.option_unitframes_RCheckIcon = "Show raid check icon"
QulightL.option_unitframes_Castbars = "Use built-in castbars"
QulightL.option_unitframes_showLFDIcons = "Show dungeon role icons in raid/party"
QulightL.option_unitframes_HealthcolorClass = "Health color class"
QulightL.option_unitframes_Powercolor = "Power bar by power color oO"
QulightL.option_unitframes_showPartyFrames = "Show party frames"
QulightL.option_unitframes_bigcastbar = "Big castbar"
QulightL.option_unitframes_widthbigcastbar = "Width big castbar"
QulightL.option_unitframes_heightbigcastbar = "Height big castbar"
--raidframes
QulightL.option_raidframes = "Raid Frames"
-- Main
QulightL.option_raidframes_aggro_border = "Aggro border"
QulightL.option_raidframes_deficit_health = "Raid deficit health"
QulightL.option_raidframes_power = "Power bar"
QulightL.option_raidframes_vertical_health = "Vertical orientation of health"
QulightL.option_raidframes_alpha_health = "Alpha of healthbars when 100%hp"
QulightL.option_raidframes_show_range = "Show range opacity for raidframes"
QulightL.option_raidframes_range_alpha = "Alpha of unitframes when unit is out of range"
QulightL.option_raidframes_hp_value = "HP text"
QulightL.option_raidframes_width = "Width"
QulightL.option_raidframes_height = "Height"
QulightL.option_raidframes_show_party = "Show party frames"
QulightL.option_raidframes_show_raid = "Show raid frames"
QulightL.option_raidframes_solo_mode = "Show player frame always"
QulightL.option_raidframes_player_in_party = "Show player frame in party"
QulightL.option_raidframes_raid_groups = "Number of groups in raid"
QulightL.option_raidframes_raid_groups_vertical = "Vertical raid groups"
QulightL.option_raidframes_icons_role = "Role icon on frames"
QulightL.option_raidframes_icons_raid_mark = "Raid marks"
QulightL.option_raidframes_icons_ready_check = "Ready check icons"
QulightL.option_raidframes_icons_leader = "Leader icon, assistant icon, master loot icon on frames"
QulightL.option_raidframes_plugins_debuffhighlight_icon = "Debuff highlight texture + icon"
QulightL.option_raidframes_plugins_aura_watch = "Raid debuff icons"
QulightL.option_raidframes_plugins_aura_watch_timer = "Timer on raid debuff icons"
QulightL.option_raidframes_plugins_healcomm = "Show incoming heal on frame"
QulightL.option_raidframes_plugins_auto_resurrection = "Auto cast resurrection on middle click when the unit is dead (doesn't work with Clique enabled)"
QulightL.option_raidframes_own_color = "Set your color for health bars"
QulightL.option_raidframes_fontsize = "Font size"
QulightL.option_raidframes_fontsizeEdge = "Add Font size"
QulightL.option_raidframes_outline = "Font style"
QulightL.option_raidframes_bar_color_value = "Health bar color by current health remaining"
QulightL.option_raidframes_color_value = "Health/mana value is colored"
QulightL.option_raidframes_plugins_smooth_bar = "Smooth bar"
QulightL.option_raidframes_show_timer = "Show cooldown timer on aura icons"
QulightL.option_raidframes_show_spiral = "Spiral on aura icons"
QulightL.option_raidframes_debuff_color_type = "Color debuff by type"
--media
QulightL.option_media = "Media"
QulightL.option_media_font = "main font for Qulight UI"
QulightL.option_media_pxfont = "1 px font for Qulight UI"
QulightL.option_media_fontsize = "Size of font "
QulightL.option_media_bordercolor = "Border color"
QulightL.option_media_backdropcolor = "Background color"
QulightL.option_media_texture = "Texture"
QulightL.option_media_blank = "Background Texture"
--bags
QulightL.option_bags = "Bags"
QulightL.option_bags_Enable = "Enable all in one bag"
QulightL.option_bags_BagBars = "Enable bags panel"
--datatext
QulightL.option_datatext = "Data Text"
QulightL.option_datatext_Durability = "Durability position (0 for disabled)"
QulightL.option_datatext_System = "Latency and FPS position (0 for disabled)"
QulightL.option_datatext_Gold = "Gold position (0 for disabled)"
QulightL.option_datatext_Guild = "Guild position (0 for disabled)"
QulightL.option_datatext_Friends = "Friends position (0 for disabled)"
QulightL.option_datatext_Bags = "Bags position (0 for disabled)"
QulightL.option_datatext_Wowtime = "Time position (0 for disabled)"
QulightL.option_datatext_Togglemenu = "ToggleMenu"
QulightL.option_datatext_specswitcher = "Spec switcher"
QulightL.option_datatext_Time24 = "Enable 24h time"
QulightL.option_datatext_Localtime = "Use Local Time instead of Server Time"
QulightL.option_datatext_classcolor = "Class color data text"
QulightL.option_datatext_color = "If Class color data text false then choose color: "
QulightL.option_datatext_power = "Attack Power\Spell Power position (0 for disabled)"
QulightL.option_datatext_mastery = "Mastery position (0 for disabled)"
QulightL.option_datatext_haste = "Haste position (0 for disabled)"
QulightL.option_datatext_crit = "Crit position (0 for disabled)"
QulightL.option_datatext_dps = "DPS position (0 for disabled)"
QulightL.option_datatext_hps = "HPS position (0 for disabled)"
QulightL.option_bags_bankcolumns = "The number of cells in the row"
QulightL.option_bags_buttonsize = "Cell Size"
QulightL.option_bags_buttonspace = "Space Between Cells"
--loot
QulightL.option_loot = "Loot"
QulightL.option_loot_lootframe = "Enable loot window"
QulightL.option_loot_rolllootframe = "Enable item roll window"
QulightL.option_loot_position = "Позиция окна розыгрыша"
--misk
QulightL.option_enable = "Enable"
QulightL.option_armory_link = "Enable Armory Link (Then dont work Maintank and aimer)"
QulightL.option_addonmanager = "Addon Manager"
QulightL.option_togglemenu = "Toggle menu"
QulightL.option_togglemenu_buttonwidth = "Button width"
QulightL.option_togglemenu_buttonheight = "Button height"
QulightL.option_togglemenu_classcolor = "Classcolor border"
QulightL.option_classtimer = "Class Timer"
QulightL.option_cooldown = "Cooldown"
QulightL.option_skinframe = "Skinframe"
QulightL.option_filger = "Filger"
QulightL.option_Threatbar = "Threatbar"
--chat
QulightL.option_chat = "Chat"
QulightL.option_chat_enable = "Enable"
QulightL.option_chat_chatbar= "Enable chat bar"
QulightL.option_chat_chatframewidth = "Chat width"
QulightL.option_chat_chatframeheight = "Chat height"
QulightL.option_chat_editboxwidth = "Editbox width"
QulightL.option_chat_editboxheight = "Editbox height"
QulightL.option_chat_tabtextcolor = "Tab text color"
QulightL.option_chat_ChatFrame = "Позиция чата"
--buffs
QulightL.option_buffs = "Buffs/Debuffs"
QulightL.option_buffs_enable = "Enable"
QulightL.option_buffs_iconsize = "Buffs size"
QulightL.option_buffs_iconsizede = "Debuffs size"
QulightL.option_buffs_timefontsize = "Time font size"
QulightL.option_buffs_countfontsize = "Count font size"
QulightL.option_buffs_spacing = "Buffs spacing"
QulightL.option_buffs_debuffspacing = "Debuffs spacing"
QulightL.option_buffs_timeYoffset = "timeYoffset"
QulightL.option_buffs_BUFFS_PER_ROW = "Buffs per row"
QulightL.option_buffs_BUFFpos = "Buffs positions"
QulightL.option_buffs_DEBUFFpos = "Debuffs positions"
--addonskinning
QulightL.option_addonsskins = "Addon Skins"
QulightL.option_addonsskins_DBM = "DBM"
QulightL.option_addonsskins_PallyPower = "PallyPower"
QulightL.option_addonsskins_Skada = "Skada"
QulightL.option_addonsskins_Recount = "Recount"
QulightL.option_addonsskins_Omen = "Omen"
QulightL.option_addonsskins_KLE = "KLE"
QulightL.option_addonsskins_Quartz = "Quartz"
QulightL.option_addonsskins_Bigwigs = "Bigwigs"
QulightL.option_addonsskins_DXE = "DXE"
QulightL.option_addonsskins_Aurora = "Aurora"
QulightL.option_addonsskins_CoolLine = "CoolLine"
--nameplates
QulightL.option_nameplates = "Nameplates"
QulightL.option_nameplates_enable = "Enable"
QulightL.option_nameplates_showlevel = "Show level"
QulightL.option_nameplates_width = "Width"
QulightL.option_nameplates_showhealth = "Show health"
QulightL.option_nameplates_enhance_threat = "Show threat color"
QulightL.option_nameplates_combat = "Only in combat"
QulightL.option_nameplates_good_color = "Good color"
QulightL.option_nameplates_near_color = "Netral color"
QulightL.option_nameplates_bad_color = "Bad color"
QulightL.option_nameplates_goodtransitioncolor = "Good good color"
QulightL.option_nameplates_badtransitioncolor = "Bad bad color"
QulightL.option_nameplates_trackccauras = "Show CC debuffs"
QulightL.option_nameplates_height = "Height"
QulightL.option_nameplatesad_height = "Health #1"
QulightL.option_nameplatesad_width = "Width #1"
QulightL.option_nameplates_show_castbar_name = "Show castbar name"
QulightL.option_nameplates_health_value = "Show health text"
QulightL.option_nameplates_name_abbrev = "abbrev"
QulightL.option_nameplates_healer_icon = "Show healer icon"
QulightL.option_nameplates_class_icon = "Show class icon"
QulightL.option_nameplates_track_auras = "Show debuffs"
QulightL.option_nameplates_auras_size = "Debuffs size"
QulightL.option_Minimap = "Minimap"
QulightL.option_Minimapenable = "Enable"
QulightL.option_Minimapminimapsize = "Minimap size"
QulightL.option_Map = "Map"
QulightL.option_mapenable = "Enable"
QulightL.option_raidmarker = "Enable Mark Bar"
-- tooltip
QulightL.option_tooltip = "Tooltip"
QulightL.option_tooltip_enable = "Enable tooltip"
QulightL.option_tooltip_hidecombat = "Hide tooltip in combat"
QulightL.option_tooltip_hidebutton = "Hide tooltip on action bar buttons"
QulightL.option_tooltip_hideuf = "Hide tooltip on unit frames"
QulightL.option_tooltip_cursor = "Enable cursor tooltip"
QulightL.option_tooltip_itemlevel = "Enable Target Item level on tooltip"
QulightL.option_tooltip_spellid = "Enable Target SpellID on tooltip"
QulightL.option_tooltip_talents = "Enable Target talents on tooltip"
QulightL.option_tooltip_title = "Disable show title in tooltip"
-- action bar
QulightL.option_actionbar = "Action Bars"
QulightL.option_actionbar_enable = "Enable action bar"
QulightL.option_actionbar_hotkey = "Show hotkey on buttons"
QulightL.option_actionbar_hideSTANCE = "Hide Shapeshift bar or Totem bar"
QulightL.option_actionbar_bottomrows = "Main bars (1-3)"
QulightL.option_actionbar_rightbars = "Right bar (0-3)"
QulightL.option_actionbar_splitbar = "Side bars"
QulightL.option_actionbar_buttonsize = "Size of the main action buttons"
QulightL.option_actionbar_buttonspacing = "Spacing of the main action buttons"
QulightL.option_actionbar_petbuttonsize = "Size of the pet action buttons"
QulightL.option_actionbar_petbuttonspacing = "Spacing of the pet action buttons"
QulightL.option_actionbar_swaptopbottombar = "Swap top bottom bars"
QulightL.option_actionbar_macrotext = "Show macros text on buttons"
QulightL.option_actionbar_verticalshapeshift = "Vertical Shift Bar"
QulightL.option_actionbar_microbar = "Micro bar"
QulightL.option_actionbar_mousemicro = "Mouseover for micro bar"
QulightL.option_actionbar_showgrid = "Always show Grid on action bar"
QulightL.option_actionbar_mainbarWidth = "MainBar Width(1-12)"
QulightL.option_actionbar_ownshdbar = "Use an empty bar for shadow dance (rogue) instead of stealth bar"
QulightL.option_actionbar_lowversion = "Other version for Action Bars"
QulightL.option_actionbar_sidebarWidth = "SideBar Width(1-6), this option work if Other version for Action Bars = false"
QulightL.option_misk = "Other"
QulightL.option_raidutility = "Raid Utility"
QulightL.option_BuffReminderRaidBuffs = "Reminder Raid Buffs"
QulightL.option_Reminder = "Reminder Solo Buffs"
QulightL.option_CooldownFlash = "Flashes an icon in the middle of your screen when a cooldown ends."
QulightL.option_interrupts = "Announce interrupts in /say"
QulightL.option_AutoScreen = "AutoScreen achievements"
QulightL.option_reset = "Reset"
QulightL.option_apply = "Apply"
QulightL.option_close = "Close"
QulightL.option_setsavedsetttings = "Set settings Per-Character"
QulightL.option_resetchar = "Are you sure you want to reset your character's settings to match your default settings?"
QulightL.option_resetall = "Are you sure you want to reset all of your settings to Default?"
QulightL.option_perchar = "Are you sure you want to change to or from 'Per Char Settings'?"
QulightL.option_makeselection = "You must make a selection before you can continue to config."
QulightL.option_bottombars = "Bottom bars:"
QulightL.option_rightbars = "Right bar(if off then damagebar on)"
QulightL.option_nameplates_showlevel = "Show level"
QulightL.option_raidcooldowns = "Raid cooldowns"
QulightL.option_DamagebarWidth = "Damage bar width(1-12)"
QulightL.option_Damagebar = "Damage bar"
QulightL.option_sidebars = "Side bars" | gpl-2.0 |
n0xus/darkstar | scripts/globals/items/smoked_salmon.lua | 35 | 1196 | -----------------------------------------
-- ID: 4380
-- Item: smoked_salmon
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 2
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4380);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -3);
end;
| gpl-3.0 |
n0xus/darkstar | scripts/globals/mobskills/Core_Meltdown.lua | 18 | 1084 | ---------------------------------------------------
-- Core Meltdown (Ghrah)
-- Reactor core fails and self-destructs, damaging any nearby targets.
-- Note: Very rare, estimated 5% chance
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:isMobType(MOBTYPE_NOTORIOUS)) then
return 1;
elseif (mob:AnimationSub() ~=0) then -- form check
return 1;
elseif (math.random(1,100) >= 5) then -- here's the 95% chance to not blow up
return 1;
else
return 0;
end;
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*math.random(7,15),ELE_NONE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,MOBPARAM_IGNORE_SHADOWS);
mob:setHP(0);
target:delHP(dmg);
return dmg;
end
| gpl-3.0 |
alexandre-mbm/SimTools | RandomWeather/Lua/socket/socket.lua | 146 | 4061 | -----------------------------------------------------------------------------
-- LuaSocket helper module
-- Author: Diego Nehab
-- RCS ID: $Id: socket.lua,v 1.22 2005/11/22 08:33:29 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module and import dependencies
-----------------------------------------------------------------------------
local base = _G
local string = require("string")
local math = require("math")
local socket = require("socket.core")
module("socket")
-----------------------------------------------------------------------------
-- Exported auxiliar functions
-----------------------------------------------------------------------------
function connect(address, port, laddress, lport)
local sock, err = socket.tcp()
if not sock then return nil, err end
if laddress then
local res, err = sock:bind(laddress, lport, -1)
if not res then return nil, err end
end
local res, err = sock:connect(address, port)
if not res then return nil, err end
return sock
end
function bind(host, port, backlog)
local sock, err = socket.tcp()
if not sock then return nil, err end
sock:setoption("reuseaddr", true)
local res, err = sock:bind(host, port)
if not res then return nil, err end
res, err = sock:listen(backlog)
if not res then return nil, err end
return sock
end
try = newtry()
function choose(table)
return function(name, opt1, opt2)
if base.type(name) ~= "string" then
name, opt1, opt2 = "default", name, opt1
end
local f = table[name or "nil"]
if not f then base.error("unknown key (".. base.tostring(name) ..")", 3)
else return f(opt1, opt2) end
end
end
-----------------------------------------------------------------------------
-- Socket sources and sinks, conforming to LTN12
-----------------------------------------------------------------------------
-- create namespaces inside LuaSocket namespace
sourcet = {}
sinkt = {}
BLOCKSIZE = 2048
sinkt["close-when-done"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if not chunk then
sock:close()
return 1
else return sock:send(chunk) end
end
})
end
sinkt["keep-open"] = function(sock)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function(self, chunk, err)
if chunk then return sock:send(chunk)
else return 1 end
end
})
end
sinkt["default"] = sinkt["keep-open"]
sink = choose(sinkt)
sourcet["by-length"] = function(sock, length)
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if length <= 0 then return nil end
local size = math.min(socket.BLOCKSIZE, length)
local chunk, err = sock:receive(size)
if err then return nil, err end
length = length - string.len(chunk)
return chunk
end
})
end
sourcet["until-closed"] = function(sock)
local done
return base.setmetatable({
getfd = function() return sock:getfd() end,
dirty = function() return sock:dirty() end
}, {
__call = function()
if done then return nil end
local chunk, err, partial = sock:receive(socket.BLOCKSIZE)
if not err then return chunk
elseif err == "closed" then
sock:close()
done = 1
return partial
else return nil, err end
end
})
end
sourcet["default"] = sourcet["until-closed"]
source = choose(sourcet)
| mit |
davymai/CN-QulightUI | Interface/AddOns/QulightUI/Addons/Actionbars/Bar1.lua | 1 | 2985 | if not Qulight["actionbar"].enable == true then return end
local bar = QuBar1
local shd = 7
if Qulight.actionbar.ownshdbar then shd = 10 end
local Page = {
["DRUID"] = "[bonusbar:1,nostealth] 7; [bonusbar:1,stealth] 8; [bonusbar:2] 8; [bonusbar:3] 9; [bonusbar:4] 10;",
["PRIEST"] = "[bonusbar:1] 7;",
["ROGUE"] = "[bonusbar:1] 7; [stance:3] "..shd..";",
["MONK"] = "[bonusbar:1] 7; [bonusbar:2] 8; [bonusbar:3] 9;",
["WARRIOR"] = "[bonusbar:1] 7; [bonusbar:2] 8;",
["WARLOCK"] = meta,
["DEFAULT"] = "[vehicleui:12] 12; [possessbar] 12; [overridebar] 14; [bar:2] 2; [bar:3] 3; [bar:4] 4; [bar:5] 5; [bar:6] 6;",
}
local function GetBar()
local condition = Page["DEFAULT"]
local class = myclass
local page = Page[class]
if page then
condition = condition.." "..page
end
condition = condition.." 1"
return condition
end
local function SetStates(self)
self:SetAttribute("_onstate-page", [[
for i, button in ipairs(buttons) do
button:SetAttribute("actionpage", tonumber(newstate))
end
]])
RegisterStateDriver(self, "page", GetBar())
end
bar:RegisterEvent("PLAYER_LOGIN")
bar:RegisterEvent("PLAYER_ENTERING_WORLD")
bar:RegisterEvent("KNOWN_CURRENCY_TYPES_UPDATE")
bar:RegisterEvent("CURRENCY_DISPLAY_UPDATE")
bar:RegisterEvent("BAG_UPDATE")
bar:RegisterEvent("UPDATE_VEHICLE_ACTIONBAR")
bar:RegisterEvent("UPDATE_OVERRIDE_ACTIONBAR")
bar:SetScript("OnEvent", function(self, event, unit, ...)
if event == "PLAYER_LOGIN" or event == "ACTIVE_TALENT_GROUP_CHANGED" then
local button
for i = 1, NUM_ACTIONBAR_BUTTONS do
button = _G["ActionButton"..i]
self:SetFrameRef("ActionButton"..i, button)
end
self:Execute([[
buttons = table.new()
for i = 1, 12 do
table.insert(buttons, self:GetFrameRef("ActionButton"..i))
end
]])
self:SetAttribute("_onstate-page", [[
for i, button in ipairs(buttons) do
button:SetAttribute("actionpage", tonumber(newstate))
end
]])
RegisterStateDriver(self, "page", GetBar())
elseif event == "PLAYER_ENTERING_WORLD" then
local button
for i = 1, 12 do
button = _G["ActionButton"..i]
button:RegisterForClicks("LeftButtonDown", "RightButtonUp")
button:SetSize(buttonsize, buttonsize)
button:ClearAllPoints()
button:SetParent(bar)
button:SetFrameStrata("BACKGROUND")
button:SetFrameLevel(15)
if i == 1 then
button:SetPoint("BOTTOMLEFT", buttonspacing, buttonspacing)
elseif i == (Qulight.actionbar.mainbarWidth+1) then
button:SetPoint("TOP", UIParent, "BOTTOM", 0, -20)
else
local previous = _G["ActionButton"..i-1]
button:SetPoint("LEFT", previous, "RIGHT", buttonspacing, 0)
end
end
elseif event == "UPDATE_VEHICLE_ACTIONBAR" or event == "UPDATE_OVERRIDE_ACTIONBAR" then
if HasVehicleActionBar() or HasOverrideActionBar() then
if not self.inVehicle then
self.inVehicle = true
end
else
if self.inVehicle then
self.inVehicle = false
end
end
else
MainMenuBar_OnEvent(self, event, ...)
end
end) | gpl-2.0 |
ihaveamac/downgrade-check | index.lua | 1 | 1655 | --ihaveamac--
-- https://github.com/ihaveamac/downgrade-check
version = "1.0"
-- 9.2 NATIVE_FIRM: 2.46-0
firmmajor, firmminor, firmrev = System.getKernel()
downgraded = false
if firmmajor <= 2 and firmminor <= 46 and firmrev <= 0 then
downgraded = true
end
Screen.waitVblankStart()
Screen.refresh()
Screen.clear(BOTTOM_SCREEN)
c_white = Color.new(255, 255, 255)
c_grey = Color.new(127, 127, 127)
Screen.debugPrint(5, 5, "downgrade-check", c_white, BOTTOM_SCREEN)
Screen.fillEmptyRect(6, 314, 17, 18, c_grey, BOTTOM_SCREEN)
if downgraded then
Screen.debugPrint(5, 25, "Congratulations! You have properly", c_white, BOTTOM_SCREEN)
Screen.debugPrint(5, 40, "downgraded your console. Enjoy!", c_white, BOTTOM_SCREEN)
else
Screen.debugPrint(5, 25, "Unfortunately you did not seem to", c_white, BOTTOM_SCREEN)
Screen.debugPrint(5, 40, "downgrade to 9.2 properly.", c_white, BOTTOM_SCREEN)
end
Screen.debugPrint(5, 80, "Installed NATIVE_FIRM:", c_white, BOTTOM_SCREEN)
Screen.debugPrint(221, 80, firmmajor.."."..firmminor.."-"..firmrev, c_white, BOTTOM_SCREEN)
Screen.debugPrint(5, 95, "9.2 NATIVE_FIRM:", c_white, BOTTOM_SCREEN)
Screen.debugPrint(221, 95, "2.46-0", c_white, BOTTOM_SCREEN)
Screen.debugPrint(5, 135, "A: exit", c_white, BOTTOM_SCREEN)
Screen.debugPrint(5, 150, "X: reboot", c_white, BOTTOM_SCREEN)
Screen.flip()
while true do
local pad = Controls.read()
if Controls.check(pad, KEY_A) then
System.exit()
end
if Controls.check(pad, KEY_X) then
Screen.waitVblankStart()
Screen.refresh()
Screen.clear(BOTTOM_SCREEN)
Screen.flip()
System.reboot()
end
end | mit |
n0xus/darkstar | scripts/globals/missions.lua | 14 | 49872 | -----------------------------------
-- Areas ID
-----------------------------------
SANDORIA = 0;
BASTOK = 1;
WINDURST = 2;
ZILART = 3;
TOAU = 4;
WOTG = 5;
COP = 6;
ASSAULT = 7;
CAMPAIGN = 8;
ACP = 9;
AMK = 10;
ASA = 11;
SOA = 12;
-----------------------------------
-- San d'Oria (0)
-----------------------------------
SMASH_THE_ORCISH_SCOUTS = 0; -- ± --
BAT_HUNT = 1; -- ± --
SAVE_THE_CHILDREN = 2; -- ± --
THE_RESCUE_DRILL = 3; -- ± --
THE_DAVOI_REPORT = 4; -- ± --
JOURNEY_ABROAD = 5; -- ± --
JOURNEY_TO_BASTOK = 6; -- ± --
JOURNEY_TO_WINDURST = 7; -- ± --
JOURNEY_TO_BASTOK2 = 8; -- ± --
JOURNEY_TO_WINDURST2 = 9; -- ± --
INFILTRATE_DAVOI = 10; -- ± --
THE_CRYSTAL_SPRING = 11; -- ± --
APPOINTMENT_TO_JEUNO = 12; -- ± --
MAGICITE_SAN_D_ORIA = 13; -- ± --
THE_RUINS_OF_FEI_YIN = 14; -- ± --
THE_SHADOW_LORD = 15; -- ± --
LEAUTE_S_LAST_WISHES = 16; -- ± --
RANPERRE_S_FINAL_REST = 17; -- ± --
PRESTIGE_OF_THE_PAPSQUE = 18; -- ± --
THE_SECRET_WEAPON = 19; -- ± --
COMING_OF_AGE = 20; -- ± --
LIGHTBRINGER = 21; -- ± --
BREAKING_BARRIERS = 22; -- ± --
THE_HEIR_TO_THE_LIGHT = 23;
-----------------------------------
-- Bastok (1)
-----------------------------------
THE_ZERUHN_REPORT = 0; -- ± --
GEOLOGICAL_SURVEY = 1; -- ± --
FETICHISM = 2; -- ± --
THE_CRYSTAL_LINE = 3; -- ± --
WADING_BEASTS = 4; -- ± --
THE_EMISSARY = 5; -- ± --
THE_EMISSARY_SANDORIA = 6; -- ± --
THE_EMISSARY_WINDURST = 7; -- ± --
THE_EMISSARY_SANDORIA2 = 8; -- ± --
THE_EMISSARY_WINDURST2 = 9; -- ± --
THE_FOUR_MUSKETEERS = 10; -- ± --
TO_THE_FORSAKEN_MINES = 11; -- ± --
JEUNO_MISSION = 12; -- ± --
MAGICITE_BASTOK = 13; -- ± --
DARKNESS_RISING = 14; -- ± --
XARCABARD_LAND_OF_TRUTHS = 15; -- ± --
RETURN_OF_THE_TALEKEEPER = 16; -- ± --
THE_PIRATE_S_COVE = 17; -- ± --
THE_FINAL_IMAGE = 18; -- ± --
ON_MY_WAY = 19;
THE_CHAINS_THAT_BIND_US = 20;
ENTER_THE_TALEKEEPER = 21;
THE_SALT_OF_THE_EARTH = 22;
WHERE_TWO_PATHS_CONVERGE = 23;
-----------------------------------
-- Windurst (2)
-----------------------------------
THE_HORUTOTO_RUINS_EXPERIMENT = 0; -- ± --
THE_HEART_OF_THE_MATTER = 1; -- ± --
THE_PRICE_OF_PEACE = 2; -- ± --
LOST_FOR_WORDS = 3; -- ± --
A_TESTING_TIME = 4; -- ± --
THE_THREE_KINGDOMS = 5; -- ± --
THE_THREE_KINGDOMS_SANDORIA = 6; -- ± --
THE_THREE_KINGDOMS_BASTOK = 7; -- ± --
THE_THREE_KINGDOMS_SANDORIA2 = 8; -- ± --
THE_THREE_KINGDOMS_BASTOK2 = 9; -- ± --
TO_EACH_HIS_OWN_RIGHT = 10; -- ± --
WRITTEN_IN_THE_STARS = 11; -- ± --
A_NEW_JOURNEY = 12; -- ± --
MAGICITE = 13; -- ± --
THE_FINAL_SEAL = 14; -- ± --
THE_SHADOW_AWAITS = 15; -- ± --
FULL_MOON_FOUNTAIN = 16; -- ± --
SAINTLY_INVITATION = 17; -- ± --
THE_SIXTH_MINISTRY = 18; -- ± --
AWAKENING_OF_THE_GODS = 19; -- ± --
VAIN = 20;
THE_JESTER_WHO_D_BE_KING = 21;
DOLL_OF_THE_DEAD = 22;
MOON_READING = 23;
-----------------------------------
-- Zilart Missions (3)
-----------------------------------
THE_NEW_FRONTIER = 0; -- ± --
WELCOME_TNORG = 4; -- ± --
KAZAMS_CHIEFTAINESS = 6; -- ± --
THE_TEMPLE_OF_UGGALEPIH = 8; -- ± --
HEADSTONE_PILGRIMAGE = 10; -- ± --
THROUGH_THE_QUICKSAND_CAVES = 12; -- ± --
THE_CHAMBER_OF_ORACLES = 14; -- ± --
RETURN_TO_DELKFUTTS_TOWER = 16; -- ± --
ROMAEVE = 18; -- ± --
THE_TEMPLE_OF_DESOLATION = 20; -- ± --
THE_HALL_OF_THE_GODS = 22; -- ± --
THE_MITHRA_AND_THE_CRYSTAL = 23; -- ± --
THE_GATE_OF_THE_GODS = 24; -- ± --
ARK_ANGELS = 26; -- ± --
THE_SEALED_SHRINE = 27; -- ± --
THE_CELESTIAL_NEXUS = 28;
AWAKENING = 30;
THE_LAST_VERSE = 31;
-----------------------------------
-- Promathia Missions (6)
-----------------------------------
ANCIENT_FLAMES_BECKON = 0 -- Category
THE_RITES_OF_LIFE = 1 -- ± --
BELOW_THE_ARKS = 2 -- ± --
THE_MOTHERCRYSTALS = 3 -- ± --
-- THE_ISLE_OF_FORGOTTEN_SAINTS = -- Category
AN_INVITATION_WEST = 5 -- ± --
THE_LOST_CITY = 15 -- ± --
DISTANT_BELIEFS = 16 -- ± --
AN_ETERNAL_MELODY = 17 -- ± --
ANCIENT_VOWS = 18 -- ± --
A_TRANSIENT_DREAM = 19 -- Category
THE_CALL_OF_THE_WYRMKING = 20 -- ± --
A_VESSEL_WITHOUT_A_CAPTAIN = 27 -- ± --
THE_ROAD_FORKS = 28 -- ± --
-- EMERALD_WATERS = -- Sub-category
-- VICISSITUDES = -- ± --
DESCENDANTS_OF_A_LINE_LOST = 29 -- ± --
-- LOUVERANCE = -- ± --
-- MEMORIES_OF_A_MAIDEN = -- Sub-category
COMEDY_OF_ERRORS_ACT_I = 30 -- ± --
-- COMEDY_OF_ERRORS_ACT_II = -- ± --
-- EXIT_STAGE_LEFT = -- ± --
TENDING_AGED_WOUNDS = 31 -- ± --
DARKNESS_NAMED = 32 -- ± --
-- THE_CRADLES_OF_CHILDREN_LOST = -- Category
SHELTERING_DOUBT = 33 -- ± --
THE_SAVAGE = 40 -- ± --
THE_SECRETS_OF_WORSHIP = 41 -- ± --
SLANDEROUS_UTTERINGS = 42 -- ± --
-- THE_RETURN_HOME = -- Category
THE_ENDURING_TUMULT_OF_WAR = 43 -- ± --
DESIRES_OF_EMPTINESS = 52 -- ± --
THREE_PATHS = 54 -- ± --
-- PAST_SINS = -- ± --
-- SOUTHERN_LEGEND = -- ± --
PARTNERS_WITHOUT_FAME = 55 -- ± --
-- A_CENTURY_OF_HARDSHIP = -- ± --
-- DEPARTURES = -- ± --
-- THE_PURSUIT_OF_PARADISE = -- ± --
SPIRAL = 56 -- ± --
-- BRANDED = -- ± --
-- PRIDE_AND_HONOR = -- ± --
-- AND_THE_COMPASS_GUIDES = -- ± --
WHERE_MESSENGERS_GATHER = 57 -- ± --
-- ENTANGLEMENT = -- ± --
-- HEAD_WIND = -- ± --
FLAMES_FOR_THE_DEAD = 58 -- ± --
-- ECHOES_OF_TIME = -- ± -- -- Category
FOR_WHOM_THE_VERSE_IS_SUNG = 60 -- ± --
A_PLACE_TO_RETURN = 65 -- ± ---- It's necessary to increase MAX_MISSIONID in charentity.h to reach values > 63
MORE_QUESTIONS_THAN_ANSWERS = 66 -- ± --
ONE_TO_BE_FEARED = 67 -- ± --
-- IN_THE_LIGHT_OF_THE_CRYSTAL = -- ± -- -- Category
CHAINS_AND_BONDS = 68 -- ± --
FLAMES_IN_THE_DARKNESS = 77 -- ± --
FIRE_IN_THE_EYES_OF_MEN = 78 -- ± --
CALM_BEFORE_THE_STORM = 80 -- ± --
THE_WARRIOR_S_PATH = 81 -- ± --
EMPTINESS_BLEEDS = 82 -- ± ---- Category
GARDEN_OF_ANTIQUITY = 87 -- ± --
A_FATE_DECIDED = 90 -- ± --
WHEN_ANGELS_FALL = 91 -- ± --
DAWN = 92 -- ± --
THE_LAST_VERSE = 94
-----------------------------------
-- Aht Urhgan Missions (4)
-----------------------------------
LAND_OF_SACRED_SERPENTS = 0;
IMMORTAL_SENTRIES = 1;
PRESIDENT_SALAHEEM = 2;
KNIGHT_OF_GOLD = 3;
CONFESSIONS_OF_ROYALTY = 4;
EASTERLY_WINDS = 5;
WESTERLY_WINDS = 6;
A_MERCENARY_LIFE = 7;
UNDERSEA_SCOUTING = 8;
ASTRAL_WAVES = 9;
IMPERIAL_SCHEMES = 10;
ROYAL_PUPPETEER = 11;
LOST_KINGDOM = 12;
THE_DOLPHIN_CREST = 13;
THE_BLACK_COFFIN = 14;
GHOSTS_OF_THE_PAST = 15;
GUESTS_OF_THE_EMPIRE = 16;
PASSING_GLORY = 17;
SWEETS_FOR_THE_SOUL = 18;
TEAHOUSE_TUMULT = 19;
FINDERS_KEEPERS = 20;
SHIELD_OF_DIPLOMACY = 21;
SOCIAL_GRACES = 22;
FOILED_AMBITION = 23;
PLAYING_THE_PART = 24;
SEAL_OF_THE_SERPENT = 25;
MISPLACED_NOBILITY = 26;
BASTION_OF_KNOWLEDGE = 27;
PUPPET_IN_PERIL = 28;
PREVALENCE_OF_PIRATES = 29;
SHADES_OF_VENGEANCE = 30;
IN_THE_BLOOD = 31;
SENTINELS_HONOR = 32;
TESTING_THE_WATERS = 33;
LEGACY_OF_THE_LOST = 34;
GAZE_OF_THE_SABOTEUR = 35;
PATH_OF_BLOOD = 36;
STIRRINGS_OF_WAR = 37;
ALLIED_RUMBLINGS = 38;
UNRAVELING_REASON = 39;
LIGHT_OF_JUDGMENT = 40;
PATH_OF_DARKNESS = 41;
FANGS_OF_THE_LION = 42;
NASHMEIRAS_PLEA = 43;
URHGAN_MISSION_44 = 44;
IMPERIAL_CORONATION = 45;
THE_EMPRESS_CROWNED = 46;
ETERNAL_MERCENARY = 47;
-----------------------------------
-- Wings of the Goddess (5)
-----------------------------------
CAVERNOUS_MAWS = 0;
BACK_TO_THE_BEGINNING = 1;
CAIT_SITH = 2;
THE_QUEEN_OF_THE_DANCE = 3;
WHILE_THE_CAT_IS_AWAY = 4;
A_TIMESWEPT_BUTTERFLY = 5;
PURPLE,_THE_NEW_BLACK = 6;
IN_THE_NAME_OF_THE_FATHER = 7;
DANCERS_IN_DISTRESS = 8;
DAUGHTER_OF_A_KNIGHT = 9;
A_SPOONFUL_OF_SUGAR = 10;
AFFAIRS_OF_STATE = 11;
BORNE_BY_THE_WIND = 12;
A_NATION_ON_THE_BRINK = 13;
CROSSROADS_OF_TIME = 14;
SANDSWEPT_MEMORIES = 15;
NORTHLAND_EXPOSURE = 16;
TRAITOR_IN_THE_MIDST = 17;
BETRAYAL_AT_BEAUCEDINE = 18;
ON_THIN_ICE = 19;
PROOF_OF_VALOR = 20;
A_SANGUINARY_PRELUDE = 21;
DUNGEONS_AND_DANCERS = 22;
DISTORTER_OF_TIME = 23;
THE_WILL_OF_THE_WORLD = 24;
FATE_IN_HAZE = 25;
THE_SCENT_OF_BATTLE = 26;
ANOTHER_WORLD = 27;
A_HAWK_IN_REPOSE = 28;
THE_BATTLE_OF_XARCABARD = 29;
PRELUDE_TO_A_STORM = 30;
STORM_S_CRESCENDO = 31;
INTO_THE_BEAST_S_MAW = 32;
THE_HUNTER_ENSNARED = 33;
FLIGHT_OF_THE_LION = 34;
FALL_OF_THE_HAWK = 35;
DARKNESS_DESCENDS = 36;
ADIEU__LILISETTE = 37;
BY_THE_FADING_LIGHT = 38;
EDGE_OF_EXISTENCE = 39;
HER_MEMORIES = 40;
FORGET_ME_NOT = 41;
PILLAR_OF_HOPE = 42;
GLIMMER_OF_LIFE = 43;
TIME_SLIPS_AWAY = 44;
WHEN_WILLS_COLLIDE = 45;
WHISPERS_OF_DAWN = 46;
A_DREAMY_INTERLUDE = 47;
CAIT_IN_THE_WOODS = 48;
FORK_IN_THE_ROAD = 49;
MAIDEN_OF_THE_DUSK = 50;
WHERE_IT_ALL_BEGAN = 51;
A_TOKEN_OF_TROTH = 52;
LEST_WE_FORGET = 53;
-----------------------------------
-- Assault (7)
-----------------------------------
LEUJAOAM_CLEANSING = 1;
ORICHALCUM_SURVEY = 2;
ESCORT_PROFESSOR_CHANOIX = 3;
SHANARHA_GRASS_CONSERVATION = 4;
COUNTING_SHEEP = 5;
SUPPLIES_RECOVERY = 6;
AZURE_EXPERIMENTS = 7;
IMPERIAL_CODE = 8;
RED_VERSUS_BLUE = 9;
BLOODY_RONDO = 10;
IMPERIAL_AGENT_RESCUE = 11;
PREEMPTIVE_STRIKE = 12;
SAGELORD_ELIMINATION = 13;
BREAKING_MORALE = 14;
THE_DOUBLE_AGENT = 15;
IMPERIAL_TREASURE_RETRIEVAL = 16;
BLITZKRIEG = 17;
MARIDS_IN_THE_MIST = 18;
AZURE_AILMENTS = 19;
THE_SUSANOO_SHUFFLE = 20;
EXCAVATION_DUTY = 21;
LEBROS_SUPPLIES = 22;
TROLL_FUGITIVES = 23;
EVADE_AND_ESCAPE = 24;
SIEGEMASTER_ASSASSINATION = 25;
APKALLU_BREEDING = 26;
WAMOURA_FARM_RAID = 27;
EGG_CONSERVATION = 28;
OPERATION__BLACK_PEARL = 29;
BETTER_THAN_ONE = 30;
SEAGULL_GROUNDED = 31;
REQUIEM = 32;
SAVING_PRIVATE_RYAAF = 33;
SHOOTING_DOWN_THE_BARON = 34;
BUILDING_BRIDGES = 35;
STOP_THE_BLOODSHED = 36;
DEFUSE_THE_THREAT = 37;
OPERATION__SNAKE_EYES = 38;
WAKE_THE_PUPPET = 39;
THE_PRICE_IS_RIGHT = 40;
GOLDEN_SALVAGE = 41;
LAMIA_NO_13 = 42;
EXTERMINATION = 43;
DEMOLITION_DUTY = 44;
SEARAT_SALVATION = 45;
APKALLU_SEIZURE = 46;
LOST_AND_FOUND = 47;
DESERTER = 48;
DESPERATELY_SEEKING_CEPHALOPODS = 49;
BELLEROPHON_S_BLISS = 50;
NYZUL_ISLE_INVESTIGATION = 51;
NYZUL_ISLE_UNCHARTED_AREA_SURVEY = 52;
-----------------------------------
-- Campaign (8)
-----------------------------------
-----------------------------------
-- A Crystalline Prophecy (9)
-----------------------------------
A_CRYSTALLINE_PROPHECY = 0; -- ± --
THE_ECHO_AWAKENS = 1; -- ± --
GATHERER_OF_LIGHT_I = 2; -- ± --
GATHERER_OF_LIGHT_II = 3;
THOSE_WHO_LURK_IN_SHADOWS_I = 4; -- ± --
THOSE_WHO_LURK_IN_SHADOWS_II = 5; -- ± --
THOSE_WHO_LURK_IN_SHADOWS_III = 6; -- ± --
REMEMBER_ME_IN_YOUR_DREAMS = 7; -- ± --
BORN_OF_HER_NIGHTMARES = 8; -- ± --
BANISHING_THE_ECHO = 9;
ODE_OF_LIFE_BESTOWING = 10;
A_CRYSTALLINE_PROPHECY_FIN = 11;
-----------------------------------
-- A Moogle Kupo d'Etat (10)
-----------------------------------
A_MOOGLE_KUPO_DETAT = 0;
DRENCHED_IT_BEGAN_WITH_A_RAINDROP = 1;
HASTEN_IN_A_JAM_IN_JEUNO = 2;
WELCOME_TO_MY_DECREPIT_DOMICILE = 3;
CURSES_A_HORRIFICALLY_HARROWING_HEX = 4;
AN_ERRAND_THE_PROFESSORS_PRICE = 5;
SHOCK_ARRANT_ABUSE_OF_AUTHORITY = 6;
LENDER_BEWARE_READ_THE_FINE_PRINT = 7;
RESCUE_A_MOOGLES_LABOR_OF_LOVE = 8;
ROAR_A_CAT_BURGLAR_BARES_HER_FANGS = 9;
RELIEF_A_TRIUMPHANT_RETURN = 10;
JOY_SUMMONED_TO_A_FABULOUS_FETE = 11;
A_CHALLENGE_YOU_COULD_BE_A_WINNER = 12;
SMASH_A_MALEVOLENT_MENACE = 13;
A_MOOGLE_KUPO_DETAT_FIN = 14;
-----------------------------------
-- A Shantotto Ascension (11)
-----------------------------------
A_SHANTOTTO_ASCENSION = 0; -- ± --
BURGEONING_DREAD = 1; -- ± --
THAT_WHICH_CURDLES_BLOOD = 2; -- ± --
SUGAR_COATED_DIRECTIVE = 3; -- ± --
ENEMY_OF_THE_EMPIRE_I = 4;
ENEMY_OF_THE_EMPIRE_II = 5;
SUGAR_COATED_SUBTERFUGE = 6;
SHANTOTTO_IN_CHAINS = 7;
FOUNTAIN_OF_TROUBLE = 8;
BATTARU_ROYALE = 9;
ROMANCING_THE_CLONE = 10;
SISTERS_IN_ARMS = 11;
PROJECT_SHANTOTTOFICATION = 12;
AN_UNEASY_PEACE = 13;
A_SHANTOTTO_ASCENSION_FIN = 14;
-----------------------------------
-- Seekers of Adoulin (12)
-----------------------------------
-- THE_SACRED_CITY_OF_ADOULIN = -- Category
RUMORS_FROM_THE_WEST = 0;
THE_GEOMAGNETRON = 1;
ONWARD_TO_ADOULIN = 2;
HEARTWIGNS_AND_THE_KINDHEARTED = 3;
PIONEER_REGISTRATION = 4;
LIFE_ON_THE_FRONTIER = 5;
MEETING_OF_THE_MINDS = 6;
ARCIELA_APPEARS_AGAIN = 7;
-- THE_ANCIENT_PACT = -- Category
BUILDING_PROSPECTS = 8;
THE_LIGHT_SHINING_IN_YOUR_EYES = 9;
THE_HEIRLOOM = 10;
AN_AIMLESS_JOURNEY = 11;
ORTHARSYNE = 12;
IN_THE_PRESENCE_OF_ROYALTY = 13;
THE_TWIN_WORLD_TREES = 14;
HONOR_AND_AUDACITY = 15;
THE_WATERGARDEN_COLISEUM = 16;
FRICTION_AND_FISSURES = 17;
THE_CELENNIA_MEMORIAL_LIBRARY = 18;
FOR_WHOM_DO_WE_TOIL = 19;
AIMING_FOR_YGNAS = 20;
CALAMITY_IN_THE_KITCHEN = 21;
ARCIELA_S_PROMISE = 22;
PREDATOR_AND_PREY = 23;
BEHIND_THE_SLUICES = 24;
THE_LEAFKIN_MONARCH = 25;
YGGDRASIL = 26;
-- SHADOWS_UPON_ADOULIN = -- Category
RETURN_OF_THE_EXORCIST = 27;
THE_MERCILESS_ONE = 28;
A_CURSE_FROM_THE_PAST = 29;
THE_PURGATION = 30;
THE_KEY = 31;
THE_PRINCESSS_DILEMMA = 32;
DARK_CLOUDS_AHEAD = 33;
THE_SMALLEST_OF_FAVORS = 34;
SUMMONED_BY_SPIRITS = 35;
EVIL_ENTITIES = 36;
ADOULIN_CALLING = 37;
THE_DISAPPEARANCE_OF_NYLINE = 38;
SHARED_CONSCIOUSNESS = 39;
CLEAR_SKIES = 40;
THE_MAN_IN_BLACK = 41;
TO_THE_VICTOR = 42;
AN_EXTRAORDINARY_GENTLEMAN = 43;
THE_ORDERS_TREASURES = 44;
AUGUSTS_HEIRLOOM = 45;
BEAUTY_AND_THE_BEAST = 46;
WILDCAT_WITH_A_GOLD_PELT = 47;
IN_SEARCH_OF_ARCIELA = 48;
LOOKING_FOR_LEADS = 49;
DRIFTING_NORTHWEST = 50;
KUMHAU_THE_FLASHFROST_NAAKUAL = 51;
SOUL_SIPHON = 52;
STONEWALLED = 53;
SALVATION = 54;
GLIMMER_OF_PORTENT = 55;
-- FIN = 56;
function rankPointMath(rank)
return 0.372*rank^2 - 1.62*rank + 6.2;
end
function getMissionRankPoints(player, missionID)
if (missionID == 3) then crystals = 9;
elseif (missionID == 4) then crystals = 17;
elseif (missionID == 5) then crystals = 42;
elseif (missionID == 10) then crystals = 12; -- 1 stack needed to unlock
elseif (missionID == 11) then crystals = 30; -- 2.5 stacks needed to unlock (2 stacks of crystals + 3.1 rank points corresponding to half a stack)
elseif (missionID == 12) then crystals = 48; -- 4 stacks to unlock (3.5 stacks + 3.1 rank points corresponding to half a stack)
elseif (missionID == 13) then crystals = 36; -- 3 stacks to unlock
-- 5.1 starts directly after Magicite, no crystals needed
elseif (missionID == 15) then crystals = 44; -- Mission unlocks at 50% rank bar ~= 44 crystals using the present formula.
elseif (missionID == 16) then crystals = 36; -- 3 stacks to unlock
elseif (missionID == 17) then crystals = 93; -- 3 additional stacks to unlock + 3 original stacks + 21 from mission 6.1
elseif (missionID == 18) then crystals = 45; -- 45 needed, from http://wiki.ffxiclopedia.org/wiki/The_Final_Image
elseif (missionID == 19) then crystals = 119; -- 4 additional stacks needed, plus mission reward of 26
elseif (missionID == 20) then crystals = 57; -- 4 3/4 stacks needed
elseif (missionID == 21) then crystals = 148; -- 5 additional stacks needed, plus mission reward of 31,
elseif (missionID == 22) then crystals = 96; -- 8 stacks needed (higher value chosen so final rank bar requirement is closer to 90%)
elseif (missionID == 23) then crystals = 228; -- Additional 8 stacks needed, plus mission reward of 36 (87% rank bar)
end;
points_needed = 1024 * (crystals-.25) / (3*rankPointMath(player:getRank()));
if (player:getRankPoints() >= points_needed) then
return 1;
else
return 0;
end
end;
function getMissionMask(player)
rank = player:getRank()
nation = player:getNation(); -- 0 = San d'Oria ; 1 = Bastok ; 2 = Windurst
mission_status = player:getCurrentMission(nation);
first_mission = 0;
repeat_mission = 0;
if (nation == WINDURST) then
if (rank >= 1) then
if (player:hasCompletedMission(WINDURST,THE_HORUTOTO_RUINS_EXPERIMENT) == false) then
-- 1-1 NOTE: This mission will not be listed in the Mission List for Windurst
--first_mission = first_mission + 1;
end
if (player:hasCompletedMission(WINDURST,THE_HEART_OF_THE_MATTER) == false) then
-- 1-2 NOTE: This mission will not be listed in the Mission List for Windurst
--first_mission = first_mission + 2;
end
if (player:hasCompletedMission(WINDURST,THE_PRICE_OF_PEACE) == false) then
-- 1-3 NOTE: This mission will not be listed in the Mission List for Windurst
--first_mission = first_mission + 4;
end
end
if (rank >= 2) then
-- 2-1
if (player:hasCompletedMission(WINDURST,LOST_FOR_WORDS) == false and getMissionRankPoints(player,3) == 1) then
first_mission = first_mission + 8;
else
if (player:hasCompletedMission(WINDURST,LOST_FOR_WORDS) and (rank > 2 or getMissionRankPoints(player,4) == 1)) then
-- 2-2 Repeatable
repeat_mission = repeat_mission + 16;
end
if (player:hasCompletedMission(WINDURST,THE_THREE_KINGDOMS) == false and getMissionRankPoints(player,5) == 1) then
-- 2-3
first_mission = first_mission + 32;
end
end
end
if (rank >= 3) then
-- 3-1
if (player:hasCompletedMission(WINDURST,TO_EACH_HIS_OWN_RIGHT) == false and getMissionRankPoints(player,10) == 1) then
first_mission = first_mission + 1024;
else
if (player:hasCompletedMission(WINDURST,WRITTEN_IN_THE_STARS) == false and getMissionRankPoints(player,11) == 1) then
-- 3-2 Repeatable & Skippable
repeat_mission = repeat_mission + 2048;
elseif (rank > 3 or getMissionRankPoints(player,11) == 1) then
-- 3-2 Repeatable & Skippable
repeat_mission = repeat_mission + 2048;
end
if (player:hasCompletedMission(WINDURST,A_NEW_JOURNEY) == false and getMissionRankPoints(player,12) == 1) then
-- 3-3
first_mission = first_mission + 4096;
end
end
end
if (rank == 4) then
-- The mission is triggered by the Ambassador in Jeuno
-- first_mission = first_mission + 8192;
end
if (rank == 5) then
if (player:hasCompletedMission(WINDURST,THE_FINAL_SEAL) == false and getMissionRankPoints(player,0) == 1 and mission_status == 0) then
first_mission = first_mission + 16384;
end
if (player:hasCompletedMission(WINDURST,THE_FINAL_SEAL) and player:hasCompletedMission(WINDURST,THE_SHADOW_AWAITS) == false and getMissionRankPoints(player,15) == 1) then
-- 5-2
first_mission = first_mission + 32768;
end
end
if (rank == 6) then
if (player:hasCompletedMission(WINDURST,FULL_MOON_FOUNTAIN) == false and getMissionRankPoints(player,16) == 1) then
-- 6-1
first_mission = first_mission + 65536;
elseif (player:hasCompletedMission(WINDURST,SAINTLY_INVITATION) == false and getMissionRankPoints(player,17) == 1) then
-- 6-2
first_mission = first_mission + 131072;
end
end
if (rank == 7) then
if (player:hasCompletedMission(WINDURST,THE_SIXTH_MINISTRY) == false and getMissionRankPoints(player,18) == 1) then
-- 7-1
first_mission = first_mission + 262144;
elseif (player:hasCompletedMission(WINDURST,AWAKENING_OF_THE_GODS) == false and getMissionRankPoints(player,19) == 1) then
-- 7-2
first_mission = first_mission + 524288;
end
end
if (rank == 8) then
if (player:hasCompletedMission(WINDURST,VAIN) == false and getMissionRankPoints(player,20) == 1) then
-- 8-1
first_mission = first_mission + 1048576;
elseif (player:hasCompletedMission(WINDURST,THE_JESTER_WHO_D_BE_KING) == false and getMissionRankPoints(player,21) == 1) then
-- 8-2
first_mission = first_mission + 2097152;
end
end
if (rank == 9) then
if (player:hasCompletedMission(WINDURST,DOLL_OF_THE_DEAD) == false and getMissionRankPoints(player,22) == 1) then
-- 9-1
first_mission = first_mission + 4194304;
elseif (player:hasCompletedMission(WINDURST,MOON_READING) == false and getMissionRankPoints(player,23) == 1) then
-- 9-2
first_mission = first_mission + 8388608;
end
end
elseif (nation == SANDORIA) then
if (rank >= 1) then
if (player:hasCompletedMission(SANDORIA,SMASH_THE_ORCISH_SCOUTS) == false) then -- The first mission is repeatable in San d'Oria
-- 1-1
repeat_mission = repeat_mission + 1;
elseif (player:hasCompletedMission(SANDORIA,BAT_HUNT) == false) then
-- 1-2 If we completed 1-1, we can start and repeat this mission
repeat_mission = repeat_mission + 2 + 1;
elseif (player:hasCompletedMission(SANDORIA,SAVE_THE_CHILDREN) == false) then
-- 1-3 If we completed 1-2, we can start and repeat this mission
repeat_mission = repeat_mission + 4 + 2 + 1;
else
repeat_mission = repeat_mission + 4 + 2 + 1;
end
end
if (rank >= 2) then
-- 2-1
if (player:hasCompletedMission(SANDORIA,THE_RESCUE_DRILL) == false and getMissionRankPoints(player,3) == 1) then
first_mission = first_mission + 8;
else
if (rank > 2 or getMissionRankPoints(player,4) == 1) then
-- 2-2 Repeatable & Skippable
repeat_mission = repeat_mission + 16;
end
if (player:hasCompletedMission(SANDORIA,JOURNEY_ABROAD) == false and getMissionRankPoints(player,5) == 1) then
-- 2-3
first_mission = first_mission + 32;
end
end
end
if (rank >= 3) then
if (rank > 3 or getMissionRankPoints(player,10) == 1) then
-- 3-1
repeat_mission = repeat_mission + 1024;
end
if (player:hasCompletedMission(SANDORIA,INFILTRATE_DAVOI) == true and getMissionRankPoints(player,11) == 1) then
-- 3-2 Repeatable & Skippable
repeat_mission = repeat_mission + 2048;
end
if (player:hasCompletedMission(SANDORIA,APPOINTMENT_TO_JEUNO) == false and getMissionRankPoints(player,12) == 1) then
-- 3-3
first_mission = first_mission + 4096;
end
end
if (rank == 4) then
-- The mission is triggered by the Ambassador in Jeuno
-- first_mission = first_mission + 8192;
end
if (rank == 5) then
if (player:hasCompletedMission(SANDORIA,THE_RUINS_OF_FEI_YIN) == false and player:hasKeyItem(69) == false) then
first_mission = first_mission + 16384;
end
if (player:hasCompletedMission(SANDORIA,THE_SHADOW_LORD) == false and player:hasCompletedMission(SANDORIA,THE_RUINS_OF_FEI_YIN) and getMissionRankPoints(player,15) == 1) then
-- 5-2
first_mission = first_mission + 32768;
end
end
if (rank == 6) then
if (player:hasCompletedMission(SANDORIA,LEAUTE_S_LAST_WISHES) == false and getMissionRankPoints(player,16) == 1) then
-- 6-1
first_mission = first_mission + 65536;
elseif (player:hasCompletedMission(SANDORIA,RANPERRE_S_FINAL_REST) == false and getMissionRankPoints(player,17) == 1) then
-- 6-2
first_mission = first_mission + 131072;
end
end
if (rank == 7) then
if (player:hasCompletedMission(SANDORIA,PRESTIGE_OF_THE_PAPSQUE) == false and getMissionRankPoints(player,18) == 1) then
-- 7-1
first_mission = first_mission + 262144;
elseif (player:hasCompletedMission(SANDORIA,THE_SECRET_WEAPON) == false and getMissionRankPoints(player,19) == 1) then
-- 7-2
first_mission = first_mission + 524288;
end
end
if (rank == 8) then
if (player:hasCompletedMission(SANDORIA,COMING_OF_AGE) == false and getMissionRankPoints(player,20) == 1) then
-- 8-1
first_mission = first_mission + 1048576;
elseif (player:hasCompletedMission(SANDORIA,LIGHTBRINGER) == false and getMissionRankPoints(player,21) == 1 and player:getVar("Mission8-1Completed") == 1) then
-- 8-2
first_mission = first_mission + 2097152;
end
end
if (rank == 9) then
if (player:hasCompletedMission(SANDORIA,BREAKING_BARRIERS) == false and getMissionRankPoints(player,22) == 1) then
-- 9-1
first_mission = first_mission + 4194304;
elseif (player:hasCompletedMission(SANDORIA,BREAKING_BARRIERS) == false and getMissionRankPoints(player,22) == 1 and player:getVar("Cutscenes_8-2") == 2) then
-- 9-2
first_mission = first_mission + 8388608;
elseif (player:hasCompletedMission(SANDORIA,THE_HEIR_TO_THE_LIGHT) == false and getMissionRankPoints(player,23) == 1) then
-- 9-2
first_mission = first_mission + 8388608;
end
end
elseif (nation == BASTOK) then
if (rank >= 1) then
if (player:hasCompletedMission(BASTOK,THE_ZERUHN_REPORT) == false) then
-- 1-1 NOTE: This mission will not be listed in the Mission List for Bastok
--first_mission = first_mission + 1;
end
if (player:hasCompletedMission(BASTOK,GEOLOGICAL_SURVEY) == false) then
-- 1-2 NOTE: This mission will not be listed in the Mission List for Bastok
first_mission = first_mission + 2;
end
if (player:hasCompletedMission(BASTOK,GEOLOGICAL_SURVEY) == true) then
-- 1-3
repeat_mission = repeat_mission + 4;
end
end
if (rank >= 2) then
-- 2-1
if (player:hasCompletedMission(BASTOK,THE_CRYSTAL_LINE) == false and getMissionRankPoints(player,3) == 1) then
first_mission = first_mission + 8;
else
if (rank > 2 or getMissionRankPoints(player,4) == 1) then
-- 2-2 Repeatable
repeat_mission = repeat_mission + 16;
end
if (player:hasCompletedMission(BASTOK,THE_EMISSARY) == false and getMissionRankPoints(player,5) == 1) then
-- 2-3
first_mission = first_mission + 32;
end
end
end
if (rank >= 3) then
-- 3-1
if (player:hasCompletedMission(BASTOK,THE_FOUR_MUSKETEERS) == false and getMissionRankPoints(player,10) == 1) then
first_mission = first_mission + 1024;
else
if (rank > 3 or getMissionRankPoints(player,11) == 1) then
-- 3-2 Repeatable & Skippable
repeat_mission = repeat_mission + 2048;
end
if (player:hasCompletedMission(BASTOK,JEUNO_MISSION) == false and getMissionRankPoints(player,12) == 1) then
-- 3-3
first_mission = first_mission + 4096;
end
end
end
if (rank == 4) then
-- The mission is triggered by the Ambassador in Jeuno
-- first_mission = first_mission + 8192;
end
if (rank == 5) then
if (player:hasCompletedMission(BASTOK,DARKNESS_RISING) == false and getMissionRankPoints(player,0) == 1 and mission_status == 0) then
first_mission = first_mission + 16384;
end
if (player:hasCompletedMission(BASTOK,DARKNESS_RISING) and player:hasCompletedMission(BASTOK,XARCABARD_LAND_OF_TRUTHS) == false and getMissionRankPoints(player,15) == 1) then
-- 5-2
first_mission = first_mission + 32768;
end
end
if (rank == 6) then
if (player:hasCompletedMission(BASTOK,RETURN_OF_THE_TALEKEEPER) == false and getMissionRankPoints(player,16) == 1) then
-- 6-1
first_mission = first_mission + 65536;
elseif (player:hasCompletedMission(BASTOK,THE_PIRATE_S_COVE) == false and getMissionRankPoints(player,17) == 1) then
-- 6-2
first_mission = first_mission + 131072;
end
end
if (rank == 7) then
if (player:hasCompletedMission(BASTOK,THE_FINAL_IMAGE) == false and getMissionRankPoints(player,18) == 1) then
-- 7-1
first_mission = first_mission + 262144;
elseif (player:hasCompletedMission(BASTOK,ON_MY_WAY) == false and getMissionRankPoints(player,19) == 1) then
-- 7-2
first_mission = first_mission + 524288;
end
end
if (rank == 8) then
if (player:hasCompletedMission(BASTOK,THE_CHAINS_THAT_BIND_US) == false and getMissionRankPoints(player,20) == 1) then
-- 8-1
first_mission = first_mission + 1048576;
elseif (player:hasCompletedMission(BASTOK,ENTER_THE_TALEKEEPER) == false and getMissionRankPoints(player,21) == 1) then
-- 8-2
first_mission = first_mission + 2097152;
end
end
if (rank == 9) then
if (player:hasCompletedMission(BASTOK,THE_SALT_OF_THE_EARTH) == false and getMissionRankPoints(player,22) == 1) then
-- 9-1
first_mission = first_mission + 4194304;
elseif (player:hasCompletedMission(BASTOK,WHERE_TWO_PATHS_CONVERGE) == false and getMissionRankPoints(player,23) == 1) then
-- 9-2
first_mission = first_mission + 8388608;
end
end
end
if (player:getCurrentMission(nation) == THE_RUINS_OF_FEI_YIN and player:getVar("MissionStatus") == 8) then
mission_mask = 2147483647 - 16384;
else
mission_mask = 2147483647 - repeat_mission - first_mission; -- 2^31 -1 - ..
end
return mission_mask,repeat_mission;
end;
function getMissionOffset(player,guard,pMission,MissionStatus)
offset = 0; cs = 0; params = {0,0,0,0,0,0,0,0};
nation = player:getNation();
if (nation == SANDORIA) then
if (guard == 1) then GuardCS = {0x03fe,0x03fd,0x0401,0x03ec,0x0400,0x03ed,0x03ee,0x0404,0x0405,0x03f4,0x0407};
elseif (guard == 2) then GuardCS = {0x07e6,0x07e5,0x07e9,0x07d4,0x07e8,0x07d5,0x07d6,0x07ec,0x07ed,0x07dc,0x07ef};
end
switch (pMission) : caseof {
[0] = function (x) offset = 0; end, -- Mission 1-1
[1] = function (x) if (MissionStatus == 2) then cs = GuardCS[1]; else cs = GuardCS[2]; end end, -- Mission 1-2 (1) after check tombstone
[2] = function (x) if (MissionStatus == 0) then cs = GuardCS[3]; -- Mission 1-3 before Battlefield
elseif (MissionStatus == 4 and player:hasCompletedMission(0,2) == false) then cs = GuardCS[4]; -- Mission 1-3 after Battlefield
elseif (MissionStatus == 4) then cs = GuardCS[5]; else offset = 24; end end, -- Mission 1-3 after Battlefield (Finish Quest)
[3] = function (x) if (MissionStatus == 11) then cs = GuardCS[6]; else offset = 36; end end,
[4] = function (x) if (MissionStatus == 3 and player:hasCompletedMission(0,4)) then cs = GuardCS[7];
elseif (MissionStatus == 3) then cs = GuardCS[8]; params = {0,0,0,44}; else offset = 44; end end,
[5] = function (x) if (MissionStatus == 0) then offset = 50; else offset = 51; end end,
[10] = function (x) if (MissionStatus == 0) then cs = GuardCS[9];
elseif (MissionStatus == 4) then offset = 55;
elseif (MissionStatus == 5) then offset = 60;
elseif (MissionStatus == 10) then cs = GuardCS[10]; end end,
[11] = function (x) if (MissionStatus == 0) then offset = 68;
elseif (MissionStatus == 2) then cs = GuardCS[11]; end end,
[12] = function (x) if (MissionStatus == 0) then offset = 74; end end,
[14] = function (x) if (MissionStatus == 0) then cs = 0x003D; end end,
}
return cs, params, offset;
elseif (nation == BASTOK) then
switch (pMission) : caseof {
[0] = function (x) offset = 0; end,
[1] = function (x) offset = 3; end,
[2] = function (x) offset = 6; end,
[3] = function (x) offset = 19; end,
[4] = function (x) offset = 21; end,
[5] = function (x) offset = 23; end,
[10] = function (x) offset = 27; end,
[11] = function (x) offset = 30; end,
[12] = function (x) offset = 35; end,
[14] = function (x) cs = 0x03EF; end,
[15] = function (x) offset = 39; end,
[16] = function (x) offset = 0; end,
[17] = function (x) offset = 3; end,
[18] = function (x) offset = 5; end,
[19] = function (x) offset = 7; end,
[20] = function (x) offset = 10; end,
[21] = function (x) offset = 12; end,
[22] = function (x) offset = 14; end,
[23] = function (x) offset = 19; end,
}
return cs, params, offset;
elseif (nation == WINDURST) then
if (guard == 1) then GuardCS = {0x007F,0x0088,0x0096,0x009A,0x00A0,0x01D9,0x00b1};
elseif (guard == 2) then GuardCS = {0x007b,0x0083,0x0136,0x0094,0x009c,0x00b1,0x00d7};
elseif (guard == 3) then GuardCS = {0x0059,0x0069,0x006e,0x0072,0x0078,0x0085,0x008a};
elseif (guard == 4) then GuardCS = {0x0063,0x006b,0x0070,0x0074,0x007a,0x007f,0x0086};
end
switch (pMission) : caseof {
[0] = function (x) cs = GuardCS[1]; end,
[1] = function (x) cs = GuardCS[2]; end,
[2] = function (x) if (MissionStatus <= 2) then cs = GuardCS[3]; else cs = GuardCS[4]; end end,
[3] = function (x) cs = GuardCS[5]; end,
[4] = function (x) cs = GuardCS[6]; end,
[5] = function (x) cs = GuardCS[7]; end,
}
return cs, params, offset;
end
end;
function finishMissionTimeline(player,guard,csid,option)
nation = player:getNation();
-- To prevent the cs conflict, use the 1st and 2nd for guard and 3/4 for npc
-- missionid, {Guard1CS,option}, {Guard2CS,option}, {NPC1 CS,option}, {NPC2 CS,option}, {{function,value},...},
-- 1: player:addMission(nation,mission);
-- 2: player:messageSpecial(YOU_ACCEPT_THE_MISSION);
-- 3: player:setVar(variablename,value);
-- 4: player:tradeComplete();
-- 5: player:addRankPoints(number);
-- 6: player:setRankPoints(0);
-- 7: player:addPoint(player:getNation(),number); player:messageSpecial(YOUVE_EARNED_CONQUEST_POINTS);
-- 8: player:addGil(GIL_RATE*number); player:messageSpecial(GIL_OBTAINED,GIL_RATE*number);
-- 9: player:delKeyItem(number);
-- 10: player:addKeyItem(number); player:messageSpecial(KEYITEM_OBTAINED,number);
-- 11: player:setRank(number);
-- 12: player:completeMission(nation,mission);
-- 13: player:addTitle(number);
-- 14: player:setVar("MissionStatus",value);
if (nation == SANDORIA) then
if ((csid == 0x03f1 or csid == 0x07d9) and option ~= 1073741824 and option ~= 31) then
if (option > 100) then
badoption = {101,1,102,2,104,4,110,10,111,11};
for op = 1, table.getn(badoption), 2 do
if (option == badoption[op]) then
timeline = {badoption[op+1],{0x03f1,badoption[op]},{0x07d9,badoption[op]},{0,0},{0,0},{{1},{2}}}; end
end
elseif (option == 14) then
timeline = {option,{0x03f1,option},{0x07d9,option},{0,0},{0,0},{{1},{2},{3,"MissionStatus",9}}};
else
timeline = {option,{0x03f1,option},{0x07d9,option},{0,0},{0,0},{{1},{2}}};
end
else
timeline = {
-- MissionID,{Guard#1 DialogID, option},{Guard#2 DialogID, option},{NPC#1 DialogID, option},{NPC#2 DialogID, option},{function list}
0,{0x03e8,0},{0x07d0,0},{0,0}, {0,0},{{1},{2}}, -- MISSION 1-1 (First Mission [START])
0,{0x03fc,0},{0x07e4,0},{0,0}, {0,0},{{4},{5,150},{12},{14,0}}, -- MISSION 1-1
0,{0x03ea,0},{0x07d2,0},{0,0}, {0,0},{{4},{5,150},{12}}, -- MISSION 1-1 [Repeat]
1,{0x03ff,0},{0x07e7,0},{0,0}, {0,0},{{4},{14,0},{5,200},{12}}, -- MISSION 1-2
1,{0x03eb,0},{0x07d3,0},{0,0}, {0,0},{{4},{14,0},{5,200},{12}}, -- MISSION 1-2 [Repeat]
2,{0x03ec,0},{0x07d4,0},{0,0}, {0,0},{{11,2},{3,"OptionalCSforSTC",1},{14,0},{6},{8,1000},{12}}, -- MISSION 1-3
2,{0x0400,0},{0x07e8,0},{0,0}, {0,0},{{14,0},{5,250},{12}}, -- MISSION 1-3 [Repeat]
3,{0x03ed,0},{0x07d5,0},{0,0}, {0,0},{{9,65},{14,0},{5,300},{12}}, -- MISSION 2-1
4,{0,0}, {0,0}, {0x02b7,0},{0,0},{{9,44},{14,0},{5,350},{12}}, -- MISSION 2-2 (Papal Chambers)
5,{0,0}, {0,0}, {0x01fb,0},{0,0},{{10,35},{6},{13,207},{8,3000},{11,3},{9,29},{14,0},{12}}, -- MISSION 2-3 (Halver)
10,{0,0}, {0,0}, {0x022a,0},{0,0},{{9,237},{14,0},{5,400},{12}}, -- MISSION 3-1 (Prince Trion (door))
10,{0x03f4,0},{0x07dc,0},{0,0}, {0,0},{{14,0},{5,300},{12}}, -- MISSION 3-1 (Guard)[Repeat]
11,{0x0406,0},{0x07ee,0},{0,0}, {0,0},{{4},{14,2}}, -- MISSION 3-2 (dialog with the guard after trade)
11,{0,0}, {0,0}, {0x022c,0},{0,0},{{14,0},{5,400},{12}}, -- MISSION 3-2 (Chalvatot)
11,{0x03f5,0},{0x07dd,0},{0,0}, {0,0},{{4},{14,0},{5,400},{12}}, -- MISSION 3-2 (Guard)[Repeat]
12,{0,0}, {0,0}, {0x0027,0},{0,0},{{11,4},{14,0},{6},{8,5000},{12}}, -- MISSION 3-3 (Finish (Nelcabrit))
13,{0,0}, {0,0}, {0x0024,0},{0,0},{{11,5},{14,0},{13,212},{10,69},{6},{8,10000},{12},{1,14}}, -- MISSION 4-1 (Finish (Nelcabrit))
14,{0,0}, {0,0}, {0x0215,0},{0,0},{{10,72},{14,10}}, -- MISSION 5-1 (Finish (Halver))
14,{0,0}, {0,0}, {0x0216,0},{0,0},{{9,73},{5,400},{14,0},{13,10},{12}}, -- MISSION 5-1 (Finish (Halver))
15,{0,0}, {0,0}, {0x0224,0},{0,0},{{11,6},{14,5}}, -- MISSION 5-2 (Finish 1st Part (Halver))
15,{0,0}, {0,0}, {0x003D,0},{0,0},{{14,0},{9,74},{8,20000},{6},{12}}, -- MISSION 5-2 (Finish 2nd Part (Trion in Great Hall))
16,{0,0}, {0,0}, {0x006f,0},{0,0},{{14,0},{9,268},{10,270},{12}}, -- MISSION 6-1 (Finish (Chalvatot))
17,{0x040a,0},{0x0409,0},{0,0},{0,0},{{14,0},{11,7},{8,40000},{6},{12}}, -- MISSION 6-2 (Finish (Guard))
18,{0,0}, {0,0}, {0x0007,0},{0,0},{{14,1}}, -- MISSION 7-1 (setVar("MissionStatus",1) (Door: Papal Chambers))
18,{0,0}, {0,0}, {0x0008,0},{0,0},{{14,0},{9,283},{5,1000},{12}}, -- MISSION 7-1 (Finish (Door: Papal Chambers))
19,{0x0414,0},{0x0413,0},{0,0},{0,0},{{14,0},{6},{3,"SecretWeaponStatus",0},{9,284},{11,8},{8,60000},{12}}, -- MISSION 7-2 (Finish)
20,{0,0}, {0,0}, {0x0066,0},{0,0},{{14,0},{9,288},{5,800},{12}}, -- MISSION 8-1 (Finish)
21,{0,0}, {0,0}, {0x0068,0},{0,0},{{14,0},{9,284},{11,9},{8,80000},{6},{12}}, -- MISSION 8-2 (Finish (Door: Great Hall))
22,{0,0}, {0,0}, {0x004c,0},{0,0},{{14,0},{9,481},{9,482},{9,483},{5,900},{12}} -- MISSION 9-1 (Finish (Door: Great Hall))
--[[0,{0,0},{0,0},{0,0},{0,0},{0},{0,0},{0,0},{0,0},{0,0},{0},
0,{0,0},{0,0},{0,0},{0,0},{0},{0,0},{0,0},{0,0},{0,0},{0}, ]]--
};
end
elseif (nation == BASTOK) then
if (csid == 0x03E9 and option ~= 1073741824 and option ~= 31) then
timeline = {option,{0x03E9,option},{0,0},{0,0},{0,0},{{1},{2}}};
else
timeline = {
0,{0x03e8,0},{0,0},{0,0},{0,0},{{1},{2}}, -- MISSION 1-1 (First Mission [START])
1,{0x01f8,0},{0,0},{0,0},{0,0},{{9,4},{12}}, -- MISSION 1-2 (Finish Mission)
2,{0x03F0,0},{0,0},{0,0},{0,0},{{4},{11,2},{8,1000},{12}}, -- MISSION 1-3
2,{0x03ED,0},{0,0},{0,0},{0,0},{{4},{8,1000},{12}}, -- MISSION 1-3 [Repeat]
3,{0x02c8,0},{0,0},{0,0},{0,0},{{9,12},{14,0},{5,200},{12}}, -- MISSION 2-1 (Finish (Ayame))
4,{0x0174,0},{0,0},{0,0},{0,0},{{4},{5,250},{12}}, -- MISSION 2-2 (Finish (Alois))
4,{0x0175,0},{0,0},{0,0},{0,0},{{4},{5,250},{12}}, -- MISSION 2-2 (Finish (Alois)) [Repeat]
5,{0x02ca,0},{0,0},{0,0},{0,0},{{10,35},{6},{13,207},{8,3000},{11,3},{9,29},{14,0},{12}}, -- MISSION 2-3 (Finish (Naji))
10,{0x000b,0},{0,0},{0,0},{0,0},{{14,0},{5,350},{12}}, -- MISSION 3-1 (Pashhow Marshlands Zone)
11,{0x03F2,0},{0,0},{0,0},{0,0},{{4},{5,400},{12}}, -- MISSION 3-2
11,{0x03EE,0},{0,0},{0,0},{0,0},{{4},{5,400},{12}}, -- MISSION 3-2 [Repeat]
12,{0x0026,0},{0,0},{0,0},{0,0},{{11,4},{14,0},{6},{8,5000},{12}}, -- MISSION 3-3 (Finish (Goggehn))
13,{0x0023,0},{0,0},{0,0},{0,0},{{11,5},{14,0},{13,212},{10,70},{6},{8,10000},{12},{1,14}}, -- MISSION 4-1 (Finish (Goggehn))
14,{0x02d2,0},{0,0},{0,0},{0,0},{{14,0},{9,73},{5,600},{12}}, -- MISSION 5-1 (Finish (Naji))
15,{0x025b,0},{0,0},{0,0},{0,0},{{11,6},{14,0},{9,74},{8,20000},{6},{12}}, -- MISSION 5-2 (Finish (Karst))
16,{0x00b6,0},{0,0},{0,0},{0,0},{{14,0},{9,266},{5,650},{12}}, -- MISSION 6-1 (Finish (Tall Mountain))
17,{0x02fa,0},{0,0},{0,0},{0,0},{{14,0},{6},{11,7},{8,40000},{12}}, -- MISSION 6-2 (Finish (Naji))
18,{0x02fc,0},{0,0},{0,0},{0,0},{{14,0},{9,289},{5,700},{12}}, -- MISSION 7-1 (Finish (Cid))
19,{0x02fe,0},{0,0},{0,0},{0,0},{{14,0},{6},{11,8},{8,60000},{3,"OptionalCSforOMW",1},{12}}, -- MISSION 7-2 (Finish (Karst))
20,{0x0300,0},{0,0},{0,0},{0,0},{{14,0},{5,1133},{12}}, -- MISSION 8-1 (Finish (Iron Eater))
21,{0x00b0,0},{0,0},{0,0},{0,0},{{14,0},{6},{11,9},{9,293},{8,80000},{12}}, -- MISSION 8-2 (Finish (Bastok Mines))
};
end
elseif (nation == WINDURST) then
guardlist = {0x0072,0x006f,0x004e,0x005d};
if (csid == guardlist[guard] and option ~= 1073741824 and option ~= 31) then
timeline = {option,{guardlist[guard],option},{guardlist[guard],option},{guardlist[guard],option},{guardlist[guard],option},{{1},{2}}};
else
timeline = {
0,{0x0079,1},{0x0076,1},{0x0053,1},{0x0060,1},{{1},{2}}, -- MISSION 1-1 (First Mission [START])
0,{0x005e,0},{0,0}, {0,0}, {0,0}, {{14,0},{5,150},{9,28},{12}}, -- MISSION 1-1 (Finish (Hakkuru-Rinkuru))
1,{0x0084,1},{0x0082,1},{0x0068,1},{0x006a,1},{{1},{2}}, -- MISSION 1-2 [START]
1,{0x008f,0},{0,0}, {0,0}, {0,0}, {{14,0},{5,200},{12}}, -- MISSION 1-2 (Finish (Apururu)) [WITHOUT ORB]
1,{0x0091,0},{0,0}, {0,0}, {0,0}, {{14,0},{5,250},{12}}, -- MISSION 1-2 (Finish (Apururu)) [WITH ORB]
2,{0x0095,2},{0x0083,2},{0x006d,2},{0x006f,2},{{1},{2}}, -- MISSION 1-3 [START]
2,{0x009A,0},{0x0094,0},{0x0072,0},{0x0074,0},{{11,2},{14,0},{5,300},{8,1000},{12}}, -- MISSION 1-3
3,{0x00a8,0},{0,0}, {0,0}, {0,0}, {{14,0},{5,350},{12}}, -- MISSION 2-1 (Finish (Tosuka-Porika))
4,{0x00C9,0},{0,0}, {0,0}, {0,0}, {{14,0},{9,38},{5,400},{12}}, -- MISSION 2-2 (Finish (Moreno-Toeno)) (+35 mob killed)
4,{0x00CE,0},{0,0}, {0,0}, {0,0}, {{14,0},{9,38},{5,400},{12}}, -- MISSION 2-2 (Finish (Moreno-Toeno)) (+35 mob killed) [Repeat]
4,{0x00C8,0},{0,0}, {0,0}, {0,0}, {{14,0},{9,38},{5,250},{12}}, -- MISSION 2-2 (Finish (Moreno-Toeno)) (30-34 mob killed)
4,{0x00D1,0},{0,0}, {0,0}, {0,0}, {{14,0},{9,38},{5,250},{12}}, -- MISSION 2-2 (Finish (Moreno-Toeno)) (30-34 mob killed) [Repeat]
5,{0x0065,0},{0,0}, {0,0}, {0,0}, {{10,35},{6},{13,207},{8,3000},{11,3},{9,29},{14,0},{12}},-- MISSION 2-3 (Finish (Kupipi))
10,{0,0}, {0x0072,0},{0,0}, {0,0}, {{5,450},{14,0},{12}}, -- MISSION 3-1 (Finish (Rhy Epocan))
11,{0x0087,0},{0,0}, {0,0}, {0,0}, {{5,500},{14,0},{12}}, -- MISSION 3-2 (Finish (Zubaba))
11,{0x0097,0},{0,0}, {0,0}, {0,0}, {{5,400},{14,0},{12}}, -- MISSION 3-2 (Finish (Zubaba)) [Repeat]
12,{0x0028,0},{0,0}, {0,0}, {0,0}, {{11,4},{9,30},{14,0},{6},{8,5000},{12}}, -- MISSION 3-3 (Finish (Ambassador's door))
13,{0x0025,0},{0,0}, {0,0}, {0,0}, {{11,5},{14,0},{13,212},{10,71},{6},{8,10000},{12}}, -- MISSION 4-1 (Finish (Pakh Jatalfih))
14,{0x00C0,0},{0,0}, {0,0}, {0,0}, {{14,0},{9,73},{5,600},{12}}, -- MISSION 5-1 (Finish (Star Sibyl))
15,{0x00D8,0},{0,0}, {0,0}, {0,0}, {{11,6},{14,0},{9,74},{8,20000},{6},{12}}, -- MISSION 5-2 (Finish (Star Sibyl))
16,{0,0}, {0,0}, {0x0032,0},{0,0}, {{14,0},{5,650},{0,0},{0,0},{0,0},{12}}, -- MISSION 6-1 (Finish (Zone: Full Moon Fountain))
17,{0,0}, {0,0}, {0x0138,0},{0,0}, {{14,0},{11,7},{8,40000},{6},{0,0},{12}}, -- MISSION 6-2 (Finish (Star Sibyl))
18,{0,0}, {0,0}, {0x02d4,0},{0,0}, {{14,0},{5,700},{10,251},{0,0},{0,0},{12}}, -- MISSION 7-1 (Finish (Tosuka-Porika))
19,{0,0}, {0,0}, {0x02E6,0},{0,0}, {{14,0},{11,8},{8,60000},{6},{0,0},{12}}, -- MISSION 7-2 (Finish (Leepe-Hoppe))
20,{0,0}, {0,0}, {0x02F6,0},{0,0}, {{14,0},{5,750},{0,0},{0},{0,0},{12}}, -- MISSION 8-1 (Finish (Morno-Toeno))
21,{0,0}, {0,0}, {0x0261,0},{0,0}, {{14,0},{11,9},{8,80000},{6},{0,0},{12}}, -- MISSION 8-2 (Finish (Apururu))
22,{0,0}, {0,0}, {0x003D,0},{0,0}, {{14,0},{5,800},{13,293},{0},{0,0},{12}}, -- MISSION 9-1 (Finish (Zone: Full Moon Fountain))
23,{0,0}, {0,0}, {0x0197,0},{0,0}, {{13,294},{11,10},{8,100000},{6},{0,0},{12}} -- MISSION 9-2 (Finish (Vestal Chamber))
};
end
end
for cs = 1, table.getn(timeline), 6 do
if (csid == timeline[cs + guard][1] and option == timeline[cs + guard][2]) then
for nb = 1, table.getn(timeline[cs + 5]), 1 do
messList = timeline[cs + 5][nb];
switch (messList[1]) : caseof {
[1] = function (x) if (messList[2] ~= nil) then player:addMission(nation,messList[2]); else player:addMission(nation,timeline[cs]); end end,
[2] = function (x) player:messageSpecial(YOU_ACCEPT_THE_MISSION); end,
[3] = function (x) player:setVar(messList[2],messList[3]); end,
[4] = function (x) player:tradeComplete(); end,
[5] = function (x) if ((player:getRankPoints() + messList[2]) > 4000) then player:setRankPoints(4000); else player:addRankPoints(messList[2]); end end,
[6] = function (x) player:setRankPoints(0); end,
[7] = function (x) player:addCP(messList[2]); player:messageSpecial(YOUVE_EARNED_CONQUEST_POINTS); end,
[8] = function (x) player:addGil(GIL_RATE*messList[2]); player:messageSpecial(GIL_OBTAINED,GIL_RATE*messList[2]); end,
[9] = function (x) player:delKeyItem(messList[2]); end,
[10] = function (x) player:addKeyItem(messList[2]); player:messageSpecial(KEYITEM_OBTAINED,messList[2]); end,
[11] = function (x) player:setRank(messList[2]); end,
[12] = function (x) player:completeMission(nation,timeline[cs]); end,
[13] = function (x) player:addTitle(messList[2]); end,
[14] = function (x) player:setVar("MissionStatus",messList[2]); end,
}
end
end
end
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Temenos/mobs/Goblin_Slaughterman.lua | 16 | 1072 | -----------------------------------
-- Area: Temenos N T
-- NPC: Goblin_Slaughterman
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (mobID ==16928773) then
GetNPCByID(16928768+18):setPos(330,70,468);
GetNPCByID(16928768+18):setStatus(STATUS_NORMAL);
elseif (mobID ==16928772) then
GetNPCByID(16928770+450):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
gpedro/server | data/scripts/otstd/actions/rope.lua | 3 | 1329 | otstd.rope = {}
otstd.ropes = {
[2120] = {},
[6392] = {},
[7731] = {}
}
otstd.ropespots = {
[384] = {},
[418] = {}
}
function otstd.rope.callback(event)
local toPos = event.targetPosition
local tile = toPos and map:getTile(toPos)
if not tile then
return
end
local hole = tile:getThing(toPos.stackpos)
if not hole or not typeof(hole, "Item") then
return
end
for spotid, _ in pairs(otstd.ropespots) do
if spotid == hole:getItemID() then
-- Rope up player
local npos = hole:getPosition()
npos.y = npos.y + 1
npos.z = npos.z - 1
event.player:moveTo(npos)
return
end
end
for spotid, _ in pairs(otstd.holes) do
if spotid == hole:getItemID() then
-- Rope up item
local pos = hole:getPosition()
pos.z = pos.z + 1
local spottile = map:getTile(pos)
if spottile then
local top = spottile:getTopMoveableThing()
if top then
local npos = hole:getPosition()
npos.y = npos.y + 1
top:moveTo(npos)
return
end
end
end
end
event.retval = RET_NOTPOSSIBLE
end
function otstd.rope.registerHandlers()
for id, data in pairs(otstd.ropes) do
if data.listener ~= nil then
stopListener(data.listener)
end
data.listener =
registerOnUseItemNearby("itemid", id, otstd.rope.callback)
end
end
otstd.rope.registerHandlers()
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Mazween.lua | 34 | 1639 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Mazween
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MAZWEEN_SHOP_DIALOG);
stock = {0x1313,11200, -- Scroll of Sleepga
0x12A6,18720, -- Scroll of Sleep II
0x1292,25200, -- Poison II
0x12E7,14000, -- Bio II
0x1296,5160, -- Poisonga
0x1316,19932, -- Stone III
4779,22682, -- Water III
0x12DD,27744, -- Aero III
0x129C,33306, -- Fire III
0x12E1,39368, -- Blizzard III
0x12F6,45930, -- Thunder III
0x1303,27000, -- Absorb-TP
0x1311,44000, -- Absorb-ACC
0x12A1,30780, -- Drain II
0x1315,70560, -- Dread Spikes
4856,79800} -- Aspir II
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 |
niello/deusexmachina | Deps/CEGUI/cegui/src/ScriptModules/Lua/support/tolua++bin/lua/container.lua | 15 | 16995 | -- tolua: container abstract class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id$
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- table to store namespaced typedefs/enums in global scope
global_typedefs = {}
global_enums = {}
-- Container class
-- Represents a container of features to be bound
-- to lua.
classContainer =
{
curr = nil,
}
classContainer.__index = classContainer
setmetatable(classContainer,classFeature)
-- output tags
function classContainer:decltype ()
push(self)
local i=1
while self[i] do
self[i]:decltype()
i = i+1
end
pop()
end
-- write support code
function classContainer:supcode ()
if not self:check_public_access() then
return
end
push(self)
local i=1
while self[i] do
if self[i]:check_public_access() then
self[i]:supcode()
end
i = i+1
end
pop()
end
function classContainer:hasvar ()
local i=1
while self[i] do
if self[i]:isvariable() then
return 1
end
i = i+1
end
return 0
end
-- Internal container constructor
function _Container (self)
setmetatable(self,classContainer)
self.n = 0
self.typedefs = {tolua_n=0}
self.usertypes = {}
self.enums = {tolua_n=0}
self.lnames = {}
return self
end
-- push container
function push (t)
t.prox = classContainer.curr
classContainer.curr = t
end
-- pop container
function pop ()
--print("name",classContainer.curr.name)
--foreach(classContainer.curr.usertypes,print)
--print("______________")
classContainer.curr = classContainer.curr.prox
end
-- get current namespace
function getcurrnamespace ()
return getnamespace(classContainer.curr)
end
-- append to current container
function append (t)
return classContainer.curr:append(t)
end
-- append typedef to current container
function appendtypedef (t)
return classContainer.curr:appendtypedef(t)
end
-- append usertype to current container
function appendusertype (t)
return classContainer.curr:appendusertype(t)
end
-- append enum to current container
function appendenum (t)
return classContainer.curr:appendenum(t)
end
-- substitute typedef
function applytypedef (mod,type)
return classContainer.curr:applytypedef(mod,type)
end
-- check if is type
function findtype (type)
local t = classContainer.curr:findtype(type)
return t
end
-- check if is typedef
function istypedef (type)
return classContainer.curr:istypedef(type)
end
-- get fulltype (with namespace)
function fulltype (t)
local curr = classContainer.curr
while curr do
if curr then
if curr.typedefs and curr.typedefs[t] then
return curr.typedefs[t]
elseif curr.usertypes and curr.usertypes[t] then
return curr.usertypes[t]
end
end
curr = curr.prox
end
return t
end
-- checks if it requires collection
function classContainer:requirecollection (t)
push(self)
local i=1
local r = false
while self[i] do
r = self[i]:requirecollection(t) or r
i = i+1
end
pop()
return r
end
-- get namesapce
function getnamespace (curr)
local namespace = ''
while curr do
if curr and
( curr.classtype == 'class' or curr.classtype == 'namespace')
then
namespace = (curr.original_name or curr.name) .. '::' .. namespace
--namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- get namespace (only namespace)
function getonlynamespace ()
local curr = classContainer.curr
local namespace = ''
while curr do
if curr.classtype == 'class' then
return namespace
elseif curr.classtype == 'namespace' then
namespace = curr.name .. '::' .. namespace
end
curr = curr.prox
end
return namespace
end
-- check if is enum
function isenum (type)
return classContainer.curr:isenum(type)
end
-- append feature to container
function classContainer:append (t)
self.n = self.n + 1
self[self.n] = t
t.parent = self
end
-- append typedef
function classContainer:appendtypedef (t)
local namespace = getnamespace(classContainer.curr)
self.typedefs.tolua_n = self.typedefs.tolua_n + 1
self.typedefs[self.typedefs.tolua_n] = t
self.typedefs[t.utype] = namespace .. t.utype
global_typedefs[namespace..t.utype] = t
t.ftype = findtype(t.type) or t.type
--print("appending typedef "..t.utype.." as "..namespace..t.utype.." with ftype "..t.ftype)
append_global_type(namespace..t.utype)
if t.ftype and isenum(t.ftype) then
global_enums[namespace..t.utype] = true
end
end
-- append usertype: return full type
function classContainer:appendusertype (t)
local container
if t == (self.original_name or self.name) then
container = self.prox
else
container = self
end
local ft = getnamespace(container) .. t
container.usertypes[t] = ft
_usertype[ft] = ft
return ft
end
-- append enum
function classContainer:appendenum (t)
local namespace = getnamespace(classContainer.curr)
self.enums.tolua_n = self.enums.tolua_n + 1
self.enums[self.enums.tolua_n] = t
global_enums[namespace..t.name] = t
end
-- determine lua function name overload
function classContainer:overload (lname)
if not self.lnames[lname] then
self.lnames[lname] = 0
else
self.lnames[lname] = self.lnames[lname] + 1
end
return format("%02d",self.lnames[lname])
end
-- applies typedef: returns the 'the facto' modifier and type
function classContainer:applytypedef (mod,type)
if global_typedefs[type] then
--print("found typedef "..global_typedefs[type].type)
local mod1, type1 = global_typedefs[type].mod, global_typedefs[type].ftype
local mod2, type2 = applytypedef(mod.." "..mod1, type1)
--return mod2 .. ' ' .. mod1, type2
return mod2, type2
end
do return mod,type end
end
-- check if it is a typedef
function classContainer:istypedef (type)
local env = self
while env do
if env.typedefs then
local i=1
while env.typedefs[i] do
if env.typedefs[i].utype == type then
return type
end
i = i+1
end
end
env = env.parent
end
return nil
end
function find_enum_var(var)
if tonumber(var) then return var end
local c = classContainer.curr
while c do
local ns = getnamespace(c)
for k,v in pairs(_global_enums) do
if match_type(var, v, ns) then
return v
end
end
if c.base and c.base ~= '' then
c = _global_classes[c:findtype(c.base)]
else
c = nil
end
end
return var
end
-- check if is a registered type: return full type or nil
function classContainer:findtype (t)
t = string.gsub(t, "=.*", "")
if _basic[t] then
return t
end
local _,_,em = string.find(t, "([&%*])%s*$")
t = string.gsub(t, "%s*([&%*])%s*$", "")
p = self
while p and type(p)=='table' do
local st = getnamespace(p)
for i=_global_types.n,1,-1 do -- in reverse order
if match_type(t, _global_types[i], st) then
return _global_types[i]..(em or "")
end
end
if p.base and p.base ~= '' and p.base ~= t then
--print("type is "..t..", p is "..p.base.." self.type is "..self.type.." self.name is "..self.name)
p = _global_classes[p:findtype(p.base)]
else
p = nil
end
end
return nil
end
function append_global_type(t, class)
_global_types.n = _global_types.n +1
_global_types[_global_types.n] = t
_global_types_hash[t] = 1
if class then append_class_type(t, class) end
end
function append_class_type(t,class)
if _global_classes[t] then
class.flags = _global_classes[t].flags
class.lnames = _global_classes[t].lnames
if _global_classes[t].base and (_global_classes[t].base ~= '') then
class.base = _global_classes[t].base or class.base
end
end
_global_classes[t] = class
class.flags = class.flags or {}
end
function match_type(childtype, regtype, st)
--print("findtype "..childtype..", "..regtype..", "..st)
local b,e = string.find(regtype, childtype, -string.len(childtype), true)
if b then
if e == string.len(regtype) and
(b == 1 or (string.sub(regtype, b-1, b-1) == ':' and
string.sub(regtype, 1, b-1) == string.sub(st, 1, b-1))) then
return true
end
end
return false
end
function findtype_on_childs(self, t)
local tchild
if self.classtype == 'class' or self.classtype == 'namespace' then
for k,v in ipairs(self) do
if v.classtype == 'class' or v.classtype == 'namespace' then
if v.typedefs and v.typedefs[t] then
return v.typedefs[t]
elseif v.usertypes and v.usertypes[t] then
return v.usertypes[t]
end
tchild = findtype_on_childs(v, t)
if tchild then return tchild end
end
end
end
return nil
end
function classContainer:isenum (type)
if global_enums[type] then
return type
else
return false
end
local basetype = gsub(type,"^.*::","")
local env = self
while env do
if env.enums then
local i=1
while env.enums[i] do
if env.enums[i].name == basetype then
return true
end
i = i+1
end
end
env = env.parent
end
return false
end
methodisvirtual = false -- a global
-- parse chunk
function classContainer:doparse (s)
--print ("parse "..s)
-- try the parser hook
do
local sub = parser_hook(s)
if sub then
return sub
end
end
-- try the null statement
do
local b,e,code = string.find(s, "^%s*;")
if b then
return strsub(s,e+1)
end
end
-- try empty verbatim line
do
local b,e,code = string.find(s, "^%s*$\n")
if b then
return strsub(s,e+1)
end
end
-- try Lua code
do
local b,e,code = strfind(s,"^%s*(%b\1\2)")
if b then
Code(strsub(code,2,-2))
return strsub(s,e+1)
end
end
-- try C code
do
local b,e,code = strfind(s,"^%s*(%b\3\4)")
if b then
code = '{'..strsub(code,2,-2)..'\n}\n'
Verbatim(code,'r') -- verbatim code for 'r'egister fragment
return strsub(s,e+1)
end
end
-- try C code for preamble section
do
local b,e,code = string.find(s, "^%s*(%b\5\6)")
if b then
code = string.sub(code, 2, -2).."\n"
Verbatim(code, '')
return string.sub(s, e+1)
end
end
-- try default_property directive
do
local b,e,ptype = strfind(s, "^%s*TOLUA_PROPERTY_TYPE%s*%(+%s*([^%)%s]*)%s*%)+%s*;?")
if b then
if not ptype or ptype == "" then
ptype = "default"
end
self:set_property_type(ptype)
return strsub(s, e+1)
end
end
-- try protected_destructor directive
do
local b,e = string.find(s, "^%s*TOLUA_PROTECTED_DESTRUCTOR%s*;?")
if b then
if self.set_protected_destructor then
self:set_protected_destructor(true)
end
return strsub(s, e+1)
end
end
-- try 'extern' keyword
do
local b,e = string.find(s, "^%s*extern%s+")
if b then
-- do nothing
return strsub(s, e+1)
end
end
-- try 'virtual' keyworkd
do
local b,e = string.find(s, "^%s*virtual%s+")
if b then
methodisvirtual = true
return strsub(s, e+1)
end
end
-- try labels (public, private, etc)
do
local b,e = string.find(s, "^%s*%w*%s*:[^:]")
if b then
return strsub(s, e) -- preserve the [^:]
end
end
-- try module
do
local b,e,name,body = strfind(s,"^%s*module%s%s*([_%w][_%w]*)%s*(%b{})%s*")
if b then
_curr_code = strsub(s,b,e)
Module(name,body)
return strsub(s,e+1)
end
end
-- try namesapce
do
local b,e,name,body = strfind(s,"^%s*namespace%s%s*([_%w][_%w]*)%s*(%b{})%s*;?")
if b then
_curr_code = strsub(s,b,e)
Namespace(name,body)
return strsub(s,e+1)
end
end
-- try define
do
local b,e,name = strfind(s,"^%s*#define%s%s*([^%s]*)[^\n]*\n%s*")
if b then
_curr_code = strsub(s,b,e)
Define(name)
return strsub(s,e+1)
end
end
-- try enumerates
do
local b,e,name,body,varname = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*([^%s;]*)%s*;?%s*")
if b then
--error("#Sorry, declaration of enums and variables on the same statement is not supported.\nDeclare your variable separately (example: '"..name.." "..varname..";')")
_curr_code = strsub(s,b,e)
Enumerate(name,body,varname)
return strsub(s,e+1)
end
end
-- do
-- local b,e,name,body = strfind(s,"^%s*enum%s+(%S*)%s*(%b{})%s*;?%s*")
-- if b then
-- _curr_code = strsub(s,b,e)
-- Enumerate(name,body)
-- return strsub(s,e+1)
-- end
-- end
do
local b,e,body,name = strfind(s,"^%s*typedef%s+enum[^{]*(%b{})%s*([%w_][^%s]*)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Enumerate(name,body)
return strsub(s,e+1)
end
end
-- try operator
do
local b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:<>,]-%s+operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
if not b then
-- try inline
b,e,decl,kind,arg,const = strfind(s,"^%s*([_%w][_%w%s%*&:<>,]-%s+operator)%s*([^%s][^%s]*)%s*(%b())%s*(c?o?n?s?t?)[%s\n]*%b{}%s*;?%s*")
end
if not b then
-- try cast operator
b,e,decl,kind,arg,const = strfind(s, "^%s*(operator)%s+([%w_:%d<>%*%&%s]+)%s*(%b())%s*(c?o?n?s?t?)");
if b then
local _,ie = string.find(s, "^%s*%b{}", e+1)
if ie then
e = ie
end
end
end
if b then
_curr_code = strsub(s,b,e)
Operator(decl,kind,arg,const)
return strsub(s,e+1)
end
end
-- try function
do
--local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w])%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
local b,e,decl,arg,const,virt = strfind(s,"^%s*([^%(\n]+)%s*(%b())%s*(c?o?n?s?t?)%s*(=?%s*0?)%s*;%s*")
if not b then
-- try function with template
b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w]%b<>)%s*(%b())%s*(c?o?n?s?t?)%s*=?%s*0?%s*;%s*")
end
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?)%s*;%s*")
end
if b then
if virt and string.find(virt, "[=0]") then
if self.flags then
self.flags.pure_virtual = true
end
end
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try inline function
do
local b,e,decl,arg,const = strfind(s,"^%s*([^%(\n]+)%s*(%b())%s*(c?o?n?s?t?)[^;{]*%b{}%s*;?%s*")
--local b,e,decl,arg,const = strfind(s,"^%s*([~_%w][_@%w%s%*&:<>]*[_%w>])%s*(%b())%s*(c?o?n?s?t?)[^;]*%b{}%s*;?%s*")
if not b then
-- try a single letter function name
b,e,decl,arg,const = strfind(s,"^%s*([_%w])%s*(%b())%s*(c?o?n?s?t?).-%b{}%s*;?%s*")
end
if b then
_curr_code = strsub(s,b,e)
Function(decl,arg,const)
return strsub(s,e+1)
end
end
-- try class
do
local b,e,name,base,body
base = '' body = ''
b,e,name = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*;") -- dummy class
if not b then
b,e,name = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*;") -- dummy struct
if not b then
b,e,name,base,body = strfind(s,"^%s*class%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*struct%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
b,e,name,base,body = strfind(s,"^%s*union%s*([_%w][_%w@]*)%s*(.-)%s*(%b{})%s*;%s*")
if not b then
base = ''
b,e,body,name = strfind(s,"^%s*typedef%s%s*struct%s%s*[_%w]*%s*(%b{})%s*([_%w][_%w@]*)%s*;%s*")
end
end
end
end
end
if b then
if base ~= '' then
base = string.gsub(base, "^%s*:%s*", "")
base = string.gsub(base, "%s*public%s*", "")
base = split(base, ",")
--local b,e
--b,e,base = strfind(base,".-([_%w][_%w<>,:]*)$")
else
base = {}
end
_curr_code = strsub(s,b,e)
Class(name,base,body)
return strsub(s,e+1)
end
end
-- try typedef
do
local b,e,types = strfind(s,"^%s*typedef%s%s*(.-)%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Typedef(types)
return strsub(s,e+1)
end
end
-- try variable
do
local b,e,decl = strfind(s,"^%s*([_%w][_@%s%w%d%*&:<>,]*[_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
local list = split_c_tokens(decl, ",")
Variable(list[1])
if list.n > 1 then
local _,_,type = strfind(list[1], "(.-)%s+([^%s]*)$");
local i =2;
while list[i] do
Variable(type.." "..list[i])
i=i+1
end
end
--Variable(decl)
return strsub(s,e+1)
end
end
-- try string
do
local b,e,decl = strfind(s,"^%s*([_%w]?[_%s%w%d]-char%s+[_@%w%d]*%s*%[%s*%S+%s*%])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Variable(decl)
return strsub(s,e+1)
end
end
-- try array
do
local b,e,decl = strfind(s,"^%s*([_%w][][_@%s%w%d%*&:]*[]_%w%d])%s*;%s*")
if b then
_curr_code = strsub(s,b,e)
Array(decl)
return strsub(s,e+1)
end
end
-- no matching
if gsub(s,"%s%s*","") ~= "" then
_curr_code = s
error("#parse error")
else
return ""
end
end
function classContainer:parse (s)
self.curr_member_access = nil
while s ~= '' do
s = self:doparse(s)
methodisvirtual = false
end
end
-- property types
function get_property_type()
return classContainer.curr:get_property_type()
end
function classContainer:set_property_type(ptype)
ptype = string.gsub(ptype, "^%s*", "")
ptype = string.gsub(ptype, "%s*$", "")
self.property_type = ptype
end
function classContainer:get_property_type()
return self.property_type or (self.parent and self.parent:get_property_type()) or "default"
end
| mit |
n0xus/darkstar | scripts/zones/Port_Windurst/npcs/Sigismund.lua | 36 | 2342 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Sigismund
-- Starts and Finishes Quest: To Catch a Falling Star
-- Working 100%
-- @zone = 240
-- @pos = -110 -10 82
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
starstatus = player:getQuestStatus(WINDURST,TO_CATCH_A_FALLIHG_STAR);
if (starstatus == 1 and trade:hasItemQty(546,1) == true and trade:getItemCount() == 1 and trade:getGil() == 0) then
player:startEvent(0x00c7); -- Quest Finish
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
starstatus = player:getQuestStatus(WINDURST,TO_CATCH_A_FALLIHG_STAR);
if (starstatus == QUEST_AVAILABLE) then
player:startEvent(0x00c4,0,546); -- Quest Start
elseif (starstatus == QUEST_ACCEPTED) then
player:startEvent(0x00c5,0,546); -- Quest Reminder
elseif (starstatus == QUEST_COMPLETED and player:getVar("QuestCatchAFallingStar_prog") > 0) then
player:startEvent(0x00c8); -- After Quest
player:setVar("QuestCatchAFallingStar_prog",0)
else
player:startEvent(0x0165);
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 == 0x00c4) then
player:addQuest(WINDURST,TO_CATCH_A_FALLIHG_STAR);
elseif (csid == 0x00c7) then
player:tradeComplete(trade);
player:completeQuest(WINDURST,TO_CATCH_A_FALLIHG_STAR);
player:addFame(WINDURST,WIN_FAME*75);
player:addItem(12316);
player:messageSpecial(ITEM_OBTAINED,12316);
player:setVar("QuestCatchAFallingStar_prog",2);
end
end;
| gpl-3.0 |
chengyi818/openwrt | customer/packages/luci/modules/admin-mini/luasrc/controller/mini/index.lua | 79 | 1429 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.mini.index", package.seeall)
function index()
local root = node()
if not root.lock then
root.target = alias("mini")
root.index = true
end
entry({"about"}, template("about"))
local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10)
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.index = true
entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true
entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true
entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10)
entry({"mini", "index", "logout"}, call("action_logout"), _("Logout"))
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| gpl-2.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/modules/admin-mini/luasrc/controller/mini/index.lua | 79 | 1429 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
module("luci.controller.mini.index", package.seeall)
function index()
local root = node()
if not root.lock then
root.target = alias("mini")
root.index = true
end
entry({"about"}, template("about"))
local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10)
page.sysauth = "root"
page.sysauth_authenticator = "htmlauth"
page.index = true
entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true
entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true
entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10)
entry({"mini", "index", "logout"}, call("action_logout"), _("Logout"))
end
function action_logout()
local dsp = require "luci.dispatcher"
local sauth = require "luci.sauth"
if dsp.context.authsession then
sauth.kill(dsp.context.authsession)
dsp.context.urltoken.stok = nil
end
luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url())
luci.http.redirect(luci.dispatcher.build_url())
end
| gpl-2.0 |
chengyi818/openwrt | customer/packages/luci/applications/luci-statistics/luasrc/model/cbi/luci_statistics/email.lua | 78 | 1934 | --[[
Luci configuration model for statistics - collectd email plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
m = Map("luci_statistics",
translate("E-Mail Plugin Configuration"),
translate(
"The email plugin creates a unix socket which can be used " ..
"to transmit email-statistics to a running collectd daemon. " ..
"This plugin is primarily intended to be used in conjunction " ..
"with Mail::SpamAssasin::Plugin::Collectd but can be used in " ..
"other ways as well."
))
-- collectd_email config section
s = m:section( NamedSection, "collectd_email", "luci_statistics" )
-- collectd_email.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_email.socketfile (SocketFile)
socketfile = s:option( Value, "SocketFile", translate("Socket file") )
socketfile.default = "/var/run/collect-email.sock"
socketfile:depends( "enable", 1 )
-- collectd_email.socketgroup (SocketGroup)
socketgroup = s:option( Value, "SocketGroup", translate("Socket group") )
socketgroup.default = "nobody"
socketgroup.rmempty = true
socketgroup.optional = true
socketgroup:depends( "enable", 1 )
-- collectd_email.socketperms (SocketPerms)
socketperms = s:option( Value, "SocketPerms", translate("Socket permissions") )
socketperms.default = "0770"
socketperms.rmempty = true
socketperms.optional = true
socketperms:depends( "enable", 1 )
-- collectd_email.maxconns (MaxConns)
maxconns = s:option( Value, "MaxConns", translate("Maximum allowed connections") )
maxconns.default = 5
maxconns.isinteger = true
maxconns.rmempty = true
maxconns.optional = true
maxconns:depends( "enable", 1 )
return m
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Ifrits_Cauldron/npcs/qm4.lua | 16 | 1477 | -----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: ???
-- Involved in Mission: Bastok 6-2
-- @pos 171 0 -25 205
-----------------------------------
package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Ifrits_Cauldron/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getCurrentMission(BASTOK) == THE_PIRATE_S_COVE and player:getVar("MissionStatus") == 2) then
if (GetMobAction(17616897) == 0 and GetMobAction(17616898) == 0 and trade:hasItemQty(646,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(17616897):updateClaim(player);
SpawnMob(17616898):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 |
ppriest/mame | 3rdparty/genie/tests/base/test_path.lua | 52 | 6597 | --
-- tests/base/test_path.lua
-- Automated test suite for the action list.
-- Copyright (c) 2008-2010 Jason Perkins and the Premake project
--
T.path = { }
local suite = T.path
--
-- path.getabsolute() tests
--
function suite.getabsolute_ReturnsCorrectPath_OnMissingSubdir()
local expected = path.translate(os.getcwd(), "/") .. "/a/b/c"
test.isequal(expected, path.getabsolute("a/b/c"))
end
function suite.getabsolute_RemovesDotDots_OnWindowsAbsolute()
test.isequal("c:/ProjectB/bin", path.getabsolute("c:/ProjectA/../ProjectB/bin"))
end
function suite.getabsolute_RemovesDotDots_OnPosixAbsolute()
test.isequal("/ProjectB/bin", path.getabsolute("/ProjectA/../ProjectB/bin"))
end
function suite.getabsolute_OnTrailingSlash()
local expected = path.translate(os.getcwd(), "/") .. "/a/b/c"
test.isequal(expected, path.getabsolute("a/b/c/"))
end
function suite.getabsolute_OnLeadingEnvVar()
test.isequal("$(HOME)/user", path.getabsolute("$(HOME)/user"))
end
function suite.getabsolute_OnMultipleEnvVar()
test.isequal("$(HOME)/$(USER)", path.getabsolute("$(HOME)/$(USER)"))
end
function suite.getabsolute_OnTrailingEnvVar()
local expected = path.translate(os.getcwd(), "/") .. "/home/$(USER)"
test.isequal(expected, path.getabsolute("home/$(USER)"))
end
--
-- path.getbasename() tests
--
function suite.getbasename_ReturnsCorrectName_OnDirAndExtension()
test.isequal("filename", path.getbasename("folder/filename.ext"))
end
--
-- path.getdirectory() tests
--
function suite.getdirectory_ReturnsEmptyString_OnNoDirectory()
test.isequal(".", path.getdirectory("filename.ext"))
end
function suite.getdirectory_ReturnsDirectory_OnSingleLevelPath()
test.isequal("dir0", path.getdirectory("dir0/filename.ext"))
end
function suite.getdirectory_ReturnsDirectory_OnMultiLeveLPath()
test.isequal("dir0/dir1/dir2", path.getdirectory("dir0/dir1/dir2/filename.ext"))
end
function suite.getdirectory_ReturnsRootPath_OnRootPathOnly()
test.isequal("/", path.getdirectory("/filename.ext"))
end
--
-- path.getdrive() tests
--
function suite.getdrive_ReturnsNil_OnNotWindows()
test.isnil(path.getdrive("/hello"))
end
function suite.getdrive_ReturnsLetter_OnWindowsAbsolute()
test.isequal("x", path.getdrive("x:/hello"))
end
--
-- path.getextension() tests
--
function suite.getextension_ReturnsEmptyString_OnNoExtension()
test.isequal("", path.getextension("filename"))
end
function suite.getextension_ReturnsExtension()
test.isequal(".txt", path.getextension("filename.txt"))
end
function suite.getextension_OnMultipleDots()
test.isequal(".txt", path.getextension("filename.mod.txt"))
end
function suite.getextension_OnLeadingNumeric()
test.isequal(".7z", path.getextension("filename.7z"))
end
function suite.getextension_OnUnderscore()
test.isequal(".a_c", path.getextension("filename.a_c"))
end
function suite.getextension_OnHyphen()
test.isequal(".a-c", path.getextension("filename.a-c"))
end
--
-- path.getrelative() tests
--
function suite.getrelative_ReturnsDot_OnMatchingPaths()
test.isequal(".", path.getrelative("/a/b/c", "/a/b/c"))
end
function suite.getrelative_ReturnsDoubleDot_OnChildToParent()
test.isequal("..", path.getrelative("/a/b/c", "/a/b"))
end
function suite.getrelative_ReturnsDoubleDot_OnSiblingToSibling()
test.isequal("../d", path.getrelative("/a/b/c", "/a/b/d"))
end
function suite.getrelative_ReturnsChildPath_OnParentToChild()
test.isequal("d", path.getrelative("/a/b/c", "/a/b/c/d"))
end
function suite.getrelative_ReturnsChildPath_OnWindowsAbsolute()
test.isequal("obj/debug", path.getrelative("C:/Code/Premake4", "C:/Code/Premake4/obj/debug"))
end
function suite.getrelative_ReturnsAbsPath_OnDifferentDriveLetters()
test.isequal("D:/Files", path.getrelative("C:/Code/Premake4", "D:/Files"))
end
function suite.getrelative_ReturnsAbsPath_OnDollarMacro()
test.isequal("$(SDK_HOME)/include", path.getrelative("C:/Code/Premake4", "$(SDK_HOME)/include"))
end
function suite.getrelative_ReturnsAbsPath_OnRootedPath()
test.isequal("/opt/include", path.getrelative("/home/me/src/project", "/opt/include"))
end
--
-- path.isabsolute() tests
--
function suite.isabsolute_ReturnsTrue_OnAbsolutePosixPath()
test.istrue(path.isabsolute("/a/b/c"))
end
function suite.isabsolute_ReturnsTrue_OnAbsoluteWindowsPathWithDrive()
test.istrue(path.isabsolute("C:/a/b/c"))
end
function suite.isabsolute_ReturnsFalse_OnRelativePath()
test.isfalse(path.isabsolute("a/b/c"))
end
function suite.isabsolute_ReturnsTrue_OnDollarSign()
test.istrue(path.isabsolute("$(SDK_HOME)/include"))
end
--
-- path.join() tests
--
function suite.join_OnValidParts()
test.isequal("p1/p2", path.join("p1", "p2"))
end
function suite.join_OnAbsoluteUnixPath()
test.isequal("/p2", path.join("p1", "/p2"))
end
function suite.join_OnAbsoluteWindowsPath()
test.isequal("C:/p2", path.join("p1", "C:/p2"))
end
function suite.join_OnCurrentDirectory()
test.isequal("p2", path.join(".", "p2"))
end
function suite.join_OnNilSecondPart()
test.isequal("p1", path.join("p1", nil))
end
function suite.join_onMoreThanTwoParts()
test.isequal("p1/p2/p3", path.join("p1", "p2", "p3"))
end
function suite.join_removesExtraInternalSlashes()
test.isequal("p1/p2", path.join("p1/", "p2"))
end
function suite.join_removesTrailingSlash()
test.isequal("p1/p2", path.join("p1", "p2/"))
end
function suite.join_ignoresNilParts()
test.isequal("p2", path.join(nil, "p2", nil))
end
function suite.join_ignoresEmptyParts()
test.isequal("p2", path.join("", "p2", ""))
end
--
-- path.rebase() tests
--
function suite.rebase_WithEndingSlashOnPath()
local cwd = os.getcwd()
test.isequal("src", path.rebase("../src/", cwd, path.getdirectory(cwd)))
end
--
-- path.translate() tests
--
function suite.translate_ReturnsTranslatedPath_OnValidPath()
test.isequal("dir/dir/file", path.translate("dir\\dir\\file", "/"))
end
function suite.translate_ReturnsCorrectSeparator_OnMixedPath()
local actual = path.translate("dir\\dir/file")
if (os.is("windows")) then
test.isequal("dir\\dir\\file", actual)
else
test.isequal("dir/dir/file", actual)
end
end
--
-- path.wildcards tests
--
function suite.wildcards_MatchesTrailingStar()
local p = path.wildcards("**/xcode/*")
test.isequal(".*/xcode/[^/]*", p)
end
function suite.wildcards_MatchPlusSign()
local patt = path.wildcards("file+name.*")
local name = "file+name.c"
test.isequal(name, name:match(patt))
end
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm15.lua | 25 | 1460 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm15 (???)
-- Involved in Quest: Hitting the Marquisate (THF AF3)
-- @pos 19.893 -5.500 325.767 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 8) then
player:messageSpecial(HEAT_FROM_CEILING);
-- TODO: player must wait 10 minutes before they can spawn bomb again
SpawnMob(17596533,120):updateClaim(player); -- Chandelier
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/FriendListColors/libs/AceGUI-3.0/widgets/AceGUIContainer-DropDownGroup.lua | 65 | 4515 | --[[-----------------------------------------------------------------------------
DropdownGroup Container
Container controlled by a dropdown on the top.
-------------------------------------------------------------------------------]]
local Type, Version = "DropdownGroup", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local assert, pairs, type = assert, pairs, type
-- WoW APIs
local CreateFrame = CreateFrame
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function SelectedGroup(self, event, value)
local group = self.parentgroup
local status = group.status or group.localstatus
status.selected = value
self.parentgroup:Fire("OnGroupSelected", value)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self.dropdown:SetText("")
self:SetDropdownWidth(200)
self:SetTitle("")
end,
["OnRelease"] = function(self)
self.dropdown.list = nil
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end,
["SetTitle"] = function(self, title)
self.titletext:SetText(title)
self.dropdown.frame:ClearAllPoints()
if title and title ~= "" then
self.dropdown.frame:SetPoint("TOPRIGHT", -2, 0)
else
self.dropdown.frame:SetPoint("TOPLEFT", -1, 0)
end
end,
["SetGroupList"] = function(self,list,order)
self.dropdown:SetList(list,order)
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
end,
["SetGroup"] = function(self,group)
self.dropdown:SetValue(group)
local status = self.status or self.localstatus
status.selected = group
self:Fire("OnGroupSelected", group)
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local contentwidth = width - 26
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - 63
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["LayoutFinished"] = function(self, width, height)
self:SetHeight((height or 0) + 63)
end,
["SetDropdownWidth"] = function(self, width)
self.dropdown:SetWidth(width)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local function Constructor()
local frame = CreateFrame("Frame")
frame:SetHeight(100)
frame:SetWidth(100)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
local titletext = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
titletext:SetPoint("TOPLEFT", 4, -5)
titletext:SetPoint("TOPRIGHT", -4, -5)
titletext:SetJustifyH("LEFT")
titletext:SetHeight(18)
local dropdown = AceGUI:Create("Dropdown")
dropdown.frame:SetParent(frame)
dropdown.frame:SetFrameLevel(dropdown.frame:GetFrameLevel() + 2)
dropdown:SetCallback("OnValueChanged", SelectedGroup)
dropdown.frame:SetPoint("TOPLEFT", -1, 0)
dropdown.frame:Show()
dropdown:SetLabel("")
local border = CreateFrame("Frame", nil, frame)
border:SetPoint("TOPLEFT", 0, -26)
border:SetPoint("BOTTOMRIGHT", 0, 3)
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1,0.1,0.1,0.5)
border:SetBackdropBorderColor(0.4,0.4,0.4)
--Container Support
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -10)
content:SetPoint("BOTTOMRIGHT", -10, 10)
local widget = {
frame = frame,
localstatus = {},
titletext = titletext,
dropdown = dropdown,
border = border,
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
dropdown.parentgroup = widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/Skada/lib/AceGUI-3.0-SharedMediaWidgets/Libs/AceGUI-3.0/widgets/AceGUIContainer-DropDownGroup.lua | 65 | 4515 | --[[-----------------------------------------------------------------------------
DropdownGroup Container
Container controlled by a dropdown on the top.
-------------------------------------------------------------------------------]]
local Type, Version = "DropdownGroup", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local assert, pairs, type = assert, pairs, type
-- WoW APIs
local CreateFrame = CreateFrame
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function SelectedGroup(self, event, value)
local group = self.parentgroup
local status = group.status or group.localstatus
status.selected = value
self.parentgroup:Fire("OnGroupSelected", value)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self.dropdown:SetText("")
self:SetDropdownWidth(200)
self:SetTitle("")
end,
["OnRelease"] = function(self)
self.dropdown.list = nil
self.status = nil
for k in pairs(self.localstatus) do
self.localstatus[k] = nil
end
end,
["SetTitle"] = function(self, title)
self.titletext:SetText(title)
self.dropdown.frame:ClearAllPoints()
if title and title ~= "" then
self.dropdown.frame:SetPoint("TOPRIGHT", -2, 0)
else
self.dropdown.frame:SetPoint("TOPLEFT", -1, 0)
end
end,
["SetGroupList"] = function(self,list,order)
self.dropdown:SetList(list,order)
end,
["SetStatusTable"] = function(self, status)
assert(type(status) == "table")
self.status = status
end,
["SetGroup"] = function(self,group)
self.dropdown:SetValue(group)
local status = self.status or self.localstatus
status.selected = group
self:Fire("OnGroupSelected", group)
end,
["OnWidthSet"] = function(self, width)
local content = self.content
local contentwidth = width - 26
if contentwidth < 0 then
contentwidth = 0
end
content:SetWidth(contentwidth)
content.width = contentwidth
end,
["OnHeightSet"] = function(self, height)
local content = self.content
local contentheight = height - 63
if contentheight < 0 then
contentheight = 0
end
content:SetHeight(contentheight)
content.height = contentheight
end,
["LayoutFinished"] = function(self, width, height)
self:SetHeight((height or 0) + 63)
end,
["SetDropdownWidth"] = function(self, width)
self.dropdown:SetWidth(width)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local PaneBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\Tooltips\\UI-Tooltip-Border",
tile = true, tileSize = 16, edgeSize = 16,
insets = { left = 3, right = 3, top = 5, bottom = 3 }
}
local function Constructor()
local frame = CreateFrame("Frame")
frame:SetHeight(100)
frame:SetWidth(100)
frame:SetFrameStrata("FULLSCREEN_DIALOG")
local titletext = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
titletext:SetPoint("TOPLEFT", 4, -5)
titletext:SetPoint("TOPRIGHT", -4, -5)
titletext:SetJustifyH("LEFT")
titletext:SetHeight(18)
local dropdown = AceGUI:Create("Dropdown")
dropdown.frame:SetParent(frame)
dropdown.frame:SetFrameLevel(dropdown.frame:GetFrameLevel() + 2)
dropdown:SetCallback("OnValueChanged", SelectedGroup)
dropdown.frame:SetPoint("TOPLEFT", -1, 0)
dropdown.frame:Show()
dropdown:SetLabel("")
local border = CreateFrame("Frame", nil, frame)
border:SetPoint("TOPLEFT", 0, -26)
border:SetPoint("BOTTOMRIGHT", 0, 3)
border:SetBackdrop(PaneBackdrop)
border:SetBackdropColor(0.1,0.1,0.1,0.5)
border:SetBackdropBorderColor(0.4,0.4,0.4)
--Container Support
local content = CreateFrame("Frame", nil, border)
content:SetPoint("TOPLEFT", 10, -10)
content:SetPoint("BOTTOMRIGHT", -10, 10)
local widget = {
frame = frame,
localstatus = {},
titletext = titletext,
dropdown = dropdown,
border = border,
content = content,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
dropdown.parentgroup = widget
return AceGUI:RegisterAsContainer(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Misareaux_Coast/npcs/_0p8.lua | 17 | 1782 | -----------------------------------
-- Area: Misareaux Coast
-- NPC: Iron Gate
-- Entrance to Sacrarium
-----------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local currentCoP = player:getCurrentMission(COP);
local PromathiaStatus = player:getVar("PromathiaStatus");
if (currentCoP == THE_SECRETS_OF_WORSHIP and PromathiaStatus == 1) then
player:startEvent(0x0009);
elseif (player:hasCompletedMission(COP,THE_LAST_VERSE) or (currentCoP == THE_SECRETS_OF_WORSHIP and PromathiaStatus >= 2)or(currentCoP > THE_SECRETS_OF_WORSHIP)) then
player:startEvent(0x01f6);
else
player:messageSpecial(DOOR_CLOSED);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0009 and option == 1) then
player:setVar("PromathiaStatus",2);
player:setPos(-220.075,-15.999,79.634,62,28); -- To Sacrarium {R}
elseif (csid == 0x01f6 and option == 1) then
player:setPos(-220.075,-15.999,79.634,62,28); -- To Sacrarium {R}
end
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Lower_Jeuno/npcs/_l04.lua | 36 | 1559 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -73.039 6 -95.633
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
if (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (player:getVar("cService") == 7) then
player:setVar("cService",8);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 20) then
player:setVar("cService",21);
end
end
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
mopplayer/BLESS | klib/lua/klib.lua | 42 | 20155 | --[[
The MIT License
Copyright (c) 2011, Attractive Chaos <attractor@live.co.uk>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
]]--
--[[
This is a Lua library, more exactly a collection of Lua snippets, covering
utilities (e.g. getopt), string operations (e.g. split), statistics (e.g.
Fisher's exact test), special functions (e.g. logarithm gamma) and matrix
operations (e.g. Gauss-Jordan elimination). The routines are designed to be
as independent as possible, such that one can copy-paste relevant pieces of
code without worrying about additional library dependencies.
If you use routines from this library, please include the licensing
information above where appropriate.
]]--
--[[
Library functions and dependencies. "a>b" means "a is required by b"; "b<a"
means "b depends on a".
os.getopt()
string:split()
io.xopen()
table.ksmall()
table.shuffle()
math.lgamma() >math.lbinom() >math.igamma()
math.igamma() <math.lgamma() >matrix.chi2()
math.erfc()
math.lbinom() <math.lgamma() >math.fisher_exact()
math.bernstein_poly() <math.lbinom()
math.fisher_exact() <math.lbinom()
math.jackknife()
math.pearson()
math.spearman()
math.fmin()
matrix
matrix.add()
matrix.T() >matrix.mul()
matrix.mul() <matrix.T()
matrix.tostring()
matrix.chi2() <math.igamma()
matrix.solve()
]]--
-- Description: getopt() translated from the BSD getopt(); compatible with the default Unix getopt()
--[[ Example:
for o, a in os.getopt(arg, 'a:b') do
print(o, a)
end
]]--
function os.getopt(args, ostr)
local arg, place = nil, 0;
return function ()
if place == 0 then -- update scanning pointer
place = 1
if #args == 0 or args[1]:sub(1, 1) ~= '-' then place = 0; return nil end
if #args[1] >= 2 then
place = place + 1
if args[1]:sub(2, 2) == '-' then -- found "--"
place = 0
table.remove(args, 1);
return nil;
end
end
end
local optopt = args[1]:sub(place, place);
place = place + 1;
local oli = ostr:find(optopt);
if optopt == ':' or oli == nil then -- unknown option
if optopt == '-' then return nil end
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
return '?';
end
oli = oli + 1;
if ostr:sub(oli, oli) ~= ':' then -- do not need argument
arg = nil;
if place > #args[1] then
table.remove(args, 1);
place = 0;
end
else -- need an argument
if place <= #args[1] then -- no white space
arg = args[1]:sub(place);
else
table.remove(args, 1);
if #args == 0 then -- an option requiring argument is the last one
place = 0;
if ostr:sub(1, 1) == ':' then return ':' end
return '?';
else arg = args[1] end
end
table.remove(args, 1);
place = 0;
end
return optopt, arg;
end
end
-- Description: string split
function string:split(sep, n)
local a, start = {}, 1;
sep = sep or "%s+";
repeat
local b, e = self:find(sep, start);
if b == nil then
table.insert(a, self:sub(start));
break
end
a[#a+1] = self:sub(start, b - 1);
start = e + 1;
if n and #a == n then
table.insert(a, self:sub(start));
break
end
until start > #self;
return a;
end
-- Description: smart file open
function io.xopen(fn, mode)
mode = mode or 'r';
if fn == nil then return io.stdin;
elseif fn == '-' then return (mode == 'r' and io.stdin) or io.stdout;
elseif fn:sub(-3) == '.gz' then return (mode == 'r' and io.popen('gzip -dc ' .. fn, 'r')) or io.popen('gzip > ' .. fn, 'w');
elseif fn:sub(-4) == '.bz2' then return (mode == 'r' and io.popen('bzip2 -dc ' .. fn, 'r')) or io.popen('bgzip2 > ' .. fn, 'w');
else return io.open(fn, mode) end
end
-- Description: find the k-th smallest element in an array (Ref. http://ndevilla.free.fr/median/)
function table.ksmall(arr, k)
local low, high = 1, #arr;
while true do
if high <= low then return arr[k] end
if high == low + 1 then
if arr[high] < arr[low] then arr[high], arr[low] = arr[low], arr[high] end;
return arr[k];
end
local mid = math.floor((high + low) / 2);
if arr[high] < arr[mid] then arr[mid], arr[high] = arr[high], arr[mid] end
if arr[high] < arr[low] then arr[low], arr[high] = arr[high], arr[low] end
if arr[low] < arr[mid] then arr[low], arr[mid] = arr[mid], arr[low] end
arr[mid], arr[low+1] = arr[low+1], arr[mid];
local ll, hh = low + 1, high;
while true do
repeat ll = ll + 1 until arr[ll] >= arr[low]
repeat hh = hh - 1 until arr[low] >= arr[hh]
if hh < ll then break end
arr[ll], arr[hh] = arr[hh], arr[ll];
end
arr[low], arr[hh] = arr[hh], arr[low];
if hh <= k then low = ll end
if hh >= k then high = hh - 1 end
end
end
-- Description: shuffle/permutate an array
function table.shuffle(a)
for i = #a, 1, -1 do
local j = math.random(i)
a[j], a[i] = a[i], a[j]
end
end
--
-- Mathematics
--
-- Description: log gamma function
-- Required by: math.lbinom()
-- Reference: AS245, 2nd algorithm, http://lib.stat.cmu.edu/apstat/245
function math.lgamma(z)
local x;
x = 0.1659470187408462e-06 / (z+7);
x = x + 0.9934937113930748e-05 / (z+6);
x = x - 0.1385710331296526 / (z+5);
x = x + 12.50734324009056 / (z+4);
x = x - 176.6150291498386 / (z+3);
x = x + 771.3234287757674 / (z+2);
x = x - 1259.139216722289 / (z+1);
x = x + 676.5203681218835 / z;
x = x + 0.9999999999995183;
return math.log(x) - 5.58106146679532777 - z + (z-0.5) * math.log(z+6.5);
end
-- Description: regularized incomplete gamma function
-- Dependent on: math.lgamma()
--[[
Formulas are taken from Wiki, with additional input from Numerical
Recipes in C (for modified Lentz's algorithm) and AS245
(http://lib.stat.cmu.edu/apstat/245).
A good online calculator is available at:
http://www.danielsoper.com/statcalc/calc23.aspx
It calculates upper incomplete gamma function, which equals
math.igamma(s,z,true)*math.exp(math.lgamma(s))
]]--
function math.igamma(s, z, complement)
local function _kf_gammap(s, z)
local sum, x = 1, 1;
for k = 1, 100 do
x = x * z / (s + k);
sum = sum + x;
if x / sum < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s + 1.) + math.log(sum));
end
local function _kf_gammaq(s, z)
local C, D, f, TINY;
f = 1. + z - s; C = f; D = 0.; TINY = 1e-290;
-- Modified Lentz's algorithm for computing continued fraction. See Numerical Recipes in C, 2nd edition, section 5.2
for j = 1, 100 do
local d;
local a, b = j * (s - j), j*2 + 1 + z - s;
D = b + a * D;
if D < TINY then D = TINY end
C = b + a / C;
if C < TINY then C = TINY end
D = 1. / D;
d = C * D;
f = f * d;
if math.abs(d - 1) < 1e-14 then break end
end
return math.exp(s * math.log(z) - z - math.lgamma(s) - math.log(f));
end
if complement then
return ((z <= 1 or z < s) and 1 - _kf_gammap(s, z)) or _kf_gammaq(s, z);
else
return ((z <= 1 or z < s) and _kf_gammap(s, z)) or (1 - _kf_gammaq(s, z));
end
end
math.M_SQRT2 = 1.41421356237309504880 -- sqrt(2)
math.M_SQRT1_2 = 0.70710678118654752440 -- 1/sqrt(2)
-- Description: complement error function erfc(x): \Phi(x) = 0.5 * erfc(-x/M_SQRT2)
function math.erfc(x)
local z = math.abs(x) * math.M_SQRT2
if z > 37 then return (x > 0 and 0) or 2 end
local expntl = math.exp(-0.5 * z * z)
local p
if z < 10. / math.M_SQRT2 then -- for small z
p = expntl * ((((((.03526249659989109 * z + .7003830644436881) * z + 6.37396220353165) * z + 33.912866078383)
* z + 112.0792914978709) * z + 221.2135961699311) * z + 220.2068679123761)
/ (((((((.08838834764831844 * z + 1.755667163182642) * z + 16.06417757920695) * z + 86.78073220294608)
* z + 296.5642487796737) * z + 637.3336333788311) * z + 793.8265125199484) * z + 440.4137358247522);
else p = expntl / 2.506628274631001 / (z + 1. / (z + 2. / (z + 3. / (z + 4. / (z + .65))))) end
return (x > 0 and 2 * p) or 2 * (1 - p)
end
-- Description: log binomial coefficient
-- Dependent on: math.lgamma()
-- Required by: math.fisher_exact()
function math.lbinom(n, m)
if m == nil then
local a = {};
a[0], a[n] = 0, 0;
local t = math.lgamma(n+1);
for m = 1, n-1 do a[m] = t - math.lgamma(m+1) - math.lgamma(n-m+1) end
return a;
else return math.lgamma(n+1) - math.lgamma(m+1) - math.lgamma(n-m+1) end
end
-- Description: Berstein polynomials (mainly for Bezier curves)
-- Dependent on: math.lbinom()
-- Note: to compute derivative: let beta_new[i]=beta[i+1]-beta[i]
function math.bernstein_poly(beta)
local n = #beta - 1;
local lbc = math.lbinom(n); -- log binomial coefficients
return function (t)
assert(t >= 0 and t <= 1);
if t == 0 then return beta[1] end
if t == 1 then return beta[n+1] end
local sum, logt, logt1 = 0, math.log(t), math.log(1-t);
for i = 0, n do sum = sum + beta[i+1] * math.exp(lbc[i] + i * logt + (n-i) * logt1) end
return sum;
end
end
-- Description: Fisher's exact test
-- Dependent on: math.lbinom()
-- Return: left-, right- and two-tail P-values
--[[
Fisher's exact test for 2x2 congintency tables:
n11 n12 | n1_
n21 n22 | n2_
-----------+----
n_1 n_2 | n
Reference: http://www.langsrud.com/fisher.htm
]]--
function math.fisher_exact(n11, n12, n21, n22)
local aux; -- keep the states of n* for acceleration
-- Description: hypergeometric function
local function hypergeo(n11, n1_, n_1, n)
return math.exp(math.lbinom(n1_, n11) + math.lbinom(n-n1_, n_1-n11) - math.lbinom(n, n_1));
end
-- Description: incremental hypergeometric function
-- Note: aux = {n11, n1_, n_1, n, p}
local function hypergeo_inc(n11, n1_, n_1, n)
if n1_ ~= 0 or n_1 ~= 0 or n ~= 0 then
aux = {n11, n1_, n_1, n, 1};
else -- then only n11 is changed
local mod;
_, mod = math.modf(n11 / 11);
if mod ~= 0 and n11 + aux[4] - aux[2] - aux[3] ~= 0 then
if n11 == aux[1] + 1 then -- increase by 1
aux[5] = aux[5] * (aux[2] - aux[1]) / n11 * (aux[3] - aux[1]) / (n11 + aux[4] - aux[2] - aux[3]);
aux[1] = n11;
return aux[5];
end
if n11 == aux[1] - 1 then -- descrease by 1
aux[5] = aux[5] * aux[1] / (aux[2] - n11) * (aux[1] + aux[4] - aux[2] - aux[3]) / (aux[3] - n11);
aux[1] = n11;
return aux[5];
end
end
aux[1] = n11;
end
aux[5] = hypergeo(aux[1], aux[2], aux[3], aux[4]);
return aux[5];
end
-- Description: computing the P-value by Fisher's exact test
local max, min, left, right, n1_, n_1, n, two, p, q, i, j;
n1_, n_1, n = n11 + n12, n11 + n21, n11 + n12 + n21 + n22;
max = (n_1 < n1_ and n_1) or n1_; -- max n11, for the right tail
min = n1_ + n_1 - n;
if min < 0 then min = 0 end -- min n11, for the left tail
two, left, right = 1, 1, 1;
if min == max then return 1 end -- no need to do test
q = hypergeo_inc(n11, n1_, n_1, n); -- the probability of the current table
-- left tail
i, left, p = min + 1, 0, hypergeo_inc(min, 0, 0, 0);
while p < 0.99999999 * q do
left, p, i = left + p, hypergeo_inc(i, 0, 0, 0), i + 1;
end
i = i - 1;
if p < 1.00000001 * q then left = left + p;
else i = i - 1 end
-- right tail
j, right, p = max - 1, 0, hypergeo_inc(max, 0, 0, 0);
while p < 0.99999999 * q do
right, p, j = right + p, hypergeo_inc(j, 0, 0, 0), j - 1;
end
j = j + 1;
if p < 1.00000001 * q then right = right + p;
else j = j + 1 end
-- two-tail
two = left + right;
if two > 1 then two = 1 end
-- adjust left and right
if math.abs(i - n11) < math.abs(j - n11) then right = 1 - left + q;
else left = 1 - right + q end
return left, right, two;
end
-- Description: Delete-m Jackknife
--[[
Given g groups of values with a statistics estimated from m[i] samples in
i-th group being t[i], compute the mean and the variance. t0 below is the
estimate from all samples. Reference:
Busing et al. (1999) Delete-m Jackknife for unequal m. Statistics and Computing, 9:3-8.
]]--
function math.jackknife(g, m, t, t0)
local h, n, sum = {}, 0, 0;
for j = 1, g do n = n + m[j] end
if t0 == nil then -- When t0 is absent, estimate it in a naive way
t0 = 0;
for j = 1, g do t0 = t0 + m[j] * t[j] end
t0 = t0 / n;
end
local mean, var = 0, 0;
for j = 1, g do
h[j] = n / m[j];
mean = mean + (1 - m[j] / n) * t[j];
end
mean = g * t0 - mean; -- Eq. (8)
for j = 1, g do
local x = h[j] * t0 - (h[j] - 1) * t[j] - mean;
var = var + 1 / (h[j] - 1) * x * x;
end
var = var / g;
return mean, var;
end
-- Description: Pearson correlation coefficient
-- Input: a is an n*2 table
function math.pearson(a)
-- compute the mean
local x1, y1 = 0, 0
for _, v in pairs(a) do
x1, y1 = x1 + v[1], y1 + v[2]
end
-- compute the coefficient
x1, y1 = x1 / #a, y1 / #a
local x2, y2, xy = 0, 0, 0
for _, v in pairs(a) do
local tx, ty = v[1] - x1, v[2] - y1
xy, x2, y2 = xy + tx * ty, x2 + tx * tx, y2 + ty * ty
end
return xy / math.sqrt(x2) / math.sqrt(y2)
end
-- Description: Spearman correlation coefficient
function math.spearman(a)
local function aux_func(t) -- auxiliary function
return (t == 1 and 0) or (t*t - 1) * t / 12
end
for _, v in pairs(a) do v.r = {} end
local T, S = {}, {}
-- compute the rank
for k = 1, 2 do
table.sort(a, function(u,v) return u[k]<v[k] end)
local same = 1
T[k] = 0
for i = 2, #a + 1 do
if i <= #a and a[i-1][k] == a[i][k] then same = same + 1
else
local rank = (i-1) * 2 - same + 1
for j = i - same, i - 1 do a[j].r[k] = rank end
if same > 1 then T[k], same = T[k] + aux_func(same), 1 end
end
end
S[k] = aux_func(#a) - T[k]
end
-- compute the coefficient
local sum = 0
for _, v in pairs(a) do -- TODO: use nested loops to reduce loss of precision
local t = (v.r[1] - v.r[2]) / 2
sum = sum + t * t
end
return (S[1] + S[2] - sum) / 2 / math.sqrt(S[1] * S[2])
end
-- Description: Hooke-Jeeves derivative-free optimization
function math.fmin(func, x, data, r, eps, max_calls)
local n, n_calls = #x, 0;
r = r or 0.5;
eps = eps or 1e-7;
max_calls = max_calls or 50000
function fmin_aux(x1, data, fx1, dx) -- auxiliary function
local ftmp;
for k = 1, n do
x1[k] = x1[k] + dx[k];
local ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp;
else -- search the opposite direction
dx[k] = -dx[k];
x1[k] = x1[k] + dx[k] + dx[k];
ftmp = func(x1, data); n_calls = n_calls + 1;
if ftmp < fx1 then fx1 = ftmp
else x1[k] = x1[k] - dx[k] end -- back to the original x[k]
end
end
return fx1; -- here: fx1=f(n,x1)
end
local dx, x1 = {}, {};
for k = 1, n do -- initial directions, based on MGJ
dx[k] = math.abs(x[k]) * r;
if dx[k] == 0 then dx[k] = r end;
end
local radius = r;
local fx1, fx;
fx = func(x, data); fx1 = fx; n_calls = n_calls + 1;
while true do
for i = 1, n do x1[i] = x[i] end; -- x1 = x
fx1 = fmin_aux(x1, data, fx, dx);
while fx1 < fx do
for k = 1, n do
local t = x[k];
dx[k] = (x1[k] > x[k] and math.abs(dx[k])) or -math.abs(dx[k]);
x[k] = x1[k];
x1[k] = x1[k] + x1[k] - t;
end
fx = fx1;
if n_calls >= max_calls then break end
fx1 = func(x1, data); n_calls = n_calls + 1;
fx1 = fmin_aux(x1, data, fx1, dx);
if fx1 >= fx then break end
local kk = n;
for k = 1, n do
if math.abs(x1[k] - x[k]) > .5 * math.abs(dx[k]) then
kk = k;
break;
end
end
if kk == n then break end
end
if radius >= eps then
if n_calls >= max_calls then break end
radius = radius * r;
for k = 1, n do dx[k] = dx[k] * r end
else break end
end
return fx1, n_calls;
end
--
-- Matrix
--
matrix = {}
-- Description: matrix transpose
-- Required by: matrix.mul()
function matrix.T(a)
local m, n, x = #a, #a[1], {};
for i = 1, n do
x[i] = {};
for j = 1, m do x[i][j] = a[j][i] end
end
return x;
end
-- Description: matrix add
function matrix.add(a, b)
assert(#a == #b and #a[1] == #b[1]);
local m, n, x = #a, #a[1], {};
for i = 1, m do
x[i] = {};
local ai, bi, xi = a[i], b[i], x[i];
for j = 1, n do xi[j] = ai[j] + bi[j] end
end
return x;
end
-- Description: matrix mul
-- Dependent on: matrix.T()
-- Note: much slower without transpose
function matrix.mul(a, b)
assert(#a[1] == #b);
local m, n, p, x = #a, #a[1], #b[1], {};
local c = matrix.T(b); -- transpose for efficiency
for i = 1, m do
x[i] = {}
local xi = x[i];
for j = 1, p do
local sum, ai, cj = 0, a[i], c[j];
for k = 1, n do sum = sum + ai[k] * cj[k] end
xi[j] = sum;
end
end
return x;
end
-- Description: matrix print
function matrix.tostring(a)
local z = {};
for i = 1, #a do
z[i] = table.concat(a[i], "\t");
end
return table.concat(z, "\n");
end
-- Description: chi^2 test for contingency tables
-- Dependent on: math.igamma()
function matrix.chi2(a)
if #a == 2 and #a[1] == 2 then -- 2x2 table
local x, z
x = (a[1][1] + a[1][2]) * (a[2][1] + a[2][2]) * (a[1][1] + a[2][1]) * (a[1][2] + a[2][2])
if x == 0 then return 0, 1, false end
z = a[1][1] * a[2][2] - a[1][2] * a[2][1]
z = (a[1][1] + a[1][2] + a[2][1] + a[2][2]) * z * z / x
return z, math.igamma(.5, .5 * z, true), true
else -- generic table
local rs, cs, n, m, N, z = {}, {}, #a, #a[1], 0, 0
for i = 1, n do rs[i] = 0 end
for j = 1, m do cs[j] = 0 end
for i = 1, n do -- compute column sum and row sum
for j = 1, m do cs[j], rs[i] = cs[j] + a[i][j], rs[i] + a[i][j] end
end
for i = 1, n do N = N + rs[i] end
for i = 1, n do -- compute the chi^2 statistics
for j = 1, m do
local E = rs[i] * cs[j] / N;
z = z + (a[i][j] - E) * (a[i][j] - E) / E
end
end
return z, math.igamma(.5 * (n-1) * (m-1), .5 * z, true), true;
end
end
-- Description: Gauss-Jordan elimination (solving equations; computing inverse)
-- Note: on return, a[n][n] is the inverse; b[n][m] is the solution
-- Reference: Section 2.1, Numerical Recipes in C, 2nd edition
function matrix.solve(a, b)
assert(#a == #a[1]);
local n, m = #a, (b and #b[1]) or 0;
local xc, xr, ipiv = {}, {}, {};
local ic, ir;
for j = 1, n do ipiv[j] = 0 end
for i = 1, n do
local big = 0;
for j = 1, n do
local aj = a[j];
if ipiv[j] ~= 1 then
for k = 1, n do
if ipiv[k] == 0 then
if math.abs(aj[k]) >= big then
big = math.abs(aj[k]);
ir, ic = j, k;
end
elseif ipiv[k] > 1 then return -2 end -- singular matrix
end
end
end
ipiv[ic] = ipiv[ic] + 1;
if ir ~= ic then
for l = 1, n do a[ir][l], a[ic][l] = a[ic][l], a[ir][l] end
if b then
for l = 1, m do b[ir][l], b[ic][l] = b[ic][l], b[ir][l] end
end
end
xr[i], xc[i] = ir, ic;
if a[ic][ic] == 0 then return -3 end -- singular matrix
local pivinv = 1 / a[ic][ic];
a[ic][ic] = 1;
for l = 1, n do a[ic][l] = a[ic][l] * pivinv end
if b then
for l = 1, n do b[ic][l] = b[ic][l] * pivinv end
end
for ll = 1, n do
if ll ~= ic then
local tmp = a[ll][ic];
a[ll][ic] = 0;
local all, aic = a[ll], a[ic];
for l = 1, n do all[l] = all[l] - aic[l] * tmp end
if b then
local bll, bic = b[ll], b[ic];
for l = 1, m do bll[l] = bll[l] - bic[l] * tmp end
end
end
end
end
for l = n, 1, -1 do
if xr[l] ~= xc[l] then
for k = 1, n do a[k][xr[l]], a[k][xc[l]] = a[k][xc[l]], a[k][xr[l]] end
end
end
return 0;
end
| gpl-3.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/statistics/rrdtool/definitions/cpu.lua | 76 | 1096 | --[[
Luci statistics - cpu plugin diagram definition
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: cpu.lua 2274 2008-06-03 23:15:16Z jow $
]]--
module("luci.statistics.rrdtool.definitions.cpu",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
return {
title = "%H: Processor usage on core #%pi",
y_min = "0",
vlabel = "Percent",
number_format = "%5.1lf%%",
data = {
instances = {
cpu = { "idle", "user", "system", "nice" }
},
options = {
cpu_idle = { color = "ffffff" },
cpu_nice = { color = "00e000" },
cpu_user = { color = "0000ff" },
cpu_wait = { color = "ffb000" },
cpu_system = { color = "ff0000" },
cpu_softirq = { color = "ff00ff" },
cpu_interrupt = { color = "a000a0" },
cpu_steal = { color = "000000" }
}
}
}
end
| gpl-2.0 |
xennygrimmato/nmt | src/OpenNMT/onmt/utils/Cuda.lua | 5 | 4263 | local Cuda = {
fp16 = false,
gpuIds = {},
activated = false
}
local options = {
{
'-gpuid', { 0 },
[[List of GPU identifiers (1-indexed). CPU is used when set to 0.]]
},
{
'-fallback_to_cpu', false,
[[If GPU can't be used, rollback on the CPU.]]
},
{
'-fp16', false,
[[Use half-precision float on GPU.]]
},
{
'-no_nccl', false,
[[Disable usage of nccl in parallel mode.]]
}
}
function Cuda.declareOpts(cmd)
cmd:setCmdLineOptions(options, 'Cuda')
end
function Cuda.init(opt, masterGPU)
for _, id in ipairs(opt.gpuid) do
onmt.utils.Error.assert(id ~= nil and id >= 0, 'invalid GPU identifier: ' .. id)
if id > 0 then
table.insert(Cuda.gpuIds, id)
end
end
Cuda.activated = #Cuda.gpuIds > 0
if Cuda.activated then
local _, err = pcall(function()
require('cutorch')
require('cunn')
Cuda.fp16 = opt.fp16
if masterGPU == nil then
masterGPU = 1
-- Validate GPU identifiers.
for i = 1, #Cuda.gpuIds do
onmt.utils.Error.assert(Cuda.gpuIds[i] <= cutorch.getDeviceCount(),
'GPU ' .. Cuda.gpuIds[i] .. ' is requested but only '
.. cutorch.getDeviceCount() .. ' GPUs are available')
end
_G.logger:info('Using GPU(s): ' .. table.concat(Cuda.gpuIds, ', '))
if cutorch.isCachingAllocatorEnabled and cutorch.isCachingAllocatorEnabled() then
_G.logger:warning('The caching CUDA memory allocator is enabled. This allocator improves performance at the cost of a higher GPU memory usage. To optimize for memory, consider disabling it by setting the environment variable: THC_CACHING_ALLOCATOR=0')
end
end
cutorch.setDevice(Cuda.gpuIds[masterGPU])
if opt.seed then
cutorch.manualSeed(opt.seed)
end
end)
if err then
if opt.fallback_to_cpu then
_G.logger:warning('Falling back to CPU')
Cuda.activated = false
else
error(err)
end
end
if Cuda.fp16 and not cutorch.hasHalf then
error("installed cutorch does not support half-tensor")
end
end
end
-- returns RNGState for CPU and enabled GPUs
function Cuda.getRNGStates()
local rngStates = { torch.getRNGState() }
for _,idx in ipairs(Cuda.gpuIds) do
table.insert(rngStates, cutorch.getRNGState(idx))
end
return rngStates
end
-- set RNGState from saved state
function Cuda.setRNGStates(rngStates)
if not rngStates then
return
end
_G.logger:info("Restoring random number generator states...")
torch.setRNGState(rngStates[1])
if #rngStates-1 ~= #Cuda.gpuIds then
_G.logger:warning('GPU count does not match for resetting random number generator. Skipping.')
else
for idx = 2, #rngStates do
cutorch.setRNGState(rngStates[idx], idx-1)
end
end
end
--[[
Recursively move all supported objects in `obj` on the GPU.
When using CPU only, converts to float instead of the default double.
]]
function Cuda.convert(obj)
local objtype = torch.typename(obj)
if objtype then
if Cuda.activated and obj.cuda ~= nil then
if objtype:find('torch%..*LongTensor') then
return obj:type('torch.CudaLongTensor')
elseif Cuda.fp16 then
return obj:type('torch.CudaHalfTensor')
else
return obj:type('torch.CudaTensor')
end
elseif not Cuda.activated and obj.float ~= nil then
-- Defaults to float instead of double.
if objtype:find('torch%..*LongTensor') then
return obj:type('torch.LongTensor')
else
return obj:type('torch.FloatTensor')
end
end
end
if objtype or type(obj) == 'table' then
for k, v in pairs(obj) do
obj[k] = Cuda.convert(v)
end
end
return obj
end
--[[
Synchronize operations on current device if working on GPU.
Do nothing otherwise.
]]
function Cuda.synchronize()
if Cuda.activated then cutorch.synchronize() end
end
--[[
Number of available GPU.
]]
function Cuda.gpuCount()
return #Cuda.gpuIds
end
--[[
Free memory on the current GPU device.
]]
function Cuda.freeMemory()
if Cuda.activated then
local freeMemory = cutorch.getMemoryUsage(cutorch.getDevice())
return freeMemory
end
return 0
end
return Cuda
| lgpl-3.0 |
n0xus/darkstar | scripts/zones/Apollyon/mobs/Kerkopes.lua | 16 | 1585 | -----------------------------------
-- Area: Apollyon NE
-- NPC: Kerkopes
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (mobID ==16933102) then -- item
GetNPCByID(16932864+154):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+154):setStatus(STATUS_NORMAL);
elseif (mobID ==16933104) then -- timer T1
GetNPCByID(16932864+153):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+153):setStatus(STATUS_NORMAL);
elseif (mobID ==16933106) then -- timer T2
GetNPCByID(16932864+95):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+95):setStatus(STATUS_NORMAL);
elseif (mobID ==16933108) then -- timer T3
GetNPCByID(16932864+96):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+96):setStatus(STATUS_NORMAL);
elseif (mobID ==16933109) then -- recover
GetNPCByID(16932864+155):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+155):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
ArchiveTeam/ziplist-grab | ziplist.lua | 1 | 2973 | dofile("urlcode.lua")
dofile("table_show.lua")
JSON = (loadfile "JSON.lua")()
local url_count = 0
local tries = 0
load_json_file = function(file)
if file then
local f = io.open(file)
local data = f:read("*all")
f:close()
return JSON:decode(data)
else
return nil
end
end
read_file = function(file)
if file then
local f = assert(io.open(file))
local data = f:read("*all")
f:close()
return data
else
return ""
end
end
wget.callbacks.get_urls = function(file, url, is_css, iri)
local urls = {}
local html = nil
html = read_file(file)
if string.match(url, "http[s]?://www%.ziplist%.com/[^/]+/[^/]+/.+[^/]") then
for customurl in string.gmatch(html, '"[^"]+":{"[^"]+":"(http[s]?://[^"]+)"') do
table.insert(urls, { url=customurl })
end
for customurl in string.gmatch(url, 'http[s]?://www%.ziplist%.com(/[^/]+/[^/]+/.+[^/])') do
local newbase = "http://3po.ziplist.com/recipe/tags?url="
local newend = "&jsonp=CN.ad.ziplist.tags="
local newurl = newbase..customurl..newend
local newurl2 = newbase..customurl
table.insert(urls, { url=newurl })
table.insert(urls, { url=newurl2 })
end
end
return urls
end
wget.callbacks.httploop_result = function(url, err, http_stat)
-- NEW for 2014: Slightly more verbose messages because people keep
-- complaining that it's not moving or not working
local status_code = http_stat["statcode"]
url_count = url_count + 1
io.stdout:write(url_count .. "=" .. status_code .. " " .. url["url"] .. ". \n")
io.stdout:flush()
if status_code == 410 and string.match(url["url"], "/not_found") then
return wget.actions.EXIT
elseif status_code >= 500 or
(status_code >= 400 and status_code ~= 404 and status_code ~= 403) then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 1")
tries = tries + 1
if tries >= 20 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
elseif status_code == 0 then
io.stdout:write("\nServer returned "..http_stat.statcode..". Sleeping.\n")
io.stdout:flush()
os.execute("sleep 10")
tries = tries + 1
if tries >= 10 then
io.stdout:write("\nI give up...\n")
io.stdout:flush()
return wget.actions.ABORT
else
return wget.actions.CONTINUE
end
end
tries = 0
-- We're okay; sleep a bit (if we have to) and continue
-- local sleep_time = 0.1 * (math.random(75, 1000) / 100.0)
local sleep_time = 0
-- if string.match(url["host"], "cdn") or string.match(url["host"], "media") then
-- -- We should be able to go fast on images since that's what a web browser does
-- sleep_time = 0
-- end
if sleep_time > 0.001 then
os.execute("sleep " .. sleep_time)
end
return wget.actions.NOTHING
end
| unlicense |
lduboeuf/lit | commands/update.lua | 2 | 2928 | local log = require('log').log
local updater = require('auto-updater')
local uv = require('uv')
local pathJoin = require('luvi').path.join
local exec = require('exec')
local prompt = require('prompt')(require('pretty-print'))
local miniz = require('miniz')
local binDir = pathJoin(uv.exepath(), "..")
local function updateLit()
local config = require('autoconfig')
config.checked = nil
config.toupdate = nil
config.save()
return updater.check(require('../package'), uv.exepath())
end
local function updateLuvit()
local luvitPath = pathJoin(binDir, "luvit")
if require('ffi').os == "Windows" then
luvitPath = luvitPath .. ".exe"
end
if uv.fs_stat(luvitPath) then
local bundle = require('luvi').makeBundle({luvitPath})
local fs = {
readFile = bundle.readfile,
stat = bundle.stat,
}
return updater.check(require('pkg').query(fs, "."), luvitPath)
else
return updater.check({ name = "luvit/luvit" }, luvitPath)
end
end
local function updateLuvi()
local target = pathJoin(binDir, "luvi")
if require('ffi').os == "Windows" then
target = target .. ".exe"
end
local new, old
local toupdate = require('luvi').version
if uv.fs_stat(target) then
local stdout = exec(target, "-v")
local version = stdout:match("luvi (v[^ \n]+)")
if version and version == toupdate then
log("luvi is up to date", version, "highlight")
return
end
if version then
log("found system luvi", version)
local res = prompt("Are you sure you wish to update " .. target .. " to luvi " .. toupdate .. "?", "Y/n")
if not res:match("[yY]") then
log("canceled update", version, "err")
return
end
end
log("updating luvi", toupdate)
new = target .. ".new"
old = target .. ".old"
else
log("installing luvi binary", target, "highlight")
old = nil
new = target
end
local fd = assert(uv.fs_open(new, "w", 511)) -- 0777
local source = uv.exepath()
local reader = miniz.new_reader(source)
local binSize
if reader then
-- If contains a zip, find where the zip starts
binSize = reader:get_offset()
else
-- Otherwise just read the file size
binSize = uv.fs_stat(source).size
end
local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600
assert(uv.fs_sendfile(fd, fd2, 0, binSize))
uv.fs_close(fd2)
uv.fs_close(fd)
if old then
log("replacing luvi binary", target, "highlight")
uv.fs_rename(target, old)
uv.fs_rename(new, target)
uv.fs_unlink(old)
log("luvi update complete", toupdate, "success")
else
log("luvi install complete", toupdate, "success")
end
end
local commands = {
luvi = updateLuvi,
luvit = updateLuvit,
lit = updateLit,
all = function ()
updateLit()
updateLuvit()
updateLuvi()
end
}
local cmd = commands[args[2] or "all"]
if not cmd then
error("Unknown update command: " .. args[2])
end
cmd()
| apache-2.0 |
ozhanf/ozhanf--bot | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.